`cfg`
cfg is compile-time conditional compilation. #[cfg(unix)] keeps an item on Unix and strips it elsewhere, so the other branch is not type-checked as live code.
Detailed Explanation
#[cfg(target_os = "windows")] on a function means that function exists only when the target is Windows. On Linux the item is gone. Callers on Linux must not call it, so you usually provide a matching #[cfg(not(target_os = "windows"))] alternative, or you put the cfg inside the function with if cfg!(unix) { ... }.
cfg! is a boolean the compiler knows at compile time. Both branches of if cfg!(unix) are parsed, but the dead one is eliminated. Items with #[cfg] are not parsed as existing at all in the off configuration, which is why you can call Unix-only APIs inside a #[cfg(unix)] function without a Windows crate even seeing those names.
Predicates compose. all(...), any(...), not(...) combine them. Common predicates: target_os, target_family (unix, windows), target_arch, target_endian, debug_assertions (true in the dev profile), test (true when building tests), and feature = "name" for Cargo features. A feature is an optional dependency or an optional slice of your crate, declared in Cargo.toml under [features].
#[cfg_attr(pred, attr)] applies attr only when pred holds. #[cfg_attr(feature = "serde", derive(Serialize))] is the usual form. #[cfg(test)] on a mod tests is how unit tests live next to the code they test without shipping in the release library.
This is not a runtime OS check. If you need to detect something at runtime, you read an environment variable or call an API. cfg is for things that are false for the entire build: the target, the profile, the feature set. Using cfg for a setting the user will change without recompiling is a mistake.
When you write #[cfg]: OS-specific files, optional features, test-only helpers. When you write cfg!: a small branch inside a shared function. When you do not: business logic that differs by tenant or by config file.
Code Examples
fn overflow_checks() -> bool {
cfg!(debug_assertions)
}
#[cfg(test)]
mod tests {
#[test]
fn unit_is_empty() {
assert_eq!(std::mem::size_of::<()>(), 0);
}
}
fn main() {
if overflow_checks() {
println!("dev profile");
} else {
println!("release profile");
}
}Common Gotchas
The off `#[cfg]` item does not exist
A call without a matching cfg on the caller is a compile error on that target. Provide both sides, or gate the caller too.
`cfg!` still type-checks both branches
You cannot call a Unix-only function inside `if cfg!(unix)` on a Windows build. Put that call in a `#[cfg(unix)]` item.
`debug_assertions` is the profile flag you usually want
It is on in `dev` and off in `release`. Do not invent your own `debug` feature for overflow or logging.
Features must be additive
Turning a feature on may add APIs, not change the meaning of existing ones. Two crates enabling different features of your crate get one unification; conflicts are your bug.