在Linux上实现跨平台开发的第一步是安装Rust官方工具链。通过rustup(Rust版本管理工具)安装稳定版Rust,并确保环境变量配置正确:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
rustc --version # 验证安装(显示Rust版本即成功)
使用cargo(Rust包管理器)创建新项目,作为跨平台开发的基础:
cargo new cross_platform_project
cd cross_platform_project
Rust通过条件编译(#[cfg]属性)支持不同平台的代码分支。例如,针对Linux与其他平台的差异化逻辑:
#[cfg(target_os = "linux")]
fn platform_specific_function() {
println!("Running on Linux");
}
#[cfg(not(target_os = "linux"))]
fn platform_specific_function() {
println!("Running on non-Linux system");
}
fn main() {
platform_specific_function(); // 根据目标平台调用对应函数
}
此外,优先使用跨平台库(如std::fs、tokio、serde),避免直接调用平台特定API(如libc),减少适配成本。
若需为非Linux目标(如Windows、macOS、ARM设备)编译,需通过rustup添加目标平台工具链,并配置链接器:
# 添加目标平台(以Windows 64位为例)
rustup target add x86_64-pc-windows-gnu
# 配置Cargo使用交叉编译工具链(可选,针对特定目标)
mkdir -p .cargo
cat <<EOF > .cargo/config.toml
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc" # 需提前安装mingw工具链
EOF
注:交叉编译需安装目标平台的C工具链(如Windows需
mingw-w64,ARM需gcc-arm-linux-gnueabihf),可通过Linux包管理器(apt、yum)安装。
cargo build --release生成优化后的Linux可执行文件(位于target/release/)。cargo build --target x86_64-pc-windows-gnu --release
生成的可执行文件可直接在目标系统运行(如.exe文件在Windows上执行)。.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]
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
若需将Linux应用分发给其他用户,可使用工具生成安装包:
cargo-deb并生成包:cargo install cargo-deb
cargo deb --release # 生成target/release/*.deb
cargo-rpm并生成包:cargo install cargo-rpm
cargo rpm --release # 生成target/release/*.rpm
生成的包可通过dpkg(Debian/Ubuntu)或rpm(Fedora/CentOS)安装到目标Linux系统。
serde),避免依赖系统库(如openssl);若必须使用系统库,通过pkg-config或vcpkg管理跨平台兼容性。musl工具链(rustup target add x86_64-unknown-linux-musl),生成静态链接的二进制文件:cargo build --target x86_64-unknown-linux-musl --release
此文件可在大多数Linux系统上直接运行,无需安装Rust或依赖库。