Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem understanding templates in c++

Template code is not compiled until the template function is used. But where does it save the compiled code, is it saved in the object file from which used the template function in the first place?

For example, main.cpp is calling a template function from the file test.h, the compiler generates an object file main.o, Is the template function inside the main.o file? because template code is not inlined, is it?

like image 450
hidayat Avatar asked Mar 30 '10 13:03

hidayat


2 Answers

It's totally compiler implementation dependant. Most compilers will generate code around, inline or in cpp-like files and then compile with that. Sometimes, with optimization setup, some compilers will even reuse the same code instead of recreate it for each cpp.

So you have to see your compiler's doc for more details.

like image 124
Klaim Avatar answered Oct 12 '22 12:10

Klaim


Yes, the template function code is emitted in the main.o file. Some of it may be inlined, as any other code may be inlined, but in general, code for templates is emitted in any file in which the template is instantiated. Think of it as first instantiating the template code to produce normal non-template functions, and then compiling those functions with whatever inlining and optimization the compiler applies to any other function.

When the same template instantiation (e.g. std::vector<int>) occurs in multiple compilation units (.cpp files), there is a bit of difficulty, because the code is instantiated in each of them. There are various ways of handling this, sometimes involving a cleanup step in the linking phase where duplicate template instantiations are resolved into a single one; your compiler manual can provide more information on exactly how it handles that situation.

like image 22
Michael Ekstrand Avatar answered Oct 12 '22 11:10

Michael Ekstrand