条件编译 cfg ​

核心概念 ​

条件编译(conditional compilation)通过 #[cfg(...)] 属性和 cfg!(...) 宏,让编译器根据条件决定是否编译某段代码。未满足条件的代码会被完全移除,不会出现在最终的二进制文件中。这是 Rust 实现跨平台兼容、feature 开关、调试/发布差异化等功能的核心机制。

#[cfg(...)] 用在项(函数、结构体、模块等)上方,决定该项是否参与编译。cfg!(...) 是一个宏,返回 bool 值,用在表达式中做运行时分支(但条件在编译时求值)。

rust
// #[cfg] 属性:决定是否编译
#[cfg(target_os = "windows")]
fn platform_name() -> &'static str {
    "Windows"
}

#[cfg(target_os = "linux")]
fn platform_name() -> &'static str {
    "Linux"
}

#[cfg(target_os = "macos")]
fn platform_name() -> &'static str {
    "macOS"
}

fn main() {
    println!("当前平台: {}", platform_name());

    // cfg! 宏:编译时求值的布尔表达式
    if cfg!(debug_assertions) {
        println!("这是 debug 构建");
    } else {
        println!("这是 release 构建");
    }

    // cfg! 用于条件赋值
    let max_threads = if cfg!(target_pointer_width = "64") {
        16
    } else {
        4
    };
    println!("最大线程数: {}", max_threads);
}

cfg 谓词 ​

rust
// === 操作系统 ===
#[cfg(windows)]              // Windows
#[cfg(unix)]                  // Unix 系统
#[cfg(target_os = "linux")]   // Linux
#[cfg(target_os = "macos")]   // macOS
#[cfg(target_os = "android")] // Android
#[cfg(target_os = "ios")]     // iOS

// === 架构 ===
#[cfg(target_arch = "x86_64")]   // x86-64
#[cfg(target_arch = "aarch64")]  // ARM64
#[cfg(target_arch = "wasm32")]   // WebAssembly

// === 指针宽度 ===
#[cfg(target_pointer_width = "32")]  // 32 位平台
#[cfg(target_pointer_width = "64")]  // 64 位平台

// === 字节序 ===
#[cfg(target_endian = "little")]  // 小端序
#[cfg(target_endian = "big")]     // 大端序

// === 编译环境 ===
#[cfg(target_env = "gnu")]    // GNU 工具链
#[cfg(target_env = "msvc")]   // MSVC 工具链
#[cfg(target_env = "musl")]   // musl libc

// === 调试/发布 ===
#[cfg(debug_assertions)]      // debug 构建
#[cfg(not(debug_assertions))] // release 构建

// === Feature 标志 ===
#[cfg(feature = "json")]      // 启用了 json feature
#[cfg(feature = "async")]     // 启用了 async feature

// === 测试 ===
#[cfg(test)]                  // 测试编译
#[cfg(doctest)]               // 文档测试

// === 自定义标志(通过 build.rs 设置)===
#[cfg(custom_flag)]           // cargo::rustc-cfg=custom_flag
#[cfg(db = "postgres")]       // cargo::rustc-cfg=db="postgres"

fn main() {}

逻辑组合 ​

rust
// all():所有条件都满足(与)
#[cfg(all(unix, target_arch = "x86_64"))]
fn unix_x86_only() {
    println!("64 位 Unix 系统");
}

// any():任一条件满足(或)
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn desktop_unix() {
    println!("Linux 或 macOS");
}

// not():条件不满足(非)
#[cfg(not(windows))]
fn not_windows() {
    println!("非 Windows 系统");
}

// 嵌套组合
#[cfg(all(unix, not(target_os = "macos"), target_pointer_width = "64"))]
fn linux_64bit() {
    println!("64 位 Linux(不含 macOS)");
}

// 复杂组合
#[cfg(all(
    any(target_os = "linux", target_os = "macos"),
    target_arch = "x86_64",
    not(feature = "no_std")
))]
fn desktop_with_std() {
    println!("桌面 x86_64 且有 std 支持");
}

fn main() {
    #[cfg(unix)]
    unix_x86_only();

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    desktop_unix();

    #[cfg(not(windows))]
    not_windows();
}

cfg 的应用位置 ​

rust
// === 函数 ===
#[cfg(windows)]
fn win_specific() {}

// === 结构体 ===
#[cfg(feature = "serde")]
#[derive(serde::Serialize)]
struct Data {
    value: i32,
}

// === 字段 ===
struct Config {
    name: String,
    #[cfg(feature = "debug_info")]
    debug_level: u8,
}

// === impl 块 ===
struct MyType;

#[cfg(feature = "json")]
impl MyType {
    fn to_json(&self) -> String {
        "{}".to_string()
    }
}

// === 模块 ===
#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}

// === use 语句 ===
#[cfg(feature = "async")]
use tokio::runtime::Runtime;

// === 表达式中(cfg! 宏)===
fn buffer_size() -> usize {
    if cfg!(target_pointer_width = "64") {
        8192
    } else {
        4096
    }
}

fn main() {
    println!("缓冲区大小: {}", buffer_size());
}

基本示例 ​

rust
// 跨平台文件路径处理

#[cfg(windows)]
const PATH_SEPARATOR: char = '\\';

#[cfg(not(windows))]
const PATH_SEPARATOR: char = '/';

fn join_path(base: &str, name: &str) -> String {
    format!("{}{}{}", base, PATH_SEPARATOR, name)
}

// 根据构建模式调整日志级别
fn log_level() -> &'static str {
    if cfg!(debug_assertions) {
        "debug"
    } else {
        "info"
    }
}

// 平台相关的进程信息
fn process_id() -> u32 {
    std::process::id()
}

#[cfg(target_pointer_width = "64")]
fn arch_info() -> &'static str {
    "64 位架构"
}

#[cfg(target_pointer_width = "32")]
fn arch_info() -> &'static str {
    "32 位架构"
}

fn main() {
    let path = join_path("home", "user");
    println!("路径: {}", path);
    println!("日志级别: {}", log_level());
    println!("进程 ID: {}", process_id());
    println!("架构: {}", arch_info());
    println!("分隔符: '{}'", PATH_SEPARATOR);
}

常见问题 ​

问题一:#[cfg] 和 cfg! 有什么区别?

#[cfg] 是属性,决定被标注的项是否参与编译,不满足条件的代码完全不存在。cfg! 是宏,返回 bool,两个分支的代码都必须合法(虽然不满足条件的分支会被优化掉)。

问题二:怎么查看当前平台支持哪些 cfg 条件?

运行 rustc --print cfg 查看。交叉编译时用 rustc --target <target> --print cfg。

问题三:cfg 条件可以自定义吗?

可以。通过 build.rs 中的 println!("cargo::rustc-cfg=my_flag") 设置自定义标志,或者通过 RUSTFLAGS='--cfg my_flag' 环境变量设置。

问题四:#[cfg(test)] 和 #[test] 有什么关系?

#[cfg(test)] 标注的代码只在测试编译时存在。#[test] 标注具体的测试函数。通常 #[cfg(test)] mod tests { #[test] fn ... } 配合使用。

适用场景 ​

  • 跨平台代码:根据操作系统和架构编译不同实现
  • Feature 开关:根据 Cargo features 启用功能模块
  • Debug/Release 差异:调试信息、断言、日志级别
  • 测试代码隔离:#[cfg(test)] 隔离测试模块
  • no_std 支持:#[cfg(feature = "std")] 控制标准库依赖

注意事项 ​

  • #[cfg] 不满足条件时代码完全移除
  • cfg! 两个分支代码都必须类型合法
  • 自定义 cfg 标志通过 build.rs 或 RUSTFLAGS 设置
  • rustc --print cfg 查看可用的 cfg 谓词
  • all()、any()、not() 可以任意嵌套
  • cfg 条件中的字符串比较区分大小写

总结 ​

条件编译通过 #[cfg(...)] 属性和 cfg!(...) 宏实现。#[cfg] 决定项是否参与编译(不满足条件则完全移除),cfg! 返回布尔值用于表达式。内置的 cfg 谓词包括 target_os、target_arch、feature、debug_assertions、test 等,通过 all()、any()、not() 组合复杂条件。自定义 cfg 标志通过 build.rs 设置。条件编译广泛用于跨平台兼容、feature 开关、debug/release 差异化和测试代码隔离。