I decided to compile a very basic C program and take a look at the generated code with objdump -d
.
int main(int argc, char *argv[]) {
exit(0
gcc -s
strips symbol names out of the final executable so you can't tell where different parts of the machine code came from.
Most of it is not from your main
. To just see that, look at gcc -S
output (asm source), e.g. on https://godbolt.org/. How to remove "noise" from GCC/clang assembly output?
Most of that is the CRT (C RunTime) startup code that eventually calls your main
after initializing the standard library. (e.g. allocating memory for stdio buffers and so on.) It gets linked in regardless of how efficient your main
is. e.g. compiling an empty int main(void){}
with gcc -Os
(optimize for size) will barely make it any smaller.
You could in theory compile with gcc -nostdlib
and write your own _start
that uses inline asm to make an exit system call.
See also
_start
, but the answers there show how).C program does a lots of stuff before calling the main
function. It has to initialize .data and .bss segments, set the stack, go through the constructors and destructors (yes gcc in C has a special attributes for such a functions) and initializes the library.
gcc destructor and constructor functions:
void __attribute__ ((constructor)) funcname(void);
void __attribute__ ((destructor)) funcname(void);
you may have as many constructors and destructors as you wish.
constructors are called before call to the main
function, destructors on exit from the program (after the main
termination)
https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html#Function-Attributes
gcc generates unnecessary (?) instructions
Yes, because you invoked GCC without asking for any compiler optimizations.
My recommendation: compile with
gcc -fverbose-asm -O2 -S test.c
then look inside the generated test.s
assembler code.
BTW, most of the code is from crt0, which is given by, not emitted by, gcc
. Build your executable with gcc -O2 -v test.c -o testprog
to understand what GCC really does. Read documentation of GCC internals.
Since GCC is free software, you are allowed to look inside its source code and improve it. But the crt0 stuff is tricky, and operating system specific.
Consider also reading about linkers and loaders, about ELF executables, and How to write shared libraries, and the Linux Assembler HowTo.