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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With