Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where memory for extern variable will be stored and by which file

Tags:

c++

extern

I read about extern variable, but no where found answer related to its memory allocation, My question is Who will allocate memory for Extern variable, and in which memory segment.

int a; // file 1

extern int a; // file 2

here file 1 will allocate memory for a or file 2. In data segment or in stack ?

Thanks.

like image 272
anand Avatar asked Aug 02 '13 06:08

anand


2 Answers

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

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

In C++, the globals are stored in a per-process data area.


Difference between declaration and definition :

To understand how external variables relate to the extern keyword, it is necessary to know the difference between defining and declaring a variable.

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

The declaration informs the compiler that a variable by that name and type exists, but the compiler need not allocate memory for it since it is allocated elsewhere.

like image 172
Pierre Fourgeaud Avatar answered Oct 20 '22 03:10

Pierre Fourgeaud


In file 2 an integer type variable called a has been declared (remember no definition i.e. no memory allocation for a so far). And we can do this declaration as many times as needed. Where is in file 1 an integer type variable called a has been declared as well as defined. (remember that definition is the super set of declaration). Here the memory for a is also allocated.

like image 40
Hitesh Vaghani Avatar answered Oct 20 '22 01:10

Hitesh Vaghani