External and global variables with the same name in C

I'm trying to figure out what happens if we have something like this in a program:

extern int x;

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

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

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

+4
source share
3 answers

They are not two variables. They are the same.

extern int x;

is an ad x.

and

int x=0;

gives a definition for x. It is beautiful and truly.


You may have several ads like:

extern int x;
extern int x;

too, and it will compile too.

, , . . 6.2.2 . . m .

+7

.

extern int x;

x int extern explictly , .

int x = 0;

extern → http://en.cppreference.com/w/cpp/language/storage_duration

extern ( ). , , . , , extern .

+3

"extern" : " - . , , ".

, :

extern int x;
// This is a valid name, but the variable will be defined "externally", eg, somewhere else.

[...] 

int x=0;
// OH!  Here is where the definition is.  Now we know where that "extern" variable came from.
// And we know that it starts with value 0.

, extern .

More typically, the definition is in one file .C, but externin another .C, which will be linked together during the build process.

+2
source

Source: https://habr.com/ru/post/1669202/


All Articles