CentOS 上编译 C++ 报错的原因非常多,没有一个统一答案,但常见原因可以归纳成以下几类。你可以对照看看是哪一种,或者把具体报错信息发出来,我可以直接帮你定位。
很多人以为装了 gcc 就能编 C++,其实 C++ 需要 g++
g++ test.cpp -o test
# 报错:command not found: g++
✅ 解决:
yum install -y gcc-c++
很多最小化安装的 CentOS 根本没有编译环境
✅ 解决:
yum groupinstall "Development Tools" -y
比如:
fatal error: iostream: No such file or directory
原因:
✅ 解决:
yum install -y gcc-c++
比如 auto、nullptr、thread 报错
❌ 错误:
g++ test.cpp
✅ 正确:
g++ -std=c++11 test.cpp
g++ -std=c++14 test.cpp
g++ -std=c++17 test.cpp
CentOS 7 默认:
g++ 4.8.5
不支持:
✅ 解决(升级):
yum install -y centos-release-scl
yum install -y devtoolset-9
scl enable devtoolset-9 bash
比如用了 pthread、math
❌ 错误:
undefined reference to `pthread_create`
✅ 解决:
g++ test.cpp -lpthread
g++ test.cpp -lm
.c → 按 C 编译.cpp / .cc / .cxx → 按 C++ 编译❌ 错误:
gcc test.c # 实际是 C++ 代码
✅ 正确:
g++ test.cpp
把下面信息发给我,我可以直接告诉你哪里错了:
cat /etc/redhat-release
g++ --version
完整报错信息(复制粘贴)
你的编译命令
如果你愿意,可以直接把报错贴出来,我帮你一行一行分析。