# Defining functions in namespace

## Recommended Posts

Hi, I'm defining functions in namespaces in the header files but the compiler gives a lot of warnings: "warning LNK4006: already defined; second definition ignored" I don't want to put these definitions in the source files because I want them inlined. Is there a way around this?

##### Share on other sites
Sure, simply define the function once per translation unit. You shouldn't need to define it more than once, anyway.

##### Share on other sites
Quote:
 Original post by ToohrVykSure, simply define the function once per translation unit. You shouldn't need to define it more than once, anyway.

I only define them once, just that the header file gets included multiple times, so those functions appear in multiple .obj files.

##### Share on other sites
I see. You did mark them as inline, didn't you?

Right. Thanks!

##### Share on other sites
Inline is a dangerous keyword. Really and truely it is. Some of the strangest bugs I've run into are because of explicity or implicitly "inline" code.

An alternative is to place them in anonymous sub namespaces.

namespace my_namespace{  namespace {    int get_my_int() {return 7;};  }}

Compilers can and often will inline code that they can see inline even without the inline keyword.

(
"inline" functions have external linkage, but if two inline functions have the same linkage, one of them is silently discarded. And if somehow the two inline functions have different bodies, but the same signature, you just lost the compiler game.
)

What, doing that is stupid? Well, how about:

// in A.cpp:class PrivateHelper {  int x;public:  PrivateHelper():x(1) {}};// in B.cpp:class PrivateHelper {  double d;public:  PrivateHelper:d(1.0) {}};

Spot the implicit inline and the undefined behaviour! Go go memory corruption that depends on the order of compilation!

Anonymous namespaces are your friend. The inline keyword is evil.

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627638
• Total Posts
2978330

• 10
• 12
• 22
• 13
• 34