Search code examples
cstaticlinkagestorage-class-specifier

Whether Global Variables in C, static or extern?


I just started learning C programming. In some of the books and web articles, I could find that any Global Variable in C by default corresponds to static storage class but has external linkage. Does this mean it is partially static and partially extern? Because as per my understanding any global variable with static storage class specifier has internal linkage only and can be accessed within the same file.

P.S: I referred this question Global variables in C are static or not? , but could not get really whether Global variables are static or extern by default in C.


Solution

  • Global Variable in C by default corresponds to static storage class but has external linkage. Does this mean it is partially static and partially extern?

    The English word “static” has muddled and multiple meanings in C, and, yes, the default for a variable declared outside a function is to have static storage duration and external linkage.

    Because there are multiple concepts here and some mixed use of word meanings, we should clarify some terminology and formatting:

    • Use code style to refer to specific text in source code, such as the keyword static. When speaking of static storage duration or external linkage, “static” and “external” are mere English adjectives and should not be in code style.
    • “Global” means visible throughout an entire program. The C standard does not use this word for this purpose. It uses “external” to refer to things that are outside of (external to) any function. (But it also uses “external” for other purposes.) A global variable could not have internal linkage, because it would not be visible throughout the entire program.
    • A variable consists of an object (memory reserved for representing the value) and an identifier (the name). Storage duration is a property of the object. Linkage is a property of the identifier.

    The English word “static” generally means unchanging. The C standard uses this word and the keyword static in multiple ways:

    • Static storage duration means the memory for an object is reserved throughout all of program execution.
    • Using the static keyword in a declaration, other than as below, both gives an object static storage duration and, in a declaration outside a function, gives the identifier internal linkage.
    • Using the static keyword inside subscript markers in a parameter declaration, as in void foo(int a[static 3]), indicates that the parameter points to at least the stated number of elements.
    • Static assertions, using _Static_assert, provide compile-time tests (which can help detect bugs or ensure a program is being compiled with expected settings).

    These multiple uses are unfortunate and are due at least partly to the history of how the C language was developed.