在 Linux 下用 C++ 运行报错 的原因非常多,不能一概而论。下面我按最常见情况给你一个排查清单,并配上典型错误示例和解决方法。你可以对照看看,或者直接把报错信息贴出来,我可以精确定位。
| 现象 | 原因 | 解决方法 |
|---|---|---|
command not found |
没装 g++ | sudo apt install g++ |
No such file or directory |
路径或文件名错 | 检查路径 |
undefined reference |
只编译没链接 / 缺库 | 加 -o、加 -lxxx |
segmentation fault |
野指针、越界 | 用 gdb 调试 |
Permission denied |
没执行权限 | chmod +x a.out |
error: iostream: No such file |
没装开发环境 | 安装 build-essential |
| 编译通过但运行没输出 | 程序逻辑问题 | 加调试输出 |
// main.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello Linux" << endl;
return 0;
}
g++ main.cpp -o main
./main
g++: command not found
✅ 解决:
sudo apt update
sudo apt install g++ build-essential
g++ main.cpp
./a.out
✅ 实际上是对的,但如果你:
g++ -c main.cpp
./main.o ❌
就会报错:
cannot execute binary file
✅ 正确:
g++ main.cpp -o main
./main
#include <iostream>
报错:
iostream: No such file or directory
✅ 解决:
sudo apt install build-essential
// main.cpp
#include <cmath>
int main() {
double x = sqrt(2.0);
}
编译:
g++ main.cpp
✅ 正确:
g++ main.cpp -lm
int *p = nullptr;
*p = 10; // ❌
运行:
Segmentation fault (core dumped)
✅ 用 gdb 调试:
g++ main.cpp -g
gdb ./a.out
run
bt
bash: ./main: Permission denied
✅ 解决:
chmod +x main
./main
g++ -Wall -Wextra -g main.cpp -o main
2>&1 | tee build.log
你可以直接贴出:
我可以一步一步帮你改到能跑 ✅