为什么常量存储在C存储器映射的文本段中? [英] Why are constants stored in the text segment in a C memory map?

查看:95
本文介绍了为什么常量存储在C存储器映射的文本段中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,请考虑以下代码片段,这些代码片段是在具有相应内存映射的Linux计算机(64位)上用gcc编译的

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

在这里,因为有一个全局变量初始化为2.它已存储在数据段中 考虑如下所示使其为const的情况

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 ?

推荐答案

在现代系统上,常量位于对象文件的一部分中,该部分保留为只读数据.在默认模式下,该部分通过size命令与文本"(程序代码)部分集中在一起,但是您可以使其更详细:

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

看看第一个命令产生的文本"数字是第二个问题产生的.text.rodata.eh_frame数字的总和吗?

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?

您可以使用objdump命令确定常量位于.rodata中,而不位于.text中:

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

("g"表示全局,"O"表示"Object",而"F"表示Function.)

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

这篇关于为什么常量存储在C存储器映射的文本段中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆