Discovering the compiler and C basics (2)
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 disk. You should create a folder for every 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, then 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 functionmain
: The function's identifier(void)
: The parameter list, there are no arguments so we put thevoid
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
, we will see later how to retrieve this returned value.By convention, returning
0
means everything went well, but returning another value (like1
) means an error occurred.
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 sort of intermediate compiled file. Then you can compile the object file into a binary file.
In another post, We will see when to compile to an object instead of a binary.