Global initialized variables declared as "const" go to the text segment, and those declared "Static" go to the data segment. What for?

#include <stdio.h>

const int str[1000] = {0};

int main(void)
{
    printf("arr is %d\n", str[0]);
    return 0;
}

It has the following output:

[-exercises/adam/stack2]:size a.out
   text    data     bss     dec     hex filename
   5133     272      24    5429    1535 a.out

While:

#include <stdio.h>

static int str[1000] = {0};

int main(void)
{
    printf("arr is %d\n", str[0]);
    return 0;
}

It has the following output:

[-exercises/adam/stack2]:size a.out
   text    data     bss     dec     hex filename
   1080    4292      24    5396    1514 a.out

When the array is not initialized, it again goes into the text segment for "const" and BSS for "static".

The variable is global and must be accessible from anywhere in the executable file from which it is (due to the lack of "static"), but given its variable, I don’t know why it is placed in the text segment instead of the data segment

+5
source share
5 answers

. const static ; . , , static const, () const text, -t20 > -qualified static const -qualified external data.

bss, , ELF, bss . size .

+6

:

static - . : auto, register, extern typedef. . , , . , .

,

const . . const - , , , , .

, , ; const , text/code segment, .

+7

. const segfault.

+3

const, , . , static, , , , , - .

, const text . , text flash , , . data, bss .. .

+1

const , .

, TEXT , MMU. . const , . .

Uninitialized data declared static will go into the BSS segment to save space in the executable. This area is allocated in memory by the bootloader. The initialized data declared static will go into the DATA segment, which is read-write.

+1
source

All Articles