Why does it happen, although both resides in the same memory?
Short answer:
From C11 ( 6.2.2 Identifier Relationships ), paragraph 4:
If the declaration of the file area identifier for an object or function contains a storageclass static specifier, the identifier has an internal relationship .
Internal communication means that it is visible only inside the translation unit .
Detailed answer:
A global variable (without static) has an external connection, which means that it is visible to other translational units.
When you declare static variables with a file scope, it has an internal relationship, but when you declare it with a block scope, it has no binding.
Let's take a look at a few terms (inspired by C (static) keywords )
The variable C has one of the following relationships:
- no communication: - Variables with a block area do not have a link. This means that they are private to the block in which they are defined. All variables with automatic, streaming, and dynamic storage periods have this relationship, as well as variables declared static in the block area. A variable with a file region can have internal or external binding.
- intercom: - The variable can refer to all areas in the current translation unit. All variables declared in the file region have this link, including variables declared static in the file region.
- external communication: - The variable can refer to any other translation units in the entire program. All variables declared either extern or const without an explicit storage class specifier, but not static, have this link.
eg -
int i = 5; // file scope, external linkage static int j = 3; // file scope, internal linkage ... ... int main() { ... ... } int func () { static int num;// block scope β no linkage . . . }
By declaring a static variable at the file level ( static inside a function has a different meaning), you prohibit other devices from accessing it, for example. if you try to use a variable inside another device (declared using extern ), the linker will not find this symbol.
My accent :)
source share