Understanding the static storage class in C

static is the default storage class for global variables. The two variables below ( Count and Road ) have a static storage class.

 static int Count; int Road; int main() { printf("%d\n", Road); return 0; } 

My question is: if global variables are static by default (which means that we limit the scope of this global variable to this particular .c file), then how can we extern use these variables in another file?

This question may be very simple for many of you, but I'm really confused and want to know the right details.

+6
source share
2 answers

In formal C term specifiers, such as extern , static , register , etc., storage class specifiers are called, but the actual properties of the objects that they control the qualifiers are called storage duration and association.

In your question, you seem to be confusing these two unrelated concepts: storage duration and communication. This is actually a relationship that describes the appearance of an object.

All variables defined in the file area have a static retention period (regardless of whether the declaration used the static ). It just means that they live forever, but do not say anything about their appearance. Meanwhile, variables defined with the static have an internal connection, and variables defined without any keywords or with the extern keyword have an external connection.

In your example, the Road variable has a static storage duration and external link, so you can access it directly from other translation units. The Count variable has a static storage duration and internal communication, so you cannot access it directly from other translation units.

If you declare a variable without a storage class specifier (for example, Road in your example), it will be considered as a so-called preliminary definition and, finally, it will allow (in your example) a variable with static storage time and external communication, Thus, from this point view, we can say that the default class specifier (implied) for file scope variables is actually extern , not static .

+10
source

The Count variable is only available by name in this one source file due to the preceding static . Formally they say that it has an internal relationship (see ISO / IEC 9899: 2011 Β§6.2.2 Identifier relationships).

The Road variable may be available from other source files if these files included the equivalent of extern int Road; as one of the operators. Formally they say that it has an external connection.

Typically, most people call the Count static variable and the Road global variable.

See also. What are extern variables in C?

+6
source

Source: https://habr.com/ru/post/947612/


All Articles