In Rust, why does `if cfg!(windows) { windows_dir() }` fail on Linux when `windows_dir` is declared under `#[cfg(windows)]`?
answer
- macro versus attribute
- expands to a bool literal
- both branches stay in the code
- E0425 on the removed item
basics
~20 scfg!(windows) only expands to the literal true or false; it removes nothing. Both if branches stay in the program and must compile on every target, but the #[cfg(windows)] item was deleted on Linux, so the call fails with E0425.
solid answer
~40 s`cfg!` takes the same predicate syntax as the attribute but expands to the literal `true` or `false` at compile time, and the `if` then branches on a constant. It does not delete either branch, so the Windows branch is still name-resolved and type-checked on Linux. Meanwhile `#[cfg(windows)]` really did remove `windows_dir`, so the call fails with E0425 and a note that the item was configured out. The fix is to gate the statement or block itself with `#[cfg(windows)]`, give the function a body on every platform, or use `cfg_select!`. `cfg!` is the right tool when every branch is valid everywhere, such as picking a path separator, and the standard library's `debug_assert!` uses `if cfg!(debug_assertions)` so that its expression is always type-checked.
code
rust · 7 lines#[cfg(windows)]
fn windows_dir() -> &'static str { "C:\\ProgramData" }
fn data_dir() -> &'static str {
if cfg!(windows) { windows_dir() } else { "/var/lib" }
}
fn main() { println!("{}", data_dir()); }go deeper
Recall that cfg! gives a true or false value while #[cfg] deletes the code it is attached to.
Explain why both branches of an if cfg!(...) must compile on every target, read the E0425 note about a configured-out item, and name the three fixes.
Choose cfg! on purpose to keep every platform's code type-checked on any host, as debug_assert! does, and #[cfg] only where a branch cannot compile elsewhere.
Set a team rule for when cfg! is preferred because it keeps all branches checked, and when the platform split belongs in modules instead.
## Two tools with the same predicate syntax Rust has two everyday ways to ask "am I compiling for Windows?", and they look alike because they take the same **configuration predicate** syntax: - the **`#[cfg(windows)]` attribute**, which keeps or removes the code it is attached to; - the **`cfg!(windows)` macro**, which the standard library documents as evaluating "boolean combinations of configuration flags at compile-time". The difference is the whole answer. The documentation of `cfg!` says it plainly: unlike `#[cfg]`, it **does not remove any code and only evaluates to true or false**, so every block of an `if`/`else` that uses it as a condition must be valid, whatever the macro evaluates to. ## Why the snippet fails on Linux Walk through what rustc does with this code on a Linux target: 1. `#[cfg(windows)] fn windows_dir()` — the predicate is false, so the item is **removed** before name resolution. On Linux there is no function called `windows_dir`. 2. `if cfg!(windows) { windows_dir() } else { "/var/lib" }` — `cfg!(windows)` expands to the literal `false`. The `if` is now `if false { windows_dir() } else { "/var/lib" }`. 3. Both branches of an ordinary `if` are compiled. rustc tries to resolve `windows_dir` in the first branch, finds nothing, and stops with **E0425**: "cannot find function `windows_dir` in this scope". rustc 1.99 even adds a note pointing at the item "configured out" by its `#[cfg]`. The program never reaches run time, so whether the branch would execute is irrelevant. A constant condition does let the optimiser drop the dead branch from the binary, but only after the branch has been type-checked and borrow-checked like any other code. ## Three ways to fix it | Fix | How | When it fits | |---|---|---| | Gate the statement or block | `#[cfg(windows)] { ... }` or a `#[cfg(windows)]` statement | the call only makes sense on one platform | | Give the function every platform | `#[cfg(windows)] fn data_dir()` plus `#[cfg(not(windows))] fn data_dir()` with the same signature | callers should not care about the platform | | Select with `cfg_select!` | arms for `windows` and `_` | several alternatives, in item or expression position (stable since 1.95) | The second fix is usually the cleanest for callers: they call `data_dir()` and the platform decision lives next to the definitions. ## When `cfg!` is the right tool `cfg!` is not a weaker `#[cfg]`; it has its own job. Because it leaves every branch in place, **every platform's branch is type-checked on every host**. That is a feature whenever all branches are valid everywhere: - choosing a path separator, a default directory string or a buffer size; - enabling extra checks with `if cfg!(debug_assertions) { ... }`; - logging the build configuration; - keeping rarely built code from rotting, since a Linux developer's build still checks the Windows branch. The standard library uses exactly this trick. `debug_assert!` expands to `if cfg!(debug_assertions) { assert!(...) }`, and its documentation says "the result of expanding `debug_assert!` is always type checked". In a default optimised build `debug_assertions` is off, so the condition is `false` and the check does not run — but a stale assertion that names a removed field still fails the release build immediately, instead of hiding until someone compiles in debug mode. ## Where the attribute cannot go A natural reaction is to put the attribute on the expression instead: `let dir = #[cfg(windows)] windows_dir();`. rustc 1.99 rejects attributes on bare expressions with **E0658**, "attributes on expressions are experimental". `#[cfg]` is accepted on items, statements, struct fields, match arms and elements of array, tuple and struct-literal lists. To pick a value, use `cfg!` when both values compile everywhere, or `cfg_select!` in expression position when they do not. ## Common misconceptions - **"`cfg!` checks the operating system at run time."** It is resolved by the compiler; the binary contains a constant. A program compiled for Linux cannot discover at start-up that it should take the Windows branch. - **"The false branch of `if cfg!(...)` is never checked."** It is checked like any code; only `#[cfg]` and `cfg_select!` remove code. - **"`#[cfg]` and `cfg!` are interchangeable."** They are interchangeable only when every branch compiles on every target, and then `cfg!` usually gives the better guarantee. The interview-ready summary: `#[cfg]` deletes code, `cfg!` produces a boolean. Use the attribute when a branch cannot compile elsewhere, and the macro when you want every branch kept honest on every build.
- Why does `debug_assert!` expand to `if cfg!(debug_assertions)` instead of using `#[cfg(debug_assertions)]`?So the assertion is still compiled in release builds: the standard library's documentation says the result of expanding `debug_assert!` is always type checked. A renamed field or changed signature breaks the release build immediately instead of hiding until someone builds in debug. In a default optimised build the condition is the constant `false`, so the check does not run.
- Can you write `let x = #[cfg(unix)] 5;` to pick a value per platform?No. rustc 1.99 rejects it with E0658, "attributes on expressions are experimental". `#[cfg]` works on items, statements, struct fields, match arms and elements of array, tuple and struct-literal lists, but not on a bare expression. For a value, use `cfg!` when both values are valid everywhere, or `cfg_select!` (stable since 1.95) in expression position.
A #[cfg] item is a page torn out of a manual before it goes to the printer; cfg! prints every page and only ticks a box saying which one applies, so every printed page still has to be proofread.
- cfg!(windows) strips the Windows branch on other platforms, just like the attribute.
- cfg! checks the operating system when the program starts.
- With cfg! the false branch is never type-checked, so it may call missing functions.
- #[cfg] can be put on any expression, such as let x = #[cfg(unix)] 5.
- debug_assert! is removed from release builds before the compiler checks it.