Sub topic 9
Cargo Features and Conditional Compilation
This chapter assumes you can read a Cargo.toml, know the difference between a package and a crate, and have used cargo build and cargo run. You should also understand how dependencies are declared. Here you will learn how Cargo features let one package build in several configurations, and how cfg attributes make the compiler include or skip code.
What a feature is
A feature is a named switch defined in Cargo.toml. When the switch is on, Cargo passes a --cfg feature="name" flag to rustc. Code guarded by #[cfg(feature = "name")] is compiled only when that flag is present. Code that is not selected is parsed but never type-checked or compiled into the output.
Features serve three common purposes:
- Optional functionality, such as serialization support, that not every user needs.
- Optional dependencies, so a crate is not downloaded or built unless a feature asks for it.
- Smaller or faster builds, since unused code and dependencies are left out.
Declaring features
Features live in the [features] table. This manifest, which this chapter builds on, declares an optional dependency and a feature that enables it.
[package]
name = "my_geometry"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
[dev-dependencies]
pretty_assertions = "1"
[features]
default = []
serde = ["dep:serde"]Three details matter here.
optional = truemarksserdeas a dependency that is built only when something enables it.serde = ["dep:serde"]defines a feature namedserde. Thedep:prefix means "turn on the dependency named serde". Usingdep:also stops Cargo from creating an automatic feature with the dependency's name, so you control the public feature names.default = []lists the features that are on unless the user opts out. An empty list means nothing is on by default.
The features = ["derive"] inside the dependency is different. It selects a feature of serde itself, and it is applied whenever serde is built.
Using a feature in code
The cfg attribute guards an item. The attribute below compiles the derive only when the serde feature is on.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct Square(pub u32);
pub fn area(s: &Square) -> u32 {
s.0 * s.0
}
#[cfg(feature = "serde")]
pub fn to_json(s: &Square) -> String {
serde_json::to_string(s).unwrap()
}
#[cfg(not(feature = "serde"))]
pub fn to_json(s: &Square) -> String {
format!("{{\"side\":{}}}", s.0)
}This shows the main forms of cfg:
#[cfg(...)]removes the item when the condition is false.#[cfg_attr(condition, attribute)]applies another attribute only when the condition is true.cfg(not(...)),cfg(all(...)), andcfg(any(...))combine conditions.
The example assumes serde_json is also available. In a real manifest you would list it as an optional dependency and include it in the serde feature, for example serde = ["dep:serde", "dep:serde_json"].
Both to_json functions have the same name and signature. Only one exists in any given build, so there is no conflict. If their signatures drifted apart, callers would break in only one configuration. That is the main maintenance cost of features.
Turning features on and off
You control features from the command line.
cargo build --features serde
cargo build --no-default-features
cargo build --all-features
cargo test --features "serde other"--features adds features. --no-default-features removes the default set. --all-features enables every feature. Inside a workspace, you can name the member explicitly with --features my_geometry/serde.
A dependent crate enables features in its own manifest.
[dependencies]
my_geometry = { version = "0.1", features = ["serde"] }Features are additive
Cargo builds each crate once per build, even when several crates depend on it. If crate A asks for my_geometry with feature x and crate B asks for it with feature y, Cargo compiles my_geometry once with both x and y. This is called feature unification.
So features should only add capability. Two rules follow from that:
- Do not write a feature that removes public items or changes the behavior of existing ones. Another crate in the dependency graph may turn it on and break you.
- Do not make two features mutually exclusive. If you must, detect the conflict with
compile_error!, and expect users to hit it.
#[cfg(all(feature = "fast", feature = "small"))]
compile_error!("features `fast` and `small` cannot both be enabled");A feature that only adds is safe to unify. A feature that selects one behavior in place of another is not.
Features that enable other features
A feature can turn on other features of the same package or of a dependency. This is how you build groups.
[features]
default = ["std"]
std = []
json = ["serde", "dep:serde_json"]
serde = ["dep:serde"]
full = ["json", "std"]Here full enables json and std. Enabling json also enables serde and the optional serde_json dependency. Cargo follows the chain and stops when no new features appear.
To enable a feature of a dependency, write "dependency/feature". For example, "serde?/derive" with the question mark enables derive on serde only if something else has already turned serde on. Without the ?, the dependency is turned on as well.
Choosing defaults
The default list is a public decision. Users who write my_geometry = "0.1" get every default feature. Adding a feature to default later can change builds for existing users, and removing one can break them.
Keep these guidelines in mind:
- Put only what most users want in
default. - Library crates should avoid heavy defaults, because every downstream crate pays for them.
- A user can opt out with
default-features = false, so keep the non-default build working and test it.
Other conditional compilation
Features are one source of cfg conditions. The compiler also sets conditions describing the target and the build.
| Condition | Meaning |
|---|---|
| `target_os = "linux"` | The operating system being built for |
| `target_pointer_width = "64"` | Pointer size in bits |
| `unix` and `windows` | Shorthand for operating system families |
| `debug_assertions` | On in debug builds, off in release builds by default |
| `test` | On when compiling for `cargo test` |
The last row explains #[cfg(test)] from the unit-testing chapter. It is the same mechanism, applied to a built-in condition.
Besides the attribute, the cfg! macro returns a boolean you can use in ordinary expressions.
fn main() {
if cfg!(debug_assertions) {
println!("debug build");
} else {
println!("release build");
}
#[cfg(target_os = "linux")]
println!("running on linux");
}Remember the difference. #[cfg(...)] removes code before it is checked. cfg!(...) expands to true or false, and both branches must still compile.
Testing across features
Because each feature combination is a different program, one cargo test run covers only one combination. Test the ones that matter.
cargo test
cargo test --no-default-features
cargo test --features serde
cargo test --all-featuresTests that depend on a feature should be guarded the same way as the code.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn area_works() {
assert_eq!(area(&Square(3)), 9);
}
#[cfg(feature = "serde")]
#[test]
fn json_has_expected_shape() {
assert_eq!(to_json(&Square(3)), "3");
}
}Integration tests and doc tests can fail to compile when a feature is off, because they use only the public API. Guard them with #![cfg(feature = "serde")] at the top of a test file, or declare required-features for a target in Cargo.toml.
Common mistakes
- Referencing an optional dependency in code without a matching
cfg. The build fails when the feature is off. - Forgetting to test with
--no-default-features, so the minimal build silently breaks. - Typing a feature name that does not exist in
[features]. Recent compilers warn about unexpectedcfgnames, so read those warnings. - Using features for mutually exclusive choices, which unification can break.
- Putting a heavy dependency in
defaultand forcing it on every user.
Exercise
A crate has default = ["std"] and an optional dependency serde exposed through serde = ["dep:serde"]. You want a build with no default features but with serialization. Which command do you run, and what happens if another crate in your dependency graph also enables std on the same crate?
Show answer
Run cargo build --no-default-features --features serde. This turns off std for your request and turns on serde. If another crate in the graph enables std, feature unification builds the crate once with both std and serde on, so your build also gets std. Features are additive, so you cannot rely on std being off.
Exercise
What is the difference between #[cfg(debug_assertions)] on a statement and if cfg!(debug_assertions) { ... }?
Show answer
The attribute removes the statement before type checking, so the code inside may reference items that do not exist in the other configuration. The cfg! macro becomes the constant true or false, and both branches of the if must still compile in every configuration.