0

I tried implementing simple Stack data structure, but when parsing code on header and source file, instead of doing everything in one main file, I stumbled upon unresonable error:

/usr/bin/ld: /tmp/ccdtxuy6.o: in function `main':
main.cpp:(.text+0x35): undefined reference to `Stack<int>::push(int)'
/usr/bin/ld: main.cpp:(.text+0x66): undefined reference to `Stack<int>::push(int)'
collect2: error: ld returned 1 exit status
make: *** [Makefile:4: build] Error 1

src/main.cpp

#include <iostream>

#include "../headers/stack.hpp"

int main() {
  Stack<int> stack1;
  stack1.push(5);
  std::cout << stack1.lastElement << "\n";
  stack1.push(6);
  std::cout << stack1.lastElement << "\n";
  return EXIT_SUCCESS;
}

headers/stack.hpp

#include <vector>

template <typename T> class Stack {
private:
  std::vector<T> mem;

public:
  T lastElement;
  // void pop(T element);
  void push(T element);
};

src/stack.cpp

#include "../headers/stack.hpp"

template <typename T> void Stack<T>::push(T element) {
  mem.push_back(element);
  lastElement = element;
}

my command for compilling and linking: g++ src/*.cpp -o hello

btw I use Ubuntu 20.04

Mat
  • 195,986
  • 40
  • 382
  • 396
  • You forgot to explicitly istantiate the template in the .cpp file. A solution may be to add this line at the end of the cpp file: `template class Stack `. In this way you are allowing to construct objects of the Stack class using the int as template parameter. The same holds in the case you want to make objects with other types. – Gianluca Bianco Feb 07 '22 at 14:11

0 Answers0