【问题标题】:Why am I getting this undefined symbols for architecture x86_64 error [duplicate]为什么我会收到架构 x86_64 错误的未定义符号 [重复]
【发布时间】:2015-01-13 05:23:05
【问题描述】:

我收到一个未定义符号的架构 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;
};

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。

【问题讨论】:

  • 您还应该修复 StackLinkedList.h 中的 include sentinel 语句,并将 #endif ... 行移动到头文件的末尾。否则,如果您多次包含头文件,编译器将尝试重新定义您的类,这可能会导致构建问题。

标签: c++ xcode linker-errors


【解决方案1】:

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

Why can templates only be implemented in the header file? 了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2017-02-15
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多