2012-12-31 44 views
6

我想編譯並鏈接我的彙編程序上的第一個程序。 我嘗試編譯下面的代碼:如何在MacOSX上使用nasm編譯

; %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文件.. 如何正確編譯我的系統的程序?

+0

'-f macho64'也許? – JasonD

+0

nasm無法識別此選項 –

+0

您運行的是哪個版本的nasm? – JasonD

回答

9

我會建議先更新您的NASM

之後,嘗試運行此:

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

注意到新的命令添加上述(macho64)JasonD的建議,而且還增加了-lSystemld命令從拋以下錯誤停止LD:

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

是的,我添加-lSystem。但是現在我有「Segmentation fault:11」 –

+0

segfault是代碼執行的問題。在'jl'指令之後,添加'ret'指令(因爲您使用的是主指令)。請注意,如果您正在使用純x86組件,則需要使用'int 0x80'中的退出系統調用(但在本例中不使用)退出。請記住,當您的代碼完成時,PC計數器需要知道繼續執行的位置。 – RageD

1

我注意到大多數例子都顯示獨立的彙編程序,但是從C調用程序集可能更常見。我創建了一個簡單的C程序,它使用最小的nasm組裝函數l IKE在此:

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 

你可以看到整個事情,包括NASM CLI選項生成文件,在這裏:

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

它通過打印某些特定於CPU的功能的可用性,可以輕鬆實現某些功能。 (但是它是通過使用CPUID而不檢查它是否可用,如果CPU是Intel並且比i486更新,那很好)。

該示例在Mac OS X Snow Leopard上用nasm港口集合。刪除下劃線前綴是移植到Linux x86_64所必需的唯一更改。

+0

此外,我確實需要更新NASM,因爲在我可以使用'-fmacho64'之前,這裏的其他評論說。 –

相關問題