首页 > 解决方案 > 如果我使用单独的 .cpp 和 .hpp 文件,则使用内部函数的未定义引用

问题描述

资源:

测试.hpp

template<class R>
class Base
{
public:
    virtual R copy() = 0;
    virtual ~Base() = default;
    R test();
    R testCallback();
};

class Derived: public Base<Derived>
{
public:
    Derived()
    {
    }

    Derived copy();
};

测试.cpp

#include "test.hpp"

template<class R>
R Base<R>::testCallback()
{
    return R();
}

template<class R>
R Base<R>::test()
{
    return testCallback();
}

Derived Derived::copy()
{
    return Derived();
}

应用程序.cpp

#include "test.hpp"

int main(int argc, char const *argv[])
{
    Derived a = Derived();
    Derived b = a.test();
    return 0;
}

对于应用程序编译,我使用:

g++ 源/test.cpp 源/app.cpp -o 测试

之后我得到了错误:

对 «Base::test()» 的未定义引用

如果我将所有代码从中剪切test.cpp并放入app.cpp. 如果我R test()在头文件中标记为虚函数,它也可以工作。

为什么链接器看不到test()实现函数?我做错了什么?

标签: c++headerlinker-errors

解决方案


推荐阅读