When you link object files into your program the linker will resolve any unresolved symbols in your program. If you want to eliminate dead code (what is not done by GCC by default), you could do the following:
- Build object files with
-fdata-sections
and -ffunction-sections
flags (refer to GCC manual for more information);
- Link object files using the
-Wl,--gc-sections
optimization flag which tells the linker to discard unreferenced sections.
NOTE: Only unused static
functions are stripped out automatically.
Theoretically presence of redundant symbols only affects the size of the resulting program. However, I've stumbled across the posts where people reported from 1% to 2% performance improvement after stripping the dead code. Of course the code base has to be of substantial size to notice such an effect.
Beware that sometimes this approach may not work properly. For instance, I've experienced crashes or linkage problems on some systems, probably due to bugs in the implementation of this feature.
Furthermore, don't think that these flags improve performance and/or size in every case. There are good reasons why this feature is turned on via flags and not present by default. In fact,
sometimes linker may create larger object and executable files and/or slower code, not to mention that you will definitely experience problems with debugging too.
To conclude, be very cautious when using this feature, and always profile your code before and after as recommended in other answers.
Finally, if you are really after speed, you can check my other answer on some useful GCC optimization flags.
Last but not least, the so-called Link Time Optimization (LTO) is a huge new and promising concept that has been introduced into GCC, and recently became more or less stable to use. The respective flag is -lto
, see here and here for more information. Although nowadays it is usable, not everything is shiny on some platforms yet. For instance, on Windows the GCC ports MinGW/MinGW-w64 are still struggling to make LTO support of production quality.