Reading the following undefined reference to template function I solved my problem, however my template function is actually being called, within the library so it is being implementation I would have thought this should have defined its type in the shared objects, however I keep getting linker errors. Consider...
I have the following files (common.h, common.cpp, myclass.h and myclass.cpp) defined below:
common.h
namespace myn
{
template<class T> T map(T val1, T val2);
};
common.cpp
#include "common.h"
template<class T> T myn::map(T val1, T val2)
{
return val1+val2;
}
myclass.h
#include "common.h"
class myclass
{
private:
int val;
public:
myclass(int v1, int v2);
};
myclass.cpp
#include "myclass.h"
myclass::myclass(int v1, int v2)
{
this->val = myn::map<int>(v1, v2);
}
I compile the library using:
g++ -Wall -fPIC -c common.cpp -o common.o
g++ -Wall -fPIC -c myclass.cpp -o myclass.o
g++ -shared -Wl,-soname,libmylib.so -o libmylib.so common.o myclass.o
When given main.cpp
:
#include "common.h"
#include "myclass.h"
int main(int argc, char ** argv)
{
myclass * x = 0;
if (argc == 1)
x = new myclass(20, 40);
else
x = new myclass(2343, 435);
delete x;
return 0;
}
I compile using:
g++ -Wall -L. main.cpp -o main.out -lmylib
I get the following error:
./libmylib.so: undefined reference to `int myn::map<int>(int, int)'
collect2: error: ld returned 1 exit status
Shouldn't the <int>
version of the map
function be defined? I know that if i try doing something like myn::map<char>('a', 'b');
It should complain as it has not been defined, but surely in my case <int>
template is defined.