“Linux 下 C++ 编译报错”是一个非常宽泛的问题,需要看具体报错信息才能准确判断。不过,我可以先给你总结 Linux C++ 常见编译报错原因 + 典型示例 + 排查方法,你对照一下通常就能定位。
g++: command not found
✅ 解决:
sudo apt install g++ # Ubuntu/Debian
sudo yum install gcc-c++ # CentOS
cc hello.cpp
✅ 正确:
g++ hello.cpp -o hello
fatal error: xxx.h: No such file or directory
✅ 原因:
-I✅ 解决:
g++ main.cpp -I/path/to/include
undefined reference to `func()'
✅ 原因:
.cpp,没链接 .o✅ 解决:
g++ main.cpp func.cpp -o app
或
g++ main.cpp -lxxx -L/path/to/lib
error: ‘for’ loop initial declarations are only allowed in C99 or C++11
✅ 解决:
g++ main.cpp -std=c++11
expected ‘;’ before ‘}’ token
✅ 检查:
}undefined reference to `main'
❌ 错误:
void main() {}
✅ 正确:
int main() { return 0; }
例如:
test.cpp:12:5: error: ...
如果你愿意,直接把下面内容贴出来,我可以逐行帮你看:
我可以告诉你:是哪一行、为什么错、怎么改。