Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block scope linkage C standard

The following identifiers have no linkage: an identifier declared to be anything other than an object or a function; an identifier declared to be a function parameter; a block scope identifier for an object declared without the storage-class specifier extern.

{
    static int a; //no linkage
}

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.

{
    static int a; //no linkage
    extern int a; //a should get external linkage, no?
}

GCC error: extern declaration of a follows declaration with no linkage

Can somebody explain me why do I get this error?

Thank you

like image 226
mindless Avatar asked Aug 30 '11 07:08

mindless


2 Answers

Your supposition is correct: the second declaration of a has external linkage. However, you get an error because your code violates a constraint in §6.7:

3 If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space, except for tags as specified in 6.7.2.3.

That is, once you've declared a to have no linkage, you can't redeclare it again in the same scope.


A valid example of this rule being invoked is:

int a = 10;  /* External linkage */

void foo(void)
{
    int a = 5;  /* No linkage */

    printf("%d\n", a);    /* Prints 5 */

    {
        extern int a;  /* External linkage */

        printf("%d\n", a);    /* Prints 10 */
    }
}
like image 111
caf Avatar answered Nov 20 '22 09:11

caf


if the prior declaration specifies no linkage

means

if the prior declaration specifies not a sign of linkage

and not

if the prior declaration specifies that it has no linkage

This is confusing and ambiguous; not the usual way to write a standard...

like image 23
glglgl Avatar answered Nov 20 '22 08:11

glglgl