温馨提示×

centos编译rust注意什么

小樊
57
2026-10-17 11:12:32
栏目: 编程语言

在 CentOS 上编译 Rust 程序(或编译 Rust 工具链本身)时,有几个常见坑和注意点,下面按「使用 Rust 编译程序」和「从源码编译 Rust 工具链」两种情况说明。


一、在 CentOS 上使用 Rust 编译程序(最常见)

1️⃣ 系统版本与 glibc

  • CentOS 7:glibc 2.17,较旧
    • 编译出的二进制在 CentOS 7+ 可用
    • 但不兼容更低版本(如某些老 Linux)
  • CentOS 8 / Stream:glibc 较新,兼容性更好

✅ 建议:

ldd --version

确认 glibc 版本


2️⃣ 安装 Rust(推荐方式)

不要用 yum 自带的 rust(版本很旧)

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

更新:

rustup update

3️⃣ C 依赖与 gcc

很多 Rust crate 依赖 C 库(如 openssl、zlib)

安装基础编译工具

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

CentOS 7 特别注意

  • gcc 版本低(4.8)
  • 某些新版 crate 可能不支持

可安装 devtoolset:

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

4️⃣ OpenSSL 问题(高频坑)

Rust 的 openssl crate 很容易炸

✅ 推荐方案(省事):

[dependencies]
openssl = { version = "0.10", features = ["vendored"] }

或改用:

rustls = "0.21"

5️⃣ 静态编译(可选)

如果你希望二进制不依赖系统库:

cargo build --release --target x86_64-unknown-linux-musl

需要:

rustup target add x86_64-unknown-linux-musl

6️⃣ 编译慢

  • 第一次编译很慢(依赖多)
  • 可用缓存:
export CARGO_HOME=/path/to/cache

二、从源码编译 Rust 工具链(不常见)

1️⃣ 依赖

sudo yum install -y \
  git curl gcc gcc-c++ make \
  python3 cmake openssl-devel

2️⃣ Python 版本

  • CentOS 7 默认 python2
  • Rust 编译需要 python3
sudo yum install python3

3️⃣ 编译命令

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 + 缓存

四、总结建议(CentOS 最佳实践)

✅ 用 rustup
✅ 装 devtoolset(CentOS 7)
✅ 避免系统 openssl
✅ 需要分发就用 musl

如果你说的是 CentOS 几?编译什么项目(如 tokio / rocket / 数据库),我可以给你更具体的配置。

0 踩