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

2019-02-09 19:38发布

问题:

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

回答1:

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


回答2:

It seems you are still using the 32-bit version. If you nasm -hf it should list macho64. If not you'll need to update again.

You could try in the console brew update . If this performs an update then brew search nasm where it should bring up nasm. Then simply brew install nasm. This should install nasm to your computer. Be sure sure to look out for the location where it was installed. Mine was installed at /usr/local/cellar/nasm/2.11.02/bin/ . Then by typing nasm -hf it should bring up a list of available formats which you should see macho64 available.



标签: macos gcc nasm