在 Ubuntu 下 C++ 报错 的原因非常多,需要具体问题具体分析。你可以把完整报错信息贴出来,我可以精准帮你定位。
下面我先给你一个常见原因速查表,你可以对照看看属于哪一类。
g++: command not found
✅ 解决:
sudo apt update
sudo apt install g++
检查版本:
g++ --version
❌ 错误示例:
g++ main.cpp
✅ 正确:
g++ main.cpp -o main
./main
fatal error: iostream: No such file or directory
✅ 原因:
.cpp✅ 解决:
sudo apt install build-essential
error: ‘xxx’ was not declared in this scope
✅ 解决(推荐):
g++ main.cpp -std=c++17 -o main
例如:
cout << "hello world"
❌ 少了分号
✅ 正确:
cout << "hello world";
using namespace std;cout << "hello";
✅ 改法之一:
std::cout << "hello";
或:
using namespace std;
multiple definition of `main'
✅ 检查:
.cpp 文件里都写了 main.cpp 文件undefined reference to `xxx`
✅ 常见原因:
.cpp 文件一起编译✅ 示例:
g++ main.cpp func.cpp -o main
Permission denied
✅ 解决:
chmod +x main
./main
sudo apt install build-essential
编译命令模板:
g++ xxx.cpp -std=c++17 -Wall -o xxx
请直接贴出以下 任意一项或全部:
1️⃣ 完整报错信息(全部复制)
2️⃣ 你的 C++ 代码
3️⃣ 你用的编译命令
4️⃣ Ubuntu 版本(如 20.04 / 22.04)
例如:
Ubuntu 22.04
g++ test.cpp
错误信息:
error: ‘cout’ was not declared in this scope
我可以一步一步帮你改 ✅