在 CentOS 上运行 C++ 程序报错的原因有很多,需要看具体错误信息才能准确判断。不过下面我按常见情况给你一个系统性的排查清单,你可以对照看看属于哪一种。
现象
-bash: g++: command not found
解决
sudo yum install gcc-c++
验证:
g++ --version
现象
error: ‘xxx’ was not declared in this scope
或
‘nullptr’ was not declared
原因:CentOS 默认可能用较老标准
解决
g++ test.cpp -std=c++11 -o test
推荐:
-std=c++14 或 -std=c++17
现象
fatal error: xxx.h: No such file or directory
解决
sudo yum install xxx-devel
例如:
sudo yum install openssl-devel
现象
./test: error while loading shared libraries: libxxx.so.1: cannot open shared object file
原因
解决
查找库:
ldd ./test
临时解决:
export LD_LIBRARY_PATH=/path/to/lib:$LD_LIBRARY_PATH
永久(不推荐随便改):
echo '/path/to/lib' | sudo tee /etc/ld.so.conf.d/xxx.conf
sudo ldconfig
现象
bash: ./test: Permission denied
解决
chmod +x test
./test
现象
/lib64/libc.so.6: version `GLIBC_2.28' not found
原因
解决
sudo yum install gcc-c++
g++ main.cpp -std=c++17 -o main
./main
请把以下信息发我:
cat /etc/centos-release
我可以一步一步帮你定位 ✅