Search code examples
c++gcclinkerld

how to find the bottleneck in linking?


I have a project which is very slow in linking (~ 2mins and I feel this is slow). I am aware of faster linker such as gold or lld, but I cannot change a linker.

I used a lot of C++11 templates in my code and I suspect that some template code may get instantiated repeatedly in multiple object files, but I have no clue how to find if this is true.

I wonder if there is a way to profile the whole linking stage like what we do to profile a program and try to find the bottleneck. For example, a tool that I can use to inspect how many times a symbol (unnecessarily) appear in different object files and then get discarded during linking can help me to find out which template code might be the cause. The above about repeated symbols in object files is only my speculation - I need an evidence based approach. Then based on this finding, I will think about how to improve my code to reduce linking time.

I use CMake, GNU g++ and ld as my build tools and I'm working in Linux platform.

Thanks.


Solution

  • One way to approach this problem is to dump defined symbols of each object file and archive included in the link with nm --demangle --defined-only --extern-only and build a mapping {symbol, definition_count}. Sort this mapping by definition_count high-to-low and print.