Jump to content
  • Advertisement
Sign in to follow this  
snooty

Defining functions in namespace

This topic is 4308 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!