Where will the memory for the external variable be stored and by which file

I read about the extern variable, but did not find the answer related to its memory allocation. My question is: who will allocate memory for the Extern variable and in which segment of memory.

int a; // file 1 extern int a; // file 2 

here file 1 will allocate memory for file or file 2. In the data segment or on the stack?

Thanks.

+8
c ++ extern
source share
2 answers

The keyword extern means "declare without definition." In other words, this is a way to explicitly declare a variable or force to declare without a definition.

So, in file2 you simply declared a variable without definition (no memory allocated). In file1 you declared and defined an integer variable. Here you allocated memory on the BSS segment because you have an uninitialized global (for C).

In C ++, global tables are stored in an area for each process .


Difference between declaration and definition:

To understand how external variables relate to the extern keyword, you need to know the difference between the definition and declaration of a variable.

When a variable is defined, the compiler allocates memory for this variable and, possibly, also initializes its contents to a certain value. When a variable is declared, the compiler requires that the variable be defined elsewhere.

The declaration tells the compiler that a variable with this name and type exists, but the compiler does not need to allocate memory for it, since it is allocated elsewhere.

+7
source share

An integer variable with the name a declared in file 2 (do not remember the definition, i.e. there is no memory allocation for a until now). And we can make this expression as many times as necessary. Where file 1 is located, a specific integer variable named a declared and defined. (remember that a definition is a super-set of declarations). It also allocates memory for a .

+5
source share

All Articles