温馨提示×

centos如何用cargo构建

小樊
42
2026-10-26 08:26:53
栏目: 编程语言

在 CentOS 上使用 cargo(Rust 的构建工具)一般分为下面几个步骤:


一、安装 Rust 和 Cargo

方式 1:使用官方脚本(推荐)

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

安装完成后,加载环境:

source $HOME/.cargo/env

验证:

cargo --version
rustc --version

方式 2:使用 yum(版本较旧,不推荐)

sudo yum install rust cargo

二、安装编译依赖(CentOS 常见)

如果是 CentOS 7/8,可能需要:

sudo yum groupinstall "Development Tools"
sudo yum install openssl-devel

三、用 Cargo 构建项目

1️⃣ 新建项目

cargo new my_project
cd my_project

2️⃣ 构建

cargo build

-release 模式:

cargo build --release

3️⃣ 运行

cargo run

4️⃣ 只检查不生成二进制

cargo check

四、常见问题

❌ 报错:glibc / gcc 版本太低

CentOS 7 默认 gcc 太旧,可升级:

sudo yum install centos-release-scl
sudo yum install devtoolset-9
scl enable devtoolset-9 bash

❌ 网络问题(crates.io 无法访问)

可配置镜像(如清华源):

mkdir -p ~/.cargo
cat > ~/.cargo/config.toml <<EOF
[source.crates-io]
replace-with = "tuna"

[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/crates.io-index"
EOF

五、总结

✅ CentOS 上使用 cargo 的核心步骤:

  1. 安装 Rust(rustup)
  2. 安装编译工具链
  3. cargo build / cargo run

如果你用的是 CentOS 7 还是 8/Stream,或者遇到具体报错,可以把错误信息贴出来,我可以帮你具体分析。

0 踩