CentOS 下 C++ 编译报错的原因非常多,不能一概而论,需要看具体错误信息。不过我可以给你总结一下在 CentOS 上 C++ 编译最常见的原因和对应解决办法,你可以对照看看。
很多人刚装好 CentOS,直接 g++ test.cpp,结果报错:
command not found: g++
✅ 解决:
sudo yum groupinstall "Development Tools"
# 或
sudo yum install gcc gcc-c++
验证:
g++ --version
例如:
auto x = 1;
报错类似:
error: ‘auto’ not allowed in C++98
✅ 解决:
g++ test.cpp -std=c++11
# 或
g++ test.cpp -std=c++17
报错示例:
fatal error: xxx.h: No such file or directory
常见原因:
-I✅ 解决:
sudo yum install xxx-devel
例如:
sudo yum install openssl-devel
编译时:
g++ main.cpp -I/usr/include/xxx
报错示例:
undefined reference to `pthread_create'
✅ 解决(加链接库):
g++ main.cpp -lpthread
常见库:
-lpthread-lm-lstdc++-lcurl-lboost_system比如:
✅ 解决(升级 gcc):
sudo yum install centos-release-scl
sudo yum install devtoolset-9
scl enable devtoolset-9 bash
报错:
Permission denied
✅ 解决:
chmod +x a.out
# 或
sudo g++ test.cpp
请直接把完整的报错信息贴出来,例如:
g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:5: error: ...
我可以帮你精确判断是哪一种原因。
cat /etc/redhat-release)只要你贴出来,我就能告诉你 为什么报错 + 怎么改 ✅