I just can't get my head around why this won't compile.
I have three files:
main.cpp
#include "expression.h"
int main(int argc, char** argv)
{
return 0;
}
expression.h
#ifndef _EXPRESSION_H
#define _EXPRESSION_H
namespace OP
{
char getSymbol(const unsigned char& o)
{
return '-';
}
};
#endif /* _EXPRESSION_H */
And expression.cpp
#include "expression.h"
(Ofc there is more inside of it, but even if I comment everything except for the #include
out it doesn't work)
I compile it with
g++ main.cpp expression.cpp -o main.exe
This is the error I get:
C:\Users\SCHIER~1\AppData\Local\Temp\ccNPDxb6.o:expression.cpp:(.text+0x0): multiple definition of `OP::getSymbol(unsigned char const&)'
C:\Users\SCHIER~1\AppData\Local\Temp\cc6W7Cpm.o:main.cpp:(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
The thing is, it seems to parse expression.h
two times. If I just compile it using main.cpp
OR expression.cpp
I don't get the error. The compiler just ignores my #ifndef and continues...
Any clues?
The thing is, it seems to parse expression.h two times.
Of course it does. You include it in two different cpp files. Each inclusion dumps the content of the header into that translation unit, so you get two definitions of the same function, making the linker rightfully complain. This has nothing to do with include guards, which protect you from accidentally including twice in the same file.
You can, however, have a function defined in a header. So long as it's marked inline. So do this:
namespace OP
{
inline char getSymbol(const unsigned char& o)
{
return '-';
}
}
inline
here is a promise that all of those functions are the exact same one, to the letter. So the multiple definitions are in fact considered one and the same. Be careful not to break this promise however (don't use any construct that can change the function body depending on where it's included).
And by the way, a namespace doesn't need to be terminated with a ;
, so I took the liberty of removing it.