Our First C Program

| 2 min read

Hello, world!

In keeping with the programming tradition, the first program we write when learning a new programming language prints the greeting “Hello, world!” to the screen. Here’s one way to do it in C:

hello.c
#include <stdio.h>

int main()
{
    puts("Hello, world!"); // Greet the world!
    return 0;
}

(In the discussion that follows, we will refer to this program as the “hello-world program.”)

We will shortly explain how it works. But first, let’s see the result of runnng it on our computer.

Assuming the hello-world program is saved in a file named hello.c, as indicated above, here’s how we compile and run it:

$ gcc hello.c
$ ./a.out
Hello, world!

We invoke the gcc command—the GNU C compiler—in the first command line to compiler our C program into an equivalent machine-language program.1 GCC, like all traditional C compilers on Unix systems, stores the generated machine language program in a file named a.out—assuming, of course, that there are no errors in the source program. We then run the generated program a.out in the second command line, which prints the expected greeting message.

Exercise-1. I urge you to type in the hello-world program shown above into your code editor, save it in a file, and then compile and run it. (This is a hands-on tutorial, remember?) If you were able to complete these steps successfully, bravo—you deserve a pat on your back!

Explaining Hello-world

Let’s now try and get some idea about how the hello-world program works without getting lost in too many details.

In C programs, all the “action” happens inside functions. A C program consists of one or more functions. And the function named “main” is special: it’s the entry-point of the program.


  1. GCC—as the GNU C compiler is commonly called—is a popular C compiler seen on many Unix-like systems, including Linux. It is almost 40 years old by now, its 1.0 version having been released in May 1987. In its early days, GCC used to stand for “GNU C Compiler.” But for quite some years now, GCC is not a single compiler any more. Instead, it’s a suite of compilers for several different programming languages. So “GCC” now stands for “GNU Compiler Collection.” Nevertheless, we will mean the C compiler when we use the term GCC in this tutorial. ↩︎