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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With