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.