static
is the default storage class for global variables. The two variables below (Count
and Road
) both have static
storage class.
static int Count;
int Road;
int main()
{
printf("%d\n", Road);
return 0;
}
My question is: if by default global variables are static
(which means we are limiting the scope of that global variable to that particular .c
file) then how can we extern
those variables in another file?
This question might be very basic to many of you but I am really confused and want to learn the correct details.
In the formal C terminology specifiers like extern
, static
, register
etc. are called storage-class specifiers, but the actual object properties these specifiers control are called storage duration and linkage.
In your question you seem to be mixing these two unrelated concepts: storage duration and linkage. It is actually linkage that describes external visibility of the object.
All variables defined in file scope have static storage duration (regardless of whether you used the keyword static
in the declaration). This simply means that they live forever, but it does not say anything about their external visibility. Meanwhile, variables defined with keyword static
have internal linkage, while variables defined without any keywords or with keyword extern
have external linkage.
In your example variable Road
has static storage duration and external linkage, which is why you can access it directly from other translation units. Variable Count
has static storage duration and internal linkage, which is why you can't access it directly from other translation units.
If you declare a variable without a storage class specifier (like Road
in your example), it will be treated as so called tentative definition and finally resolve (in your example) to a variable with static storage duration and external linkage. So, from that point of view it is right to say that the default (implied) storage class specifier for file scope variables is actually extern
, not static
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With