In Rust, how do you write one function with separate Linux, macOS and Windows bodies using `#[cfg]`, and what happens to the unused ones?
answer
- one copy per target
- target_os key-value predicate
- removed before type checking
- fallback with not(any(...))
basics
~20 sWrite one copy of the function per platform, each gated by a cfg predicate such as target_os = "linux" or windows, plus a not(any(...)) fallback. rustc deletes every copy whose predicate is false before it resolves names or checks types.
solid answer
~30 sI write the function once per platform with the same signature: `#[cfg(target_os = "linux")]`, `#[cfg(target_os = "macos")]`, `#[cfg(windows)]`, and a fallback under `#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]`. The compiler evaluates each predicate against the target and removes every item whose predicate is false, so exactly one `backend_name` is left by the time names are resolved and types are checked. The removed copies still have to parse, but they are never type-checked on this target, which is why CI has to build each platform. If no copy survives, callers fail with E0425; if two survive, the duplicate fails with E0428.
code
rust · 23 lines#[cfg(target_os = "linux")]
fn backend_name() -> &'static str {
"inotify"
}
#[cfg(target_os = "macos")]
fn backend_name() -> &'static str {
"FSEvents"
}
#[cfg(windows)]
fn backend_name() -> &'static str {
"ReadDirectoryChangesW"
}
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
fn backend_name() -> &'static str {
"polling"
}
fn main() {
println!("watching with {}", backend_name());
}go deeper
Recall the shape: one copy per platform with target_os or windows, a not(any(...)) fallback, and the same signature on every copy.
Explain that removal happens before name resolution and type checking, why removed code must still parse, and the E0425 and E0428 failures when zero or two copies survive.
Show you know cfg-gated code rots silently on other hosts, so every target needs a CI build, and pick unix versus target_os deliberately for the API being called.
Frame scattered item-level cfg as fine for a few functions but costly at scale, and argue when to move to per-platform modules behind one facade.
## What `#[cfg]` does **Conditional compilation** means some source code is compiled only under certain conditions. In Rust the main tool is the **`cfg` attribute**: you attach `#[cfg(predicate)]` to a piece of code, and rustc evaluates the **configuration predicate** against the target it is compiling for. The Reference states the effect precisely: if the predicate is true, the attribute is simply dropped and the code stays; if it is false, **the form is removed from the source code**. That removal happens early, during expansion, before **name resolution** (working out what each path refers to) and before **type checking**. So for a given build, a removed function does not exist at all: it is not compiled, not type-checked, not linked, and not callable. Writing one function per platform is therefore not "several functions, one of which runs" — it is "one function, chosen at compile time". ## The predicates you use for platforms A predicate is built from **configuration options**, which are either bare names (`unix`) or key-value pairs (`target_os = "linux"`). The compiler sets the target ones for you; you can list them for your host with `rustc --print cfg`. | Predicate | What it tests | Example values | |---|---|---| | `target_os = "..."` | the operating system | `"linux"`, `"macos"`, `"windows"`, `"ios"`, `"freebsd"`, `"none"` | | `target_family = "..."` | the broad family | `"unix"`, `"windows"`, `"wasm"` | | `unix`, `windows` | shorthand names | set when the family is unix or windows | | `target_arch = "..."` | the CPU architecture | `"x86_64"`, `"aarch64"`, `"arm"` | | `target_pointer_width = "..."` | pointer size in bits | `"16"`, `"32"`, `"64"` | | `debug_assertions` | builds without optimisations, by default | a bare name | Three operators combine predicates: - **`all(a, b, ...)`** is true when every predicate is true, and true for an empty list. - **`any(a, b, ...)`** is true when at least one is true, and false for an empty list. - **`not(a)`** inverts one predicate. Note what is *not* a built-in name: there is no bare `macos` or `linux`. `#[cfg(macos)]` is simply never true, and under Cargo the `unexpected_cfgs` lint warns about it. Use `target_os = "macos"`. ## Writing one function per platform The recipe has four steps: 1. Write each platform's version with the **same name and signature**. 2. Gate each with its predicate: `#[cfg(target_os = "linux")]`, `#[cfg(target_os = "macos")]`, `#[cfg(windows)]`. 3. Add a **fallback** whose predicate is the negation of all the others: `#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]`. It can contain a portable implementation, or you can replace it with `compile_error!("unsupported platform")` to make the limitation explicit. 4. Call the function normally. Callers never mention a platform. The predicates must be **mutually exclusive and exhaustive** for the targets you support, because rustc does nothing to choose between survivors: - If **no** copy survives, every call fails with **E0425**, "cannot find function `backend_name` in this scope", and rustc adds a note that an item was configured out. - If **two** copies survive — say one under `unix` and one under `target_os = "macos"` on a Mac — the second is a duplicate definition, **E0428**, "the name `backend_name` is defined multiple times". The `cfg_select!` macro, stable since Rust 1.95, removes most of this bookkeeping by taking the first matching arm. ## What removal does and does not skip Removal is thorough, but it is not "ignore the text": - **Parsing still happens.** The attribute is attached to a parsed item, so a syntax error such as `let x = ;` inside a `#[cfg(windows)]` function breaks the build on every platform. - **Type checking does not.** A type mismatch or a call to a function that only exists on Windows inside the Windows copy goes unnoticed on Linux and macOS. This is why platform code can rot quietly, and why a crate with platform branches needs a CI build for each target it supports. - **Nothing reaches the binary.** The removed code is not compiled or linked, so it costs no size and cannot be called by accident. ## Where `#[cfg]` can go The Reference allows `cfg` anywhere attributes are allowed, which in practice means: - **items**: functions, structs, `impl` blocks, `mod` and `use` declarations; - **statements** inside a function body, such as a `#[cfg(debug_assertions)]` logging line; - **struct fields**, **enum variants** and **match arms**; - **elements** of array, tuple and struct-literal lists, such as `vec![1, #[cfg(unix)] 2]`. A bare expression is the exception: `let x = #[cfg(unix)] 5;` fails with E0658, "attributes on expressions are experimental". To choose a *value* per platform, use the `cfg!` macro when both values are valid everywhere, or `cfg_select!` in expression position. In an interview, the strong answer names the predicate syntax, says the false copies are removed before type checking, and adds the two consequences: you need a fallback for unsupported targets, and you need to build every target to know the hidden copies still compile.
- What happens if the crate only has the Linux, macOS and Windows copies and someone builds it for FreeBSD?All three predicates are false, so all three items are removed and every call site fails with E0425, "cannot find function `backend_name` in this scope"; rustc adds a note that an item was configured out. Either add a fallback under `not(any(...))`, or state the limitation with `#[cfg(not(any(...)))] compile_error!("unsupported platform");` so the error says why.
- Why can a `#[cfg(windows)]` function containing a type error still build on macOS?The item is removed before name resolution and type checking, so its body is never type-checked for that target. It must still parse, because the attribute is attached to a parsed item: a syntax error such as `let x = ;` fails on every platform. A type error only shows up when someone compiles for Windows.
- What does `#[cfg(unix)]` select, and is it the same as Linux?`unix` is set whenever `target_family = "unix"` is set: Linux, macOS, the BSDs, Android, iOS and others, and even `wasm32-unknown-emscripten`, which reports both the unix and wasm families. It is broader than `target_os = "linux"`, so use it for code that relies on POSIX behaviour and `target_os` for one specific kernel API.
- The copies for other platforms are compiled and simply never called at run time.
- Code in a disabled cfg branch is skipped entirely, so it does not even have to parse.
- cfg(macos) or cfg(linux) targets that operating system; only unix and windows are bare names.
- A missing platform branch shows up as a panic when that platform runs the program.
- cfg(unix) selects only Linux, not macOS or the BSDs.