Compiling a C Program
C Programming Language
C is a general-purpose, high-level programming language that was developed by mathematician and physicist Dennis Ritchie. It is a language that is commonly used due to it's flexibility and relatively easy to learn structure. Unlike interpreted languages such as Python, C is known as a compiled language.
The Compiled Language
C takes a source code, something that looks like this:
and compiles the source code so that it can be converted into machine readable, or low-level code that is executable.
Compilation is achieved by using a compiler tool such as GCC, the GNU compiler collection. There are many other commonly used compilers out there but this article will be dealing with GCC.
How to compile a C program
There are four important processes that should happen to successfully compile your C code. They are: preprocessor, compiler, assembler, and linker.
Step 1: Preprocessor
The program 'example.c' above includes a line of text '#include <stdio.h> this is known as a header which tells the program to include the standard I/O library. It includes standard functions such as 'printf()' which displays input on the screen.
Preprocessor processes the #include directives as well as your source code. Comments (the text in read) are for humans only so the preprocessor has no reason to translate it to the machine.
The Linux command above is used to achieve the pre-processing step. '-E' is a command option that specifies preprocessing initiatives only. It is then written into an output file called 'example.i'.
Step 2: Compiler
The next command will create an object code file in binary format. This process will take the output of the preprocessor, in our case, the 'example.i' file as well as the source code from 'example.c' and initiates an assembler code.
'-C' is the gcc option that specifies making an object code that will not be executable.
Step 3: Assembler
Assembly is the next stage in compilation. The Assembler converts assembly source code into machine-code. The output of this processes is stored in an object file.
Step 4: Linker
The final stage of compilation. During this process the linker collects the necessary object files and/or libraries and combines them to create an executable file.
The above command can be executed to successfully achieve the entire compilation process and produce your executable file 'example'.
Result!
After granting execute permissions for the file 'example' you can now use the execute command './' followed by your file name to execute your C code. As you can see we have successfully compiled our original source code and the printf() statement was executed in the terminal!