【发布时间】:2016-07-25 06:04:36
【问题描述】:
我正在尝试测试 Micheal T. Goodrich 等人在“C++ 中的数据结构和算法”中的单链表示例。我添加了一些作者省略的细节以使其可运行。
代码如下:
#ifndef S_LINKED_LIST
#define S_LINKED_LIST
template <typename E>
class SLinkedList;
template <typename E>
class SNode
{
private:
E elem;
SNode<E> * next;
friend class SLinkedList<E>;
};
template <typename E>
class SLinkedList
{
private:
SNode<E> * head;
public:
SLinkedList();
~SLinkedList();
bool empty() const;
const E& front() const;
void addFront(const E& e);
void removeFront();
};
#endif /*SLinkedList.h*/
实施:
#include "SLinkedList.h"
#include <iostream>
template <typename E>
SLinkedList<E>::SLinkedList():head(NULL){}
template <typename E>
SLinkedList<E>::~SLinkedList()
{while(!empty()) removeFront();}
template <typename E>
bool SLinkedList<E>::empty() const
{return head == NULL;}
template <typename E>
const E& SLinkedList<E>::front() const
{return head->elem;}
template <typename E>
void SLinkedList<E>::addFront(const E& e)
{
SNode<E> * newNode = new SNode<E>;
newNode->elem = e;
newNode->next = head;
head = newNode;
}
template <typename E>
void SLinkedList<E>::removeFront()
{
SNode<E> * old = head;
head = old->next;
delete old;
}/*SLinkedList.cpp*/
测试文件:
#include <iostream>
#include "SLinkedList.h"
int main()
{
SLinkedList<std::string> newlist;
newlist.addFront("MSP");
std::cout << newlist.front();
return 0;
}/*test_slinkedlist.cpp*/
运行g++ -c SLinkedList.cpp 和g++ -c test_slinkedlist.cpp 后
我得到目标文件SLinkedList.o 和test_slinkedlist.o 没有错误。
但是当我运行 g++ -o result test_slinkedlist.o SLinkedList.o 时,我得到了链接器错误:
Undefined symbols for architecture x86_64:
...
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
我花了一天时间调试这个链接器问题,但找不到。我怀疑这很明显。
操作系统:OS X
完整的错误信息:
Undefined symbols for architecture x86_64:
"SLinkedList<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::addFront(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from:
_main in test_slinkedlist.o
"SLinkedList<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::SLinkedList()", referenced from:
_main in test_slinkedlist.o
"SLinkedList<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::~SLinkedList()", referenced from:
_main in test_slinkedlist.o
"SLinkedList<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::front() const", referenced from:
_main in test_slinkedlist.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
【问题讨论】:
-
@Revolver_Ocelot 我可以看到你说它是重复的原因,但我认为它可能对像我这样从 C 切换到 C++ 并从 C 继承习惯并且不知道什么关键词的人有所帮助搜索以获取此问题和您的评论,以了解下一步该去哪里。感谢您的建议。
标签: c++ linked-list linker