2015-11-15 31 views
2

我是新組裝人員。我有代碼問題。我正在嘗試使用scanf創建簡單的程序。NASM scanf未定義參考(LINUX)

這是代碼:

nasm -f elf64 -o program.o program.asm 

和:

global main 
extern printf 
extern scanf 

section .text 

section .data 
message: db "The result is = %d", 10, 0 
request: db "Enter the number: ", 0 
integer1: times 4 db 0 ; 32-bits integer = 4 bytes 
formatin: db "%d", 0 

main: 
; Ask for an integer 
push request 
call printf 
add esp, 4 ; remove the parameter 

push integer1 ; address of integer1, where the input is going to be stored 
push formatin ; arguments are right to left (first parameter) 
call scanf 
add esp, 8 ; remove the parameters 

; Move the value under the address integer1 to EAX 
mov eax, [integer1] 

; Print out the content of eax register 
push rax 
push message 
call printf 
add esp, 8 

; Linux terminate the app 
MOV AL, 1 
MOV EBX, 0 
INT 80h 

我編譯

ld -o program program.o 

但是當我嘗試LD我得到錯誤:

program.o: In function `main': 
program.asm:(.data+0x34): undefined reference to `printf' 
program.asm:(.data+0x46): undefined reference to `scanf' 
program.asm:(.data+0x5b): undefined reference to `printf' 

我正在使用64位Linux。

感謝您的幫助。

+2

這些函數來自libc。使用'gcc -o program program.o'鏈接。另外,不要使用exit syscall來終止程序,而只是使用'ret'或'call exit'。而且,這是一個32位的程序,所以最好使用'-f elf32'和'gcc -m32'。 – Jester

+0

當我嘗試用gcc我得到thia錯誤:輸入文件'program.o'的i386體系結構與i386不兼容:x86-64輸出和collect2:錯誤:ld返回1退出狀態 – cirval

+0

正如我所說的,使用'gcc -m32 ' – Jester

回答

1

您沒有使用ld命令鏈接任何庫。 scanfprintf在C庫中定義,這樣你就可以鏈接:

ld -o program program.o -lc 

,或者您可以使用定義這些功能,如果您有它可用一些其他的庫。