问题
I have a class defined like this (trivial includes and preprocessor wrappers, etc. are omitted, but they are there):
In Matrix.h
namespace matrixmanip {
template<typename T>
class Matrix {
public:
void someFunc() const;
//...
};
template<typename T>
void Matrix<T>::someFunc() const {
//...
}
} // namespace matrixmanip
In bitTransform.h
#include "Matrix.h"
namespace matrixmanip {
Matrix<char> bitExpand(const Matrix<char> &mat);
} // namespace matrixmanip
In bitTransform.cpp
#include "bitTransform.h"
using namespace matrixmanip;
Matrix<char> bitExpand(const Matrix<char> &mat) {
mat.someFunc();
//...
}
In tester.cpp
#include "Matrix.h"
#include "bitTransform.h"
matrixmanip::Matrix<char> A ... // construct a character matrix, details of which are unimportant here
matrixmanip::Matrix<char> B = matrixmanip::bitExpand(A);
However, when I compile and link like this:
g++ -c tester.cpp
g++ -c bitTransform.cpp
g++ -Wall -O2 tester.o bitTransform.o -o tester
I get an undefined reference error, specifically
/tmp/ccateMEK.o: In function `main':
tester.cpp:(.text+0xbf9): undefined reference to `matrixmanip::bitExpand(matrixmanip::Matrix<char> const&)'
collect2: error: ld returned 1 exit status
Why am I getting this error? It seems to me that my namespace resolution is okay and my linkage is fine...
回答1:
bitExpand
defines a free function in global namespace, not in matrixmanip
namespace. using
directive does not move definitions into the namespace being used. You should put definition in proper namespace directly:
namespace matrixmanip
{
Matrix<char> bitExpand(const Matrix<char> &mat)
{
mat.someFunc();
//...
}
}
来源:https://stackoverflow.com/questions/53578238/template-class-and-free-function-namespace-problems-with-implementation