c - Order of `static` definition and `extern declaration` in a translation unit -


i unable understand why doesn't work.

extern int i;  int main() {   printf(" %d ", i);   }  static int =3; 

also, doesn't work:

extern int i;  static int =3;  int main() {   printf(" %d ", i);   } 

but if static variable defined before extern declaration works:

static int =3;  extern int i;  int main() {   printf(" %d ", i);   } 

as understand extern int itells i present somewhere else , here how looks lik(int i)

but, somewhere else means:

1) maybe, later point in same translation unit global variable.

2) maybe, in other translational unit.

i thinking (1) valid though static int = 3 has restricted i's scope current translation unit defined.

isn't static int =3 global( mean atleast visible in translation unit) here though has restricted scope translation unit? why isn't compiler unable find it?

when compile first 2 versions following compile time error:

 error: static declaration of ‘i’ follows non-static declaration  note: previous declaration of ‘i’ here 

i unable understand error message. also, why complaining static declaration isn't definition also?

c11 6.2.2 linkages of identifiers section 4

for identifier declared storage-class specifier extern in scope in prior declaration of identifier visible,31) if prior declaration specifies internal or external linkage, linkage of identifier @ later declaration same linkage specified @ prior declaration. if no prior declaration visible, or if prior declaration specifies no linkage, identifier has external linkage.

so second declaration follow first, examples, 1st , 2nd example i have extern storage-class. compiler thinks that's error.

while in 3rd example, i static because static shows first. should no problem.

and, in section 7 of c11 6.2.2 linkages of identifiers

if, within translation unit, same identifier appears both internal , external linkage, behavior undefined.

so it's better not declare same variable both static , extern in same translation unit.


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -