You need to mark your function inline
, like following:
#ifndef MY_HEADER
#define MY_HEADER
inline int MyFunction(int x)
{
return x + 1;
}
#endif
Explanation:
Every time you include your .h in any .cpp file, you end up with a definition of the function. Linker doesn't like multiple definitions. However, if you mark function inline
, you are telling compiler to make sure linker will be satisfied.
The real way of how to make the linker happy is dependent on the compiler and linker, but in practice, it boils down to two strategies:
- Inlining the function - which means, the function definition is actually removed from the generated code. Instead, whatever the function was supposed to do would be done where the function was called.
- Marking function as local name - linker knows that local names are specific to a particular file, and will always keep them separate.