I am writing a templatized Matrix class, and I include the declarations in Matrix.h, the implementation in Matrix.cpp. I have a test file testMatrix.cpp.
The beginning of the files look like this:
Matrix.h
#ifndef _MATRIX
#define _MATRIX
#include <string.h>
// Definition of Matrix class
#endif
Matrix.cpp
#include "Matrix.h"
#include <iostream>
using namespace std;
// ...Implementation
testMatrix.cpp
#include "Matrix.h"
#include <iostream>
using namespace std;
int main () {
cout << "Test constructors...\n";
cout << "Unitialized matrix (4, 4):\n";
Matrix<int> mi1 (4, 4);
mi1.print ();
cout << "4*4 matrix initialized to -1:\n";
Matrix<int> mi2 (4, 4, -1);
mi2.print();
cout << "Constructing mi3 as a copy of mi2:\n";
Matrix<int> mi3 (mi2);
mi3.print();
cout << "Assigning mi3 to mi1:\n";
mi1 = mi3;
mi1.print();
return 0;
}
The command line I used to compile:
g++ -Wall -lrt -g Matrix.cpp testMatrix.cpp -o testMatrix
The compiler keeps giving me the error:
/tmp/ccofoNiO.o: In function `main':
/afs/ir/users/t/i/tianxind/practice/Essential_C++/testMatrix.cpp:9: undefined reference to `Matrix<int>::print() const'
collect2: ld returned 1 exit status
Does anyone have an idea what went wrong here? Thanks so much!
The implementation of template functions/classes has to be visible to the compiler at the point of instantiation. This means that you should put the whole templates in the header file, not in a
.cppfile.