nasm/gcc issue on 64-bit Mac OS X Lion

math4tots picture math4tots · Feb 16, 2012 · Viewed 8.3k times · Source

I was reading this article, and at one point it gives me this nasm program:

; tiny.asm
BITS 32
GLOBAL main
SECTION .text
main:
              mov     eax, 42
              ret

And tells me to run the following commands:

$ nasm -f elf tiny.asm
$ gcc -Wall -s tiny.o

I got the following error:

ld: warning: option -s is obsolete and being ignored
ld: warning: ignoring file tiny.o, file was built for unsupported file format which is not the architecture being linked (x86_64)
Undefined symbols for architecture x86_64:
  "_main", referenced from:
      start in crt1.10.6.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

I ventured a guess at what might be the problem, and changed the BITS line to read:

 BITS 64

But then when I run nasm -f elf tiny.asm I get:

tiny.asm:2: error: `64' is not a valid segment size; must be 16 or 32

How do I modify the code to work on my machine?

Edit:

I took Alex's advice from the comments and downloaded a newer version. However,

./nasm-2.09.10/nasm -f elf tiny.asm

complains

tiny.asm:2: error: elf32 output format does not support 64-bit code

On the other hand,

./nasm-2.09.10/nasm -f elf64 tiny.asm
gcc -Wall -s tiny.o

complains

ld: warning: ignoring file tiny.o, file was built for unsupported file format which is not the architecture being linked (x86_64)
Undefined symbols for architecture x86_64:
  "_main", referenced from:
      start in crt1.10.6.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

Answer

jupp0r picture jupp0r · Feb 16, 2012

There are OS X-specific adjustments you have to make in order for your example to work: The main method is prepended with a _ by the OS X linker:

; tiny.asm
BITS 32
GLOBAL _main
SECTION .text
_main:
    mov     eax, 42
    ret

The second is that you have to use the mach file format:

nasm -f macho tiny.asm

Now you can link it (using -m32 to indicate a 32 bit object file):

gcc -m32 tiny.o