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

问题描述 投票:0回答:4

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

; %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文件.. 如何正确地为我的系统编译程序?

assembly nasm
4个回答
18
投票

我建议首先更新您的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
投票

我注意到大多数示例都显示独立的汇编程序,但从 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 是 Intel 并且比 i486 更新,那也没关系。)

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


0
投票

也许尝试静态链接?

ld -macosx_version_min 10.13 -e _main -static main.o

0
投票

您需要为AArm64架构编写它并使用gcc编译它。 这是我的简单程序,仅与系统代码 1 一起存在:

// main.s

.global _start
_start:
   mov x0, 1             // Set exit status 1 in x0.
   mov x8, 93            // System call number for exit in ARM64.
   svc 0                 // Invoke system call.

编译:

gcc -o main  main.s 

奔跑

./main

验证应用程序的退出代码以确保它与我们在汇编代码中设置的代码1一起存在:

echo $?
``
© www.soinside.com 2019 - 2024. All rights reserved.