gcc generates unnecessary (?) instructions

后端 未结 3 1232
长情又很酷
长情又很酷 2021-01-15 22:50

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         


        
相关标签:
3条回答
  • 2021-01-15 23:20

    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

    • A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux
    • How Get arguments value using inline assembly in C without Glibc? (getting command line args complicates the exercise of writing your own _start, but the answers there show how).
    0 讨论(0)
  • 2021-01-15 23:35

    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

    0 讨论(0)
  • 2021-01-15 23:37

    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.

    0 讨论(0)
提交回复
热议问题