How are multiple prior declarations resolved for a new declaration with extern?

The third declaration, extern char x, should declare x with external linkage, based on C 2018 6.2.2 4, which says:

For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

At the declaration extern char x, the first declaration of x is not visible, as it has been hidden by the second declaration. Therefore, it does not qualify for “a prior declaration of that identifier is visible.” The second declaration of x is visible, so it is a “prior declaration” for the purposes of the above paragraph.

Then the last sentence should control: The prior declaration specifies no linkage (6.2.2 6, a block-scope identifier without extern has no linkage), so the third x has external linkage.

Then 6.2.2 7 is violated because the first x has internal linkage and the third x has external linkage:

If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.

Since no syntax rule or constraint is violated, the C implementation is not required by the standard to report a diagnostic. Since the behavior is undefined, it may do anything, including accept this code and make the third x refer to the same object as the first x. Therefore, neither Clang nor GCC’s behaviors violate the standard in this regard. However, since 6.2.2 7 is violated, a diagnostic may be preferred, and its absence could be consider a defect of Clang.

(Credit to Paul Ogilvie and T.C. for informing my thinking on this with their comments.)

Leave a Comment