在 CentOS 上遇到 gcc 编译慢,通常不是单一原因,可以按下面几个方向逐项排查和优化。
先区分:
查看方式:
top
htop
iostat -x 1
make -j$(nproc)
例如:
make -j8
⚠️ 不要 make -j 不加参数,容易内存爆炸。
cmake --build . -- -j$(nproc)
或:
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)
-march=native
gcc -march=native -O2
-O3(有时反而慢)-O2 通常比 -O3 编译更快-O3 会增加优化时间如果是大型项目:
./configure --disable-xxx
gcc --version
yum install centos-release-scl
yum install devtoolset-11
scl enable devtoolset-11 bash
或:
gcc 11 / 12 / 13
⚠️ 新 gcc 编译速度 明显更快
✅ 适合 C++ 大型项目
#include "stdafx.h"
CMake 示例:
target_precompile_headers(myapp PRIVATE stdafx.h)
✅ 优化建议:
#include缓存编译结果,二次编译极快
yum install ccache
使用方式:
export CC="ccache gcc"
export CXX="ccache g++"
或直接:
ccache gcc main.c
查看命中率:
ccache -s
适合服务器集群:
yum install distcc
NFS 编译速度会 非常慢
mkdir /tmp/build
mount -t tmpfs tmpfs /tmp/build
free -h
-j 数量✅ CentOS 7/8 实战方案
devtoolset-11
ccache
make -j$(nproc)
-O2
你可以告诉我:
我可以直接给你 最优编译参数和 Makefile 配置。