2

I've been programming with C++ for quite a while and I enjoy using templates a lot. What I've been wondering recently due to my foray into embedded programming is how one should expect the linker to behave with respect to code duplication in template instances where the template parameter is different.

For multiple instances of the same template with same parameters this is well known to be optimized away during link time (see also: How does C++ link template instances)

However in my case I'm interested if the linker will recognize any duplicated code between two templates that were instantiated with different parameters. As they are different types I would assume that they would not automatically be collapsed. However since they might have some functions that do not depend on the template parameters and would thus be identical between the two classes one might assume that a linker could optimize those away and thus save space.

What would be the expected behaviour in this case?

Blackclaws
  • 436
  • 5
  • 20
  • Have you tried godbolt? – lorro Jul 29 '16 at 16:01
  • Yes see for example: https://godbolt.org/g/jbx2ms however this is only the compiler as far as I can tell and not the linker. There is identical code there at the bottom which the linker could optimize away I guess but I don't know if it usually would. – Blackclaws Jul 29 '16 at 16:14

1 Answers1

6

gold linker does exactly that.

Safe ICF: Pointer Safe and Unwinding Aware Identical Code Folding in Gold:

We have found that large C++ applications and shared libraries tend to have many functions whose code is identical with another function. As much as 10% of the code could theoretically be eliminated by merging such identical functions into a single copy. This optimization, Identical Code Folding (ICF), has been implemented in the gold linker. At link time, ICF detects functions with identical object code and merges them into a single copy.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • Looks good. It also appears gcc has an option that does that during linking https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html, however they state that some things are only cought by gold while some things are only cought by gcc – Blackclaws Jul 29 '16 at 16:38
  • @Blackclaws I have been using gold linker since 2011 and I like that it links a few times faster than the old `ld` and also has a nice feature `-detect-odr-violations`. – Maxim Egorushkin Jul 29 '16 at 22:41