c++中对链接函数的未定义引用
C++ undefined reference to a linked function
我有一个c++项目的链接问题,我不知道是什么错了。代码的玩笑。
clitest.cpp
#include <iostream>
#include "node.h"
using namespace std;
int main(int argc, char** argv)
{
node<int> *ndNew = new node<int>(7);
return 0;
}
node.h
#ifndef NODE_H
#define NODE_H
#include <vector>
template <typename T>
class node
{
private:
node<T>* ndFather;
std::vector<node<T>* > vecSons;
public:
T* Data;
node(const T &Data);
};
#endif
node.cpp
#include "node.h"
using namespace std;
template <typename T>
node<T>::node(const T &Data)
{
this->Data = &Data;
this->ndFather = 0;
this->vecSons = (new vector<T>());
};
使用的编译器命令是
g++ -Wall -g clitest.cpp node.cpp -o clitest
错误日志是这样的
clitest.cpp: In function ‘int main(int, char**)’:
clitest.cpp:8:16: warning: unused variable ‘ndNew’ [-Wunused-variable]
node<int> *ndNew = new node<int>(7);
^
/tmp/cc258ryG.o: In function `main':
clitest.cpp:8: undefined reference to `node<int>::node(int const&)'
collect2: error: ld returned 1 exit status
make: *** [blist] Error 1
我花了相当多的时间来改变代码,试图找出问题,我要么错过了一些基本的东西,要么是我不知道c++链接的东西。
当使用模板时,编译器需要知道如何在类实例化时为类生成代码。未定义的引用错误是由于编译器没有生成node<int>::node(int const &)
构造函数导致的。例如,为什么模板只能在头文件中实现?
你有几个选择:
- 将实现放在node.h (node.cpp被删除,因为它不需要)
- 将实现放在node.h底部#include的文件中(通常该文件称为node.tpp)
我建议把实现放在node.h和删除node.cpp。请注意,示例中的代码在c++中是无效的:成员变量vecSons不是指针,因此vecSons = new vector<T>()
行将给出编译器错误。下面的代码可以作为完整实现的起点:
#ifndef NODE_H
#define NODE_H
#include <vector>
template <typename T>
class node
{
private:
node<T>* ndFather;
std::vector<node<T>* > vecSons;
public:
const T* Data;
node(const T &d) :
ndFather(0),
vecSons(),
Data(&d)
{
}
};
#endif
在。cpp文件之前使用-I.
,以便编译器知道查找。h文件。
g++ -Wall -I. clitest.cpp node.cpp -o clitest
或者只是-I
:
g++ -Wall -I clitest.cpp node.cpp -o clitest
相关文章:
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 对 Scalar ::Scalar() 的未定义引用
- 对复制 CTOR 和 CTOR 的未定义引用
- 对显式实例化的模板函数的未定义引用
- TensorRT (C++ API) 对"createNvOnnxParser_INTERNAL"的未定义引用
- 2个模板化类的非模板友元函数未定义引用错误
- 编译 libfluid 样本控制器时对"event_base_del_virtual"的未定义引用
- 获取对function_name的未定义引用
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- 对结构方法的未定义引用
- 使用内联函数 c++ 的未定义引用
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 对 DLOPEN 的未定义引用
- QT C++中对全局变量的未定义引用
- 快速数学导致对"__pow_finite"的未定义引用
- 对 boost::system::d etail::system_category_instance 的未定义引用,从
- OpenCV 3.4.3 中对 'cv::String::d eallocate()' 错误的未定义引用