2014-01-15 27 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