Ben Ben - 2 months ago 21
C Question

error: extern declaration of 'i' follows declaration with no linkage

In the following program, I thought that

extern int i;
will change the following
i
to refer to the
i
defined outside
main
:

#include <stdio.h>

extern int i=1; // warning: 'i' initialized and declared 'extern'

int main()
{
int i=2;
printf("%d\n", i);
extern int i; // error: extern declaration of 'i' follows declaration with no linkage
printf("%d\n", i);
return 0;
}


What is the reason of the "error: extern declaration of 'i' follows declaration with no linkage", where "declaration with no linkage" refers to
int i=2;
?

After I remove
int i=2
in
main
,


  • the error is gone,

  • the warning "warning: 'i' initialized and declared 'extern'" on
    extern int i=1;
    also disappear . Why is that?



Thank you for explanations!

Answer Source

Once you define a variable named i inside your main function, the i at file scope is masked and cannot be accessed (unless you have its address).

When you later add the declaration extern int i, this conflicts with the local variable named i at the same scope since locals can't have external linkage. It does not give you access to the global i.

When you remove the local i, the extern int i declaration matches up with the definition at file scope, so there is no error. As for the warning on extern int i=1;, that did not go away for me on gcc 4.1.2, so that depends on the compiler.