在 CentOS 上运行 C++ 程序报错,原因可能有很多种,需要你提供具体报错信息才能准确判断。不过我可以先给你总结最常见的原因和排查方法,你可以对照看看。
现象
bash: g++: command not found
解决
sudo yum install gcc gcc-c++ -y
错误示例
g++ test.cpp
./a.out: Permission denied
正确方式
g++ test.cpp -o test
./test
例如:
#include <iostream>解决
g++ test.cpp -std=c++11 -o test
现象
./test: error while loading shared libraries: libxxx.so: cannot open shared object file
解决
ldd test # 查看缺哪个库
sudo yum install xxx
bash: ./test: Permission denied
解决
chmod +x test
例如:
解决
g++ test.cpp -static -o test
getenforce
如果是 Enforcing,可临时关闭测试:
sudo setenforce 0
dos2unix test.cpp
请贴出:
cat /etc/redhat-release
如果你愿意,把报错截图或文字直接发给我,我可以一步一步帮你定位 ✅