• Advertisement
Sign in to follow this  

namespace and static in C++

This topic is 4277 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

Ok say I have a header with a namespace: header.h
#ifndef HEADER_H
#define 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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
Share on other sites
Quote:
Original post by SiCrane
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.


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


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


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement