1

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?

Robin Hsu
  • 4,164
  • 3
  • 20
  • 37
  • Each implementation use its own approach, see [this for gcc](https://gcc.gnu.org/onlinedocs/gcc/Template-Instantiation.html) – Danh Nov 24 '16 at 04:37
  • Before you get a program it goes through the compilation stage and linker stage. I don't know for sure exactly when it gets removed, but it would have to be the worst IDE in the world to actually create a finished program with two copies of the same instantiated template. – Zebrafish Nov 24 '16 at 04:39

1 Answers1

3

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).

Community
  • 1
  • 1
BeeOnRope
  • 60,350
  • 16
  • 207
  • 386