I am working on a school assignment, and I get this strange error (I am quite new to C++).
I should find the first value between 1500 and 1900. When I build it the first time, everything is ok, but when I build it the next time, I get this error:
error LNK2005: "bool __cdecl greaterThan1500SmallerThan1900(int)" (?greaterThan1500SmallerThan1900@@YA_NH@Z) already defined in Lab5.obj
If I then change the code slightly (change the type in the predicate function to double) it builds again one time.
template<typename T>
T MyStlClass<T>::myFindIf(list<T> &theList) {
list<T>::iterator it = find_if(theList.begin(), theList.end(), greaterThan1500SmallerThan1900);
return *it;
}
bool greaterThan1500SmallerThan1900(int value){
return (value >= 1500 && value <= 1900);
}
I have read on this site that it is because that I include the “.cpp” file, but on the other hand, I have also read, that I need to include the “.cpp” file, when I am using templates.
Throw away/downvote/identify for us the resource that told you to do that.
There is a good reason that it did so, but the recommendation was wrong and it has led you directly to this issue.
Never
#includea.cpp.The file you put template definitions in should be called something like
.ipprather than.cpp, so that then your IDE does not confuse it with a “regular” source file and build it with the rest of your project. Such a file is then, like a.h, only#included.