While I had an intuitive understanding of the notions, I was quite curious about what they truly meant; what the rules were and why they were what they were.
So I wrote a full blog post about it, which is as thorough as it's going to get without being the standard, but is much simpler to understand.
Here are the key insights:
(An object in C is a variable or a function)
The scope of a declaration is the part of the code where the
declaration is seen and can be used.
Note that this says nothing about whether the object associated to the
declaration can be accessed from some other part of the code via
another declaration!
We identify a unique object by its memory: the storage for a variable
or the function code.
Duration indicates whether the object associated to the declaration
persists throughout the program's execution (static duration) or whether it is allocated
dynamically when the declaration's scope is entered (dynamic duration).
Linkage is what determines if multiple declarations of the same object
refer to the same object, or to separate ones.
About Linkage, if we simplify a bit:
- no linkage: the declaration refers to a unique object
- internal linkage: all declarations in a compilation unit refer to the same object
- external linkage: all declarations with external linkage in the program refer to the same object
Finally, a handy rule:
One can determine the linkage and duration of any declaration using
only three rules (most prioritary rule first):
Within functions, declarations without extern
have no linkage.
Within functions, declarations without extern
or static
have automatic duration. Any other declaration, at any scope, has static
duration.
Within a compilation unit, objects have internal linkage if there is a declaration with the static
storage class specifier. This
declaration must happen before any extern
declaration, and there
cannot be any declaration without storage class specifier (or a
compilation error ensues). Otherwise, they have external linkage.
I hope this helps!