开发者

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 se开发者_JS百科tting1:

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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜