Common Standard Macros
cfg!
The cfg! macro evaluates a compile-time configuration predicate (target_os, target_arch, feature, debug_assertions, unix, windows, and all() / any() / not() combinators) and expands to a compile-time bool literal (true or false).
cfg!(...) Macro vs. #[cfg(...)] Attribute
Rust provides two ways to branch on compile-time configuration flags, and their difference in type-checking is critical:
| Construct | Syntax | What Happens to the Inactive Branch? | Can Reference Platform-Specific APIs? |
|---|---|---|---|
#[cfg(...)] attribute |
#[cfg(target_os = "macos")] fn f() {} |
Completely stripped from AST before name resolution and type checking | Yes (inactive branch can reference Windows-only or Unix-only crates/types) |
cfg!(...) macro |
if cfg!(target_os = "macos") { ... } |
Parsed and type-checked on ALL platforms, then dead-code eliminated by LLVM | No (both branches must compile and type-check on the current target) |
#[cfg(unix)] if cfg!(unix) {
fn os_only() { ... } // Checked by rustc on BOTH Unix and Windows!
// Stripped on Windows // Eliminated by optimizer when false
Common Configuration Predicates
| Predicate | Meaning |
|---|---|
cfg!(target_os = "macos") / "linux" / "windows" |
Target operating system |
cfg!(target_arch = "aarch64") / "x86_64" |
Target CPU architecture |
cfg!(target_family = "unix") or cfg!(unix) |
Any Unix-like target (macOS, Linux, BSD) |
cfg!(target_endian = "little") |
Byte endianness of target CPU |
cfg!(target_pointer_width = "64") |
Pointer width in bits |
cfg!(debug_assertions) |
true in dev/test builds, false in --release by default |
cfg!(feature = "serde") |
true when Cargo feature "serde" is enabled |
cfg!(all(unix, target_pointer_width = "64")) |
Logical AND (all), OR (any), NOT (not) |
const IS_64_BIT_UNIX: bool = cfg!(all(unix, target_pointer_width = "64"));
fn main() {
let os_family = if cfg!(unix) {
"unix-like"
} else if cfg!(windows) {
"windows"
} else {
"other"
};
println!("OS family: {os_family}");
println!("64-bit Unix build: {IS_64_BIT_UNIX}");
println!("Debug assertions: {}", cfg!(debug_assertions));
}
OS family: unix-like
64-bit Unix build: true
Debug assertions: true