我想知道链接器如何计算.bss
节的大小?
我有一个带有两个变量的测试程序,一个初始化为零,另一个初始化为非零。我希望 .bss 的大小是 4 并且确实如此。
# cat test.c && gcc -o test.o -c test.c && ld -o test test.o && readelf -Ss test
int _start=0;
int a = 2;
......
Section Headers:
[Nr] Name Type Address Offset
Size EntSize Flags Link Info Align
[ 1] .data PROGBITS 00000000006000b0 000000b0
0000000000000004 0000000000000000 WA 0 0 4
[ 2] .bss NOBITS 00000000006000b4 000000b4
0000000000000004 0000000000000000 WA 0 0 4
.....
Symbol table '.symtab' contains 11 entries:
Num: Value Size Type Bind Vis Ndx Name
6: 00000000006000b4 4 OBJECT GLOBAL DEFAULT 2 _start
10: 00000000006000b0 4 OBJECT GLOBAL DEFAULT 1 a
然后我添加第二个零初始化变量。这次我希望.bss的大小是8,但它是12(0xc)。
# cat test.c && gcc -o test.o -c test.c && ld -o test test.o && readelf -Ss test
int _start=0;
int a = 2;
int b = 0;
......
Section Headers:
[Nr] Name Type Address Offset
Size EntSize Flags Link Info Align
[ 1] .data PROGBITS 00000000006000b0 000000b0
0000000000000004 0000000000000000 WA 0 0 4
[ 2] .bss NOBITS 00000000006000b4 000000b4
000000000000000c 0000000000000000 WA 0 0 4
......
Symbol table '.symtab' contains 12 entries:
Num: Value Size Type Bind Vis Ndx Name
6: 00000000006000b8 4 OBJECT GLOBAL DEFAULT 2 b
7: 00000000006000b4 4 OBJECT GLOBAL DEFAULT 2 _start
11: 00000000006000b0 4 OBJECT GLOBAL DEFAULT 1 a
我继续添加第三个零初始化变量。这次我希望 .bss 的大小是 12 并且确实如此。
# cat test.c && gcc -o test.o -c test.c && ld -o test test.o && readelf -Ss test
int _start=0;
int a = 2;
int b = 0;
int c = 0;
......
Section Headers:
[Nr] Name Type Address Offset
Size EntSize Flags Link Info Align
[ 0] NULL 0000000000000000 00000000
0000000000000000 0000000000000000 0 0 0
[ 1] .data PROGBITS 00000000006000b0 000000b0
0000000000000004 0000000000000000 WA 0 0 4
[ 2] .bss NOBITS 00000000006000b4 000000b4
000000000000000c 0000000000000000 WA 0 0 4
......
Symbol table '.symtab' contains 13 entries:
Num: Value Size Type Bind Vis Ndx Name
6: 00000000006000b8 4 OBJECT GLOBAL DEFAULT 2 b
7: 00000000006000b4 4 OBJECT GLOBAL DEFAULT 2 _start
8: 00000000006000bc 4 OBJECT GLOBAL DEFAULT 2 c
12: 00000000006000b0 4 OBJECT GLOBAL DEFAULT 1 a
我继续添加第四个零初始化变量。这次我希望.bss 的大小是16,但它是20(0x14)。
# cat test.c && gcc -o test.o -c test.c && ld -o test test.o && readelf -Ss test
int _start=0;
int a = 2;
int b = 0;
int c = 0;
int d = 0;
......
Section Headers:
[Nr] Name Type Address Offset
Size EntSize Flags Link Info Align
[ 1] .data PROGBITS 00000000006000b0 000000b0
0000000000000004 0000000000000000 WA 0 0 4
[ 2] .bss NOBITS 00000000006000b4 000000b4
0000000000000014 0000000000000000 WA 0 0 4
......
Symbol table '.symtab' contains 14 entries:
Num: Value Size Type Bind Vis Ndx Name
6: 00000000006000b8 4 OBJECT GLOBAL DEFAULT 2 b
7: 00000000006000b4 4 OBJECT GLOBAL DEFAULT 2 _start
8: 00000000006000bc 4 OBJECT GLOBAL DEFAULT 2 c
10: 00000000006000c0 4 OBJECT GLOBAL DEFAULT 2 d
13: 00000000006000b0 4 OBJECT GLOBAL DEFAULT 1 a
有时结果符合我的预期,有时则不然。还有其他因素会影响链接器的输出吗?