温馨提示×

Ubuntu Rust编译器怎么设置

小樊
40
2025-12-20 12:21:20
栏目: 编程语言

Ubuntu 上设置 Rust 编译器的推荐做法


一 安装与初始化

  • 安装依赖工具(便于后续编译本地依赖与构建):
    • 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 -V、cargo -V
  • 国内下载加速(可选,设置环境变量后再运行安装脚本):
    • export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static
    • export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup
  • 备选方式(系统仓库安装,版本通常较旧,适合只需基础使用):
    • sudo apt install -y rustc cargo
    • 验证:rustc -Vv、which rustc

二 配置 Cargo 与国内源

  • 配置 crates.io 镜像(提升依赖下载速度,写入用户级配置):
    • mkdir -p $HOME/.cargo
    • 将以下内容写入 $HOME/.cargo/config.toml
      • [registries.crates-io]
        • index = “https://mirrors.tuna.tsinghua.edu.cn/crates.io-index”
  • 说明:上述为 TOML 格式;如使用旧版文件 $HOME/.cargo/config(INI 风格),可用:
    • [source.crates-io]
      • registry = “https://github.com/rust-lang/crates.io-index”
      • replace-with = ‘ustc’
    • [source.ustc]
      • registry = “git://mirrors.ustc.edu.cn/crates.io-index”

三 常用工具与交叉编译设置

  • 更新与组件管理:
    • 更新工具链:rustup update
    • 安装常用组件:rustup component add llvm-tools-preview、rustup component add rustfmt、rustup component add clippy
    • 二进制工具集:cargo install cargo-binutils(提供 objdump、nm、size 等)
  • 交叉编译示例(添加目标三元组):
    • 查看可用目标:rustup target list
    • 安装 RISC-V 目标(嵌入式常用):rustup target add riscv32imac-unknown-none-elf
  • 主机工具链依赖(解决链接/构建问题):
    • sudo apt install -y pkg-config libssl-dev

四 快速验证与第一个程序

  • 使用 rustc 直接编译运行:
    • echo ‘fn main(){println!(“Hello, Rust on Ubuntu”);}’ > main.rs
    • rustc main.rs && ./main
  • 使用 Cargo 管理项目:
    • cargo new hello_cargo && cd hello_cargo
    • cargo run(开发构建)或 cargo build --release(发布构建)
    • 可执行文件位于:target/debug/hello_cargo 或 target/release/hello_cargo

五 常见问题与排查

  • 报错 linker ‘cc’ not found:
    • 原因:缺少 GNU 编译工具链
    • 解决:sudo apt install -y build-essential
  • 安装或更新缓慢:
    • 检查是否设置了 RUSTUP_DIST_SERVER / RUSTUP_UPDATE_ROOT 镜像环境变量,或配置 Cargo 镜像源
  • 版本过旧(APT 安装场景):
    • 建议改用 rustup 获取最新稳定版工具链,便于多版本与组件管理

0