BlueBug
BlueBug

Reputation: 369

c++ strange behavior of static function with static variables

I am trying to create bunch of void methods and call them later in program. I will demonstrate the code ahead to help better understand my issue.

.h file
static float sfloat;
namespace someNamespace
{
static void foo();
}
.cpp file
void someNamespace::foo(){cout<<sfloat<<endl}

I initialize sfloat in other .cpp file

otherFile.cpp
void initializeAndUseFoo(){sfloat = 5; someNamespace::foo();}

As far as my understanding goes, I expect foo to print out 5 but it prints out 0 instead. This behavior occurs across all other static variables that I have as well(pointer included). It seemed that somehow the variables inside the function are never initialized as the value I assign.

However if I call out "sfloat" not through the function then I can call it out properly.(if I just print it out on console with just

cout<<"just print it not through the function : " <<sfloat<<endl;

then it is indeed 5

Thank you for reading.

Upvotes: 1

Views: 504

Answers (2)

SingerOfTheFall
SingerOfTheFall

Reputation: 29966

A global static variable is static within one compilation unit. If you make another compilation unit, it will have a separate copy of that static variable.

This SO question explains what a compilation unit is in C++.

Since your variable is static and global in the same time, there will be a single instance of it in it's compilation unit. If you want to access that exact variable from another file, you will have to use the extern keyword. Without it, a new copy of that variable will be created in each compilation unit. You can find some information here, for example.

Upvotes: 4

Luchian Grigore
Luchian Grigore

Reputation: 258618

That's not a class, it's a namespace. static inside the namespace or at global scope gives methods and variables internal linkage. That means a copy of each will be available for each translation unit.

Because you modify (not initialize) sfloat in otherFile.cpp, only that version of the variable is modified. The original, initialized in .cpp file, retains the same value (which is the version printed by someNamespace::foo().

Upvotes: 3

Related Questions