Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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.
// Outer attribute: applies only to the item immediately following it
#[cfg(predicate)]
struct ConditionalStruct;

// Inner attribute: applies to the entire enclosing scope (e.g., top of a file)
#![cfg(predicate)]

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”)]
2. **Name-Value Pairs:** Evaluates to true if the specific configuration key matches the provided string value. These are typically populated by the compiler based on the target triple.
   ```rust
#[cfg(target_os = "linux")]
#[cfg(target_arch = "x86_64")]
#[cfg(target_env = "msvc")]
  1. Boolean Flags: Evaluates to true if the configuration flag is currently set in the compilation environment.
#[cfg(test)] #[cfg(debug_assertions)]

## Logical Operators
Predicates can be combined or inverted using built-in logical operators. These operators can be nested arbitrarily deep.
* **`all(...)`**: Evaluates to true if *every* comma-separated predicate within the parentheses evaluates to true.
  ```rust
#[cfg(all(target_os = "windows", target_arch = "x86_64"))]
fn windows_x64_only() {}
  • 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()
* **`not(...)`**: Evaluates to true if the single predicate within the parentheses evaluates to false.
  ```rust
#[cfg(not(test))]
fn exclude_from_tests() {}

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.
// If the "serialization" feature is enabled, this expands to:
// #[derive(Serialize, Deserialize)]
// struct MyData;
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
struct MyData;

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.

# Passing a custom flag via rustc
rustc --cfg custom_flag main.rs
// Evaluates to true based on the compiler flag above
#[cfg(custom_flag)]
fn custom_implementation() {}

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.
fn check_os() {
    let is_windows = cfg!(target_os = "windows");
    
    if is_windows {
        // This block is still parsed and type-checked on non-Windows platforms,
        // but the compiler will optimize the branch away.
    }
}
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.
Master Rust with Deep Grasping Methodology!Learn More