I have read about global and local variables and static keyword, but i dont know which is the difference between something like this:
int x; //Global variable
int main(){
//Code...
}
And this:
static int x; //Static Global variable
int main(){
//Code...
}
I know some properties of the static keyword, and i know why is useful for local variables, but i dont know which is the use for global variables
I have read that using static for global variables is used for accesing the variable only in the C file it is declared/defined, but, i mean, if we dont use extern we just cant access that global variable in other c files anyway
I think that a "static global" variable is used to prevent the use of the extern keyword in order to prevent the use of that variable in multiple C files, is that correct?
Thanks in advance!
CodePudding user response:
Yes, it is correct.
A global static variable can only be accessed in the file where it is created(file scope).
CodePudding user response:
"Global" is not a formal term, but it generally means "variable that can be accessed anywhere". Therefore global.
To dive into some formal terms:
- The formal and correct term for a variable declared outside a function is declared at file scope.
- What formally defines how a variable may be accessed in C is referred to as linkage.
- A variable declared at file scope generally has external linkage and can be referred to from elsewhere with
extern
.
So the correct term to use for your first example is "file scope variable with external linkage".
Whenever we add the storage class specifier static
to a declaration, we force the variable or function to instead get internal linkage. This means that it is only accessible from within the translation unit (the .c file and all .h files it includes) where it was declared.
It is the opposite of global, so saying "static global" doesn't make any sense. You cannot refer to such a variable with extern
. Instead the correct term is "file scope variable with internal linkage".
The main purpose of static
is indeed private encapsulation, since the internal linkage guarantees that the variable or function cannot be accessed by other .c files.
But static
also at the same time gives static storage duration to a variable, meaning it is guaranteed to persist throughout the execution of the program and that it has some initialization rules guaranteed. Now as it happens, variables at file scope always gets static storage duration, static
or not, so it isn't very relevant to your example. But as you earlier discovered, static storage duration does make a big difference for local variables, since their value will then be preserved throughout multiple function calls.
More details here: What does the static keyword do in C?