G said:
I have one more question. In multi source file programs, I put extern
declaractions for variables I want to share amongst many source files
in a headder, and include that in all those source files. I never used
to include that in the file I defined the file-scope variable. I
tried it after a suggestion and it works. But is this 100% proper (not
undefined)?
No. This is perfectly fine to do. This is actually more convenient
(add the header in every source file that requires the use of the
identifier) and allows the compiler to better catch descrepancies
between the single definition and the form of the declarations.
Technically, after preprocessing that source file has this at the top:
extern T var; /* came in from #include */
T var; /* was in the .c file */
I know the behaviour when extern declaration follows a non-extern
declaraction is okay, because the extern takes the
linkage/characteristics of the non-extern declaration (either static or
implicity external).
Yes. The standard says...
6.2.2 Linkage of Identifiers
+++++++++++++++++++++++++++++
(4) For an identifier with the storage-class specifier extern in a
scope in which a prior declaration of that identifier is visible [and
has internal or external linkage] ... the linkage of that later
declaration is the same ... (continued below)
So this explains a situation such as:
T var; /* has external linkage */
extern T var; /* has same linkage - external */
OR
static T var; /* has internal linkage */
extern T var; /* has same linkage - internal */
Note: "NO LINKAGE" doesn't have the same affect on later extern
declarations.
You said you already knew this, which is good because it will help
understand what happens when the order is switched.
But how does this work when extern declaration
PRECEDES a non-extern declaration?
The standard says...
6.2.2 Linkage of Identifiers
+++++++++++++++++++++++++++++
(4 continued from above)... If no prior declaration is visible [for
declaration with extern storage-class specifier], or if the prior
declaration specifies no linkage, then the identifier has external
linkage.
(5) ... If the declaration of an identifier for an object has file
scope and no storage-class specifier, its linkage is external.
This gives you the answer to your question. The first sentence tells
us that extern declaraed identifiers have external linkage if there is
no previous identical identifier with external/internal linkage. The
second sentence tells us that a declaration at file scope without a
storage class specifier has external linkage.
So in your question:
/* external linkage - no previous internal/external linkage */
extern T var;
T var; /* external linkage - no storage class specifier & file scope */
So both become declaration with external linkage, and specify the same
objects (linkage works when identifiers are in the same scope , or
different scopes.)