What happens when you type gcc main.c?

Van Phan
2 min readFeb 7, 2019

--

Steps to form an executable file from C source code

To answer the title question, you have to ask yourself “what is gcc?” and “what is main c?”

  • What is gcc?

GCC , also known as GNU Compiler Collection, is a compiler system which was produced by GNU project. GCC can support multiprogramming languages such as C, C++, Fortran and so on. Most of Unix-like operating systems use gcc as a standard compiler.

  • What is main.c?

“main.c” is basically a typical C source file. Most C source files have a .c extension at the end. You can easily create a C source file using text editors such as emacs, vi, vim, nano, and so on. The below example is using emacs to create a C source file named “main”.

emacs main.c

When using gcc for a C source file, for instance “gcc main.c” will help the operating system compile and produce an execute binary file. However, there are several steps before producing a complete execute file.

  1. Preprocessor

In the first step, the source file is handled by a preprocessor. It takes your file codes and converts them into other sources codes. In this process, the preprocessor will take away everything that it doesn't need (such as comments) and convert the need ones. It starts with the # character (#include) and interprets it.

we use -E flag to stop after pre-processing:

gcc -E main.c

2. Compiler

In the second step, the compiler will use your preprocessed code and convert it into sets of assembly language. It will change the file “main.c” to a file named “main.s”

The -S flag will be used in this step:

gcc -S main.c

3. Assembler

After having sets of assembly language, the compiler will assemble and convert them into binary. In this step, all the C file source extension will be changed to .s extension.

The -c option is used with the purpose that compiling sources without linking.

gcc -c main.c

4. Linker

In the last step, all the file binary code will be taken and linked together to create a complete execute file.

Use can use the command below to do that:

gcc [source file name] -o [output file name]

And to make sure that all your code is checked by the -Wall gcc option to recognize all the bugs in your file.

gcc -Wall [source file]

For more information, you can search at “man gcc” to read its description and options.

--

--