Reputation: 69
I'm reading k&r book. In section 4.6,it says: The static declarations, applied to an external variables or functions , limits the scope of that object to the rest of the source file being compiled. I'm confused with the scope of static external variables when written with extern keyword in different source files.
Upvotes: 0
Views: 338
Reputation: 222714
Any identifier declared outside a function has file scope. The declaration is only visible inside the current translation unit, which is one source file along with all files included via the #include
preprocessing directive.
By default, identifiers for objects declared at file scope have external linkage. This means that, if the same identifier is declared in separate translation units, it refers to the same object. (An object is a region of storage that can represent a value. What you think of as a variable is a combination of its name, the identifier, and the memory used for it, the object.)
When a declaration for an object includes static
, the identifier has internal linkage. This means that other declarations inside the same translation unit with internal linkage will refer to the same object, but declarations in another translation unit will not refer to the same object.
Note that, for historic reasons, there are multiple meanings and effects associated with static and external. All declarations outside of functions (including declarations of functions) are external declarations in the language of the C standard, even if they include static
. In this usage, “external” means outside a function. In regard to the phrase external linkage, “external” refers to linkage outside the translation unit. In declarations, the keyword static
can affect both linkage (changing it from a default of external when outside a function or from no linkage when inside a function) and also storage duration (changing it from a default of automatic inside a function to static storage duration). One might also say that definition int a[5]
is a static definition in the sense that the array size is fixed. Unfortunately, we are simply stuck with these multiple effects and meanings, and you will have to learn them.
Upvotes: 3