0

Here is an extern and a static variable with same name. The output prints the static variable a=10. Why is there no syntax error and how would I access extern a if needed?

#include<stdio.h>
extern int a;
static int a=10;

main()
{
    printf("%d\n",a);
}
Michael Albers
  • 3,721
  • 3
  • 21
  • 32
Anjaneyulu
  • 434
  • 5
  • 21
  • 1
    Archaic compiler? You should be getting errors for your main. – Jonathan Leffler Oct 15 '16 at 00:44
  • @JonathanLeffler Are you sure? Where does C standard explain the static-after-extern case? – AlexD Oct 15 '16 at 01:24
  • @AlexD: My comment says nothing about the main subject of the question. I'm only observing that C99 and C11 both require `int main(void)` or similar. A compiler that accepts what was in the question is working with the archaic C89 or C90 standard. That's all. – Jonathan Leffler Oct 15 '16 at 01:28
  • @JonathanLeffler Ah, understood, thanks! – AlexD Oct 15 '16 at 01:33

1 Answers1

2

The C standard allows the opposite, extern after static:

6.2.2 Linkages of identifiers
....
3 If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.

4 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 same time it states:

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

BTW, the C++ standard makes it explicit:

7.1.1 Storage class specifiers
....

static int b; // b has internal linkage
extern int b; // b still has internal linkage

....

extern int d; // d has external linkage
static int d; // error: inconsistent linkage
AlexD
  • 32,156
  • 3
  • 71
  • 65