centos

如何简化CentOS C++配置流程

小樊
45
2026-01-08 00:46:42
栏目: 编程语言

简化 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

常见坑与快速修复

一键验证脚本

#!/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 "验证通过"

0
看了该问题的人还看了