在 C++ 中,如何找出最终可执行文件的大小来自何处?

How do I find out where the size of the final executable comes from in C++?

假设我有一个 C++ 程序,它在编译时生成一个大小为数兆字节的可执行二进制文件。我如何找出这个尺寸的来源?是否有工具可以显示 X% 的大小来自文件或 class Y 等?

理想情况下,我正在寻找类似于 Disk Usage Analyzer 的工具,它可以将构成可执行文件的内容分解为某种饼图或其他图表。如果没有,至少拥有可用的信息将允许创建图表。

最终目标是确定我可以从可执行文件中排除的部分程序,以缩小它并优化大小,从最大的不必要代码开始。

您可以看一下 Bloaty McBloatface,它声称正是为此而设计的:

Ever wondered what's making your binary big? Bloaty McBloatface will show you a size profile of the binary so you can understand what's taking up space inside.

Bloaty performs a deep analysis of the binary. Using custom ELF, DWARF, and Mach-O parsers, Bloaty aims to accurately attribute every byte of the binary to the symbol or compileunit that produced it. It will even disassemble the binary looking for references to anonymous data. For more information about the analysis performed by Bloaty, please see doc/how-bloaty-works.md.

Bloaty works on binaries, shared objects, object files, and static libraries (.a files). The following file formats are supported:

ELF
Mach-O
WebAssembly (experimental)