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.
Best Answer
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
.
The variable Count
is only accessible by name within this one source file because of the static
that precedes it. Formally, it is said to have internal linkage (see ISO/IEC 9899:2011 §6.2.2 Linkages of Identifiers).
The variable Road
could be accessed from other source files if those files included the equivalent of extern int Road;
as one of the statements. Formally, it is said to have external linkage.
Generally, most people would call Count
a static variable and Road
a global variable.
See also What are extern
variables in C?