Rust 用 cfg 与 feature 做跨平台条件编译:按 target_os 分派实现、可选依赖与 CI 验证

未来之星2026-11-1317 次阅读

一份代码要在三个系统上跑

写本地同步工具时,配置目录在 macOS 上是 ~/Library/Application Support,Linux 走 XDG_CONFIG_HOME,Windows 用 %APPDATA%;文件权限检查要用到 std::os::unix 里的扩展 trait,这在 Windows 上根本不存在。第一版用 cfg!(target_os = "windows") 做运行期分支,结果 Windows 专有的类型在 macOS 上照样参与类型检查,编译直接报错。正确做法是让整段代码只在对应目标上被编译进去,而不是在运行时判断。

#[cfg] 作用于整个条目

cfg 属性可以挂在 mod、fn、impl、use,甚至结构体字段上。条件为假时该条目在解析后被丢弃,连名字解析和类型检查都不做,因此平台专有 API 可以放心写在里面。cfg! 宏只是一个编译期布尔值,两条分支都会保留并参与编译,不能用来隔离平台专有类型。

// 错误示范:unix 扩展在 windows target 上不存在,照样编译报错
if cfg!(unix) {
    // use std::os::unix::fs::PermissionsExt; 放在这里没用
}

// 正确:整个函数只在 unix 目标上编译
#[cfg(unix)]
fn mode_of(path: &std::path::Path) -> std::io::Result<u32> {
    use std::os::unix::fs::PermissionsExt;
    Ok(std::fs::metadata(path)?.permissions().mode())
}

用模块按 target_os 分派路径实现

先建一个只依赖标准库的工程,目录结构不必复杂。Cargo.toml 里声明一个可选依赖,用来演示 feature 开关;平台判断全部放在 paths.rs 里,对外只暴露一个稳定的 config_dir 函数。

# Cargo.toml
[package]
name = "app-paths"
version = "0.1.0"
edition = "2021"

[features]
default = []
json = ["dep:serde_json"]

[dependencies]
serde_json = { version = "1", optional = true }
// src/paths.rs
use std::path::PathBuf;

pub fn config_dir(app: &str) -> PathBuf {
    platform_dir(app)
}

#[cfg(target_os = "macos")]
fn platform_dir(app: &str) -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
    PathBuf::from(home).join("Library").join("Application Support").join(app)
}

#[cfg(target_os = "linux")]
fn platform_dir(app: &str) -> PathBuf {
    let base = std::env::var("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
            PathBuf::from(home).join(".config")
        });
    base.join(app)
}

#[cfg(target_os = "windows")]
fn platform_dir(app: &str) -> PathBuf {
    let base = std::env::var("APPDATA")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("."));
    base.join(app)
}

// 兜底分支:新平台上一编译就能发现问题,而不是报「找不到函数」
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn platform_dir(app: &str) -> PathBuf {
    PathBuf::from(".").join(app)
}

#[cfg(unix)]
pub fn is_private(path: &std::path::Path) -> std::io::Result<bool> {
    use std::os::unix::fs::PermissionsExt;
    let mode = std::fs::metadata(path)?.permissions().mode();
    Ok(mode & 0o077 == 0)
}

#[cfg(windows)]
pub fn is_private(_path: &std::path::Path) -> std::io::Result<bool> {
    // Windows 下按 ACL 判断,这里先保持接口一致
    Ok(true)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn config_dir_ends_with_app() {
        assert!(config_dir("myapp").ends_with("myapp"));
    }
}

三个平台各写一个同名函数,调用方完全不用关心当前系统。兜底分支里给一个默认实现,比让编译器报「找不到 platform_dir」更容易定位问题;也可以故意在兜底里 compile_error!,强制每个新平台显式适配。

feature 控制可选依赖与可选模块

Cargo.toml 里用 dep: 前缀可以阻止 Cargo 自动生成同名隐式 feature,让开关只由自己定义。代码里用 #[cfg(feature = "json")] 包住模块声明与调用点,不开这个 feature 时 serde_json 连下载和编译都不会发生。

// src/report.rs,只在 --features json 时编译
use std::path::Path;

pub fn print_json(path: &Path) {
    let value = serde_json::json!({ "config_dir": path.to_string_lossy() });
    println!("{}", value);
}
// src/main.rs
mod paths;
#[cfg(feature = "json")]
mod report;

fn main() {
    let dir = paths::config_dir("myapp");
    println!("config dir: {}", dir.display());

    #[cfg(feature = "json")]
    report::print_json(&dir);

    if let Ok(private) = paths::is_private(&dir) {
        println!("private: {}", private);
    }
}
cargo run
cargo run --features json
cargo test --all-features
cargo check --no-default-features

注意 feature 只会叠加不会互斥,default 里放了什么、--all-features 打开什么,组合数会随开关增长,CI 里至少要把全开与全关两种组合都过一遍。

把目标平台真的编一遍

#[cfg(test)] 里的单元测试按宿主机编译,在 macOS 上通过不代表 Linux 分支能过。target 由 --target 决定,不由构建机决定,所以跨平台逻辑必须真的用目标三元组 cargo check 一次。ARM Mac 上可以用 cargo-zigbuild 交叉编译到 x86_64-unknown-linux-gnu,或者先在 CI 的 Linux runner 上跑。

# CI 片段
- name: check
  run: |
    cargo check --all-features
    cargo check --no-default-features
    cargo test --all-features
    cargo check --target x86_64-unknown-linux-gnu --all-features
    cargo check --target x86_64-pc-windows-msvc --all-features

只依赖平台判断时不必写 [target.'cfg(...)'.dependencies];如果某个平台确实需要额外 crate,就写在对应的 target 依赖表里,别在代码里靠 cfg 绕过缺失的依赖。目标依赖会按 target 选择性解析,不会把 Windows 的库拖进 Linux 构建。

工程化注意点

  • cfg 条件为假时整个条目不参与编译,cfg! 只是布尔值,不能用它隔离平台专有类型、trait 或模块。
  • 每个 cfg 组合都要有兜底分支,否则新平台会出现「找不到函数」,或者更隐蔽地走到错误实现上。
  • target 专属依赖写进 Cargo.toml 的 target 表,feature 用 dep: 前缀避免隐式开关,两者不要混为一件事。
  • feature 是加法语义,CI 里至少覆盖 --all-features 与 --no-default-features,组合多时再加常用子集。
  • 单元测试跑在宿主机上,跨平台分支必须额外用 --target 做 cargo check 才算验证过。
  • 交叉编译时 cfg 由 --target 决定,本机 cargo build 通过不代表目标平台能过;错误信息里留意 unexpected cfg 警告,通常是拼错了条件名。
未

未来之星

文章作者

一份代码要在三个系统上跑 写本地同步工具时,配置目录在 macOS 上是 ~/Library/Application...

分类
技术
发布时间
2026-11-13
字数
约 4728 字
阅读
17 次