Constructor C ++ undefined

I am just starting out with C ++ and have come across this problem. I have a Fifo class defined in Fifo.h:

/* Fifo.h */ #ifndef FIFO_H_ #define FIFO_H_ #include <atomic> #include <stdlib.h> #include <stdio.h> #include <string.h> template <class T> class Fifo { public: Fifo<T>(int len); ~Fifo<T>(); int AddTokens(T* buffer, int len); int RetrieveTokens(T* buffer, int len); private: //int len; }; #endif /* FIFO_H_ */ 

And the definitions in Fifo.cpp:

 /* Fifo.cpp*/ #include "Fifo.h" template <class T> Fifo<T>::Fifo(int len) { //_fifoptr = new FifoImpl_class((T)len); printf ("From the constructor\n"); //thisbuffer = malloc(sizeof(T)*len); } template <class T> Fifo<T>::~Fifo() { } template <class T> int Fifo<T>::AddTokens(T* buffer, int len) { printf("Added tokens\n"); return(1); } template <class T> int Fifo<T>::RetrieveTokens(T* buffer, int len) { printf("Removed tokens\n"); return(2); } 

And I am testing my class as follows (Fifotest.cpp):

 #include "Fifo.h" int main(int argc, char *argv[]) { Fifo<int> MyFifo(20); } 

Building it with gcc-4.5 gives me this error: undefined reference to Fifo<int>::~Fifo()' undefined reference to Fifo :: Fifo (int)'

It seems like I have the appropriate methods, but I cannot understand why I am getting this error. I spent time searching the Internet, and you had to run the class and change it. But then I want to know what is wrong with what I already have. Would thank for any help!

+1
source share
3 answers

If you put the template definition in the cpp file, the definitions will not be accessible outside this cpp file. When you include Fifo.h from Fifotest.cpp , the compiler sees the declaration of your template, but does not see the implementation of the methods. Once you move them to the Fifo.h header, everything should compile.

+2
source

2 points:

  • The constructor is declared erroneously.

     Fifo<T>(int len); //wrong Fifo(int len); //right 
  • Templates must be defined in the same translation unit in which they are used, therefore separate .h and .cpp files usually do not work for templates (see, for example, this question ). Move the contents of the cpp file to the header file and everything will be fine.

+2
source

You must specify the definitions in the header file. There is an export keyword in the standard, but regular compilers did not implement it.

0
source

Source: https://habr.com/ru/post/904488/


All Articles