开发者

C++ (gcc): undefined reference to `Stack<int>::Stack(int)' [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why can templates only be implemented in the header file?

I've struggled with this for a while, and I've taken a look to several questions here, but being new to C++ I haven't been able to u开发者_如何学运维nderstand where I am wrong.

Here is the code, I took it from this page and tried to make it work, but so far I haven't been lucky:

stack.h

#ifndef STACK_H
#define STACK_H
template <class T>
class Stack {
  public:
    Stack(int n);
    ~Stack() { delete[] s; };
  private:
    T* s;
    int _top;
    int _size;
};
#endif // STACK_H

stack.cpp

#include "stack.h"
template <class T>
Stack<T>::Stack(int n) {
  _size = n;
  _top = -1;
  s = new T[_size];
}

main.cpp

#include <iostream>
#include "stack.h"
using namespace std;
int main() {
  Stack<int> s(10); // undefined reference to `Stack<int>::Stack(int)'
  return 0;
}

When I compile (gcc 4.5.2) I get one error: undefined reference to Stack<int>::Stack(int). I've tried several things but without any real knowledge to support what I do. I will be really thankful if somebody can explain me what's going on.


You can only have a template class definition in a cpp file if it's a specialized definition - i.e. you know what T is.

Other than that, and your case belongs here, all definitions of your template class have to go in the header file. The compiler has to know about these each time a new instance is declared or defined because the type, and thus the behavior, changes. Definitions in a cpp file would mean a different translation unit, so the compiler couldn't possibly know about the behavior for every single T you try to apply to your template.


There is nothing to compile in "stack.cpp". Templates are only compiled when they are instantiated. Hence the linker cannot find this function which was never compiled.

You can't really separate declarations and implementations in header and source files with templates.

What you can do is copy-n-paste "stack.cpp" to the end of "stack.h". Alternatively include "stack.cpp" at the end of "stack.h", not the other way round, which achieves the same effect. In the latter case it might be wise to change the extension of the "cpp" file (see Including .cpp at end of template header file)


The compiler has to have all of the pertinent information when creating template classes and consequently templates are generally fully implemented in their header files.

There are several ways you could accomplish this, inline functions, defining the template functions in the header file, including your implementation in a separate file (at the end of your header file, with #include), etc.

Here's a similar question with more details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜