本页目录

条件编译与 cfg

#[cfg(target_os = "linux")] 让代码在编译期按平台/架构/feature 选择性地存在或消失——不是运行时 if,而是条件编译。feature flags 结合 cfg 让一个 crate 提供可选的模块和依赖,cfg_attr 减少多平台下的重复标注。

cfg: 编译期条件

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

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

cfg 不是运行时检查——不被 cfg 匹配的代码根本不会被编译⁠。你可以在一个 cfg 块中使用仅该平台支持的类型和函数。

常用 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:          自定义 feature flag (来自 Cargo.toml)

cfg_attr: 条件编译属性

#[cfg_attr(debug_assertions, derive(Debug))]    // 只在 dev build 实现 Debug
struct InternalState { ... }

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

Feature Flags

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

#[cfg(not(feature = "json"))]
mod json_support { ... }             // 无 json feature 时的 stub

cfg! 宏: 编译时常量

if cfg!(target_os = "linux") {       // 编译时求值 → 死代码被优化移除
    linux_path()
} else {
    generic_path()
}

编译器对 cfg! 做常量折叠——false branch 在 release 中通常被优化移除(dead code elimination)。适合"在同一个函数内做平台差异"的场景。

参考

  • Cargo Book: Conditional Compilation
  • Rust Reference: cfg, cfg_attr

Keywords: cfg, cfg_attr, target_os, feature flag, conditional compilation, dead code elimination