在 CentOS 上运行 C++ 程序报错,原因可能有很多种。下面我按常见情况给你梳理一下,并给出排查思路。你看看符合哪一种。
报错示例:
bash: g++: command not found
解决:
sudo yum install gcc gcc-c++ -y
报错示例:
error: ‘nullptr’ was not declared in this scope
原因:CentOS 默认 g++ 版本较低(如 4.8.5)
解决:
g++ -std=c++11 test.cpp -o test
# 或
g++ -std=c++17 test.cpp -o test
如果还不够新:
sudo yum install centos-release-scl
sudo yum install devtoolset-9
scl enable devtoolset-9 bash
报错示例:
./test: error while loading shared libraries: libxxx.so: cannot open shared object file
解决:
ldd ./test # 看缺哪个库
然后:
export LD_LIBRARY_PATH=/path/to/lib:$LD_LIBRARY_PATH
报错示例:
bash: ./test: Permission denied
解决:
chmod +x test
./test
报错示例:
./test: /lib64/libc.so.6: version `GLIBC_2.14' not found
原因:程序在更高版本系统编译,CentOS 太老
解决:
g++ -static test.cpp -o test
可能原因:
调试:
g++ -g test.cpp -o test
gdb ./test
比如:
查看:
ulimit -a
free -m
请你把完整报错信息贴出来,我可以直接帮你判断是哪一种,比如:
如果你愿意,也可以告诉我:
cat /etc/redhat-release)g++ --version)我可以一步一步帮你解决。