温馨提示×

ubuntu c++怎么写第一个程序

小樊
43
2026-08-28 11:49:04
栏目: 编程语言

在 Ubuntu 上编写并运行你的第一个 C++ 程序,可以按下面步骤来(适合零基础)。


一、安装 C++ 编译环境

打开终端(Ctrl + Alt + T),执行:

sudo apt update
sudo apt install g++

安装完成后,检查版本:

g++ --version

能看到版本号说明安装成功。


二、创建你的第一个 C++ 程序

1️⃣ 创建文件

mkdir cpp_hello
cd cpp_hello
nano hello.cpp

你也可以用 vimgedit


2️⃣ 写代码

hello.cpp 中输入以下内容:

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, Ubuntu C++!" << endl;
    return 0;
}

保存并退出:

  • Ctrl + O → 回车
  • Ctrl + X

三、编译并运行

编译

g++ hello.cpp -o hello

运行

./hello

✅ 输出:

Hello, Ubuntu C++!

四、一步到位(进阶)

如果你想用 C++17:

g++ -std=c++17 hello.cpp -o hello

五、常见问题

❓ 没有 g++ 命令?

sudo apt install build-essential

❓ 文件没有执行权限?

chmod +x hello

六、总结流程

写代码 → 编译 → 运行
hello.cpp → g++ → hello → ./hello

如果你愿意,我可以继续教你:

  • ✅ 用 VS Code 写 C++
  • ✅ 写 多文件 C++ 项目
  • ✅ 用 CMake
  • ✅ 写 面向对象 / STL / 算法

你现在用的是 Ubuntu 桌面版还是服务器版

0