I'm trying to test SinglyLinked List example in "Data Structure and Algorithm in c++" by Micheal T. Goodrich and etc. I added some details omitted by the author in order to make it runnable.
Here's the code:
#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*/
Implementation:
#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*/
test file:
#include <iostream>
#include "SLinkedList.h"
int main()
{
SLinkedList<std::string> newlist;
newlist.addFront("MSP");
std::cout << newlist.front();
return 0;
}/*test_slinkedlist.cpp*/
After running g++ -c SLinkedList.cpp
and g++ -c test_slinkedlist.cpp
I got object files SLinkedList.o
and test_slinkedlist.o
without error.
but when I run g++ -o result test_slinkedlist.o SLinkedList.o, I got linker errors:
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)
I spend a day debugging this linker issue but can't find. I suspect it's obvious.
Operating System: OS X
full error message:
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)