This question already has answers here:
“Undefined reference to” template class constructor [duplicate]
(3个答案)
6年前关闭。
我收到关于x86_64体系结构的 undefined symbol 错误,但是我不确定为什么。
我正在使用链接列表和模板创建堆栈数据类型。
StackLinkedList.h
StackLinkedList.cpp
main.cpp
错误详情:
我正在使用Xcode 6.1。
(3个答案)
6年前关闭。
我收到关于x86_64体系结构的 undefined symbol 错误,但是我不确定为什么。
我正在使用链接列表和模板创建堆栈数据类型。
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;
};
StackLinkedList.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);
}
}
main.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
中。
看到
Why can templates only be implemented in the header file?
更多细节。
关于c++ - 为什么我得到体系结构x86_64错误的 undefined symbol ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26953368/