rust - 禁用堆分配的 Rust 编译器标志是什么?

标签 rust

我正在阅读 an article这表明 Rust 有一个编译器选项来禁用堆分配:

Rust has a number of standard library features that rely on the heap, like boxes. However, Rust has compiler directives to completely disable any heap-using language features, and statically verify that none of these features are being used. It is entirely practical to write a Rust program with no heap usage.

在编译时检查任何错误的堆分配的能力对我来说非常有值(value)。你如何在 Rust 中做到这一点?我在 rustc man page 中没有看到任何相关标志.

最佳答案

没有这样的编译器标志,虽然我不认为那是这篇文章的意思:

Rust has compiler directives

我会将“指令”解析为一个属性,类似于#[foo]。据我所知,目前还没有实现此目标的特性。

请注意,您的文章早于 Rust 1.0:

Rust, version 0.11


最接近的是避免使用标准库,只使用 the core library .这避开了 liballoc 的使用,这是分配的主要机制。这样做可以防止像 BoxString 这样的类型存在,这是一个非常强大的静态保证。

#![no_std]

pub fn example() {
    Box::new(42);
}
error[E0433]: failed to resolve. Use of undeclared type or module `Box`
 --> src/lib.rs:4:5
  |
4 |     Box::new(42);
  |     ^^^ Use of undeclared type or module `Box`

但是,没有什么能阻止您重写 liballoc 中的相同代码并自行分配内存。您还可以链接到分配内存的现有库。没有神奇的编译器 channel 可以检测堆分配。

另见:

关于rust - 禁用堆分配的 Rust 编译器标志是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51934079/

相关文章:

macros - 错误 : variable 'x' is still repeating at this depth

rust - "found struct ` ThereIsNoIteratorInRepetition `"尝试使用 `quote!` 在向量上重复时

rust - 在 Rust 中实例化枚举时出错

rust - 惯用地访问可变和不可变向量的元素

windows - 为什么 usize::max_value() 在 64 位 Windows 上返回无符号 32 位整数的最大值?

rust - 特征签名中 `Self` 的生命周期参数

vector - 如何从 Rust 函数返回向量元素?

rust - 匹配语句中明显未使用的变量

rust - 我的 EXTI0 中断处理程序没有被覆盖/正常工作(STM32F3Discovery)

rust - 如何将 future::join_all() 转换为使用 FuturesUnordered?