“Ubuntu 下 C++ 报错”这个问题太宽泛了,我需要具体信息才能准确帮你。不过我可以先给你最常见的原因 + 排查方法,你可以对照看看,然后把具体报错信息贴出来。
很多新手直接用:
gcc test.cpp
但 C++ 应该用 g++。
✅ 正确方式:
g++ test.cpp -o test
./test
如果没装 g++:
sudo apt update
sudo apt install g++
比如:
#include <iostream>
报错:
fatal error: iostream: No such file or directory
✅ 原因:
build-essentialgcc 而不是 g++✅ 解决:
sudo apt install build-essential
例如:
int main()
{
cout << "hello" << endl;
}
报错:
‘cout’ was not declared in this scope
✅ 正确写法:
#include <iostream>
using namespace std;
int main() {
cout << "hello" << endl;
return 0;
}
如果你用了 auto、range for 等 C++11/17 特性:
for (auto x : v) {}
但编译时没指定标准:
g++ test.cpp
✅ 建议:
g++ -std=c++17 test.cpp -o test
例如:
undefined reference to `pthread_create`
✅ 需要加链接库:
g++ test.cpp -lpthread
从 Windows 拷过来的 .cpp 文件可能报错。
✅ 解决:
dos2unix test.cpp
你可以直接把下面内容贴出来,我可以精确定位问题:
1️⃣ 完整报错信息(复制终端内容)
2️⃣ 源代码(至少 main 函数)
3️⃣ 编译命令
4️⃣ Ubuntu 版本(可选):
lsb_release -a
// test.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello Ubuntu C++" << endl;
return 0;
}
编译运行:
g++ -std=c++17 test.cpp -o test
./test
如果你愿意,直接把报错截图或文字贴出来,我可以一步一步帮你改 ✅