Skip to content

Instantly share code, notes, and snippets.

@jamichaels
Last active July 25, 2019 13:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamichaels/a5e770105615d9e32b18 to your computer and use it in GitHub Desktop.
Save jamichaels/a5e770105615d9e32b18 to your computer and use it in GitHub Desktop.
Printing an integer to stdout with printf in 64-bit NASM (Linux)
Printing an integer to stdout with printf in 64-bit NASM (Linux)
While doing some debugging, I found myself wanting to print an address to the screen, and it
took me forever to piece together how to do it from several tutorials.
The main things you need to know are
1) use 'main:' as a label and not '_start:' - because you are calling libc, it won't work without main.
2) compile or link with -lc (that's short for libc).
3) declare printf as extern
4) zero the vector registers (put 0 into rax). I don't know why, but apparently you are supposed to.
The following program is compiled thusly:
nasm -f elf64 -o test.o test.s
gcc -o test test.o -lc
and prints:
404000
to stdout
;;;; Print a number to stdout
extern printf
global main
section .text
main:
mov rdi,printf_format
mov rsi,0x404000
xor rax,rax
call printf
mov rax,60 ; exit
syscall
section .data
printf_format: db '%x',10,0
@j4cobgarby
Copy link

https://stackoverflow.com/questions/36007975/compile-error-relocation-r-x86-64-pc32-against-undefined-symbol/41322328#41322328
It seems for some people -- at least, for me -- this is necessary.
So for anyone looking at this, if

call printf

doesn't work, try

call printf WRT ..plt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment