# namespace and static in C++

## Recommended Posts

#ifndef HEADER_H

namespace
{
int i;
}

#endif


From what I understand the int is static or internal linkage by being in the namespace. Now say I include this header in a few other .cpp files. Does each .cpp get it's own static int or do they all operate on the same one? I'm still having problems with including headers and multiple definition errors even with include guards. It seems namespace fixes the errors but I think I must be working on seperate static variables now. I went back to try to hammer out the errors in my pacman clone I started a few months back but maybe I just need to start from scratch.

##### Share on other sites
i doesn't have internal linkage, it has external linkage. However, each compilation unit gets a separate copy that is independent from all the others. If you want a shared global variable you should declare the variable as extern in the header, and then define the variable in one source file. For more details see this article.

##### Share on other sites
Quote:
 Original post by SiCranei doesn't have internal linkage, it has external linkage. However, each compilation unit gets a separate copy that is independent from all the others. If you want a shared global variable you should declare the variable as extern in the header, and then define the variable in one source file. For more details see this article.

That must be my problem. The whole internal/external thing is a bit confusing at times but I thought static was internal. I'm gonna check that article out now. Thanks SiCrane.

##### Share on other sites
static is internal. However, anonymous namespace != static. Variables in anonymous namespaces have external linkage but get name mangled so that every different source file gets a different copy.

##### Share on other sites
Ok that makes more sense. Thank you for the clarification.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628342
• Total Posts
2982177

• 9
• 24
• 9
• 9
• 13