2016-10-15 5 views
0

Hier ist eine extern und eine static Variable mit dem gleichen Namen. Der Ausgang druckt die statische Variable a = 10. Warum gibt es keinen Syntaxfehler und wie würde ich bei Bedarf auf a zugreifen?Warum generiert dieser Code keinen Fehler bei der erneuten Deklaration?

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

main() 
{ 
    printf("%d\n",a); 
} 
+1

Lichtbogen Haic Compiler? Sie sollten Fehler für Ihr Haupt erhalten. –

+0

@ JonathanLeffler Sind Sie sicher? Wo erklärt der C-Standard den statisch-nach-extern-Fall? – AlexD

+0

@AlexD: Mein Kommentar sagt nichts über das Hauptthema der Frage aus. Ich beobachte nur, dass C99 und C11 beide 'int main (void)' oder ähnliches benötigen. Ein Compiler, der akzeptiert, was in der Frage war, arbeitet mit dem archaischen C89- oder C90-Standard. Das ist alles. –

Antwort

2

Der C-Standard erlaubt das Gegenteil, extern nach 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.

Zugleich heißt es:

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

BTW, die C++ Standard es explizit macht:

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 
+0

Danke und kann ich den Quelllink bekommen ?? – Anjaneyulu

+0

extern int d; // d hat externe Verknüpfung statisch int d; // Fehler: inkonsistente Verknüpfung Ich habe das nicht bekommen this gilt für C++ – Anjaneyulu

+0

@Anjaneyulu "_can ich bekomme die Quelle Link_" Check http://StackOverflow.com/q/81656 um zu sehen, wo die C und C++ - Standards zu bekommen . – AlexD

Verwandte Themen