Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does splitting C++ code into multiple translation units introduce overhead on the executable size?

Tags:

c++

linker

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 variables) linked into it?

like image 903
sharptooth Avatar asked Mar 03 '10 11:03

sharptooth


2 Answers

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.

like image 146
AshleysBrain Avatar answered Oct 14 '22 09:10

AshleysBrain


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.

like image 2
Kerido Avatar answered Oct 14 '22 07:10

Kerido