Anonymous
Anonymous

Reputation: 337

Static variables and different namespaces in c++

I have read on static variables and know what they are, how they function when define in a .cpp file, function, and class.

But I have slight confusion when define in different namespaces in the same cpp file.

One of these voted answers here says:

When you declare a variable as static inside a .h file (within or without namespace; doesn't matter), and include that header file in various .cpp files, the static variable becomes locally scoped to each of the .cpp files.

According to the program below, namespaces does matter.

static int a = 0;
namespace hello1 {
static int a = 1;
namespace hello2 { static int a = 2;}
namespace hello3 { static int a = 3;}
}
int main()
{
    std::cout<<::a<<hello1::a<<hello1::hello2::a<<hello1::hello3::a;
    return 0;
}

output 0123

Here is what I think: a outside namespaces is the file scope. a in hello1 is hello1 scope. Since hello1 is global scope namespace, I can only have one a in namespace hello1, including other cpp files where hello1 exists. The same goes for hello2 and hello3; only one a in each hello1::hello2 and hello1::hello3.

Please correct me If I understood it correct. The namespace does matter; static variables in the same cpp file under different namespaces are different entities.

Upvotes: 0

Views: 434

Answers (1)

Miles Budnek
Miles Budnek

Reputation: 30494

That's not what the passage you quoted is talking about. It is referring to the fact that static variable names have internal-linkage. What that means is that you can't access a static variable a that is defined in "a.cpp" from "b.cpp", even if you include a declaration of a in "b.cpp". That declaration will refer to a different object.

For example:

A.hpp

static int a = 0;
void foo();

A.cpp

#include "A.hpp"
#include <iostream>

void foo() { std::cout << a << '\n'; }

B.cpp

#include "A.hpp"
#include <iostream>

int main() {
    std::cout << a << '\n';  // prints 0
    a = 1;
    foo(); // prints 0, since it uses a different a
}

In this example, "A.cpp" and "B.cpp" see different global-scope objects named a since a was declared static. Even though main modifies a's value to be 1, foo still sees it as 0 since it's looking at a different a.

This behavior is irrespective of namespaces. If a were in a namespace other than the global namespace this same behavior would occur. That is what the passage you quoted is referring to.

Upvotes: 2

Related Questions