0

Hi I'm having some problems with c++, when I try to compile my 3 files, main.cpp, My_Stack.cpp and My_Stack.hpp I get the "Undefined symbols for architecture x86_64" error, as if I hadn't included the header file and if I add "#include "My_Stack.cpp"" instead of "#include "My_Steak.hpp"" in main.cpp it works fine.


//main.cpp
#include <iostream>
#include "My_Stack.hpp"

int main(int argc, const char * argv[]) {
    My_Stack<int> s = My_Stack<int>();
    s.push(1);
    s.push(2);
    cout << s.pop() << endl;
    cout << s.pop() << endl;


}

//My_Stack.hpp
#ifndef My_Stack_hpp
#define My_Stack_hpp

#include <stdio.h>

#include <string>

using namespace std;

template<class T>
class My_Stack {

public:
    My_Stack();
    void push(T v);
    T pop();

private:
    class My_Stack_Node {
    public:
        T data;
        My_Stack_Node* next;
        My_Stack_Node(T n) {
            data = n;
            next = NULL;
        }
    };
    My_Stack_Node* head;

};


#endif /* My_Stack_hpp */

//My_Stack.cpp
#include "My_Stack.hpp"

#include <string>
#include <sstream>

using namespace std;

template<class T>
My_Stack<T>::My_Stack() {
    this->head = NULL;
}

template<class T>
void My_Stack<T>::push(T v) {
    if (this->head == NULL) {
        this->head = new My_Stack_Node(v);
    }
    else {
        My_Stack_Node* aux = new My_Stack_Node(v);
        aux->next = this->head;
        this->head = aux;
    }
}

template<class T>
T My_Stack<T>::pop() {
    My_Stack_Node* aux = this->head;
    this->head = this->head->next;
    return aux->data;
}
bfbonatto
  • 21
  • 3

1 Answers1

0

Template definitions must go inside corresponding header file i.e definitions in My_Stack.cpp must be put inside My_Stack.hpp.

Recommend you to go over the faq:
https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl

Pasting the relevant part from the faq:

A template is not a class or a function. A template is a “pattern” that the compiler uses to generate a family of classes or functions.

In order for the compiler to generate the code, it must see both the template definition (not just declaration) and the specific types/whatever used to “fill in” the template. For example, if you’re trying to use a Foo, the compiler must see both the Foo template and the fact that you’re trying to make a specific Foo.

Your compiler probably doesn’t remember the details of one .cpp file while it is compiling another .cpp file. It could, but most do not and if you are reading this FAQ, it almost definitely does not. BTW this is called the “separate compilation model.”

Arunmu
  • 6,837
  • 1
  • 24
  • 46