在 Ubuntu 上运行 C++ 文件,一般分为 安装编译器 → 编写代码 → 编译 → 运行 四个步骤。下面给你一个从零开始的完整流程。
Ubuntu 默认可能没有安装 g++,先安装:
sudo apt update
sudo apt install g++
安装完成后,检查版本:
g++ --version
hello.cpp:nano hello.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello, Ubuntu!" << endl;
return 0;
}
保存并退出(nano 中按 Ctrl + O → 回车 → Ctrl + X)。
使用 g++ 编译:
g++ hello.cpp -o hello
说明:
hello.cpp:源文件-o hello:生成可执行文件 hello如果代码有错误,会在这里提示。
./hello
输出:
Hello, Ubuntu!
g++ main.cpp func.cpp -o app
g++ hello.cpp -o hello -std=c++17
g++ hello.cpp -o hello -g
如果你不想用命令行,也可以安装:
例如安装 VS Code:
sudo snap install code --classic
g++: command not found说明没安装 g++,回到第一步重新安装。
Permission denied记得用 ./程序名 运行,不能直接 hello。
如果你愿意,我也可以:
你现在用的是 Ubuntu 桌面版还是服务器版?