Reputation: 157
I am trying to conditionally compile a certain section of code given two conditions:
My stripped-down Cargo.toml
has this generic structure
[package]
...
[features]
simulation = []
[dependencies]
crate1 = ...
crate2 = ...
[target.'cfg(target_os = "linux")'.dependencies]
crate3 = ...
crate4 = ...
Is there a way to specify in my rust code that I want one section of code to compile when the build is done via Linux and with the "simulation" feature flag off, and then another section of code to compile when the build is done via Linux with the "simulation" feature flag on? Something like:
#[cfg(feature = "simulation")] && #[cfg(target_os = "linux")] { println!("run some code here"); }
!#[cfg(feature = "simulation)] && #[cfg(target_os = "linux")] { println!("run some other code here"); }
Upvotes: 2
Views: 1264
Reputation: 43842
The conditional compilation system offers a full set of Boolean operators under the names any
, all
, and not
. Translating your example to working syntax:
#[cfg(all(feature = "simulation", target_os = "linux"))] {
println!("run some code here");
}
#[cfg(all(not(feature = "simulation"), target_os = "linux"))] {
println!("run some other code here");
}
If you have complex conditions to check then you might want to use the cfg_if
macro crate to help. In this case, though, there's a decent simplification that will actually work without any macros and not using all()
either: just nest the conditions so you can write the common one only once.
#[cfg(target_os = "linux")] {
#[cfg(feature = "simulation")]
println!("run some code here");
#[cfg(not(feature = "simulation"))]
println!("run some other code here");
}
Upvotes: 3