3

I have this error:

Undefined symbols for architecture x86_64:
  "my::Queue<int>::Queue()", referenced from:
      _main in ccdwI88X.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

for this code 'main.cpp':

#include "Queue.hpp"

int main()
{
  my::Queue<int> myqueue;
  return 0;
}

'Queue.hpp':

#ifndef QUEUE_HH__
#define QUEUE_HH__

namespace my
{
  template <typename T>
  class Queue
  {
  public:
    Queue();     
  };
}

#endif

and 'Queue.cpp':

#include "Queue.hpp"

template <typename T>
my::Queue<T>::Queue() 
{
}
Mat
  • 202,337
  • 40
  • 393
  • 406
Bebeoix
  • 579
  • 2
  • 5
  • 17
  • 1
    Please read at least the first question in the "related" list on the right of this page. – Mat Apr 21 '12 at 22:54
  • I read it, but it's not the same problem that I have. Thanks anyway. – Bebeoix Apr 21 '12 at 23:03
  • He recommend to put the definitions of the class to a header file, but I did that (Queue.hpp) and it doesn't work anyway... – Bebeoix Apr 21 '12 at 23:05
  • 2
    The code you have in your post does not have the complete definition of your class template constructor in the header. It only has a declaration. – Mat Apr 21 '12 at 23:06
  • possible duplicate of [C++ Linking Errors: Undefined symbols using a templated class](http://stackoverflow.com/questions/312115/c-linking-errors-undefined-symbols-using-a-templated-class) – Troubadour Apr 21 '12 at 23:10

2 Answers2

5

The answer posted here: https://stackoverflow.com/a/312402/700926 is what I think you need.

If I edit your Queue.cpp file to this:

#include "Queue.hpp"

template <typename T>
my::Queue<T>::Queue() 
{

}

template class my::Queue<int>;

.. it compiles fine.

For the detailed explanation, please consult the URL i mentioned at first.

Community
  • 1
  • 1
Lasse Christiansen
  • 10,205
  • 7
  • 50
  • 79
  • Ok it works. But I was thinking that the principle of template is that it can take a type we don't know in advance... What if I want to create a lib with my queue class and I want use it in the future without knowing wich type T I will use ? – Bebeoix Apr 21 '12 at 23:10
  • As mentioned here: http://stackoverflow.com/a/312402/700926 : "If you don't know with which template parameters the template will be used, you have to put all the definitions into the header". That should be what you are looking for :) – Lasse Christiansen Apr 21 '12 at 23:13
  • Ok it works thanks. But it's like in the main.cpp I include the .hpp followed by the .cpp. Kind of weird. – Bebeoix Apr 21 '12 at 23:26
1

The easiest and safest thing to do when using templates is always to put the class functions definition (implementation) inside the .hpp file and not in a separate .cpp file.

All the details are also here: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12

nplatis
  • 432
  • 2
  • 8