在 CentOS 上进行 Rust 跨平台开发的标准流程
一 环境准备与国内源加速
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh,随后执行 source $HOME/.cargo/env,用 rustc -V、cargo -V 验证安装是否成功。为提升国内下载速度,可设置镜像环境变量(写入 ~/.bashrc 或 ~/.zshrc):
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustupexport RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup$HOME/.cargo/config.toml):[source.crates-io]
replace-with = 'ustc'
[source.ustc]
registry = "https://mirrors.ustc.edu.cn/crates.io-index"
[net]
git-fetch-with-cli = true
以上配置可显著加速依赖拉取与工具链更新。二 项目创建与跨平台代码编写
cargo new my_app && cd my_app。#[cfg(target_os = "linux")]
fn platform_msg() { println!("Running on Linux"); }
#[cfg(target_os = "windows")]
fn platform_msg() { println!("Running on Windows"); }
fn main() { platform_msg(); }
三 交叉编译到常见平台
rustup target add x86_64-pc-windows-gnurustup target add x86_64-pc-windows-msvc(需安装对应 MSVC 工具链)rustup target add x86_64-apple-darwinrustup target add x86_64-unknown-linux-musl.cargo/config.toml):[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"
在 CentOS 上安装 mingw 工具链(提供 x86_64-w64-mingw32-gcc):sudo dnf install mingw64-gcc(或 sudo yum install mingw64-gcc,视仓库而定)。cargo build --target x86_64-pc-windows-gnu --releasecargo build --target x86_64-unknown-linux-musl --release
产物路径分别为 target/x86_64-pc-windows-gnu/release/ 与 target/x86_64-unknown-linux-musl/release/。提示:从 Linux 交叉编译 macOS 通常较复杂,建议使用 macOS runner 进行构建与签名。四 打包与分发
cargo-deb 后执行 cargo deb --release,生成 .debcargo-rpm 后执行 cargo rpm --release,生成 .rpm.exe 可直接在 Windows 运行;若需 MSI/安装器,可结合外部打包工具(如 WiX)或 CI 模板完成。五 自动化多平台构建与注意事项
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: rustup default stable
- name: Build
run: cargo build --release
- name: Test
run: cargo test --release
RUST_LOG=info 控制日志级别,便于跨平台问题定位。