Why are constants stored in the text segment in a

2020-06-25 05:21发布

问题:

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 ?

回答1:

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 size command in its default mode, but you can make it give you more detail:

$ size test.o  # compiled from the code in the question
   text    data     bss     dec     hex filename
     58       0       0      58      3a test.o

$ size -A test.o
test.o  :
section           size   addr
.text                6      0
.data                0      0
.bss                 0      0
.rodata              4      0
.comment            29      0
.note.GNU-stack      0      0
.eh_frame           48      0
Total               87

See how the "text" number produced by the first command is the sum of the .text, .rodata, and .eh_frame numbers produced by the second question?

You can tell that the constant is in .rodata and not .text with the objdump command:

$ objdump -t test.o | grep -w global
0000000000000000 g     O .rodata    0000000000000004 global

(The 'g' is for global, and the 'O' is for 'Object' as opposed to 'F' for Function.)



回答2:

The text segment is read-only, so by placing the constant in the text segment, the compiler ensures it is truly constant. It has to be stored somewhere since it is declared as being accessible to other object files, and the choices are therefore the data and text segments.

If it were a static variable, the compiler might be able to eliminate it because it is unused, whether constant or not. If it was static and constant, the compiler might eliminate it in favour of using its value in the code it generates.



回答3:

Im going to go back to my previous edit. I believe that since it can never change its simply a compiler optimization to not store constants in the data segment at all since they cant change.