Reputation: 2238
I know... basics somehow but I don't get it. I read that I can put my function definition inside my header and include it then. I've never done that so far because I liked my definition in a .cpp file seperate to it's declaration in a header file.
Now I had just two functions and I don't want an extra file for those definitions.
Header.h
const QString reviewToString(const int); //Declaration - do I even need it now?
const QString statusToString(const int); //Declaration - do I even need it now?
const QString reviewToString(const int r) //Definition
{
switch(r)
{
case 0:
return "Excellent";
case 1:
return "Great";
case 2:
return "Okay";
case 3:
return "Poor";
case 4:
return "Terrible";
default:
return "Unknown";
}
}
const QString statusToString(const int s) //Definition
{
switch(s)
{
case 0:
return "Watched";
case 1:
return "Bought";
default:
return "Not Watched";
}
}
This is an extract of my headerfile. I got some other enum
s and struct
s but they're not that important for these functions because they just translate an integer to a QString which will be displayed somewhere else. I also have an include guard.
Now I get tons of errors like this one :
multiple definition of `reviewToString(int)'
Why is that? Why can't I just declare and / or define them in this header?
Upvotes: 2
Views: 494
Reputation: 12907
The problem here is the One Definition Rule. (C++ Standard §3.2)
Basically, you can't have multiple definitions for a function in your entire program. You can however make the functions inline
(otherwise, you'll have to put them in a .cpp
file).
Upvotes: 3
Reputation: 56863
You need to add inline
to the definition. Without it, each translation unit will create its own copy and the linker will not know that those are supposed to be duplicates and that he is allowed to throw away all but one of those copies.
Better yet, don't add the definition to the header, just the declaration is enough. Move the implementation to its own translation unit (.cpp
-file). You don't need the inline
there and it has multiple benefits that become more and more important as your project grows.
Upvotes: 5