Bill Yan
Bill Yan

Reputation: 3468

Which scope has a static variable?

I am writing a simple program which has few settings. The settings are static variables defined in a config.h header file.

For example, inside config.h:

static int setting1 = 10 ;

In another file, kkk.cpp, I have a function which changes the value of setting1:

void classA::functionA()
{
    setting1=5;
    classB.functionB();
}

However, in the classB.functionB, which is defined under file eee.cpp

void classB::functionB()
{
    int hh=setting1;
    printf("%d",hh);
}

hh is still the old value of setting1 (setting1 == 10).

Although the setting1 is a global static, its value cannot be changed? Why?

Upvotes: 2

Views: 148

Answers (1)

James McNellis
James McNellis

Reputation: 355009

If you declare a namespace-scope variable as static in a header file and then include that header file in multiple source files, there will be one instance of that variable per source file in which it is included. A static namespace-scope variable has internal linkage.

You have a few options:

  • Declare the variable in one of the .cpp files

  • Declare the variable as extern in the header file and then define it in only one of the .cpp files

  • Use a static member variable and define it in one .cpp file

Upvotes: 6

Related Questions