__attribute__ 的 GCC 变量被视为已初始化

GCC variable with __attribute__ is treated like an initialized

如果我使用__attribute__(section(".section_i")),该变量被视为已初始化变量。 让我们快速看一下下面的例子(声明为全局变量):

 static unsigned char array[1024] __attribute__((section (".section_i")));

即使我没有初始化数组,上面的声明也会将数据大小增加 1k。 如何将 变量 标记为未初始化以避免增加数据部分?

static unsigned char array[1024] __attribute__((section (".section_i")));

The above declaration will increase the data size by 1k even though I have not initialized the array. How can I mark the variable as not initialized to avoid the increasing of data section?

好的,这实际上不是关于 "initialized" 或 "not initialized";这是关于变量是否被视为"common",不需要在可执行映像的数据中预先分配space。 (未链接的目标文件有段;完全链接的可执行文件和共享库有段。)

https://gcc.gnu.org/onlinedocs/gcc-7.3.0/gcc/Common-Variable-Attributes.html#Common-Variable-Attributes 这是用"common"属性控制的,所以

static unsigned char array[1024] __attribute((section(".section_i"), common));

被记录为做你想做的事(前提是你的链接器脚本配合;名为 .section_i 的部分必须放入适当的段;由于历史原因,该段的名称可能是 "BSS").但是,当我实际尝试使用我必须使用的编译器(确实是 GCC 7.3,x86_64-Linux 的本机编译器)时,它会生成可能无法正确执行操作的汇编语言。无论如何,你应该用你的编译器试试看;这很可能只是 x86-64 后端中的一个普通旧错误,并且对于您正在使用的任何嵌入式环境,在后端都可能不会重复这个错误。

请注意,在断定这不起作用之前,您应该检查完全链接的可执行映像。变量可能会在定义它的 目标文件 中占用 space,但不会在可执行文件中占用 space。

出于非常愚蠢的原因,我什至后悔自己知道并且不想尝试解释,将部分称为 .bss.section_i 而不是 .section_i 可能也有帮助。这也可能使编写链接描述文件变得更容易。