条件编译可以通过两种不同的操作符实现,如下: - cfg属性:在属性位置中使用#[cfg(...)] - cfg!宏:在布尔表达式中使用cfg!(...)
Configuration conditional checks are possible through two different operators:
- the
cfg
attribute:#[cfg(...)]
in attribute position - the
cfg!
macro:cfg!(...)
in boolean expressions
While the former enables conditional compilation, the latter conditionally evaluates to true
or false
literals allowing for checks at run-time. Both utilize identical argument syntax.
// This function only gets compiled if the target OS is linux #[cfg(target_os = "linux")] fn are_you_on_linux() { println!("You are running linux!"); } // And this function only gets compiled if the target OS is *not* linux #[cfg(not(target_os = "linux"))] fn are_you_on_linux() { println!("You are *not* running linux!"); } fn main() { are_you_on_linux(); println!("Are you sure?"); if cfg!(target_os = "linux") { println!("Yes. It's definitely linux!"); } else { println!("Yes. It's definitely *not* linux!"); } }
[root@bogon cfg]# ls Cargo.lock Cargo.toml README.md src [root@bogon cfg]# cargo build Compiling hello_world v0.1.0 (/data2/rust/cfg) Finished dev [unoptimized + debuginfo] target(s) in 0.39s [root@bogon cfg]# cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.01s Running `target/debug/hello_world` You are running linux! Are you sure? Yes. It's definitely linux! [root@bogon cfg]#
//main.rs #[cfg(some_condition)] fn conditional_function() { println!("condition met!"); } fn main() { conditional_function(); println!("Hello, world!"); }
[root@bogon src]# rustc --cfg some_condition main.rs [root@bogon src]# ./main condition met! Hello, world! [root@bogon src]# rustc main.rs error[E0425]: cannot find function `conditional_function` in this scope --> main.rs:8:5 | 8 | conditional_function(); | ^^^^^^^^^^^^^^^^^^^^ not found in this scope error: aborting due to previous error For more information about this error, try `rustc --explain E0425`. [root@bogon src]#