在Linux系统上,使用rustup(Rust官方安装工具)安装Rust编译器及核心工具链。运行以下命令完成安装并配置环境:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
安装完成后,可通过rustc --version验证是否成功。
使用cargo(Rust包管理器)创建新项目,进入项目目录:
cargo new cross_platform_project
cd cross_platform_project
cargo会自动生成Cargo.toml(依赖配置)和src/main.rs(主程序)文件。
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(); // 根据目标平台调用对应函数
}
此外,优先使用跨平台库(如crossbeam用于并发、tokio用于异步、serde用于序列化),避免直接调用平台特定API。
若需从Linux编译到其他平台(如Windows、macOS),需添加对应交叉编译目标并安装工具链。例如,编译到Windows 64位:
rustup target add x86_64-pc-windows-gnu # 使用gnu工具链
# 或
rustup target add x86_64-pc-windows-msvc # 使用MSVC工具链(需安装Visual Studio Build Tools)
对于嵌入式或轻量级场景,可使用musl工具链(静态编译):
rustup target add x86_64-unknown-linux-musl
配置.cargo/config.toml文件(可选),指定目标平台的链接参数:
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc" # 指定Windows链接器
cargo build(调试模式)或cargo build --release(优化发布模式)生成可执行文件,位于target/debug/或target/release/目录。cargo build --target=x86_64-pc-windows-gnu
.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
cargo-deb生成Debian包(.deb),或cargo-rpm生成RPM包(.rpm),便于在Linux发行版间分发:cargo install cargo-deb # 安装deb打包工具
cargo deb --release # 生成.deb文件
cargo install cargo-rpm # 安装rpm打包工具
cargo rpm --release # 生成.rpm文件
.exe文件)。使用log(日志门面)和env_logger(环境变量控制日志)库记录程序运行状态,便于跨平台调试:
# Cargo.toml添加依赖
[dependencies]
log = "0.4"
env_logger = "0.9"
代码中初始化日志并记录信息:
use log::{info, error};
fn main() {
env_logger::init(); // 初始化日志(通过RUST_LOG环境变量控制级别)
info!("Application started");
if let Err(e) = some_function() {
error!("Error occurred: {}", e); // 记录错误信息
}
}
运行程序时,通过RUST_LOG=info cargo run开启日志输出。