用途:指导把 Rust crate 编译到非宿主目标平台,覆盖目标三元组、标准库安装、链接器配置、条件编译与容器化工具链。
主要能力:
- 目标三元组格式 <arch>-<vendor>-<os>-<env>,如 x86_64-unknown-linux-musl、aarch64-apple-darwin、x86_64-pc-windows-msvc、wasm32-wasip1、thumbv7em-none-eabihf;wasm32-wasi 在 Rust 1.81 起更名为 wasm32-wasip1。
- 用 rustup target add <triple> 安装目标标准库(仅 libstd/libcore/liballoc,不含链接器或 SDK);rustup target list 查看,--installed 查看已装。
- 用 cargo build --target <triple> --release 构建,产物在 target/<triple>/release/。
- 在 .cargo/config.toml 的 [target.<triple>] 下配置 linker、runner、rustflags、rustdocflags;环境变量形式如 CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER。
- cross 工具在按目标打包的 Docker/Podman 镜像中运行 cargo:cargo install cross --git https://github.com/cross-rs/cross,然后 cross build --target <triple> --release。
- 条件编译:#[cfg(target_os = "linux")]、all/any/not 组合、运行时 cfg!(...) 宏,以及 #[cfg_attr(predicate, attr)] 按条件发出属性。
必要用法:先 rustup target add,再单独安装宿主侧交叉链接器(如 musl-gcc、gcc-mingw-w64-x86-64、aarch64-linux-gnu-gcc),并在 .cargo/config.toml 指向它,最后 cargo build --target。
适用场景:静态 Linux 二进制(musl)、从 Linux 构建 Windows(gnu/msvc)、macOS ARM、WASI/浏览器 Wasm、嵌入式 no_std。
限制:rustup target add 不安装 gcc/clang/lld;Apple SDK 许可禁止再分发,aarch64-apple-darwin 必须在 macOS 上构建;musl 存在 dlopen 已知问题;cfg! 只验证谓词,不保证运行时正确性。库 crate 不宜在 [build] 固定 target。其余细节暂未提供。