CentOS 上 C++ 编译出错的原因很多,不能一概而论。下面我按最常见情况给你一个排查清单,并给出典型错误示例和解决方法。你可以对照看看,或者直接把完整报错贴出来,我可以精准帮你定位。
g++: command not found
sudo yum install -y gcc gcc-c++
验证:
g++ --version
gcc test.cpp
或
g++ test.cpp -o test
但文件不存在。
g++ test.cpp -o test
fatal error: iostream: No such file or directory
gcc-c++gcc 而不是 g++sudo yum install gcc-c++
error: ‘nullptr’ was not declared in this scope
g++ test.cpp -std=c++11 -o test
或
g++ test.cpp -std=c++17 -o test
/usr/include/c++/...: error: ‘xxx’ is not a member of ‘std’
安装 devtoolset:
sudo yum install -y centos-release-scl
sudo yum install -y devtoolset-11
scl enable devtoolset-11 bash
验证:
g++ --version
undefined reference to `pthread_create`
g++ test.cpp -lpthread
或:
g++ test.cpp -lm -lpthread
error: stray ‘\r’ in program
dos2unix test.cpp
| 检查项 | 命令 |
|---|---|
| 是否安装 g++ | g++ --version |
| 文件是否存在 | ls test.cpp |
| 编译命令 | g++ test.cpp -o test |
| 是否用 C++11+ | 加 -std=c++11 |
| CentOS 版本 | cat /etc/centos-release |
请把下面信息发我(越全越好):
cat /etc/centos-release
g++ xxx.cpp -o xxx
完整报错信息(不要只贴一行)
源码(关键部分即可)
✅ 只要你贴出来,我可以直接告诉你:
是哪一行代码、哪个环境、怎么改。