Break down C++ code size

2019-03-13 02:51发布

I'm looking for a nice Stack Overflow-style answer to the first question in the old blog post C++ Code Size, which I'll repeat below:

I’d really like some tool (ideally, g++ based) that shows me what parts of compiled/linked code are generated from what parts of C++ source code. For instance, to see whether a particular template is being instantiated for hundreds of different types (fixable via a template specialization) or whether code is being inlined excessively, or whether particular functions are larger than expected.

7条回答
Juvenile、少年°
2楼-- · 2019-03-13 03:20

I don't know if it will help but there is a gcc flag to write the assembly code it generates to a text file for your examination.

"-S Used in place of -c to cause the assembler source file to be generated, using .s as the extension, instead of the object file. This may be useful if you need to examine the generated assembly code. "

查看更多
SAY GOODBYE
3楼-- · 2019-03-13 03:32

I recently wrote a tool, bloat-blame, which does something similar to what nategoose proposed.

查看更多
Explosion°爆炸
4楼-- · 2019-03-13 03:32

In most C compilers there is a way to generate a .map file. This file lists all of the compiled libraries their address and their size. You can use that map file to help you determine which files you should be looking to optimize first.

查看更多
男人必须洒脱
5楼-- · 2019-03-13 03:35

In Visual C++, this is essentially what .PDB files are for.

查看更多
甜甜的少女心
6楼-- · 2019-03-13 03:36

If you're looking to find sources of code bloat in your C++ code, I've used 'nm' for that. The following command will list all the symbols in your app with the biggest code and data chunks at the top:

nm --demangle --print-size --size-sort --reverse-sort <executable_or_lib_name> | less
查看更多
迷人小祖宗
7楼-- · 2019-03-13 03:36

I don't know how to map code->generated assembly in general.

For template instantiations you can use something like "strings -a |grep |sort -u|gc++filt" to get a rough picture of what's being created.

The other two items you mentioned seem pretty subjective actually. What is "too much" inlining? Are you worried your binary file is getting inflated? The only thing to do there is actually go into gdb and disassemble the caller to see what it generated, nothing to check for "excessive" inlining in general.

For function size, again I'm curious why it matters? Are you trying to find code that expands unexpectedly when compiled? How do you even define what an expected size is for a tool to examine? Again, you can always dissemble any function that you suspect is compiling to far more code than you want, and see exactly what the compiler is doing.

查看更多
登录 后发表回答