6

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?

16
  • did not get what is the problem with putting the definition in a .cpp file. Commented May 31, 2013 at 7:18
  • Do you really want your code to duplicate in different compilation units? Why not using #pragma once? Commented May 31, 2013 at 7:18
  • 1
    You mention that it shouldn't be declared "inline", but do you actually want a discrete implementation of it for every compilation unit was included into - that seems wasteful. Why not just put it in its own compilation unit and simply declare it "extern" in the header file? Commented May 31, 2013 at 7:31
  • I'd like to keep the function definition in the header and avoid putting it in a separate compilation unit Why? Commented May 31, 2013 at 7:31
  • 1
    The helper function has enough characteristics in which it shouldn't be declared inline I doubt it. If the compiler doesn't think the function should be inlined then it won't be, but the inline keyword will give the function the correct linkage to avoid the multiple definition error. Commented May 31, 2013 at 7:32

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

While your answer is factually accurate, the OP already mentioned both of these approaches and you failed to address why the OP should now consider them when he has chosen not to previously.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.