在 Rust 中,可以执行 conditional compilation如下。
#[cfg(rust_version = "1.10")]
fn my_func() {}
是否可以为 cfg
定义变量以在同一源文件中检查?
例如:
// leave off, just a quick test to enable when troubleshooting.
#define use_counter 1 // C style (not valid Rust)
#[cfg(use_counter == "1")]
static mut fn_counter: usize = 0;
fn my_func() {
#[cfg(use_counter = "1")]
unsafe { fn_counter += 1; }
}
main () {
// code calling 'my_func'
// print how many times the function is called.
#[cfg(use_counter = "1")]
unsafe { println!("Function count {}", fn_counter); }
}
我不是在问如何编写一个函数计数器,它只是一个可选地向源文件中插入逻辑的示例。
最佳答案
是的,这写成#[cfg(use_counter)]
。这些标志可以在编译时在命令行上启用或禁用,并且不会在 Cargo.toml 中公开。
fn main() {
#[cfg(use_counter)]
println!("counter is enabled");
}
使用 Cargo,在禁用功能的情况下运行:
$ cargo run
使用 Cargo,在启用的功能下运行:
$ RUSTFLAGS="--cfg use_counter" cargo run
直接在禁用功能的情况下编译:
$ rustc src/main.rs
编译启用的特性:
$ rustc src/main.rs --cfg use_counter
关于rust - 是否可以在源文件中声明配置标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38928839/