Sign in to follow this  

Defining functions in namespace

This topic is 4097 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
Sure, 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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

This topic is 4097 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this