Alok
Alok

Reputation: 101

In which segment global const variable will stored and why

after applying const qualifier to any global variable increases the size of text segment. so, why global const variable will stored in text segment.

I have tried these codes

const int i = 5;
int main()
{
        return 0;
}

output of command: size a.out

text data bss dec hex filename
1080 496 16 1592 638 a.out

int i = 5;
int main()
{
        return 0;
}

output of command: size a.out

text data bss dec hex filename
1076 500 16 1592 638 a.out


Upvotes: 2

Views: 1106

Answers (2)

Nicola Musatti
Nicola Musatti

Reputation: 18218

As the text segment is read-only it can be shared among all the processes that are running your program, thus potentially reducing memory consumption. This is even more important for shared libraries, which may be used by many programs. Whether this is what actually happens depends on your operating system's behaviour.

Putting const variables with static storage in the text segment ensures that this mechanism is exploited as much as possible.

Upvotes: 1

HAL
HAL

Reputation: 3988

The compiler has better opportunity for optimization with const variables. Here, it looks like the const value is incorporated into the code and hence the increase in the size of the text segment.

Upvotes: 0

Related Questions