You mix up static
and static storage duration.
Storage duration and linkage are different terms. There is nothing in C called "global", though the term is often sloppily used for any variable declared at file scope - that is: outside any function. More correct use of the term "global" would be that the variable has external linkage, meaning it may be referred to anywhere in the whole project.
All variables declared at file scope have static storage duration. This dictates how such variables are initialized and that they persist throughout the whole exeuction of the program (practically, it likely also means that the variable ends up in .data
or .bss
segments of the implementation).
A variable declared at file scope but without any storage class specifier (neither static
nor extern
) has external linkage, but it still got static storage duration. From 6.2.4:
If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.
But if you add a storage class specifier to a file scope variable, you specify both storage duration and linkage. 6.2.4/3:
If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static
, the identifier has internal linkage.
And as you say, a variable with internal linkage can only be referred to from the same file (strictly speaking same "translation unit").
There's some subtle difference here in case you add static
to a local variable - it then specifies storage duration but not linkage. The whole term linkage is rather confusing - simply put the purpose of the term is to dictate when two variables with the same name refer to the same object or different ones. This is mostly a concern for those making compilers/linkers as well as for spaghetti programmers. Avoid belonging to the latter category by following the advise below.
Beginners need not worry about any of the above.
Rules of thumb for beginners:
- Never declare variables outside functions unless they are
static
.
- Never declare variables in header files.
- Never use
extern
.
- Use
static
in front of functions if they aren't meant to be called from other files.
This will get you very far, and the rare cases where you actually need to share variables between different files is another story/advanced topic.