--
C Program Compilation Process
The C compilation process starts with the source code as input and converts the source code into machine-readable code. The process can be broken down into four steps: Preprocessing, Compiling, Assembling, and Linking.
We can walk through the steps with a program that prints a string:
#include <stdio.h>
int main(void) {
printf(“Testing123\n”);
return(0);
}
Before the source code heads into compilation, the preprocessor takes the source code and strips away comments and interprets any preprocessor directives(such as macros and header files). For example, #include <stdio.h>
will be replaced with contents in the stdio.h header file. You can view the preprocessed source code if you stop the compilation at this step with the -E
option in gcc: gcc -E testing123.c
. But it’s not very entertaining.
Next, the C compiler will convert the preprocessed source code into assembly code(.s extension). Viewable with gcc -S
command.
The assembler then takes the assembly code and converts it into a binary representation of our program called an object file( with .obj in Windows and .o in UNIX systems). Viewable with gcc -c
command.
In the Linking step, multiple object files will be linked together to create one executable. For example, we are using a standard C library function,printf()
in our program to print our string. The linker will locate and include the associated code into the final output file.
To compile our program with gcc, we will run gcc testing123.c
. Using the -o
option will allow us to specify the name of our output file. Otherwise, the default executable for gcc is a.out.