On this page
Conditional Compilation and cfg
#[cfg(target_os = "linux")]makes code selectively exist or disappear at compile time based on platform, architecture, or feature—not runtime if, but conditional compilation. Feature flags combined with cfg allow a crate to provide optional modules and dependencies, while cfg_attr reduces repetitive annotations across multiple platforms.
cfg: Compile-time Conditions
cfg is not a runtime check—code that does not match the cfg predicate is not compiled at all. You can use types and functions that are only available on that platform within a cfg block.
Common cfg Predicates
target_os: "linux", "macos", "windows", "android", "freebsd"
target_arch: "x86_64", "aarch64", "riscv64", "wasm32"
target_env: "gnu", "musl", "msvc"
target_feature: "avx2", "sse2", "neon"
target_pointer_width: "64", "32"
target_vendor: "apple", "pc", "unknown"
debug_assertions: true (dev), false (release)
test: true (during cargo test)
feature: custom feature flag (from Cargo.toml)
cfg_attr: Conditional Compilation Attributes
// Implement Debug only in dev builds
// 64-byte alignment on x86
Feature Flags
# Cargo.toml
[features]
json = ["serde", "serde_json"]
// stub when json feature is absent
cfg! Macro: Compile-time Constants
if cfg! else
The compiler performs constant folding on cfg!—the false branch is typically optimized away in release builds (dead code elimination). This is suitable for scenarios where you need to handle platform differences within the same function.
References
- Cargo Book: Conditional Compilation
- Rust Reference: cfg, cfg_attr
Keywords: cfg, cfg_attr, target_os, feature flag, conditional compilation, dead code elimination