Hi,
I'm trying to create a simple stack class using C++ and templates.
Everything works well and good if I amke the class totally inline.
However, as soon as I try to seperate the class into a .h and a .cpp
file, gcc throws some strange linking errors.
Compiling like this:
gcc test.cpp stackList.cpp -lstdc++ -o test
produces these errors:
/tmp/ccCJLrbl.o(.tex t+0x84): In function `main':
: undefined reference to `Stack<int>::St ack[in-charge]()'
/tmp/ccCJLrbl.o(.tex t+0x101): In function `main':
: undefined reference to `Stack<int>::pu sh(int)'
/tmp/ccCJLrbl.o(.tex t+0x10c): In function `main':
: undefined reference to `Stack<int>::si ze() const'
/tmp/ccCJLrbl.o(.tex t+0x18b): In function `main':
: undefined reference to `Stack<int>::em pty() const'
/tmp/ccCJLrbl.o(.tex t+0x19c): In function `main':
: undefined reference to `Stack<int>::si ze() const'
/tmp/ccCJLrbl.o(.tex t+0x1aa): In function `main':
: undefined reference to `Stack<int>::po p()'
/tmp/ccCJLrbl.o(.tex t+0x20f): In function `main':
: undefined reference to `Stack<int>::~S tack [in-charge]()'
/tmp/ccCJLrbl.o(.tex t+0x229): In function `main':
: undefined reference to `Stack<int>::~S tack [in-charge]()'
collect2: ld returned 1 exit status
I'm tearing my hair out... why would it not work in seperate files? My
class definition is something like this:
template <class T>
class Stack
{
private:
StackNode<T> *stackHead;
/// The number of elements on the stack. It's easier to keep count
/// of them here than to count them every time we need them.
unsigned int stackSize;
protected:
public:
/// Default constructor: set the stackSize to be 0.
Stack(void);
/// Default destructor: clean up any memory allocated.
~Stack(void);
/// push: push an item onto the stack, and incrememt the size.
bool push(T item);
/// pop: return the topmost element from the stack, removing it
from the stack at the same time:
T pop(void);
/// size: returns how many items are on the stack:
unsigned int size(void) const;
/// empty: return true if the stack is empty:
bool empty(void) const;
/// full: return true if the stack is full: - for a linked list
implementation, this can be safely ignored:
bool full(void) const;
};
and the code for a single method for the above class looks like this:
template <class T> bool Stack<T>::push( T item)
{
if (full())
return false;
StackNode<T> *node = new StackNode<T> (item);
node->Head = stackHead;
stackHead = node;
stackSize++;
return true;
}
I've been following the C++ language tutorial, and a few books I own
at home. It looks like I'm doing everything properly... Can anyone
shed some light on this?
Thanks,