c++ - 编译虚拟 C++ 程序时链接不成功

标签 c++ linker g++

我有这个文件:myfuncts.hpp:

#ifndef FUNCTS_
#define FUNCTS_
namespace root {
namespace functs {
template <typename T>
class f1 {
public:
  T r;
  f1();
};
}
}
#endif

我有实现:myfuncts.cpp:

#include "myfuncts.hpp"
template <typename T>
root::functs::f1<T>::f1() { /* do somethng */ }

然后我有我的主要例程:

#include "impulses.hpp"
int main(int argc, char** argv);
int main(it argc, char** argv) {
  root::functs::f1<double> f();
}

我编译它:

g++ main.cpp functs.cpp

得到这个:

/tmp/ccrdJEQt.o: In function main': main.cpp:(.text+0x53): undefined reference toroot::functs::f1::f1()' collect2: ld returned 1 exit status

我做错了什么?

最佳答案

您可能想阅读有关 the most vexing parse 的内容, 因为当你这样做的时候

root::functs::f1<double> f();

你声明f成为一个返回 root::functs::f1<double> 的函数对象。

您可能还想阅读 this old question ,至于为什么你实际上得到了 undefined reference错误。这是因为头文件没有完整定义类。对于模板化类,完整的实现也必须在头文件中。

关于c++ - 编译虚拟 C++ 程序时链接不成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18586484/

相关文章:

c - 如何解决链接器库顺序问题?

c++ - 构建内部依赖第三方库的c++静态库

c++ - 从 std::vector 继承时 g++ 7 中的 undefined reference

c++ - 定义 NDEBUG 时删除断言是否在内联函数之前发生?

linux - 定位和编辑加载程序的动态符号表?

c++ - 继承接口(interface)实现

c++ - Visual Studio "object file does not define any previously undefined symbols"

c++ - 对未对齐的内存访问发出警告?

c++ - 如何从 C++ 中的资源文件加载游标组?

c++ - 在 C++11 STL 之前模拟大括号列表初始化