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

<strong>Possible Duplicate:</strong> 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 understand 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:

<strong>stack.h</strong>

#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

<strong>stack.cpp</strong>

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

<strong>main.cpp</strong>

#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.

Answer1:

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.

Answer2:

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)

Answer3:

The compiler has to have all of the pertinent information when creating template classes and consequently templates are <i>generally</i> 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.

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:C++ (gcc): undefined reference to `Stack::Stack(int)' [duplicate]