Antonin Hérault
Antonin Hérault

Antonin Hérault

Discovering the compiler and C basics (2)

Antonin Hérault's photo
Antonin Hérault
·Jul 11, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Your first build
  • Overview of the "Hello world" script
  • Understanding the compiler

In the first article from this course, we saw how to do an "Hello world" script :

#include <stdio.h>

int main(void) {
    printf("Hello world!\n");
    return 0;
}

We also had to install the "gcc" compiler

Your first build

To compile a C file into an executable binary file, type gcc <filename>.c -o <output>.

So, the content has to be put in a file named "main.c", in any folder on your computer's disk. You should create a folder for each project you start, let's name it "hello_world".

Then, you can run gcc main.c -o program

Note : The output filename doesn't need an extension on Linux, because we commonly don't add one. On Windows, add the ".exe" extension : -o program.exe

The file is now compiled, the you can run it : ./program (or .\program.exe on Windows)

Program's output :

Hello world!

Congratulations ! You've just created your first C program

Overview of the "Hello world" script

  • #include <stdio.h>
    

    Here we include the input/output functions from the standard library (std)

  • int main(void) {
      ...
    }
    

    This is a function body, in that body you have to put some code lines.

    • int : The return type of the function
    • main : The function's identifier
    • (void) : The parameter list, there are no arguments so we put the void keyword by convention.
    • { ... } : Brackets containing the code lines associated with the function
  •   printf("Hello world!\n");
    

    This is a function call, here we call the printf function with one parameter : "Hello world!\n", it's a list of characters. This function comes from the standard library.

  •   return 0;
    

    The function returns a value : 0, later we will see how to retrieve this returned value.

    By convention, returning 0 means everything passed well, but returning another value (like 1) means an error happened

Understanding the compiler

In the command line we ran : gcc <file>.c -o <output>, you can see the "-o" flag. It permits to specify an output filename. If we just ran : gcc <file>.c, the output name will be "a.out".

Other arguments that are not next to a flag "-?" are files to compile.

gcc <file>.c -o <output>.o -c creates an object file, it's a kind of intermediate compiled file. Then you can compile the object file to a binary file. We will see in another post when to compile to an object file instead of a binary one.