Skip to main content

cfg

Attribute cfg 

Source
Expand description

Used for conditional compilation.

The cfg attribute allows compiling an item under specific conditions, otherwise it will be ignored.

// Only compiles this function for Linux.
#[cfg(target_os = "linux")]
fn platform_specific() {
    println!("Running on Linux");
}

// Only compiles this function if not for Linux.
#[cfg(not(target_os = "linux"))]
fn platform_specific() {
    println!("Running on something else");
}

Depending on the platform you’re targeting, only one of these two functions will be considered during the compilation.

Conditions can also be combined with all(...), any(...), and not(...).

  • all: True if all given predicates are true.
  • any: True if at least one of the given predicates is true.
  • not: True if the predicate is false and false if the predicate is true.
#[cfg(all(unix, target_pointer_width = "64"))]
fn unix_64bit() {
}

If you want to use this mechanism in an if condition in your code, you can use the cfg! macro. To conditionally apply an attribute, see cfg_attr.

For more information, see the Reference on the cfg attribute.