the memory location of static and extern storage class in C -
this question has answer here:
- can variable declared both static , extern? 4 answers
- why won't extern link static variable? 4 answers
i have 2 files sharing global variables.
in main.c
#include<stdio.h> static int b; extern int b; main() { extern int a; printf("a=%d &a:%p\n",a,&a); printf("b=%d &b:%p\n",b,&b); fn(); }
in fun.c
#include<stdio.h> int b=25; int a=10; fn() { printf("in fna=%d &a:%p\n",a,&a); printf("in fnb=%d &b:%p\n",b,&b); }
if compile both files. i'm not getting compilation error. , fine.the output
a=10 &a:0x804a018 b=0 &b:0x804a024 in fna=10 &a:0x804a018 in fnb=25 &b:0x804a014
but, in main.c if alter lines extern int b
, static int b
this
#include<stdio.h> extern int b; static int b; main() { extern int a; printf("a=%d &a:%p\n",a,&a); printf("b=%d &b:%p\n",b,&b); fn(); }
at compilation, i'm getting error.
main.c:6:12: error: static declaration of ‘b’ follows non-static declaration main.c:5:12: note: previous declaration of ‘b’ here
here issue memory @ static , extern variables stored. couldn't able conclude exact reason why compilation error @ second time
note: i'm using gcc compiler.
these 2 quotes c standard (6.2.2 linkages of identifiers) understand problem.
4 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.
and
7 if, within translation unit, same identifier appears both internal , external linkage, behavior undefined.
in translation unit
#include<stdio.h> static int b; extern int b; main() { extern int a; printf("a=%d &a:%p\n",a,&a); printf("b=%d &b:%p\n",b,&b); fn(); }
indentifier b
has internal linkage (read first quote). first declaration of b
declares identifier having internal linkage due storage-calss specifier static
. second declaration of b storage-class specifier extern
has prior declaration of b
(the first declaration) the storage class specifier static
. linkage of identifer same linkage of prior declared identifier.
in translation unit
#include<stdio.h> extern int b; static int b; main() { extern int a; printf("a=%d &a:%p\n",a,&a); printf("b=%d &b:%p\n",b,&b); fn(); }
identifier b
declared having external , internal linkage (read both quotes). compiler issues message.
at first identifier b
declared having external linkage (because there no prior declaration given linkage) , due specifier static
same identifier declared having internal linkage.
Comments
Post a Comment