在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或依賴庫。