Answer#
Rust has two ways to say "only on this system". They behave differently.
#[cfg(...)]is an attribute. The compiler drops the item (a function, a module, a statement) when the condition is false. The dropped code is not type-checked, so it can mention a crate or an API that only exists on the other system.cfg!(...)is a macro that expands totrueorfalse. Both branches of theifstay in the program and must compile on every system.
// #[cfg(...)] removes code before it is compiled; cfg!(...) is a plain bool, and both branches must compile.
#[cfg(target_os = "windows")]
fn shortcut_name() -> &'static str {
"Ctrl+,"
}
#[cfg(target_os = "macos")]
fn shortcut_name() -> &'static str {
"Cmd+,"
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
fn shortcut_name() -> &'static str {
"Ctrl+,"
}
fn main() {
println!("Settings shortcut: {}", shortcut_name());
if cfg!(target_os = "macos") {
println!("cfg!: running on macOS");
} else {
println!("cfg!: not macOS");
}
// Debug builds only:
#[cfg(debug_assertions)]
println!("debug build");
#[cfg(not(debug_assertions))]
println!("release build");
}Settings shortcut: Ctrl+,
cfg!: not macOS
debug buildThree versions of shortcut_name exist in the source, and exactly one of them is compiled. The last one, with not(any(...)), is a safety net so that the program still builds on Linux; without it, a build for another system fails with "cannot find function shortcut_name".
When to use which:
| You want | Use |
|---|---|
| to call an API that exists on one system only | #[cfg(...)] on the function or module |
| to pick a constant or a string | cfg!(...) (or a #[cfg] pair, if the values need different types) |
| to add a dependency for one system only | [target.'cfg(...)'.dependencies] (see the Cargo.toml thread) |
cfg(windows) and cfg(unix) are shorthand for the whole family. macOS counts as unix, so cfg(unix) is true on macOS too; use target_os = "macos" when you mean only Apple's system.
Common mistakes#
- Using
if cfg!(target_os = "macos") { mac_only_call() }wheremac_only_calldoes not exist on Windows. Theifis not removed, so the build fails. Use the attribute. - Forgetting the fallback for other systems, so a Linux CI job fails.
- Testing only one system. A
#[cfg]branch you never compile is code nobody has checked.
Related questions#
How do I see which cfg values are set?#
rustc --print cfg lists them for the current target.
Sources#
- The Rust Reference, Conditional compilation: https://doc.rust-lang.org/reference/conditional-compilation.html (read 2026-12-05)
- std::cfg macro: https://doc.rust-lang.org/std/macro.cfg.html (read 2026-12-05)