Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global initialized variables declared as "const" go to text segment, while those declared "Static" go to data segment. Why?

Tags:

c

static

elf

#include <stdio.h>

const int str[1000] = {0};

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

Has the following output:

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

Whereas:

#include <stdio.h>

static int str[1000] = {0};

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

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 uninitialized -- it again goes to text segment for "const" and to BSS for "static".

The variable is global and should be accessible from anywhere in the executable it is part of (because of no "static"), but given its a variable I don't know why it is placed in text segment instead of data segment?

like image 385
helpmelearn Avatar asked Oct 17 '10 17:10

helpmelearn


1 Answers

You're confused. There is no dichotomy between const and static; the two are independent. Assuming all data is initialized, both static const and external (global) const will go in text and both non-const-qualified static and non-const-qualified external will go in data.

As for bss, modern binary formats like ELF actually have separate bss for constant and nonconstant zero data. The output of the size command just doesn't show it.

like image 194
R.. GitHub STOP HELPING ICE Avatar answered Nov 15 '22 08:11

R.. GitHub STOP HELPING ICE