Sign in to follow this  
nomichi

namespace and static in C++

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

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