在 Linux 中有两种用汇编语言打印字符串的方法。
1) 对 x64 使用 syscall,对 x86 使用 int 0x80。这不是printf,而是内核例程。您可以找到更多here (x86) 和here (x64)。
2) 使用来自 glibc 的 printf。我假设你熟悉 NASM 程序的结构,所以这里有一个来自acm.mipt.ru 的不错的 x86 示例:
global main
;Declare used libc functions
extern exit
extern puts
extern scanf
extern printf
section .text
main:
;Arguments are passed in reversed order via stack (for x86)
;For x64 first six arguments are passed in straight order
; via RDI, RSI, RDX, RCX, R8, R9 and other are passed via stack
;The result comes back in EAX/RAX
push dword msg
call puts
;After passing arguments via stack, you have to clear it to
; prevent segfault with add esp, 4 * (number of arguments)
add esp, 4
push dword a
push dword b
push dword msg1
call scanf
add esp, 12
;For x64 this scanf call will look like:
; mov rdi, msg1
; mov rsi, b
; mov rdx, a
; call scanf
mov eax, dword [a]
add eax, dword [b]
push eax
push dword msg2
call printf
add esp, 8
push dword 0
call exit
add esp, 4
ret
section .data
msg : db "An example of interfacing with GLIBC.",0xA,0
msg1 : db "%d%d",0
msg2 : db "%d", 0xA, 0
section .bss
a resd 1
b resd 1
对于 x86,您可以使用 nasm -f elf32 -o foo.o foo.asm 组装它并使用 gcc -m32 -o foo foo.o 链接。对于 x64,只需将 elf32 替换为 elf64 并将 -m32 替换为 -m64。请注意,您需要gcc-multilib 才能使用 gcc 在 x64 系统上构建 x86 程序。