1 % Conditional Compilation
3 Rust has a special attribute, `#[cfg]`, which allows you to compile code
4 based on a flag passed to the compiler. It has two forms:
14 They also have some helpers:
17 #[cfg(any(unix, windows))]
20 #[cfg(all(unix, target_pointer_width = "32"))]
27 These can nest arbitrarily:
30 #[cfg(any(not(unix), all(target_os="macos", target_arch = "powerpc")))]
34 As for how to enable or disable these switches, if you’re using Cargo,
35 they get set in the [`[features]` section][features] of your `Cargo.toml`:
37 [features]: http://doc.crates.io/manifest.html#the-features-section
41 # no features by default
44 # The “secure-password” feature depends on the bcrypt package.
45 secure-password = ["bcrypt"]
48 When you do this, Cargo passes along a flag to `rustc`:
51 --cfg feature="${feature_name}"
54 The sum of these `cfg` flags will determine which ones get activated, and
55 therefore, which code gets compiled. Let’s take this code:
58 #[cfg(feature = "foo")]
63 If we compile it with `cargo build --features "foo"`, it will send the `--cfg
64 feature="foo"` flag to `rustc`, and the output will have the `mod foo` in it.
65 If we compile it with a regular `cargo build`, no extra flags get passed on,
66 and so, no `foo` module will exist.
70 You can also set another attribute based on a `cfg` variable with `cfg_attr`:
77 Will be the same as `#[b]` if `a` is set by `cfg` attribute, and nothing otherwise.
81 The `cfg!` [syntax extension][compilerplugins] lets you use these kinds of flags
82 elsewhere in your code, too:
85 if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
86 println!("Think Different!");
90 [compilerplugins]: compiler-plugins.html
92 These will be replaced by a `true` or `false` at compile-time, depending on the
93 configuration settings.