【问题标题】:How to check release / debug builds using cfg in Rust?如何在 Rust 中使用 cfg 检查发布/调试版本?
【发布时间】:2017-01-05 09:43:59
【问题描述】:

使用 C 预处理器很常见,

#if defined(NDEBUG)
    // release build
#endif

#if defined(DEBUG)
    // debug build
#endif

货物的大致等价物是:

  • cargo build --release 发布。
  • cargo build 用于调试。

如何使用 Rust 的 #[cfg(...)] 属性或 cfg!(...) 宏来做类似的事情?

我知道 Rust 的预处理器不像 C 那样工作。我检查了文档和this page lists some attributes(假设这个列表很全面)

debug_assertions 可以检查,但在用于检查更一般的调试情况时可能会产生误导。

我不确定这个问题是否应该与 Cargo 相关。

【问题讨论】:

标签: debugging rust preprocessor rust-cargo


【解决方案1】:

您可以使用debug_assertions 作为适当的配置标志。它适用于#[cfg(...)] 属性和cfg! 宏:

#[cfg(debug_assertions)]
fn example() {
    println!("Debugging enabled");
}

#[cfg(not(debug_assertions))]
fn example() {
    println!("Debugging disabled");
}

fn main() {
    if cfg!(debug_assertions) {
        println!("Debugging enabled");
    } else {
        println!("Debugging disabled");
    }

    #[cfg(debug_assertions)]
    println!("Debugging enabled");

    #[cfg(not(debug_assertions))]
    println!("Debugging disabled");

    example();
}

此配置标志在this discussion 中被命名为执行此操作的正确方法。目前没有更合适的内置条件。

来自reference

debug_assertions - 编译时默认启用 优化。这可用于启用额外的调试代码 开发,但不在生产中。例如,它控制 标准库的 debug_assert! 宏的行为。

另一种稍微复杂一点的方法是使用 #[cfg(feature = "debug")] 并创建一个构建脚本,为您的 crate 启用“调试”功能,如 here 所示。

【讨论】:

  • 仅作记录,这在构建脚本中不起作用。只是为自己找到了这个,所以我想我会分享。
  • 如果是#[cfg(debug_assertions)] 而不是#[cfg(debug_assertions)] {...},就会有error[E0658]: attributes on expressions are experimentalerror: removing an expression is not supported in this position。 Rust 1.42.0
猜你喜欢
  • 2010-09-18
  • 2023-01-15
  • 1970-01-01
  • 2012-11-13
  • 2010-10-27
  • 2020-08-02
  • 1970-01-01
相关资源
最近更新 更多