I have a very strange behavior of gcc
that I cannot understand well, maybe somebody can explain it a bit to me (it must be simple but I failed to find precise documentation about it on the Web).
I try to compile a very simple 'Hello World' program in amd64 assembly with gcc
. For that, I try to not rely on the libc nor the gcc
libraries. Just to show that I do not need to go through __libc_start_main()
at first.
Here is my code (which should be okay):
.data # Data section
msg:
.ascii "Hello World!\n"
len = . - msg
.text # Text section
.globl _start
_start:
# Write the string to stdout
movq $len, %rdx
movq $msg, %rsi
movq $1, %rdi
movq $1, %rax
syscall
# and exit
movq $0, %rdi
movq $60, %rax
syscall
Then, I try to compile it with gcc
:
#> gcc -m64 -Wall -Wextra -m64 -nostdlib -o hello_syscall hello_syscall.s
/usr/bin/ld: /tmp/ccDQWRW2.o: relocation R_X86_64_32S against `.data' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output
collect2: error: ld returned 1 exit status
Then, adding -fPIC
does not help at all. But, when I compile it with -static
it works:
#> gcc -m64 -Wall -Wextra -m64 -nostdlib -static -o hello_syscall hello_syscall.s
#> ./hello_syscall
Hello World!
So, I wonder why this behavior and if I can get rid of the -static
option or not (well, I would be happy if I just know why it is needed here!).