64位Mac OS X Lion上nasm/gcc问题

7
我正在阅读 这篇 文章, 其中有一段给出了以下 nasm 程序:
; tiny.asm
BITS 32
GLOBAL main
SECTION .text
main:
              mov     eax, 42
              ret

并告诉我运行以下命令:

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

我得到了以下错误:
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

我猜测可能存在问题,并将BITS行更改为以下内容:
 BITS 64

但是,当我运行nasm -f elf tiny.asm时,会出现以下内容:

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

如何修改代码以使其在我的机器上运行?

编辑:

我采纳了评论中Alex的建议并下载了更新版本。然而,

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

投诉

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

另一方面,
./nasm-2.09.10/nasm -f elf64 tiny.asm
gcc -Wall -s tiny.o

投诉

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

@Alex elf64 给了我“无法识别的输出格式”。至于版本,nasm -v 给了我“NASM 版本 0.98.40(Apple Computer,Inc. build 11)编译于2011年11月3日”。0.98 看起来可能是一个旧版本,但它是在2011年编译的,所以不可能那么老,对吧?为什么苹果会发布过时的软件呢?一个默认的汇编器不能在64位平台上汇编64位代码? - math4tots
你的版本已经非常过时了。我的打印出来是“NASM version 2.09.10 compiled on Jul 15 2011”。新版本在这里 - Alexey Frunze
2个回答

15

如果你想让这个例子在 OS X 上运行,那么你需要做一些特定于 OS X 的调整: 主方法名需要被 OS X 链接器前置下划线:

; tiny.asm
BITS 32
GLOBAL _main
SECTION .text
_main:
    mov     eax, 42
    ret
第二点是您必须使用mach文件格式:
nasm -f macho tiny.asm

现在您可以进行链接(使用-m32表示32位目标文件):

gcc -m32 tiny.o

对于64位代码,请使用-fmacho64。此外,您不需要bits 32,我建议避免使用它。如果您尝试将32位源代码汇编成64位目标文件或反之,则希望出现错误消息。 - Peter Cordes

2

看起来您仍在使用32位版本。如果您执行nasm -hf,它应该会列出macho64。如果没有列出,则需要再次更新。

您可以在控制台中尝试执行brew update。如果这执行了更新操作,则执行brew search nasm,其中它应该会显示nasm。然后只需执行brew install nasm即可将nasm安装到计算机上。请务必查找已安装位置。我的安装位置为/usr/local/cellar/nasm/2.11.02/bin/。然后通过输入nasm -hf,它应该会列出可用格式的列表,在其中您应该会看到可用的macho64


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接