Let's say I have the following C program:
int main() {
int a = 1;
int b = 2;
return a + b;
}
Compiling this on Compiler Explorer gives me:
main:
pushq %rbp
movq %rsp, %rbp
movl $1, -4(%rbp)
movl $2, -8(%rbp)
movl -4(%rbp), %edx
movl -8(%rbp), %eax
addl %edx, %eax
popq %rbp
ret
This is (somewhat) similar to what compiling via gcc
gives me, at least for the main
part. However, this will not compile as a "stand-alone", for example if I copy-paste the asm into a file gb.s
and run $ gcc gb.s
I get an error:
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol...
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_line): relocation 0 has invalid symbol index 2
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
-- unless I also include the .globl
at the top, for example:
.globl main
From this, I have two questions:
- Why doesn't the godbolt compiler contain that at the top, or something else to make it self-contained?
- Is there a way to run
gcc
and tell it thatmain
is the main/global section without putting.globl main
at the top?