How to Conditionally Compile Code in Rust with cfg

Use the #[cfg(...)] attribute to include or exclude Rust code based on specific build conditions like OS or custom flags.

Use the #[cfg(...)] attribute to conditionally include or exclude code based on build configuration. Place the attribute directly above the item you want to conditionally compile, such as a function or module.

#[cfg(target_os = "linux")]
fn linux_specific() {
    println!("Running on Linux");
}

#[cfg(not(target_os = "linux"))]
fn other_os() {
    println!("Running on something else");
}

To enable custom flags, pass --cfg to the compiler via RUSTFLAGS or define them in Cargo.toml under [profile.dev] or [profile.release].