Alecs
Alecs

Reputation: 2316

Eclipse undefined reference

I'm using Eclipse and MinGW. I've got undefined reference to error to all that I write in h files, that I do include in cpp-file where main located. I create an empty project, and the same thing again (

main.cpp

#include <iostream>
#include "Stack.h"

using namespace std;

int main(){
    Stack<int> stack(10);
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}

stack.h

#ifndef STACK_H_
#define STACK_H_

template <class T>
class Stack{
private:
    struct StackEl;
    StackEl *top;
public:
    Stack();
    Stack(T el);
    ~Stack();
    void Push(const T& el);
    T Pop();
};

#endif /* STACK_H_ */

and stack.cpp inplements everything from stack.h If I include not h-file, but cpp - all works. Help please!

I've got following errors

D:/Workspacee/Stack2/Debug/../src/Stack2.cpp:16: undefined reference to `Stack<int>::Stack(int)'
D:/Workspacee/Stack2/Debug/../src/Stack2.cpp:18: undefined reference to `Stack<int>::~Stack()'
D:/Workspacee/Stack2/Debug/../src/Stack2.cpp:18: undefined reference to `Stack<int>::~Stack()'

Upvotes: 1

Views: 932

Answers (2)

Alecs
Alecs

Reputation: 2316

My bad, that is becouse templates! When you use template, all code, including realization of functions, must be in header-file, or you have to write prototypes for every type you are going to use you template-functions with. I've forgot about that working with templates is not the same as with usual function :(

Upvotes: 0

eriktous
eriktous

Reputation: 6649

This is a linker error. I'm no Eclipse expert, but you have to tell it somehow to add Stack.o to the linking command.
If you include Stack.cpp instead of Stack.h, the implementations from the cpp-file get included into main.cpp by the preprocessor before compilation, so the linking stage has no unresolved references to outside functions.

Upvotes: 1

Related Questions