众所周知,我们可以使用“-ffunction-sections -fdata-sections”和“-Wl, --gc-sections”来删除未使用的代码和数据。但是如何删除未使用的 bss 符号?
1 回答
When we say that global variables initialized with 0 "are" in the bss, actually the variable does not exist in the binary.
When your program starts to run, it will reserve a section in RAM and fill this section with zeros. Places in your program that access a variable in bss will point to this section.
Variables in bss do not occupy space in the binary image.
The difference between the bss and the data is just that as we know some values are zeros at the beginning, we don't need to stock them in the binary image, thus reducing the size of the executable.
In RAM (or virtual memory, where your program will run), with those flags you mentioned, the variables in bss are removed too.
You can check this with a simple program : If you are using linux, go to /tmp and write a hello.c
#include<stdio.h>
int var1 = 0;
int var2 = 2;
int main()
{
printf("Hello\n");
return 0;
}
now, type:
make hello
objdump --sym hello | less
You will see that var1 and var2 are there.
now type :
rm hello && make hello CFLAGS="-fdata-sections -ffunction-sections -Wl,--gc-sections"
objdump --sym hello | less
You will not find them anymore.