Compile-time configuration
Quick answer
Conditional compilation selects code based on target or build configuration. This lets one project support different platforms or optional features while compiling only the appropriate items.
Attributes versus Boolean checks
#[cfg(condition)] removes an item when its condition is false. cfg!(condition) expands to a Boolean; both branches of a normal if still need to type-check. Cargo features may set feature = "name" configurations. Use all, any and not to combine conditions; the following examples work without custom features.
#[cfg(unix)] fn platform() -> &'static str { "unix" }#[cfg(not(unix))] fn platform() -> &'static str { "other" }fn main() { assert_eq!(platform() == "unix", cfg!(unix)); println!("consistent"); }Expected stdout (not executed):
consistentThe selected function agrees with the configuration Boolean.
fn main() { if cfg!(any()) { let _: u32 = "not a number"; }}Expected: compilation fails; exact diagnostic not verified.
Use a cfg attribute to exclude code that is invalid on a target.
Common mistake
A build feature is not runtime configuration and is not an authorization check.
Try it yourself
Write two cfg-selected functions using target_pointer_width and compile for your installed target.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Compile-time configuration — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A platform-specific function cannot type-check on the other platform. How should it be excluded?
Compile-time configuration — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust #[cfg(unix)] fn platform() -> &'static str { "unix" } #[cfg(not(unix))] fn platform() -> &'static str { "other" } fn main() { assert_eq!(platform() == "unix", cfg!(unix)); println!("consistent"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Compile-time configuration — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { if cfg!(any()) { let _: u32 = "not a number"; } } ``` Which outcome or interpretation best matches this example?