There are 2 ways to print a string with assembly language in Linux.
1) Use syscall
for x64, or int 0x80
for x86. It's not printf
, it's kernel routines. You can find more here (x86) and here (x64).
2) Use printf
from glibc. I assume you are familiar with the structure of NASM program, so here is a nice x86 example from acm.mipt.ru:
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
You can assembly it with nasm -f elf32 -o foo.o foo.asm
and link with gcc -m32 -o foo foo.o
for x86. For x64 just replace elf32
with elf64
and -m32
with -m64
. Note than you need gcc-multilib
to build x86 programs on x64 system using gcc.