在 CentOS 上“无法编译 C++ 程序”通常不是系统本身不支持,而是缺少编译工具或环境配置问题。下面按常见原因和解决方法说明。
CentOS 默认最小化安装时不会带 C++ 编译器。
g++ --version
如果提示:
command not found
说明没有安装。
sudo yum install gcc gcc-c++ make -y
安装后再次检查:
g++ --version
例如:
auto x = 5;
编译时:
g++ test.cpp
在老版本 GCC 中可能报错。
✅ 正确方式:
g++ -std=c++11 test.cpp
或
g++ -std=c++14 test.cpp
fatal error: iostream: No such file or directory
原因:
gcc-c++✅ 解决:
sudo yum install gcc-c++
CentOS 7 默认 GCC 是 4.8.5,不支持部分现代 C++。
gcc -v
sudo yum install centos-release-scl -y
sudo yum install devtoolset-11 -y
scl enable devtoolset-11 bash
chmod +x a.out
运行程序时:
./a.out
而不是:
a.out
cat > test.cpp <<EOF
#include <iostream>
using namespace std;
int main() {
cout << "Hello CentOS" << endl;
return 0;
}
EOF
g++ test.cpp -o test
./test
| 错误 | 原因 | 解决 |
|---|---|---|
| command not found | 没装 g++ | yum install gcc-c++ |
| iostream not found | 没装 C++ | 同上 |
| C++11 特性报错 | 没加 -std |
-std=c++11 |
| 老系统不支持 | GCC 太旧 | devtoolset |
| 编译成功但不能运行 | 没加 ./ |
./a.out |
如果你能贴出具体报错信息(命令行 + 错误提示),我可以精确告诉你是哪一步出了问题。