【发布时间】:2020-06-15 22:25:32
【问题描述】:
在我正在开发的库中,我在头文件中有类似这个模板类的东西:
template <int something>
class Base {
public:
virtual ~Base(); // Implemented in c++ file
}
class Derived : public Base<100> {
public:
~Derived() override = default();
}
析构函数是这样实现的:
template <int something>
Base<something>::~Base() {
destroyBase();
}
此代码编译为静态库。
然后,我在示例中有此代码:
{
Derived x;
x.doSomething();
} // X gets destroyed
我编译可执行文件并链接静态库。这在 Ubuntu 上运行良好,但是当我在 mac 上尝试时,链接失败了
Undefined symbols for architecture x86_64:
"Base<100>::~Base()", referenced from:
_main in my_sample.cpp.o
在这两种情况下,我都使用 clang 并使用完全相同的 cmake 设置进行编译。定义了 cpp 文件中定义的所有其他符号。这是唯一未定义的符号。发生了什么?
【问题讨论】:
-
模板必须在头文件中实现(或者定义必须在所有使用它的编译单元中都可用)。
-
啊。我明白。为什么这只发生在mac上呢?为什么它可以在 ubuntu 上运行?
-
在你的问题中,你没有说 where 你正在定义析构函数。请创建minimal reproducible example 以帮助缩小范围
标签: c++ linker linker-errors static-linking