Compilation of C Program

Sunny Bhaskar

10/26/20241 min read

The compilation of a C program involves several steps that transform the source code written by a programmer into an executable file that a computer can run. The process typically consists of the following phases:

1. Preprocessing

The first phase is preprocessing, where preprocessor directives like `#include`, `#define`, and conditional compilation (`#ifdef`) are processed. The preprocessor also removes comments and expands macros.

The output of this phase is a "preprocessed" source file, usually with a `.i` extension.

2. Compilation

The preprocessed source file is passed to the compiler. The compiler converts the C code into assembly code specific to the target machine.

This phase translates high-level C code (like loops, conditions, functions) into low-level instructions that can be understood by the computer’s processor.

The output of this phase is an assembly file, typically with a `.s` extension.

3. Assembly

The assembler takes the assembly code generated by the compiler and converts it into machine code or object code (binary form).

This phase produces an object file, which contains the machine code instructions but cannot yet be executed on its own. It usually has a `.o` or `.obj` extension.

4. Linking

The final phase is linking. The linker combines one or more object files (including libraries and other object files) into a single executable file.

It resolves references to functions and variables across different object files and includes any necessary library code (e.g., standard library functions like `printf()`).

The output of this phase is the final executable file, typically with no extension on Linux (`a.out` by default) or with a `.exe` extension on Windows.

Summary

1. Preprocessing (`source.c` -> `source.i`)

2. Compilation (`source.i` -> `source.s`)

3. Assembly (`source.s` -> `source.o`)

4. Linking (`source.o` -> executable)

Example

If you compile a C program using the `gcc` compiler:

gcc program.c -o program

`gcc` compiles `program.c` and produces an executable named `program`.

During this process, it goes through preprocessing, compilation, assembly, and linking stages automatically.

Key Points

The preprocessor handles things like including header files and macro expansion.

The compiler translates the high-level code into assembly instructions.

The assembler converts assembly into machine-level instructions (object code).

The linker combines object files and libraries to produce the final executable.

This compilation process makes C a compiled language, which means the code needs to be compiled before it can be run.

Address

Prayagraj Phaphamau

Contacts

7518998334
sunnygamingyt298@gmail.com

Subscribe to our newsletter