Feature flags in Rust
Rust allows to define feature flags to compile certain parts of a binary optionally. The Cargo Book has a section on them.
Cargo.toml
file can have a [features]
section. In this section, features can be defined, and they can allow other features.
[features]
my-feature = []
another-feature = ["my-feature"]
These markers are used in the code like:
#[cfg(feature = "my-feature")]
pub mod my_module;
The default features are listed under default
of [features]
section. If it’s not defined, it’s considered blank, so cargo build
supplies nothing as feature to the build system.
If you don’t want default
features added automatically, you can use --no-default-features
option in cargo
.
Starting from Rust 1.60, dependencies can be tied to features. When you define a dependency in [dependencies]
section, add optional = true
to its options, and in [features]
, use dep:package
syntax.
[dependencies]
pack = {version = "1.0", optional = true }
[features]
my-feature = ["dep:pack"]
This way, cargo doesn’t compile pack
if my-feature
is not enabled.
An caveat to use features is that they should be additive. There shouldn’t be a no-std
feature to remove stdlib dependency, instead you should define a std
feature and enable it by default. The reason behind this is that cargo makes sure there is a single copy of a package with only the necessary features enabled for all the binary. If you have a no-x
feature, this breaks the whole logic behind this operation.