2014-01-15 25 views
4

我正在使用测试程序来了解linux 6.3上的C内存模型,并使用了内核版本2.6.32-279.el6.x86_64。在bss和数据段中的整数可变大小

首先我必须编译下面的代码,

#include <stdio.h> 
int main(void) 
{ 
    static int i = 100; /* Initialized static variable stored in DS*/ 
    return 0; 
} 

上运行大小命令,我在下面了,

[[email protected] jan14]# size a.out 
    text data  bss  dec  hex filename 
    1040  488  16 1544  608 a.out 

那么,消除了对静态变量“我”的intialization后,我的代码变得,

include <stdio.h> 
int main(void) 
{ 
    static int i ; 
    return 0; 
} 

在编译上面的运行大小后,

[[email protected] jan14]# size a.out 
    text data  bss  dec  hex filename 
    1040  484  24 1548  60c a.out 

bss部分有8个字节增量,但数据部分只有4个字节减少。为什么在移动到bss段时大小是整数倍?

我已经测试过这个角色并且漂浮了,观察到了相同的行为。

+0

您可能希望仔细观察目标文件,生成的汇编代码和链接描述文件,以及可能的编译器和/或链接器源代码(如果使用的是例如。铛/ GCC和GNU ld)。 –

回答

4

看,答案是.bss部分有一个要求在64位对齐,.data没有这个要求。

你怎么看到这个?当你构建你的程序时,ld使用一个默认的链接器脚本来构建你的程序。你可以看到,如果添加轮候册,-verbose:

g++ main.cpp -Wl,-verbose 

当您构建64位的一个应用,这是对.bss段默认aligment:

.bss   : 
    { 
    *(.dynbss) 
    *(.bss .bss.* .gnu.linkonce.b.*) 
    *(COMMON) 
    /* Align here to ensure that the .bss section occupies space up to 
     _end. Align after .bss to ensure correct alignment even if the 
     .bss section disappears because there are no input sections. 
     FIXME: Why do we need it? When there is no .bss section, we don't 
     pad the .data section. */ 
    . = ALIGN(. != 0 ? 64/8 : 1); 
    } 

正如你可以看到ALIGN(. != 0 ? 64/8 : 1);告诉给对齐到8个字节

当生成的32位中的一个应用(克++ -m32 main.cpp中-Wl,-verbose),这是用于.bss段默认aligment:

.bss   : 
    { 
    *(.dynbss) 
    *(.bss .bss.* .gnu.linkonce.b.*) 
    *(COMMON) 
    /* Align here to ensure that the .bss section occupies space up to 
     _end. Align after .bss to ensure correct alignment even if the 
     .bss section disappears because there are no input sections. 
     FIXME: Why do we need it? When there is no .bss section, we don't 
     pad the .data section. */ 
    . = ALIGN(. != 0 ? 32/8 : 1); 
    } 

你.data段显然没有任何ALIGN默认链接脚本命令:

.data   : 
    { 
    *(.data .data.* .gnu.linkonce.d.*) 
    SORT(CONSTRUCTORS) 
    } 

相关链接:

+0

我使用-m32编译来验证它,谢谢所有的信息,skwlsp。 –

+1

非常有趣。任何人都有理由相信你的价值高于另一个价值吗? – glglgl