Does splitting C++ code into multiple translation units introduce overhead on the executable size?
I have some code shared among multiple projects in a static library. Even with function-level linking I get more object code than I'd like to in the output - see another question about that.
Surely the most straightforward solution to decreasing the amount of object code linked into the final executable would be to split the translation units so that I get more .obj files each with less object code. I can even go to extremes - put each function into a separate translation unit.
Let's pretend I don't care of the mess induced by having ten times more .cpp files and I don't care of possible link time growth.
Will such splitting into many object files introduce overhead on the executable size? Will the executable become bigger simply because there were ten times more .obj files (but overall they have exactly the same functions and varia开发者_如何学编程bles) linked into it?
Things which are more likely to affect your final EXE size (not exhaustive list):
- Whether you static or dynamically link to libraries (dynamic link is smaller since the library code is not inside your EXE)
- It's possible use of many template classes eg. vector<A>, vector<B>, vector<C> will cause code bloat, since each instantiation of vector with different types is compiled separately
- Compiler settings, eg. optimisation, size vs. speed, inlining (lots of inlining can make code larger), whole program optimisation if supported
- Linker settings, eg. if supported, removing redundant or identical data. Can help reduce size.
In short splitting code up in to more translation units probably will have no effect - same code, just reorganised. It might even make things worse if your compiler does not take in to account whole program optimisation, since each translation unit has less information about your program in it.
I think, with modern compilers the output size wins will be too subtle. As far as I know, the compilers only use those functions which are referenced in your code. Other functions and symbols are skipped from the output file.
No. I think what you need is to either recompile your static library as a shared library, or use something like: strip -g -s -R .comment to remove code that is not being used.
精彩评论