体系结构x86_64的未定义符号,链接器命令失败,退出代码为 1

Undefined symbols for architecture x86_64, linker command failed with exit code 1

本文关键字:失败 命令 退出 代码 链接 未定义 体系结构 符号 x86      更新时间:2023-10-16

我有一个"建筑x86_64的未定义符号",似乎无法理解原因。这是头文件:

#include <string>
#include <iostream>
#include <iomanip>
#include "assert.h"
using namespace std;
template <class Etype>
class AvlNode {
public:
    Etype element;
    AvlNode *parent;
    AvlNode *left;
    AvlNode *right;
    int height;
    AvlNode(Etype e,AvlNode *lt, AvlNode *rt, AvlNode *p,int h=0)
    : element(e), left(lt), right(rt), parent(p), height(h) {}
};
template <class Etype>
class AvlTree {
public:
    AvlTree() {root=NULL;}
    ~AvlTree() {makeEmpty();}
    void makeEmpty() {makeEmpty(root);}
    bool remove(Etype x) {return remove(root,x);}
    void insert(Etype x) {return insert(x,root,NULL);}
    bool tooHeavyLeft(AvlNode<Etype> * t);
    bool tooHeavyRight(AvlNode<Etype> * t);
    bool heavyRight(AvlNode<Etype> * t);
    bool heavyLeft(AvlNode<Etype> * t);
protected:
    AvlNode<Etype> *root;
    void makeEmpty(AvlNode<Etype> *& t);
    int height(AvlNode<Etype> *t);
    bool remove(AvlNode<Etype> *& t,Etype word);
    void insert(Etype x,AvlNode<Etype> *& t,AvlNode<Etype> *prev);
    void rotateWithLeftChild(AvlNode<Etype> *& t);
    void rorateWithRightChild(AvlNode<Etype> *& t);
    void doubleWithLeftChild(AvlNode<Etype> *& t);
    void doubleWithRightChild(AvlNode<Etype> *& t);
};

这是源文件:

#include "AvlTree.h"
template <class Etype>
void AvlTree<Etype>::makeEmpty(AvlNode<Etype> *& t) {
    if(t!=NULL) {
        makeEmpty(t->left);
        makeEmpty(t->right);
        delete t;
    }
    t=NULL;
}
template <class Etype>
void AvlTree<Etype>::rotateWithLeftChild(AvlNode<Etype> *&t) {
    assert(t!=NULL && t->left !=NULL);
    AvlNode<Etype> *temp = t->left;
    t->left = temp->right;
    temp->right = t;
    t->height = max( height( t->left ), height( t->right ) ) + 1;
    temp->height = max( height( temp->left ), temp->height ) + 1;
    t = temp;
}
template <class Etype>
int AvlTree<Etype>::height(AvlNode<Etype> *t) {
    return t==NULL ? -1 : t->height;
}

这是我得到的错误:

Undefined symbols for architecture x86_64:
  "AvlTree<int>::makeEmpty(AvlNode<int>*&)", referenced from:
      AvlTree<int>::makeEmpty() in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

你能找出问题所在吗?

谢谢

编辑:我只是将源文件的内容复制到头文件并编译了项目。这很好,但是,如果有人向我解释该错误的原因,我将不胜感激,因为我不知道。

错误的原因是应始终将所有模板代码放在头文件中。将您在 AvlTree 中的所有代码.cpp移动到 AvlTree.h(并使函数内联)。删除 AvlTree.cpp。链接器不能链接模板代码,它必须位于头文件中,以便编译器可以看到定义。有关解释,请参阅此处。

相关文章: