如何在Rust中使用cfg检查发布/调试版本? [英] How to check release / debug builds using cfg in Rust?
问题描述
使用C预处理程序很常见,
With the C pre-processor it's common to do,
#if defined(NDEBUG)
// release build
#endif
#if defined(DEBUG)
// debug build
#endif
货物的大致等价物是:
-
货运版本--release
进行发布. -
货物建造
以进行调试.
cargo build --release
for release.cargo build
for debug.
Rust的#[cfg(...)]
属性或 cfg!(...)
宏如何用于执行类似操作?
How would Rust's #[cfg(...)]
attribute or cfg!(...)
macro be used to do something similar?
我知道Rust的预处理器不能像C那样工作.我检查了文档,并此页面列出了一些属性.(假设此列表是详尽的)
I understand that Rust's pre-processor doesn't work like C's. I checked the documentation and this page lists some attributes. (assuming this list is comprehensive)
debug_assertions
可以检查,但是在检查更一般的调试情况时可能会产生误导.
debug_assertions
could be checked, but it may be misleading when used to check for the more general debugging case.
我不确定这个问题是否与货运有关.
I'm not sure if this question should be related to Cargo or not.
推荐答案
您可以使用 #[cfg(..)]
属性和 cfg!
宏:
You can use debug_assertions
as the appropriate configuration flag. It works with both #[cfg(...)]
attributes and the cfg!
macro:
#[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 configuration flag was named as a correct way to do this in this discussion. There is no more suitable built-in condition for now.
来自参考:
debug_assertions
-编译时默认情况下未启用优化.这可以用来启用额外的调试代码开发但没有生产.例如,它控制着标准库的debug_assert!
宏的行为.
debug_assertions
- Enabled by default when compiling without optimizations. This can be used to enable extra debugging code in development but not in production. For example, it controls the behavior of the standard library'sdebug_assert!
macro.
另一种稍微复杂些的方法是使用#[cfg(feature ="debug")]
并创建一个启用"debug"功能的构建脚本.板条箱功能,如此处.
An alternative, slightly more complicated way, is to use #[cfg(feature = "debug")]
and create a build script that enables a "debug" feature for your crate, as shown here.
这篇关于如何在Rust中使用cfg检查发布/调试版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!