c++ - 模板类和自由函数命名空间的实现问题

标签 c++ linker namespaces undefined-reference

我有一个这样定义的类(省略了琐碎的包含和预处理器包装器等,但它们在那里):

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

但是,当我这样编译和链接时:

g++ -c tester.cpp
g++ -c bitTransform.cpp
g++ -Wall -O2 tester.o bitTransform.o -o tester

我得到一个 undefined reference 错误,特别是

/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

为什么会出现此错误?在我看来,我的 namespace 解析没问题,我的链接也很好......

最佳答案

bitExpand 在全局命名空间中定义了一个自由函数,而不是在 matrixmanip 命名空间中。 using 指令不会将定义移动到正在使用的命名空间中。您应该直接将定义放在适当的命名空间中:

namespace matrixmanip
{
    Matrix<char> bitExpand(const Matrix<char> &mat)
    {
        mat.someFunc();
       //...
    }
}

关于c++ - 模板类和自由函数命名空间的实现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53578238/

相关文章:

objective-c - 在 PreferencePane 中使用框架

c++ - 静态链接库

c - 链接器如何解决动态可加载库中的重复符号?

python - 避免模​​ block 命名空间中的子模块和外部包

xml - 使用命名空间的 Xpath 测试

c++ - cucumber CPP 构建错误 : is_initialized() is not a member of unit test

c++ - boost::spirit 解析器返回空 vector

c++ - 在语言选择上选择合适的 .rc 文件

c++ - 警告 : returning reference to temporary

php - 如何在 php 中取消设置命名空间以访问全局类