Narnian12
Narnian12

Reputation: 157

Combine Conditional Compilation Parameters

I am trying to conditionally compile a certain section of code given two conditions:

  1. Whether the build is done via Linux or not
  2. Whether the user-specified feature flag "simulation" is set to true or not

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

Answers (1)

Kevin Reid
Kevin Reid

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

Related Questions