0

First: No, I am not asking about template specializations.

Assume the following example: I have a header file with a generic method:

template <typename T>
T foo(T bar) {
    return bar;
}

In a second file, called file1.cpp I use that method as foo<int>(42);. Now as far as my understanding goes the compiler will generate the object code for the template method in the generated file1.o object file.

Now if I have 10000 files which all use that method with the int template parameter, the compiler will generate the very same code 10000 times, as the object code generation is independent of all other objects (at least I think thats the case).

The question I have is: Once the linker combines all 10000 objects files into my binary, does he copy in the same code 10000 times, or can he detect this and only include the method once (per template type)?

Felix
  • 6,885
  • 1
  • 29
  • 54
  • 3
    It depends. Practically, it depends on quality of implementation of the compiler. Some implementations (e.g. compiler and linker, in combination) are capable of rolling repeated instantiations of templates into one, but NOT configured to do that by default, so you need to read documentation to find specific configuration (or command-line) options. C++11 (and later) implementations support extern templates (which, roughly, can be used to force the compiler to not instantiate a template if you know it is instantiated in another compilation unit). – Peter Apr 26 '18 at 10:32
  • In this particular example it might be better (code smaller *and* faster) to have the function inlined on each use rather than having 10000 function calls. – Bo Persson Apr 26 '18 at 10:36
  • 1
    Unrelated to template, also apply to regular inline functions. – Jarod42 Apr 26 '18 at 10:37
  • 1
    It would probably be insanity if the linker didn't merge them into one, considering these functions must have the same address – Passer By Apr 26 '18 at 10:39
  • @PasserBy - multiple instantations of a templated function (instantiated in different compilation units) do not necessarily all have the same address - that sort of thing is a quality of implementation concern. In older implementations, in particular, the default was to NOT fold replicated templated instantiations into one. It was only later that compiler-implementation techniques were developed that allow folding replicated instantiations into one. – Peter Apr 26 '18 at 10:54
  • So to summarize: It's not a simple yes/no reply, as it depends on compiler and code/optimizations etc. I guess we just have to trust the compiler-guys do their job and set compiler flags to minimize size if thats the requirement – Felix Apr 26 '18 at 11:03
  • @Peter Oops, I thought not declared before definition = implicit inline – Passer By Apr 26 '18 at 11:24

0 Answers0