简化 CentOS C++ 配置流程
一键最小环境脚本
#!/usr/bin/env bash
set -e
sudo yum update -y
sudo yum groupinstall -y "Development Tools"
sudo yum install -y gcc gcc-c++ make cmake git vim gdb
echo -e '#!/usr/bin/env bash\nexec g++ "$@"' | sudo tee /usr/local/bin/c++ >/dev/null
sudo chmod +x /usr/local/bin/c++
cat > hello.cpp <<'EOF'
#include <iostream>
int main(){ std::cout<<"Hello, CentOS C++\n"; return 0; }
EOF
g++ -O2 -o hello hello.cpp && ./hello && rm -f hello hello.cpp
echo "C++ 环境已就绪:gcc=$(gcc -dumpversion), g++=$(g++ -dumpversion), cmake=$(cmake --version | head -1)"
使用较新 GCC 的标准做法
# 1) 安装 SCL 源与工具链
sudo yum install -y centos-release-scl
sudo yum install -y devtoolset-10-gcc devtoolset-10-gcc-c++
# 2) 临时启用(当前 shell)
scl enable devtoolset-10 bash
# 3) 永久生效(登录即启用,写入当前用户)
echo "source /opt/rh/devtoolset-10/enable" >> ~/.bashrc
source ~/.bashrc
# 4) 验证
gcc --version
g++ --version
常见坑与快速修复
wget https://cmake.org/files/v3.12/cmake-3.12.3.tar.gz
tar zxvf cmake-3.12.3.tar.gz && cd cmake-3.12.3
./bootstrap --prefix=/usr/local && make -j$(nproc) && sudo make install
sudo ln -sf /usr/local/bin/cmake /usr/bin/cmake
cmake --version
sudo yum install -y perl-IPC-Cmd。一键验证脚本
#!/usr/bin/env bash
set -e
echo "gcc: $(gcc -dumpversion), g++: $(g++ -dumpversion), cmake: $(cmake --version | head -1), gdb: $(gdb --version)"
cat > test.cpp <<'EOF'
#include <iostream>
#include <memory>
int main(){
std::unique_ptr<int> p = std::make_unique<int>(42);
std::cout << "Hello, CentOS C++ with unique_ptr, value=" << *p << "\n";
return 0;
}
EOF
g++ -O2 -std=c++17 -o test test.cpp && ./test && rm -f test test.cpp
echo "验证通过"