Hei
Hei

Reputation: 1864

Declare and Define a Function in a Namespace?

I have the following header:

#ifndef MY_H_
#define MY_H_

namespace A {
void f() {
// do something
}
}
#endif

However, when I compiled, I got errors like multiple definition of A::f(). I thought that the #ifndef check is enough to avoid duplicate definitions in 1 translation unit. Maybe I miss something?

Thanks in advance.

Upvotes: 1

Views: 635

Answers (2)

IceFire
IceFire

Reputation: 4137

You should declare functions in the header file but define them in your cpp file. If you include this header file from multiple translation units (which is most probable), then there will be multiple implementations available for different translation units. Each of your cpp files that includes this header will have an implementation of f. This way, if f is to be called, it is ambiguous. By putting the implementation into a cpp file, it can be linked and used that way. But there is only one implementation available which makes it unambiguous.

So, your header file should be:

#ifndef MY_H_
#define MY_H_

namespace A
{
    void f(); // declaration only
}

#endif

and your source file:

#include "myHeader.h"

namespace A
{
    void f()
    {
        // some implementation
    }
}

Then, you should be fine. You would usually do that with all of your functions. The only exceptions are inline functions/methods or templates but this is beyond the scope of this question.

Upvotes: 0

pmed
pmed

Reputation: 1556

Add inline specifier before the function definition:

#ifndef MY_H_
#define MY_H_

namespace A {
inline void f() {
// do something
}
}
#endif

Upvotes: 2

Related Questions