I have a namespace with inline function that will be used if several source files.
When trying to link my application, the inline function are reported as duplicate symbols.
It seems as if my code would simply not inline the functions and I was wondering if this is the expected behavior and how to best deal with it.
I use the following gcc options:
-g -Wextra -pedantic -Wmissing-field-initializers -Wredundant-decls -Wfloat-equal -Wno-reorder -Wno-long-long
The same code style seems to compile and link properly when build in a VC7 environment.
The following code example shows the structure of the code:
/* header.h */
namespace myNamespace {
inline bool myFunction() {return true;}
}
/* use_1.cpp */
#include "header.h"
...
bool OK = myNamespace::myFunction();
...
/* use_2.cpp */
#include "header.h"
...
bool OK = myNamespace::myFunction();
...
Delete the build directory for the dll/exe and recompile.
There is possibly some problem with the build. It could be pre-compiled headers as alluded to by the OP in a comment above. I had exactly the same problem and deleting the build directory and recompiling solved it.
The inline keyword is taken only as a hint by the compiler. If the compiler decides that the function would be better performing without inline, it will not inline it. There are vendor-specific keywords that make the compiler inline a function - it is __attribute__((always_inline))
for GCC and __forceinline
for Visual C++.
If you really want to make sure your function won't be causing linker errors in all cases on all standard compilers, you might want to make it templated, as templated functions are guaranteed not to cause linker errors even if defined in headers. This is, however, quite unnecessary for really simple functions.