在 CentOS 上编译 Rust 程序(或编译 Rust 工具链本身)时,有几个常见坑和注意点,下面按「使用 Rust 编译程序」和「从源码编译 Rust 工具链」两种情况说明。
✅ 建议:
ldd --version
确认 glibc 版本
不要用 yum 自带的 rust(版本很旧)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source ~/.cargo/env
更新:
rustup update
很多 Rust crate 依赖 C 库(如 openssl、zlib)
sudo yum groupinstall "Development Tools"
sudo yum install -y openssl-devel zlib-devel
可安装 devtoolset:
sudo yum install centos-release-scl
sudo yum install devtoolset-11
scl enable devtoolset-11 bash
Rust 的 openssl crate 很容易炸
✅ 推荐方案(省事):
[dependencies]
openssl = { version = "0.10", features = ["vendored"] }
或改用:
rustls = "0.21"
如果你希望二进制不依赖系统库:
cargo build --release --target x86_64-unknown-linux-musl
需要:
rustup target add x86_64-unknown-linux-musl
export CARGO_HOME=/path/to/cache
sudo yum install -y \
git curl gcc gcc-c++ make \
python3 cmake openssl-devel
sudo yum install python3
git clone https://github.com/rust-lang/rust.git
cd rust
./x.py build
⚠️ 非常耗时(几十分钟到几小时)
| 错误 | 原因 | 解决 |
|---|---|---|
GLIBC_2.18 not found |
系统太旧 | 升级系统或静态编译 |
openssl-sys 报错 |
openssl 版本 | 用 vendored |
cc not found |
没装 gcc | 装 Development Tools |
| 编译极慢 | 依赖多 | 用 release + 缓存 |
✅ 用 rustup
✅ 装 devtoolset(CentOS 7)
✅ 避免系统 openssl
✅ 需要分发就用 musl
如果你说的是 CentOS 几?编译什么项目(如 tokio / rocket / 数据库),我可以给你更具体的配置。