What happens when you type GCC main.c

Muradabbaszade
3 min readOct 15, 2023

--

Source link

This command is used to compile a C source code file named main.c using the GCC (GNU Compiler Collection) compiler. Here's a breakdown of the process:

GCC Command

gcc main.c -o my_program

The command compiles the source code file “main.c” and creates an executable file with the name “my_program.” You can replace “my_program” with any name you desire.

1.Preprocessing

The gcc command initiates the compilation process. The first step is preprocessing.

The preprocessor, which is part of the GCC toolchain, takes main.c and processes it. It handles tasks like including header files, macro expansions, and removing comments.

The result is an intermediate file with a .i extension (e.g., main.i). This file is not human-readable, as it includes all the necessary code from header files and macro expansions.

To perform C preprocessing with the GNU Compiler Collection (GCC), you typically use the -E flag, which generates a preprocessed output without proceeding to compilation. For example:

gcc -E main.c -o main.i
main.i

2: Compilation

The preprocessed file (e.g., main.i) is then fed into the actual compiler.

The compiler translates the C source code into assembly code, a low-level representation that is still human-readable.

The output of this step is typically an assembly file with a .s extension (e.g., main.s).

To generate an assembly language file (with a “.s” extension) from a C source code file, you can use the -S flag with the GCC compiler. Here's the command to do that:

gcc -S my_program.c

3: Assembly

The assembly file is further processed by the assembler.

The assembler converts the assembly code into machine code specific to your computer’s architecture.

The output of this step is an object file with a .o extension (e.g., main.o). This file contains binary code that the computer can understand.

To create an object file named “my_program.o” from your C source code file “my_program.c,” you can use the following command:

gcc -c my_program.c -o my_program.o

4.Linking

The linker takes the object file created from main.c and links it with any necessary libraries and other object files to create the final executable program.

If your program uses standard libraries (e.g., stdio.h), the linker will link those libraries into the executable.

The output is an executable file, often named a.out by default. You can specify a custom name using the -o flag, like gcc -o my_program main.c.

gcc my_program.o -o my_program

Execution

Once the linking is complete, you can run the compiled program by typing ./a.out (or ./my_program if you provided a custom name).

The compiled C code is executed by the computer, and the program’s output or behavior is displayed in the terminal.

--

--