Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

static keyword keeps the scope of a global variable limited to that translation unit. If I use static int x in a .h file and include that .h file every other file, won't they all belong to the same translation unit? Then, won't x be visible everywhere? So what is the role of static now?

Also, is there any use of static const int x ,where x is a global variable? Aren't all const global variables static by default? And is a const variable's scope limited to the TU even if it confined in a for loop in the file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
332 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you write

static const int x

in an .h file then every translation unit that #include-s this .h will have its own private variable x.

If you want to have 1 global variable visible to everyone you should write

extern const int x;

in the .h file and

const int x = ...;

in one of the .cpp files.

If you want to have a static const int visible to just one translation unit - don't mention it in the .h files at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...