15796

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

  • Assignment Operator for Doubly Linked List in C++
  • Move and Forward cases use
  • Mysql: How to insert into table using select where clause
  • Doubly linked list and how to move the iterator to the next node
  • Google Script - Sidebar button keeps opening a new tab
  • Link terms on page to Wikipedia articles in pure JavaScript
  • How to connect css to html in Google Apps Scripts
  • Flot returns incorrect x value (mm/dd/yy - date) after zoom for stack bar chart
  • C++ String tokenisation from 3D .obj files
  • 'Enemy' was not declared in this scope?
  • How to add System.Windows dll to Visual Studio 2010 express?
  • C++ Coin flip program error
  • string.IsNullOrEmpty() Doesn't Seem to Work on a String within a Class within a Class
  • runtime-check whether an instance (Base*) override a parent function (Base::f())
  • PayPal API Listener Website Payments Standard URI
  • redirect_to root_url and return unless @user.activated
  • Building Qt project for C++11 standard
  • C++ friend class std::vector
  • WPF Template Binding in ToggleButton UserControl
  • Error in installing package: fatal error: stdlib.h: no such file or directory
  • Getting error 'Cannot read property 'document' of undefined' while importing exp
  • How load cv2.KeyPoint and Descriptors correctly on OpenCV 3 with Python 3?
  • Thread 1: EXC_BAD_ACCESS (code =1 address = 0x0)
  • Django invalid literal for int() with base 10
  • xtable package: Skipping some rows in the output
  • How to determine if there are bytes available to be read from boost:asio:serial_port
  • Meteor helpers not available in Angular template
  • C++ Partial template specialization - design simplification
  • Accessing IRQ description array within a module and displaying action names
  • output of program is not same as passed argument
  • Javascript Callbacks with Object constructor
  • Where to put my custom functions in Wordpress?
  • Why is the timeout on a windows udp receive socket always 500ms longer than set by SO_RCVTIMEO?
  • Akka Routing: Reply's send to router ends up as dead letters
  • Buffer size for converting unsigned long to string
  • Hits per day in Google Big Query
  • How to get Windows thread pool to call class member function?
  • unknown Exception android
  • Checking variable from a different class in C#
  • Observable and ngFor in Angular 2