The easiest way is just to move all template code into the header file (as described in other answers)
BUT this is not the only solution.
Template are not actual functions.
A template becomes a function when there is an instanciation of the function. This can be done implicitly or explicitly. Any time the function is used there is an implicit instanciation. But you can also explicitly instanciate the template function.
So you should be able to link against any instanciated version of the template function in your share lib.
Header file so we obey the one definition rule.
// tt.h
template<typename T>
int doStuff(Tconst &t);
Source file:
// tt.cpp
#include "tt.h"
template<typename T>
int doStuff(Tconst &t)
{
return 4;
}
void plop()
{
int x = 6;
// implicit instanciation of doStuff<int>(int const&);
doStuff(x);
}
// explicit instanciation of template
template int doStuff<float>(float const&);
If I compiled the above into a shared lib.
Then there would be two doStuff() methods that are available.
- doStuff<int>(int const&) // Implicit instanciation
- doStuff<float>(float const&) // explit instanciation
g++ -shared -o tt.so tt.cpp
Now if we have a seprate file that we link against the shared lib:
// main.cpp
#include "tt.h"
int main()
{
doStuff(5); // doStuff<int>()
doStuff(6.0f); // doStuff<float>()
}
g++ main.cpp t.so
Compiles fine even though main can not see any of the template code.