Debian上的Rust编译器怎么用
小樊
43
2025-12-09 02:52:57
在 Debian 上使用 Rust 编译器
一 安装与验证
- 推荐方式:使用 rustup(官方版本管理工具)
- 更新索引并安装基础构建工具(可选但推荐):sudo apt update && sudo apt install -y curl build-essential gcc make
- 安装 rustup:curl --proto ‘=https’ --tlsv1.2 -sSf https://sh.rustup.rs | sh
- 使环境变量生效:source $HOME/.cargo/env
- 验证:rustc --version、cargo --version
- 替代方式:使用 apt(仓库稳定版)
- 安装:sudo apt update && sudo apt install -y rustc cargo
- 验证:rustc --version、cargo --version
以上两种方式任选其一即可;rustup 便于多版本与工具链管理,apt 更贴近系统仓库的稳定版本。
二 快速上手 Cargo 项目
- 创建并运行
- cargo new hello_world && cd hello_world
- cargo build(构建)
- cargo run(构建并运行)
- 仅编译单个文件
- 编辑 main.rs,然后:rustc main.rs
- 运行:./main(Linux 下)
- 常用构建与运行
- 发布构建:cargo build --release
- 运行测试:cargo test
以上命令覆盖了最常见的开发与调试流程。
三 常用配置与管理
- 设置默认工具链
- 全局稳定版:rustup default stable
- 切换夜间版:rustup default nightly
- 交叉编译目标
- 添加目标:rustup target add armv7-unknown-linux-gnueabihf
- 配置镜像源(可选,加速国内下载)
- 编辑或创建 ~/.cargo/config.toml,加入例如:
[source.crates-io]
replace-with = ‘tuna’
[source.tuna]
registry = “https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git”
- 升级与卸载
- rustup 升级:rustup update
- 卸载 rustup:rustup self uninstall
这些配置可帮助你管理版本、目标平台与依赖下载效率。
四 进阶示例 WebAssembly
- 安装工具
- sudo apt install -y wabt
- cargo install wasm-bindgen-cli
- 创建 lib 项目并添加依赖
- cargo new --lib wasm_example && cd wasm_example
- Cargo.toml 中添加:wasm-bindgen = “0.2”
- 编写代码(src/lib.rs)
- use wasm_bindgen::prelude::*;
#[wasm_bindgen] pub fn add(a: i32, b: i32) -> i32 { a + b }
- 构建与导出
- cargo build --target wasm32-unknown-unknown --release
- wasm-bindgen target/wasm32-unknown-unknown/release/wasm_example.wasm --out-dir ./pkg --target web
- 本地预览
- python3 -m http.server,浏览器访问 http://localhost:8000
该示例展示了在 Debian 上将 Rust 编译为 WebAssembly 并在网页中调用的完整链路。
五 将程序打包为 Debian 包
- 安装打包工具:cargo install cargo-deb
- 在项目根目录生成 .deb:cargo deb
- 安装生成的包:sudo dpkg -i target/debian/*.deb
适合将 Rust 二进制发布为 .deb 供系统级分发与部署。