I wanted to use binary_search on my class and so I defined a operator<. It works when everything is in main file, but when I write the class in another file I got linker error.
The simplest example that shows the problem is B.h:
class B
{
public:
~B(void);
string b;
int v;
B(int val, string bb);
friend bool operator< (const B &lhs, const B &rhs);
};
bool operator< (const B &lhs, const B &rhs){
return lhs.v < rhs.v;
};
B.cpp just defines the constructor. Main is sth like this:
#include "B.h"
int main( int argc, const char* argv[] )
{
vector<B> vec;
B a1(2, "gg");
B a2(4, "gdhd");
vec.push_back(a2);
vec.push_back(a1);
bool pos = binary_search(vec.begin(),vec.end(), B(2, "ghd"));
}
The error LNK2005: "bool __cdecl operator<(class B const &,class B const &)" (??M@YA_NABVB@@0@Z) already defined in Main.obj : fatal error LNK1169: one or more multiply defined symbols found
How to fix it ?
.h
and.cpp
files? – Mark Garcia