Reputation: 88287
At the top of a cpp file, I have
namespace PQL {
class Synonym {
...
public:
...
int size();
};
}
// removing the below chunk makes it work
int Synonym::size() {
return ids.size();
}
Why does the bottom chunk make the code fail? I am creating the implementation of the function? Other functions defined a similar way works.
UPDATE:
The error I got looks like:
Error 1 error LNK2005: "public: int __thiscall PQL::Synonym::size(void)" (?size@Synonym@PQL@@QAEHXZ) already defined in main.obj H:\Dropbox\Sch\CS3202\SPA_CPP\SPA\pql.obj
Upvotes: 0
Views: 1276
Reputation: 264571
Its because your code is in a header file and being included in multiple compilation units:
inline int Synonym::size() {
// ^^^^^^^
return ids.size();
}
Adding inline tells the linker that there may be multiple definitions.
Note: The keyword 'inline' has nothing to do with code inline-ing in modern compilers.
Your header file contains:
using namespace std;
// and
using namespace PQL;
This is a very bad idea. You are now forcing this on anybody that uses your code. I would never use your header file as it would contaminate my code and cause unforeseen problems. It is OK to do this in your own source files (when you know and understand the issues) but you should never force this on other developers.
See: Why is "using namespace std" considered bad practice?
Upvotes: 1
Reputation: 14169
From your comments, I put this together: You put everything in a single Cpp file and include that file in different other files. Each of those files compiles, and each of those files has an implementation of PQL::Synonym::size()
. When linking, the linker sees all those definitions and doesn't know which one to choose.
Split your code into header and source files and just include the header in the other files.
Upvotes: 1
Reputation: 258618
Because Synonym
isn't a name in global scope.
Either use
int PQL::Synonym::size() {
return ids.size();
}
or implement the method inside the namespace.
Upvotes: 4