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

And*_*dry 1 c++ linker g++

我有这个文件myfuncts.hpp::

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

我有实施myfuncts.cpp:

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

然后我有我的主要例程:

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

我编译它:

g++ main.cpp functs.cpp
Run Code Online (Sandbox Code Playgroud)

得到了这个:

/tmp/ccrdJEQt.o:在函数main': main.cpp:(.text+0x53): undefined reference toroot :: functs :: f1 :: f1()'collect2:ld返回1退出状态

我究竟做错了什么?

Som*_*ude 6

你可能想要阅读最令人烦恼的解析,因为当你这样做

root::functs::f1<double> f();
Run Code Online (Sandbox Code Playgroud)

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

您可能还想阅读这个旧问题,了解为什么您实际收到undefined reference错误.这是因为头文件没有完全定义类.对于模板化类,完整的实现也必须在头文件中.