I was starting to code a library, and decided to do a test, but I'm getting the error in the question title (Mac OSX, gcc-4.7.1):
tlib.cpp:
template <typename T>
T dobra(const T& valor){
return valor*2;
}
tlib.h:
template <typename T>
T dobra(const T& valor);
test2.cpp:
#include "tlib.h"
#include <iostream>
using namespace std;
int main (int argc, char const *argv[])
{
double b = dobra<double>(10);
cout << b << endl;
return 0;
}
Compiling:
no25-89:CPROP canesin$ g++ -dynamiclib -Wall -std=c++11 tlib.cpp -o libdobra.so
no25-89:CPROP canesin$ g++ test2.cpp -Wall -std=c++11 -o test2 -L. -ldobra
Undefined symbols for architecture x86_64:
"double dobra<double>(double const&)", referenced from:
_main in cctLJGqf.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
no25-89:CPROP canesin$
A fact of life in C++ is that you must include a complete implementation of a template in every compilation unit it's used in, or restrict yourself to specific instantitions.
In practice, this means that you either:
Restrict yourself to only ever using (say) dobra<double>
, and put an explicit instantiation into tlib.cpp:
template double dobra<double>(const double& valor);