ide*_*n42 24 debugging preprocessor rust rust-cargo
使用C预处理器,这是常见的,
#if defined(NDEBUG)
// release build
#endif
#if defined(DEBUG)
// debug build
#endif
Run Code Online (Sandbox Code Playgroud)
货物的粗略等价物是:
cargo build --release 发布.cargo build 用于调试.如何使用Rust的#[cfg(...)]属性或cfg!(...)宏来做类似的事情?
我知道Rust的预处理器不像C那样工作.我查看了文档,此页面列出了一些属性.(假设此列表是全面的)
debug_assertions 可以检查,但用于检查更一般的调试情况可能会误导.
我不确定这个问题是否与货物有关.
Pav*_*hov 30
您可以使用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();
}
Run Code Online (Sandbox Code Playgroud)
在此讨论中,此配置标志被命名为正确的方法.目前没有更合适的内置条件.
来自参考:
debug_assertions- 在没有优化的情况下进行编译时默认启用.这可用于在开发中启用额外的调试代码,但不能在生产中启用.例如,它控制标准库debug_assert!宏的行为.
另一种,稍微复杂的方法,是使用#[cfg(feature = "debug")]和创建构建脚本,使"调试"功能,为您的板条箱,如图所示这里.