I am using a 64 bit linux machine with a x84-elf64-gcc compiler. I have just started low level programming and would like to understand how C code is actually translated into binary. This is mainly for Operating Systems developement, as I know that a processor doesn't understand ELF, or any other format, and only understands binary.
For example, the following c file:
//test.c
int func()
{
return 0x12345678;
}
When I compile with gcc:
gcc test.c
I get the following error:
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
So I'm guessing that there is an issue with the linker. I do:
gcc test.c -c
I get an ELF object file, and I do an objdump and get the expected:
0000000000000000 <func>:
0: 55 push %rbp
1: 48 89 e5 mov %rsp,%rbp
4: b8 78 56 34 12 mov $0x12345678,%eax
9: 5d pop %rbp
a: c3 retq
But when I "cross compile" a 32 bit version using the -m32 option and objdump, I get:
hello.o: file format elf32-i386
Disassembly of section .text:
00000000 <func>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: e8 fc ff ff ff call 4 <func+0x4>
8: 05 01 00 00 00 add $0x1,%eax
d: b8 78 56 34 12 mov $0x12345678,%eax
12: 5d pop %ebp
13: c3 ret
Disassembly of section .text.__x86.get_pc_thunk.ax:
00000000 <__x86.get_pc_thunk.ax>:
0: 8b 04 24 mov (%esp),%eax
3: c3 ret
I've read in a previous answer that this has to do with position independent code: undefined reference to `_GLOBAL_OFFSET_TABLE_' in gcc 32-bit code for a trivial function, freestanding OS
Why is there such a change when you compile with the -m32 option? Moreover, I was advised to use the -ffreestanding option when I compile, but it doesn't seem to have an effect here. I've read that -ffreestanding tells the compiler that there is no standard library, so what is -nostdlib then?
Note: I'm relatively new to this hardcore c programming, and I think that the main issue here is that I don't really understand how linkers/compilers work. :(