我如何编写将全局变量/静态变量放在填充的 BSS 段中的 Rust 代码?

How do I write Rust code that places globals / statics in a populated BSS segment?

我正在试验用 Rust 编写裸机嵌入式系统。 C 启动代码中通常要做的事情之一是对任何全局或静态未初始化变量的 BSS 段进行零初始化。

然而,在 Rust 中,我不知道如何创建任何全局或静态未初始化变量(即使使用 unsafe 代码)。换句话说,我不知道如何编写任何 Rust 代码,以便编译器用某些东西填充 BSS 段。

我试过了...

static BSS_Data: i32 = unsafe { core::mem::uninitialized() };

..但编译器拒绝了它。

有没有什么方法可以编写 Rust 代码(unsafe 或其他)来填充 BSS 段?在任何完全用 Rust 编写的程序中,BSS 段是否保证始终为空?

.bss 段的目的是加速所有值为零的静态存储持续时间变量的初始化。而且还要保存NVM,因为将x字节的值都0保存在flash中,然后将它们一一复制到RAM中是没有意义的。

您的问题的解决方案可能是声明一个静态变量并将其显式初始化为零。因为所有初始化为零值的具有静态存储持续时间的变量最终都在 .bss 中。

作为此的副作用,所有未初始化的静态存储持续时间变量也以 .bss 结束。因为在 C(以及 C 派生的 from/inspired 语言中)有一个要求,如果一个具有静态存储持续时间的变量没有被程序员显式初始化,它必须被初始化为值零。

例如C11标准6.7.9中正式规定:

If an object that has static or thread storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;


Pseudo code example of how .data and .bss initialization will differ.

More info of the different memory types and where different kind of variables end up in an embedded system.