Rust 在 Ubuntu 上如何配置
导读:在 Ubuntu 上配置 Rust 的完整步骤 一 安装前准备 更新索引并安装基础编译工具,避免后续编译时报错(如缺少 cc 链接器): 命令:sudo apt update && sudo apt install -y...
在 Ubuntu 上配置 Rust 的完整步骤
一 安装前准备
- 更新索引并安装基础编译工具,避免后续编译时报错(如缺少 cc 链接器):
- 命令:
sudo apt update & & sudo apt install -y curl build-essential gcc make
- 命令:
- 说明:这些依赖提供 gcc、make 等工具链,满足大多数 Rust 项目的构建需求。
二 安装与初始化 Rust 工具链
- 使用 rustup(Rust 官方工具链管理器)安装稳定版,推荐方式:
- 命令:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - 安装时选择默认选项(安装 stable + cargo)。
- 命令:
- 激活环境变量:
- 命令:
source "$HOME/.cargo/env" - 或重新打开终端,使
cargo、rustc加入 PATH。
- 命令:
- 验证安装:
- 命令:
rustc --version、cargo --version - 成功示例:
rustc 1.72.1 (2023-12-20)、cargo 1.72.1 (2023-12-20)。
- 命令:
三 国内镜像加速(可选)
- 方式一(安装阶段加速):设置环境变量后再运行安装脚本
- 命令:
export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-staticexport RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup- 再执行:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
- 命令:
- 方式二(安装后持久化):写入 shell 配置文件
- 命令:
echo 'export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static' > > ~/.profile - 命令:
echo 'export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup' > > ~/.profile
- 命令:
- 方式三(Cargo 包索引镜像):配置
~/.cargo/config.toml- 示例(清华源):
- 文件:
~/.cargo/config.toml - 内容:
[registries] crates-io = { index = "https://mirrors.tuna.tsinghua.edu.cn/crates.io-index" }
- 文件:
- 示例(清华源):
- 说明:镜像可显著提升在 中国大陆 的下载速度;如使用 git:// 索引,请确保系统允许该协议或改用 https。
四 常用配置与管理
- 工具链管理(多版本并存与切换)
- 查看:
rustup toolchain list - 安装 nightly:
rustup toolchain install nightly - 切换默认:
rustup default nightly - 临时使用某工具链:
rustup run nightly cargo build
- 查看:
- 组件与 Profile
- 查看当前 profile:
rustup show profile - 可选 profile:minimal(仅 rustc/cargo/std)、default(含 rust-docs、rustfmt、Clippy)、complete(全部组件)
- 查看当前 profile:
- 更新与卸载
- 更新工具链:
rustup update - 卸载:
rustup self uninstall
- 更新工具链:
- 常用命令
- 新建项目:
cargo new hello_world & & cd hello_world - 构建/运行:
cargo build、cargo run - 检查:
cargo check
- 新建项目:
五 常见问题与排查
- 编译时报错 linker ‘cc’ not found
- 原因:缺少 GNU 编译器工具链。
- 解决:
sudo apt install -y build-essential
- 安装或更新缓慢/失败
- 检查是否设置了 RUSTUP_DIST_SERVER 与 RUSTUP_UPDATE_ROOT,或改用 Cargo 镜像;必要时更换为 USTC 或 清华 镜像源并重试。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Rust 在 Ubuntu 上如何配置
本文地址: https://pptw.com/jishu/768916.html
