在 openEuler Linux 上安装 Rust
Rust 在 openEuler 上推荐使用官方工具链管理器 rustup 安装。相比 dnf 直接安装,rustup 可以随时切换 stable、beta、nightly 版本,也方便后续管理组件和交叉编译目标。
1. 安装基础编译依赖
Rust 编译部分 crate 时需要系统 C 编译器和链接器,openEuler 上建议先安装开发工具组:
sudo dnf update -y
sudo dnf groupinstall -y "Development Tools"
sudo dnf install -y curl git
如果后续编译用到 OpenSSL 等库,可能还需要:
sudo dnf install -y openssl-devel pkg-config
2. 配置国内镜像源(推荐)
国内服务器直接访问官方源可能较慢,可以先设置 rustup 镜像环境变量,再执行安装脚本。这里以清华大学镜像为例:
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup
如果想长期生效,可以写入 ~/.bashrc:
echo 'export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup' >> ~/.bashrc
echo 'export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup' >> ~/.bashrc
source ~/.bashrc
3. 安装 rustup 和 Rust 工具链
执行官方安装脚本:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
安装过程中选择默认选项(输入 1)即可,会自动安装 stable 版 rustc、cargo 和 rustup。
安装完成后激活环境变量:
source "$HOME/.cargo/env"
验证安装:
rustc --version
cargo --version
rustup --version
正常输出版本号即表示安装成功。
4. 配置 Cargo 国内镜像源
rustup 镜像只加速工具链下载,Cargo 拉取 crate 依赖还需要单独配置。编辑配置文件:
vim ~/.cargo/config.toml
写入以下内容(使用清华大学稀疏索引源):
[source.crates-io]
replace-with = 'tuna'
[source.tuna]
registry = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"
如果使用中科大镜像,可以改为:
[source.crates-io]
replace-with = 'ustc'
[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"
5. 创建测试项目
cargo new hello_rust
cd hello_rust
cargo run
输出 Hello, world! 即表示环境完全可用。
发布构建:
cargo build --release
编译产物位于 target/release/hello_rust。
6. 常用 rustup 命令
| 命令 | 作用 |
|---|---|
rustup update |
更新工具链 |
rustup default nightly |
切换到 nightly 通道 |
rustup install 1.80.0 |
安装指定版本 |
rustup target list |
查看可用编译目标 |
rustup target add x86_64-unknown-linux-musl |
添加交叉编译目标 |
rustup component add clippy rustfmt |
安装代码检查和格式化组件 |
rustup self uninstall |
卸载 Rust |
7. 可选:通过 dnf 安装(不推荐)
如果网络受限且对版本要求不高,也可以直接通过系统包安装:
sudo dnf install -y rust cargo
但软件源中的版本通常较旧,且无法灵活切换工具链,仅适合临时使用。
常见问题
| 问题 | 处理方式 |
|---|---|
curl: command not found |
sudo dnf install -y curl |
linker 'cc' not found |
sudo dnf groupinstall -y "Development Tools" |
安装卡在 downloading component 'rustc' |
配置 RUSTUP_DIST_SERVER 镜像后重试 |
cargo build 拉依赖超时 |
配置 ~/.cargo/config.toml 国内源 |
rustc: command not found |
执行 source "$HOME/.cargo/env" |
小结
在 openEuler 上安装 Rust,推荐流程如下:
# 1. 安装依赖
sudo dnf groupinstall -y "Development Tools"
sudo dnf install -y curl git
# 2. 配置 rustup 镜像
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup
# 3. 安装 rustup
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"
# 4. 配置 Cargo 镜像源
vim ~/.cargo/config.toml
# 5. 验证
rustc --version && cargo --version
这套方式版本可控、升级方便,后续如果要在 openEuler 上编译部署 Rust Web 服务或 CLI 工具,直接用 cargo build --release 即可。
- 点赞
- 收藏
- 关注作者
评论(0)