Reputation: 1
This is a general C or C++ code related question. Why would you need the static keyword for a global variable in C or C++ if it is already global throughout the program and if this program is only using one file.
Upvotes: 0
Views: 192
Reputation: 596256
A global variable has external linkage by default. Meaning, it can be accessed by other translation units by using extern
.
Declaring a global variable as static
gives it internal linkage. Meaning, it can only be accessed within the translation unit that it is declared in, extern
can't reach it.
If the program only has 1 translation unit (.c
/.cpp
file), declaring a global variable in that unit as static
doesn't make any difference. But, if you have multiple translation units, it starts to make more sense to declare globals as static
when you don't want to share them across translation units.
See https://en.cppreference.com/w/c/language/storage_duration for more details.
Upvotes: 4