简体   繁体   中英

g++ linker error: undefined reference

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 .cpp file.

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM