debugging 如何在Rust中使用cfg检查发布/调试版本?

jobtbby3  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(128)

对于C预处理器,

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

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

Cargo的粗略等价物是:

  • cargo build --release用于释放。
  • cargo build用于调试。

如何使用Rust的#[cfg(...)]属性或cfg!(...)宏来做类似的事情?
我知道Rust的预处理器不像C那样工作。我检查了文档,这个页面列出了一些属性。(假设这个列表是全面的)
可以检查debug_assertions,但当用于检查更一般的调试情况时,它可能会产生误导。
我不知道这个问题是否应该与货物有关。

v09wglhw

v09wglhw1#

您可以使用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所示。

相关问题