问题
I am just starting out with C++, and ran into this problem. I have a class Fifo 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 test my class like this (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)'
Looks like I have the relevant methods defined, but I am not able to figure out why I get this error. I spent time googling for it, and the option was to take a running class and modify it. But then, I want to know what is wrong with what I already have. Would appreciate any help!
回答1:
If you put template definition in cpp file, the definitions will not be available outside that cpp file.
When you include Fifo.h
from Fifotest.cpp
, the compiler sees the declaration of your template class, but it does not see the implementation of the methods. Once you move them to the Fifo.h
header, everything should compile.
回答2:
2 points:
The constructor is declared erroneously.
Fifo<T>(int len); //wrong Fifo(int len); //right
Templates should be defined in the same translation unit in which they are used, so having separate .h and .cpp files usually doesn't work for templates(see, for example, this question). Please move the contents of your cpp file to the header file and you should be fine.
回答3:
You should provide the definitions in the header file. export
keyword exists in the standard but usual compilers haven't implemented it.
来源:https://stackoverflow.com/questions/8635981/c-undefined-constructor