Skip to main content
The cfg (configuration) attribute is a built-in Rust attribute used for conditional compilation. It instructs the Rust compiler (rustc) to include or exclude the annotated Abstract Syntax Tree (AST) node based on compile-time configuration predicates. If the predicate evaluates to false, the compiler completely strips the item from the AST. This evaluation and stripping occur during the macro expansion phase, meaning macros can generate code containing cfg attributes, which the compiler will then evaluate in that same pass.

Syntax and Placement

The attribute can be applied as an outer attribute to specific items (functions, structs, modules, statements, etc.) or as an inner attribute to apply to the entire enclosing module or crate.

Configuration Predicates

The cfg attribute evaluates predicates that fall into three primary categories:
  1. Cargo Features: The most idiomatic way developers interact with cfg is through Cargo features. Cargo automatically translates features defined in Cargo.toml into name-value pair flags (--cfg feature="name") passed to rustc.
#[cfg(feature = “experimental_api”)]
  1. Boolean Flags: Evaluates to true if the configuration flag is currently set in the compilation environment.
#[cfg(test)] #[cfg(debug_assertions)]
  • any(...): Evaluates to true if at least one comma-separated predicate within the parentheses evaluates to true.
#[cfg(any(target_os = “macos”, target_os = “ios”))] fn apple_platforms_only()

The cfg_attr Attribute

The cfg_attr attribute is a closely related built-in attribute used to conditionally apply other attributes to an item. It takes a configuration predicate followed by a comma-separated list of attributes to apply if the predicate evaluates to true.

Custom Configurations

Beyond Cargo features and built-in compiler targets, custom configuration flags can be passed directly to rustc using the --cfg command-line flag or emitted via a build.rs script using the cargo::rustc-cfg instruction.

The cfg! Macro

While the #[cfg] attribute removes code from the AST, Rust also provides the cfg!() macro for inline boolean evaluation. The macro takes the exact same predicates as the attribute but evaluates to a boolean literal (true or false) at compile time.
Unlike the #[cfg] attribute, code inside a branch controlled by cfg!() must still be syntactically valid and pass the borrow checker and type checker on all platforms, because the AST nodes are not stripped.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More