Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern and global variables with the same name in C

I'm trying to figure out what happens if in some program we'll have like that:

extern int x;

void foo(){...}
void bar(){...}

void main(){
foo();
bar();
}
int x=0;

So what is suppose to happen?Why is it allowed to have two such variables with the same name?are they different?

like image 402
ChikChak Avatar asked Dec 14 '22 00:12

ChikChak


1 Answers

They are not "two" variables. They are the same.

extern int x;

is a declaration of x.

and

int x=0;

provides the definition for x. This is perfectly fine and valid.


You can have multiple declarations like:

extern int x;
extern int x;

too and it'll compile as well.

Note when you are providing the multiple declarations for the same identifier, the rules are somewhat complex. See: 6.2.2 Linkages of identifiers for details. See static declaration of m follows non-static declaration for an example.

like image 170
P.P Avatar answered Dec 28 '22 05:12

P.P