Reputation: 3
I have written my program and it works when I keep everything in the header files, and then have my main. I am now splitting them up into implementation files, but Eclipse keeps giving me errors. It gives me error at every opening brace of the constructor and functions. It says on all of them "Redefinition of (name of constructor or method), Previously declared here." What am I doing wrong, because it works in the header file?
#include "KeyValuePair.h"
template<typename Key,typename Value>
KeyValuePair<Key,Value>::KeyValuePair()
{ // error here
}
template<typename Key,typename Value>
void KeyValuePair<Key,Value>::setPair(Key key, Value value)
{ // error here
pairKey = key;
pairValue = value;
}
template<typename Key,typename Value>
Key KeyValuePair<Key,Value>::getKey() const
{ // error here
return pairKey;
}
template<typename Key,typename Value>
Value KeyValuePair<Key,Value>::getValue() const
{ // error here
return pairValue;
}
Header File:
#ifndef _KEYVALUEPAIR_H_
#define _KEYVALUEPAIR_H_
template<typename Key,typename Value>
class KeyValuePair
{
private:
Key pairKey;
Value pairValue;
public:
KeyValuePair();
void setPair(Key key,Value value);
Key getKey() const;
Value getValue() const;
};
#include "KeyValuePair.cpp"
#endif
Upvotes: 0
Views: 263
Reputation: 104524
As it stands now, your KeyValuePair.h file has a #include KeyValuePair.cpp
at the bottom. KeyValuePair.cpp also #includes the header file as well. The header file has the usual "guard" (#ifndef _KEYVALUEPAIR_H_) to prevent being included multiples times, but your CPP files does not. So when you try to compile the CPP file, it pulls in the H file, which pulls in the CPP file again. Hence, the multiple definition error.
The simplest solution for you, but not necessarily the most correct, would be to remove the #include "KeyValuePair.h"
line from the top of the KeyValueHeader.cpp file.
I suspect you are trying to actually compile KeyValuePair.cpp within your Makefile, which you need not (and should not) do. You just need to have source files needing your template class to #include "KeyValuePair.h"
.
Standard practice for templates is to keep declaration and implementation in the same header file - which implicitly avoids these kinds of issues. It's not uncommon to see the implementations of template class methods inlined inside the template class declaration and all contained in a single header file. Ruins everything you learned about separation of interface from implementation, but is easier to work with.
Upvotes: 2