How to create conditional compilation in Rust

Use #[cfg(...)] attributes to include or exclude Rust code based on target OS, debug mode, or custom build flags.

Use the #[cfg(...)] attribute to include or exclude code based on conditions like target OS, debug mode, or custom flags.

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

#[cfg(target_os = "windows")]
fn run_on_windows() {
    println!("Running on Windows");
}

fn main() {
    #[cfg(target_os = "linux")]
    run_on_linux();

    #[cfg(target_os = "windows")]
    run_on_windows();
}

To use custom flags, add them in Cargo.toml under [package.metadata] or pass them via RUSTFLAGS="--cfg my_flag" when compiling.