在 CentOS 上优化 Rust 编译(速度 / 体积 / 性能)通常从 编译配置、工具链、系统环境 三方面入手。下面按「实用程度」给你一套方案。
# Cargo.toml
[profile.release]
opt-level = 2
lto = false
codegen-units = 256
如果你不关心最终性能,只关心编译快:
[profile.dev]
opt-level = 0
debug = false
sccache(强烈推荐)避免重复编译依赖:
cargo install sccache
export RUSTC_WRAPPER=sccache
CentOS 安装依赖:
yum install -y openssl-devel
mold 链接器(速度提升明显)yum install -y mold
# .cargo/config.toml
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=mold"]
cargo build -j 8
或修改:
export CARGO_BUILD_JOBS=8
[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
strip = true
upx(可选)yum install -y upx
upx --best target/release/your_bin
[profile.release]
opt-level = 3
lto = "fat"
codegen-units = 1
target-cpu = "native"
RUSTFLAGS="-C target-cpu=native"
⚠️ 注意:native 编译的二进制不能跨机器
CentOS 7 的 glibc 较老,建议:
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "target-feature=+crt-static"]
yum install -y gcc-toolset-12
scl enable gcc-toolset-12 bash
rustup target add x86_64-unknown-linux-musl
cargo build --target x86_64-unknown-linux-musl
✅ 开发快
sccache + mold + dev profile
✅ 生产小
opt-level=z + lto + strip
✅ 高性能
opt-level=3 + fat lto + native cpu
如果你愿意,可以告诉我:
我可以直接给你 一套可复制的 Cargo.toml + 命令。