c++中对链接函数的未定义引用

C++ undefined reference to a linked function

本文关键字:未定义 引用 函数 链接 c++      更新时间:2023-10-16

我有一个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 &)构造函数导致的。例如,为什么模板只能在头文件中实现?

你有几个选择:

  1. 将实现放在node.h (node.cpp被删除,因为它不需要)
  2. 将实现放在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