Undefined reference to member function defined in separate file

时间:2016-10-11 10:12:11

标签: c++ compilation compiler-errors linker g++

I know other questions like this have been posted, but in my case I'm doing everything in those questions' answers and still I get an undefined reference error. Here is main.cpp:

#include "mainHeader.hpp"

int main() {
    Matrix2D<int> matrix2(3,3);

    matrix2(2,2) = 99; // produces an error

    return 0;
}

Here is mainHeader.hpp:

#ifndef _MAINHEADER_HPP
#define _MAINHEADER_HPP

#include <iostream>
#include <vector>

template <class T>
class Matrix2D {
private:
    std::vector< std::vector<T> > matrix;
public:
    /* Constructors */
    Matrix2D(unsigned int numberOfRows = 1, unsigned int numberOfColumns = 1) : matrix( std::vector< std::vector<T> >(numberOfRows, std::vector<T>(numberOfColumns)) ) {}

    /* Operator overloads */
    T & operator () (unsigned int, unsigned int);
};

#endif // _MAINHEADER_HPP

Finally, here is matrixClass.cpp:

#include "mainHeader.hpp"

// Overload the () operator
template <class T>
T & Matrix2D<T>::operator () (unsigned int row, unsigned int column) {
    return matrix[row][column];
}

I compile with g++ -std=c++11 -Wall -g main.cpp matrixClass.cpp -o output (on Linux Mint 64-bit) but I get the error:

/tmp/ccoSx71n.o: In function `main':
/home/.../main.cpp:7: undefined reference to `Matrix2D<int>::oper
ator()(unsigned int, unsigned int)'                                                                              
collect2: error: ld returned 1 exit status

I don't understand what the problem is, please help. Thank you!

1 个答案:

答案 0 :(得分:-1)

由于您使用模板进行操作,因此需要在.h / .hpp类中定义该函数,该类与声明的位置相同。 见Why can templates only be implemented in the header file?