GCC - How to get an executable file?
In the early 1970s, Dennis Ritchie developed the C programming language as an improvement of B. B by Ken Thompson was also a modification based on BCPL system language.?Both were Bell Labs employees leading the language implementation for the Unix operating system.
Despite C already had a compiler, in the middle 1980s GCC by Richard Stallman came out as a free, best, and faster option than proprietary technology. It was developed over C, but as it became popular other developers started using it in other languages such as C++, Objective C, and Fortran, this is the reason why GCC change the meaning of its initials from GNU C Compiler to GNU Compiler Collection.
GCC process for C
GCC compiles a C program into an executable in 4 steps as follows:
1. Pre-processing: via the GNU C Preprocessor, includes the headers (#include) and expands the macros (#define). The result is an intermediate file *.i that contains the expanded source code.
$ ls
filename.c
$ gcc -E filename.c > filename.i
$ ls
filename.c filename.i
$
2. Compilation: The compiler compiles the preprocessed source code into assembly code. The -S option specifies to produce assembly code, instead of object code. The resultant assembly file is *.s .
$ ls
filename.c filename.i
$ gcc -S filename.i
$ ls
filename.c filename.i filename.s
$
3. Assembly: The assembler converts the assembly code into machine code in the object file *.o with the option -c .
$ ls
filename.c filename.i filename.s
$ gcc -c filename.i
$ ls
filename.c filename.i filename.o filename.s
$
4. Linker: Finally, the linker links the object code with the library code to produce an executable file *.exe or *.out. An executable file requires external resources (system functions, C run-time libraries etc.) If the purpose is to merge object files, gcc can do it with the comand `ld `. If there is no need to type the command directly, the entire linking process is handled by?gcc?when invoked as follows:
$ ls
filename.c filename.i filename.o filename.s
$ gcc filename.s -o filename.exe
$ ls
filename.c filename.exe filename.i filename.o filename.s
$
Example:
Run a C file (5-print_numbers.c) through the preprocessor, compiler, assembly, and linker and save the result. Show the content of each file.
gcc -E 5-print_numbers.c > 5-print_numbers.i
gcc 5-print_numbers -S
gcc 5-print_numbers -c
gcc 5-print_numbers -o 5-print_numbers.exe
Expanded source code file (*.i):
领英推荐
Assembly code file (*.s):
Object code file (*.o):
Executable code file (*.exe):
This blog entry explained and exampled the compilation process steps of a C program using GCC such as, preprocessing, compilation, assembly, and linking. Thanks for reading!
Frontend Developer | ReactJs | NextJS | VueJS | NuxtJS |Transforming innovative ideas into robust and scalable web solutions, crafted with seamless user experiences.
2 年Currently learning C programming and this resource really helped me understnad the C compilation process. THANK YOU!