2009-12-21 15 views
7

Tôi đang học NASM và đang buộc phải biên dịch mã này (mà tôi đã tìm thấy here). Nó lắp ráp sử dụng lệnh này NASM:Lỗi đầu ra GCC "không xác định tham chiếu đến` printf '"khi sử dụng câu lệnh ngoài NASM để truy cập printf

nasm -f coff -l printf.lst printf1.asm 

để printf.o nhưng gcc liên kết lệnh này:

gcc -o printf1 printf1.o 

không thành công với các lỗi:

printf1.o:printf1.asm:(.text+0x1a): undefined reference to `printf' 
collect2: ld returned 1 exit status 

Tôi đang làm gì sai? Cảm ơn trước. (EDIT: Tôi đang sử dụng Windows 7);

; printf1.asm print an integer from storage and from a register 
; Assemble: nasm -f coff -l printf.lst printf1.asm 
; Link:  gcc -o printf1 printf1.o 
; Run:  printf1 
; Output: a=5, eax=7 

; Equivalent C code 
; /* printf1.c print an int and an expression */ 
; #include 
; int main() 
; { 
; int a=5; 
; printf("a=%d, eax=%d\n", a, a+2); 
; return 0; 
; } 

; Declare some external functions 
; 
     extern printf  ; the C function, to be called 

section .data   ; Data section, initialized variables 

     a: dd 5   ; int a=5; 
     fmt: db "a=%d, eax=%d", 10, 0 ; The printf format, "\n",'0' 


section .text    ; Code section. 

     global _main  ; the standard gcc entry point 
_main:    ; the program label for the entry point 
     push ebp  ; set up stack frame 
     mov  ebp,esp 

    mov eax, [a] ; put a from store into register 
    add eax, 2  ; a+2 
    push eax  ; value of a+2 
     push dword [a] ; value of variable a 
     push dword fmt ; address of ctrl string 
     call printf  ; Call C function 
     add  esp, 12  ; pop stack 3 push times 4 bytes 

     mov  esp, ebp ; takedown stack frame 
     pop  ebp  ; same as "leave" op 

    mov eax,0  ; normal, no error, return value 
    ret   ; return 

Trả lời

4

Tôi tin rằng bạn cần phải thực hiện đó _printf để phù hợp với quy ước gọi C (giống như bạn sử dụng _main thay vì main).

+0

Điều này hiện đang biên dịch nhưng nó đổ vỡ khi tôi mở "printf1.exe" nó chỉ đơn giản là treo. Có cách nào để gỡ lỗi các chương trình được tạo trong NASM khi chúng đang chạy không? –

+0

Chỉ cần mở nó trong WinDBG hoặc tương tự. –

+1

Tất cả các chương trình NASM liên kết gcc của tôi đều không thành công: (Tôi tự hỏi tại sao? –

Các vấn đề liên quan