I have a single global helper function which is used by a bunch of macros in a header file. The intention is to allow the macros to be usable by simply #include
'ing the single header (in other words, I'd like to keep the function definition in the header and avoid putting it in a separate compilation unit). However, this causes problems when an application #include
's this file in more than one compilation unit, as the duplicate symbols problem arises.
The helper function has enough characteristics in which it shouldn't be declared inline.
I was messing around and found that using unnamed namespaces solves the problem of duplicate symbols, i.e.:
namespace
{
void foo(...)
{
}
};
#define HELPER_A foo(1, ...);
#define HELPER_B foo(2, ...);
...
Is there any downside to this approach? Are there better alternatives?
To avoid multiple inclusions of the same header file we use the #ifndef, #define and #endif preprocessor directives. Just write the entire program in only file and include headers once only. You can use the conditional preprocessor directive named #ifndef to check whether that symbolic name has already been assigned.
Duplicate symbols occur when you have both added an implementation file (. cpp) to your project and #included it. This way, the implementation file (. cpp) gets compiled twice: once as a module in your project (as it is added to your project) and subsequently as a piece of #included code.
You are only allowed one function definition in your project unless its marked as inline
. You may have as many function declarations as you wish (aka function prototypes).
Move your function definition to a .cpp file and just leave the declaration in the header file
void foo(...); // no function body makes this a declaration only
or you could mark it inline
:
inline void foo(...) { /* ... */ }
inline
functions should be small and computationally fast as a general rule.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With