gcc generates unnecessary (?) instructions

后端 未结 3 1265
长情又很酷
长情又很酷 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).

提交回复
热议问题