2016-03-05 126 views
4

第一種情況:奇怪的行爲

#include <stdio.h> 

int main(void) 
{ 
    return 0; 
} 

尺寸輸出:

text  data  bss  dec  hex filename 

1115  552  8 1675  68b ./a.out 

第二種情況:

#include <stdio.h> 

int global; // new line compared to previous case 

int main(void) 
{ 
    return 0; 
} 

尺寸輸出:

text  data  bss  dec  hex filename 
1115  552  8 1675  68b ./a.out 

理想的情況下應該是:

bss=12 and all other (text and data) same 

第三屆情況:

#include <stdio.h> 

int global; 

int main(void) 
{ 
    static int i; // new line compared to previous case 
    return 0; 
} 

尺寸輸出:

text  data  bss  dec  hex filename 
1115  552  16 1683  693 ./a.out 

這是正確的

爲什麼在第二情況下,輸出是不正確的?

+3

你的優化標誌是什麼? – zoul

+5

這就好像被編譯器忽略,因爲它根本沒有被使用。 – Ian

+1

在第三種情況下,您是否保留'global'變量? –

回答

2

您可能正在編譯64位體系結構,其中您將內存對齊到8個字節(64位)。

A作爲一個在你的第一個情況下,簡單的程序,有一個4字節的起始BSS,但8個字節分配給對齊的目的,從而爲你聲明的全球變量,你填補了留下的4個字節。

聲明另一個4字節的變量會將8個字節添加到bss,直到它也被填充,等等。