I have always been told that compiler is sufficient smart to eliminate dead code. Much of the code that I am writing has a lot of information known at compile time but the c
Typically, if you're compiling with the -O flag on the following flags are turned on:
-fauto-inc-dec
-fcompare-elim
-fcprop-registers
-fdce
[...]
-fdce stands for Dead Code Elimination. I'd suggest you compile your binaries with and without (i.e. by turning off explicitly) this option to make sure if your binaries are as optimized as you'd like them to be.
Read about the different passes of the compiler:
- SSA Aggressive Dead Code Elimination. Turned on by the `-fssa-dce' option. This pass performs elimination of code considered unnecessary because it has no externally visible effects on the program. It operates in linear time.
As for helping the linker with dead code elimination go through this presentation. Two major takeaways being:
Compile your modules with -ffunction-sections -fdata-sections – there are no downsides to it!
- This includes static libraries, not just binaries – make it possible for users of your library to benefit from more efficient dead code removal.
- Link your binaries with --gc-sections, unless you have to link against nasty third-party static library which uses magic sections.
You may also want to take a look at this GCC bug (to see what chances of optimization may be missed and why).