COMPILATION
All the softwares, programs, websites and apps are written in a certain programming language. Basically, everything we see on the screen of our computers or smartphones are just a lot of code written in different languages and assembled together in a certain way. Every programming language has a different use, this post will focus on C language.
C source files are by convention named with .c extension and we use the command “gcc” to compile C source files. (GCC stands for GNU Compiler Collection and it is a compiler system produced by the GNU Project.)
Compilation is composed by 4 steps:
Preprocessing is the first step. The preprocessor obeys commands that begin with # (known as directives) by:
If you included a header file such as #include <stdio.h>, it will look for the stdio.h file and copy the header file into the source code file.
The preprocessor also generates macro code and replaces symbolic constants defined using #define with their values.
2. Compiling:
Compiling is the second step. It takes the output of the preprocessor and generates assembly language, an intermediate human readable language, specific to the target processor.
3. Assembly:
Assembly is the third step of compilation. The assembler will convert the assembly code into pure binary code or machine code (zeros and ones). This code is also known as object code.
4. Linking:
Linking is the final step of compilation. The linker merges all the object code from multiple modules into a single one. If we are using a function from libraries, linker will link our code with that library function code.
In static linking, the linker makes a copy of all used library functions to the executable file. In dynamic linking, the code is not copied, it is done by just placing the name of the library in the binary file.
Now that we know what compilation is about, HANDS ON:
Let´s first install gcc:
Now let´s compile:
For our example, let’s take a look at a source code inside a file called “main.c”, where “.c” is a file extension that usually means the file is written in C. This picture is inside the text editor vi:
In order for our main.c code to be executable the compiling process is necessary.
gcc options:
To run the main program, we type “./main” into the terminal (pay attention to the use of the extension, when trying the program ".c" is not mentioned).
We create an executable program with the name we want, by adding the “-o” option to the gcc command, placed after the name of the file or files we are compiling, and pressing enter (there are other ways for this final step):
YOUR FILE IS NOW COMPILED :)
For more gcc options you con read the manual:
Hope you find it helpful and easy to understand.