2011-11-20 47 views

回答

5

当然,你可以使用任何正常的C函数。下面是一个使用printf打印一些输出NASM例如:

; 
; assemble and link with: 
; nasm -f elf test.asm && gcc -m32 -o test test.o 
; 
section .text 

extern printf ; If you need other functions, list them in a similar way 

global main 

main: 

    mov eax, 0x21 ; The '!' character 
    push eax 
    push message 
    call printf 
    add esp, 8  ; Restore stack - 4 bytes for eax, and 4 bytes for 'message' 
    ret 

message db 'The character is: %c', 10, 0 

如果你只想打印单个字符,你可以使用putchar

push eax 
call putchar 

如果你想打印出来一个数字,你可以这样做:

mov ebx, 8 
push ebx 
push message 
call printf 
...  
message db 'The number is: %d', 10, 0 
+0

谢谢。但是,如果注册ebx的值为8,我想打印字符“8”。如果我尝试推ebx作为参数,它不起作用,所以有没有办法解决这个问题?欢呼 – user973758

+0

,这将相当于'printf(“%d”,8);'我加了这个答案 – Martin

1

调用putchar(3)是最简单的方法。只需将字符的值移入rdi寄存器(对于x86-64,或将edi用于x86),并调用putchar

E.g. (对于x86-64):

asm("movl $120, %rdi\n\t" 
    "call putchar\n\t"); 

将打印一个x到标准输出。

+0

错误的ABI! (x86-64 OS X,猜测给定了寄存器 - 虽然我认为你希望'%rdi'不是'%edi'-和库函数的前导'_') –

+0

你是对的=)我编辑了上面的帖子。 –

+0

您在代码中更改了它,但您的描述仍然会显示“edi寄存器”。 – porglezomp

相关问题