BLACK FRIDAY! 50% OFF!     |        Get Skills for Your IT Future!     | 

4d 06h
close
Cart icon
User menu icon
User icon
Lightbulb icon
How it works?
FAQ icon
FAQ
Contact icon
Contact
Terms of service icon
Terms of service
Privacy policy icon
Privacy Policy

Basics of C Programming: Compilation and Running a Program

C programming forms the backbone of many operating systems and applications. This article walks you through the basics of the compilation and execution process in C, step by step.

Creating a Simple Program in C

The process begins with writing source code, which must then be converted into a format the computer can understand. Here's a simple example of a C program:

#include 

int main(void) {

    int a = 2, b = 4;

    int sum = a + b;

    printf("Sum: %d \n", sum);

    return 0;

}

Save the above code in a file named addition.c. Now, open a terminal and use the following command to compile the program:

gcc addition.c -o addition
  • gcc: the C compiler.
  • addition.c: the source file.
  • -o addition: specifies the name of the executable file (in this case, addition).

To run the compiled program, type in the terminal:

./addition

After running the program, you will see the following result:

Sum: 6

The Compilation Process: Step by Step

The compilation process in C involves several stages that transform source code into an executable file.

1. Preprocessor

First, the preprocessor processes directives such as #include. For example:

#include 

This line adds the content of the standard input/output library to your code.

2. Compilation

The C source code is translated into low-level code (e.g., assembly code), which is more understandable by the processor than the source code.

3. Assembly

The assembler converts assembly code into machine code (binary), creating an object file (e.g., addition.o).

4. Linking

The linker combines object files and libraries into a single executable file, such as addition.

5. Execution

The ready-to-run executable file can be launched by the operating system. The processor executes the instructions contained in it.

How Does the Processor Understand Code?

When a program is executed, its machine code is loaded into the RAM, where the processor accesses instructions and data. The processor uses two key units to process instructions:

  • Arithmetic Logic Unit (ALU): Performs mathematical and logical operations.
  • Control Unit (CU): Manages the sequence of instruction execution.

With these components, the processor executes the tasks defined in the program.

Conclusion

Programming in C requires understanding the compilation process, from preprocessing and assembly to linking and execution. Familiarity with these stages helps you better understand how a computer transforms source code into a functioning program.