Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding duplicate symbols and retaining code in header files

Tags:

c++

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?

like image 748
jwalk Avatar asked May 31 '13 07:05

jwalk


People also ask

How can you avoid including a header file multiple times?

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.

What does duplicate symbol mean in C++?

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.


1 Answers

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.

like image 52
RobbieE Avatar answered Oct 23 '22 15:10

RobbieE