Robin Hsu Robin Hsu - 15 days ago 5
C++ Question

C++ template function, same type, multiple instantiations: shares one same copy of code? EVEN in different cpp/object files

For example, consider the following code:

// f.h
template <typename T>
int f(T x) {
return x+1;
}


If we instantiate it in both
foo.cpp
and
bar.cpp
:

//foo.cpp instantiation:
int i = f(1);


and

//bar.cpp instantiation:
int j = f(2);


Will the final program uses only one copy of code? Is that so, when
bar.cpp
is hidden but only the object file
bar.o
is provided?

I think, since each cpp files are compiled independently, both
foo.o
and
bar.o
must contains
f(int)
. The linker should see same duplicate signature, and use only one copy. Am I right?

Answer

Yes, the linker will generally fold duplicate identical template instantiations away. Doing so is pretty much required to avoid an explosion in binary size when templates are involved, and to maintain some standard required invariants such as equivalence of function pointers. This behavior is sometimes called fold by name.

Beyond that, some linkers will even fold away all symbols that happen to be identical in content (i.e., compile the same code), even if they don't originate from the same definition. This is sometimes called fold by value, but unless done carefully may break the letter of the standard (i.e., because function pointers to different functions now compare equal).