如何在MacOSX上使用nasm进行编译

时间:2012-12-31 16:00:21

标签: assembly nasm

我正在尝试编译和链接我在Assembler上的第一个程序。 我尝试编译以下代码:

; %include "stud_io.inc"    
global _main     

section .text
_main: 
    xor eax, eax
again:
    ; PRINT "Hello"
    ; PUTCHAR 10
    inc eax     
    cmp eax, 5
    jl again

在用于编译和链接程序的控制台命令下面:

-bash-3.2$ nasm -f macho main.asm -o main.o  && ld -e _main -macosx_version_min 10.8 -arch x86_64 main.o

但结果是:

ld: warning: ignoring file main.o, file was built for i386 which is not the architecture being linked (x86_64): main.o
Undefined symbols for architecture x86_64:
  "_main", referenced from:
     -u command line option
ld: symbol(s) not found for architecture x86_64

我认为有必要为x86_64编译main.asm文件。 如何正确编译我的系统程序?

3 个答案:

答案 0 :(得分:15)

我建议您先更新NASM

之后,尝试运行:

nasm -f macho64 main.asm -o main.o  && ld -e _main -macosx_version_min 10.8 -arch x86_64 main.o -lSystem

请注意,新命令添加了上面的JasonD建议(macho64),但也将-lSystem添加到ld命令以阻止ld抛出以下错误:

ld: dynamic main executables must link with libSystem.dylib for architecture x86_64

答案 1 :(得分:1)

我注意到大多数示例都显示了独立的汇编程序,但是从C调用汇编可能更常见。我创建了一个简单的C程序,它使用了这样的最小nasm汇编函数:

extern unsigned cpuid(unsigned n);

/* ... */
        unsigned n = cpuid(1);

程序集如下所示:

section .text
    global _cpuid

_cpuid:
    push rbp
    mov rbp, rsp
    mov rax, rdi
    cpuid
    mov rax, rcx
    leave
    ret

您可以在此处查看整个内容,包括makefile中的nasm CLI选项:

https://github.com/ecashin/low/tree/master/cpuid

通过打印某些特定于CPU的功能的可用性,它确实有用。 (但它通过使用CPUID而不检查它是否可用来实现。如果CPU是英特尔并且比i486更新,那就没关系。)

该示例在Mac OS X Snow Leopard上使用ports集合中的nasm进行了测试。删除下划线前缀是移植到Linux x86_64所需的唯一更改。

答案 2 :(得分:0)

也许尝试静态链接?

ld -macosx_version_min 10.13 -e _main -static main.o
相关问题