Reducing GCC target EXE code size?

不打扰是莪最后的温柔 提交于 2019-12-07 06:45:08

问题


When I compiled a no-op program:

int main(void)
{
    return 0;
}

with various compilers:

  • GCC (similar result to LLVM as well): Gave a 10-KiB executable (compiled with -s)

    • Sections: .CRT, .bss, .data, .idata, .rdata, .text, .tls

    • Depends on msvcrt.dll and kernel32.dll

  • MSVC 2010: Gave a 5.5 KiB executable (compiled with /MD /Ox)

    • Sections: .data, .rdata, .reloc, .text

    • Depends on msvcr100.dll and kernel32.dll

    • Could have been further reduced by merging .rdata with .text

  • Windows Driver Kit 7.1: Gave a 6.5 KiB executable (compiled with /MD /Ox, linked with msvcrt_winxp.obj to allow it to run on XP)

    • Sections: .data, .rdata, .text

    • Depends on msvcrt.dll and kernel32.dll

    • Could have been further reduced by merging .rdata with .text

  • Windows 2003 Driver Development Kit: Gave a 3.5 KiB executable

    • Sections: .data, .rdata, .text

    • Depends on msvcrt.dll

    • Could have been further reduced by merging .rdata with .text

  • Tiny C Compiler (TCC): Gave a 1.5 KiB executable

    • Sections: .data, .text

    • Depends on msvcrt.dll

So I guess the question is simple:

Is it possible to further reduce GCC or LLVM's target executable sizes so that they are closer to the bare-minimum possible, while still linking to msvcrt.dll?

(Edit: I'm obviously not looking for packers like UPX, etc.)


回答1:


This isn't a particularly meaningful thing to do. It might be possible to eliminate a few things, but as soon as you have a program that actually does anything then it'll pull those things straight back in again.

For example, on another platform (I don't do much Windows stuff), the minimum size for a program is larger than you would think because every program has an atexit handler to clean up. That handler has a possible error case which means it pull in printf and all the I/O stuff. Atexit itself also pulls in malloc and all the memory handing stuff. And no doubt there's a few other bits besides. The end result is a 400KB static binary size. That's annoying in a no-op program, but in reality all programs would need this stuff, so it's a moot point.

In general, if you want to minimise program size, compile with -Os, and try to use -flto or -fwhole-program (but this last will need lots of changes to your build procedure). Also, don't use -g, and do strip the final binaries (if that doesn't break them).



来源:https://stackoverflow.com/questions/8547233/reducing-gcc-target-exe-code-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!