I’m trying to create a templated C++ library. The header file of the library is as follows:
// header.h
#include <iostream>
template<typename T>
class MyClass
{
private:
T value;
public:
MyClass(): value(0) {};
void set(T v);
void print();
};
The implementation of the library source code is this:
// lib.cc
#include <header.h>
template<typename T>
void MyClass<T>::set(T v)
{
this->value = v;
}
template<typename T>
void MyClass<T>::print()
{
std::cout << this->value << std::endl;
}
And the code which uses this library is this:
// test.cc
#include <header.h>
int main()
{
MyClass<int> obj;
obj.set(10);
obj.print();
return 0;
}
I’m compiling my code using g++
via g++ -I. lib.cc test.cc
. Moreover, all the three files are in the same directory. However, when I try to compile my code, I get the following linker errors:
/usr/bin/ld: /tmp/ccbvMPJe.o: in function `main':
test.cc:(.text+0x34): undefined reference to `MyClass<int>::set(int)'
/usr/bin/ld: test.cc:(.text+0x40): undefined reference to `MyClass<int>::print()'
collect2: error: ld returned 1 exit status
Why can’t the linker find the implementations of set
and print
. It should be able to find the implementation of these two functions in the lib.cc
file. What am I doing wrong?