[Software, c++] Separate compilation of templates: Template separation and export
A recent cause of inexplicable flummoxing and gnashing of teeth was a piece of code like the one below. Look at 1.cpp - pretty straightforward. An instance ‘i1’ is instantiated. A function ‘myfunc’ is called, which returns a pointer to an object. ‘SSS1’ and ‘dummy’ are declared in 11.h. Now the templatized function is declared in ‘13.h’ and defined in ‘13.cpp’. Pretty simple, huh? I agree, there is no problem when compiling this piece of code like this:
g++ 1.cpp 13.cpp -I.
But now consider what would happen if I compile them as:
g++ -c 1.cpp -I. g++ -c 13.cpp -I. g++ 1.o 13.o
In this case, the linker, cribs about not finding dummy* myfunc(SSS1
//dummy* myfunc(SSS1
& a); //template <> dummy* myfunc(SSS1 & a); template dummy* myfunc(SSS1 & a);
Notice the addition of the “template” keyword before the definition (the commented line is what did’nt work). Somehow it is important to provide that keyword. Even “template <> ” doesn’t work. 1.cpp
#include
main(){
SSS1
11.h
template
class dummy{
};
13.h
template
13.cpp
#include “11.h”
#include “12.h”
#include “13.h”
template