Hello Please consider the code snippets below compiled with gcc on a Linux machine(64bit) with the corresponding memory map
#include <stdio.h>
int global = 2;
int main(void)
{
int local = 0;
return 0;
}
text data bss dec hex filename
1092 500 16 1608 648 mem
Here since there is a global variable initialized to 2 . Its been stored in the data segment
Consider the case of making it const as shown below
#include <stdio.h>
int const global = 2;
int main(void)
{
int local = 0;
return 0;
}
text data bss dec hex filename
1096 496 16 1608 648 mem
Here the global variable is moved from the data segment to the text segment.
Why is it moved from the data to the text segment ?
Since the data segment is divided into read and read-write areas It should have been stored in the read area of the data right ?
What happens to a uninitialized global variable initialized in the middle of the code ?
On a modern system, the constant is in a section of the object file reserved for read-only data. That section gets lumped together with the “text” (program code) section by the
sizecommand in its default mode, but you can make it give you more detail:See how the “text” number produced by the first command is the sum of the
.text,.rodata, and.eh_framenumbers produced by the second question?You can tell that the constant is in
.rodataand not.textwith theobjdumpcommand:(The ‘g’ is for global, and the ‘O’ is for ‘Object’ as opposed to ‘F’ for Function.)