3 min read #rust #cargo-and-build
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(target_os = "linux")]
fn platform_specific() { /* Linux impl */ }

#[cfg(not(target_os = "linux"))]
fn platform_specific() { /* fallback impl */ }

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

#[cfg_attr(debug_assertions, derive(Debug))]    // Implement Debug only in dev builds
struct InternalState { ... }

#[cfg_attr(target_arch = "x86_64", repr(align(64)))]  // 64-byte alignment on x86
struct CacheLine { ... }

Feature Flags

# Cargo.toml
[features]
json = ["serde", "serde_json"]
#[cfg(feature = "json")]
mod json_support { ... }

#[cfg(not(feature = "json"))]
mod json_support { ... }             // stub when json feature is absent

cfg! Macro: Compile-time Constants

if cfg!(target_os = "linux") {       // Evaluated at compile time → dead code is optimized away
    linux_path()
} else {
    generic_path()
}

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