为什么我会收到这个未定义的架构符号x86_64错误

Why am I getting this undefined symbols for architecture x86_64 error

本文关键字:符号 x86 错误 未定义 为什么      更新时间:2023-10-16

我收到一个未定义的架构符号x86_64错误,但我不确定为什么。我正在使用链表和模板制作堆栈数据类型。

StackLinkedList.h

#ifndef __StackLinkedList__StackLinkedList__
#define __StackLinkedList__StackLinkedList__
#include <iostream>
using namespace std;
#endif /* defined(__StackLinkedList__StackLinkedList__) */
template <class Item>
class StackLinkedList {
public:
    StackLinkedList();
    void push(Item p);
private:
    StackLinkedList<Item>* node;
    Item data;
};

堆栈链接列表.cpp

#include "StackLinkedList.h"
template <class Item>
StackLinkedList<Item>::StackLinkedList() {
    node = NULL;
}
template <class Item>
void StackLinkedList<Item>::push(Item p) {
    if(node == NULL) {
        StackLinkedList<Item>* nextNode;
        nextNode->data = p;
        node = nextNode;
    }else {
        node->push(p);
    }
}

主.cpp

#include "StackLinkedList.h"
int main() {
    StackLinkedList<int>* stack;
     stack->push(2);
}

错误详细信息:

Undefined symbols for architecture x86_64:
  "StackLinkedList<int>::push(int)", referenced from:
      _main 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)

我正在使用Xcode 6.1。

您必须在头文件中声明/定义模板函数,因为编译器必须在编译时使用有关实例化类型的信息。因此,将模板函数的定义放在.h文件中,而不是放在cpp中。

看为什么模板只能在头文件中实现?了解更多详情。