在Linux上,首先通过rustup(Rust官方版本管理工具)安装Rust基础工具链(如stable版本),并确保环境变量正确配置:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
rustc --version # 验证安装(显示Rust版本即成功)
若需为非Linux平台(如Windows、macOS或嵌入式系统)编译,需通过rustup添加对应的目标三元组(Target Triple)。例如:
rustup target add x86_64-pc-windows-gnu(使用GNU工具链)或x86_64-pc-windows-msvc(使用MSVC工具链);rustup target add x86_64-apple-darwin;rustup target add armv7-unknown-linux-gnueabihf。rustc --print target-list查看所有支持的目标平台。使用Rust的条件编译(#[cfg]属性)处理平台差异代码。例如:
#[cfg(target_os = "linux")]
fn platform_specific_function() {
println!("Running on Linux");
}
#[cfg(target_os = "windows")]
fn platform_specific_function() {
println!("Running on Windows");
}
fn main() {
platform_specific_function(); // 根据目标平台调用对应函数
}
此外,优先使用跨平台库(如std::fs/std::io处理文件IO、crossbeam处理并发、serde处理序列化),避免直接调用平台特定API。
若需在Linux上为其他平台(如Windows)交叉编译,需安装目标平台的链接器和C工具链。例如,为Windows交叉编译时,在Ubuntu上安装:
sudo apt install mingw-w64 # 提供x86_64-w64-mingw32-gcc等工具
或在.cargo/config.toml中指定链接器路径(针对特定目标):
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"
cargo编译运行:cargo build --release # 生成优化后的可执行文件(位于target/release/)
cargo run --release
cargo build --target=x86_64-pc-windows-gnu --release
生成的可执行文件位于target/x86_64-pc-windows-gnu/release/目录下,可直接在Windows系统运行。使用持续集成工具(如GitHub Actions)自动化跨平台测试,确保代码在所有目标平台上正常工作。例如,在项目根目录创建.github/workflows/ci.yml文件:
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest] # 测试Linux、Windows、macOS
steps:
- uses: actions/checkout@v2
- name: Install Rust
run: rustup default stable
- name: Build
run: cargo build --release
- name: Run tests
run: cargo test --release
每次推送代码或提交PR时,GitHub Actions会在多个操作系统上自动编译并运行测试。