Ubuntu 下编译 C++ 报错的原因非常多,常见情况大致可以分为下面几类。你可以对照看看自己是哪一种,也可以把具体报错信息贴出来,我能更精确地帮你定位。
很多人只装了 gcc,但编译 C++ 需要用 g++。
症状
g++: command not found
解决
sudo apt update
sudo apt install g++
验证:
g++ --version
gcc main.cpp
这会报一堆 C++ 相关错误。
正确做法
g++ main.cpp -o main
例如:
cout << "hello";
但没写:
#include <iostream>
using namespace std;
典型错误
‘cout’ was not declared in this scope
C++ 文件应该是:
.cpp.cc.cxx如果是 .c,会按 C 语言编译。
undefined reference to `xxx`
常见原因:
.cpp例如用到 pthread:
g++ main.cpp -lpthread
auto x = 5;
报错:
error: ‘auto’ not allowed
解决
g++ main.cpp -std=c++11
例如用 OpenCV、Boost、MySQL:
sudo apt install libopencv-dev
-bash: ./a.out: Permission denied
解决:
chmod +x a.out
请直接贴出:
我可以直接告诉你是哪一行、为什么错、怎么改 ✅