Rust has a special attribute, #[cfg]
`#[cfg]`, which allows you to compile code
based on a flag passed to the compiler. It has two forms:
#[cfg(foo)] #[cfg(bar = "baz")]
They also have some helpers:
fn main() { #[cfg(any(unix, windows))] fn foo() {} #[cfg(all(unix, target_pointer_width = "32"))] fn bar() {} #[cfg(not(foo))] fn not_foo() {} }#[cfg(any(unix, windows))] #[cfg(all(unix, target_pointer_width = "32"))] #[cfg(not(foo))]
These can nest arbitrarily:
fn main() { #[cfg(any(not(unix), all(target_os="macos", target_arch = "powerpc")))] fn foo() {} }
#[cfg(any(not(unix), all(target_os="macos", target_arch = "powerpc")))]
As for how to enable or disable these switches, if you’re using Cargo,
they get set in the [features]
`features` section of your Cargo.toml
`Cargo.toml`:
[features]
# no features by default
default = []
# The “secure-password” feature depends on the bcrypt package.
secure-password = ["bcrypt"]
When you do this, Cargo passes along a flag to rustc
`rustc`:
--cfg feature="${feature_name}"
The sum of these cfg
`cfg` flags will determine which ones get activated, and
therefore, which code gets compiled. Let’s take this code:
#[cfg(feature = "foo")] mod foo { }
If we compile it with cargo build --features "foo"
`cargo build --features "foo", it will send the
`, it will send the --cfg feature="foo"
`--cfg
feature="foo"flag to
` flag to rustc
`rustc, and the output will have the
`, and the output will have the mod foo
`mod fooin it. If we compile it with a regular
` in it.
If we compile it with a regular cargo build
`cargo build, no extra flags get passed on, and so, no
`, no extra flags get passed on,
and so, no foo
`foo` module will exist.
You can also set another attribute based on a cfg
`cfgvariable with
` variable with cfg_attr
`cfg_attr`:
#[cfg_attr(a, b)]
Will be the same as #[b]
`#[b]if
` if a
`ais set by
` is set by cfg
`cfg` attribute, and nothing otherwise.
The cfg!
`cfg!` syntax extension lets you use these kinds of flags
elsewhere in your code, too:
if cfg!(target_os = "macos") || cfg!(target_os = "ios") { println!("Think Different!"); }
These will be replaced by a true
`trueor
` or false
`false` at compile-time, depending on the
configuration settings.