温馨提示×

ubuntu gcc怎样写第一个程序

小樊
42
2026-10-24 15:17:45
栏目: 智能运维

下面以 Ubuntu + GCC 为例,教你写并运行你的第一个 C 程序(最常见入门示例)。


一、检查 GCC 是否安装

打开终端(Ctrl + Alt + T),输入:

gcc --version

如果看到类似 gcc (Ubuntu ...),说明已安装。

如果没安装,执行:

sudo apt update
sudo apt install gcc

二、创建第一个 C 程序

1. 创建源文件

mkdir hello
cd hello
nano hello.c

你也可以用 gedit hello.c 或 vim hello.c

2. 写入代码

#include <stdio.h>

int main() {
    printf("Hello, Ubuntu!\n");
    return 0;
}

按 Ctrl + O 保存,Ctrl + X 退出(nano)。


三、用 GCC 编译

gcc hello.c -o hello
  • hello.c:源文件
  • -o hello:生成可执行文件名为 hello

四、运行程序

./hello

输出:

Hello, Ubuntu!

五、常见问题

1. 权限问题

如果提示 Permission denied:

chmod +x hello
./hello

2. 编译多个文件

gcc main.c func.c -o app

六、可选:写 C++ 程序

如果是 C++:

sudo apt install g++
#include <iostream>
using namespace std;

int main() {
    cout << "Hello Ubuntu" << endl;
}

编译:

g++ hello.cpp -o hello
./hello

如果你愿意,我也可以教你:

  • 用 Makefile
  • 用 VS Code + Ubuntu
  • 写 Linux 系统编程
  • 或第一个 Python / C++ 程序

你想从哪一步继续?

0 踩