Undefined reference to

Mar 29, 2017 at 6:08am
Hello, I'm trying to find out why I get this error. The test code is as follow:

main.cpp:
---------
#include <iostream>
#include <cassert>
#include "stack.h"

int main()
{
Stack<int> iStack;
Stack<std::string> s;

iStack.push(1);
iStack.push(2);
s.push("value1");
s.push("value2");

std::cout << "size: " << s.size() << std::endl;
std::cout << "top element: " << s.top() << std::endl;
}

stack.h:
--------
#include <cstddef>
#include <vector>
#include <string>
#include <iostream>

template <class T> class Stack
{
public:
Stack();
void push(T x);
T pop();
T &top();
size_t size() const;
bool empty() const;

private:
std::vector<T> data;
};

stack.cpp:
----------
#include "stack.h"

template <class T> Stack<T>::Stack()
{
}

template <class T> void Stack<T>::push(T x)
{
data.push_back(x);
}

template <class T> T Stack<T>::pop()
{
T val;

if (data.size() > 0) {
val = top();
data.erase(data.end() - 1);

return val;
};
}

template <class T> T& Stack<T>::top()
{
return data.at(data.size() - 1);
}

template <class T> size_t Stack<T>::size() const
{
return data.size();
}

template <class T> bool Stack<T>::empty() const
{
return data.size() == 0 ? true : false;
}



I use the following command:
g++ -std=c++11 main.cpp stack.cpp -o main

and then I get
main.cpp:(.text+0x11): undefined reference to `Stack<int>::Stack()'
main.cpp:(.text+0x1d): undefined reference to `Stack<std::string>::Stack()'
main.cpp:(.text+0x2e): undefined reference to `Stack<int>::push(int)'
main.cpp:(.text+0x3f): undefined reference to `Stack<int>::push(int)'
main.cpp:(.text+0x73): undefined reference to `Stack<std::string>::push(std::string)'
main.cpp:(.text+0xbf): undefined reference to `Stack<std::string>::push(std::string)'
main.cpp:(.text+0xe3): undefined reference to `Stack<std::string>::size() const'
main.cpp:(.text+0x119): undefined reference to `Stack<std::string>::top()'
collect2: error: ld returned 1 exit status


But if I change the line '#include "stack.h"' in main.cpp to '#include "stack.cpp"', it works OK.

Can someone please tell my why? And what is wrong in?
Mar 29, 2017 at 6:18am
All of the template code has to go in the header file.
Topic archived. No new replies allowed.