Reputation: 93
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!
Upvotes: 1
Views: 1861
Reputation: 1136
Yeah, the implementation has to be in the header file, otherwise the compiler doesn't know the specialized function (after resolving the template) is needed.
You can also put the implementation in a .inl file (or simmilar) and include it at the end of the .h file. That's how it's usually done, to keep decleration and implementation in seperate files (to keep things clear).
Upvotes: 0
Reputation: 33161
First, make sure you've defined the print function. Then you should know that when you declare a templated class, you need to provide the implementation whenever you use that class. In other words, move the implementation out of the .cpp file and into the .h file.
Upvotes: 1
Reputation: 229573
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 .cpp
file.
Upvotes: 2