Back to course

Modular Programming (Using Multiple Source Files)

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 57: Modular Programming (Using Multiple Source Files)

As programs grow, putting all code in a single file (main.c) becomes impractical. Modular programming involves breaking the code into logical units (modules), typically consisting of a header file (.h) and a corresponding source file (.c).

The Role of Files

1. Header File (module.h)

Contains declarations (prototypes) of functions, global variables (using extern), and structure definitions.

c // utility.h #ifndef UTILITY_H #define UTILITY_H

// Function prototype: int power(int base, int exp);

#endif

2. Source File (module.c)

Contains the actual definitions (implementation) of the functions declared in the header.

c // utility.c #include "utility.h"

int power(int base, int exp) { int result = 1; for (int i = 0; i < exp; i++) { result *= base; } return result; }

3. Main File (main.c)

Includes the header file to access the prototypes and calls the functions defined elsewhere.

c // main.c #include <stdio.h> #include "utility.h" // Include the local header

int main() { int result = power(2, 5); printf("2^5 = %d\n", result); return 0; }

Compilation Process

When using multiple files, you must compile them together:

bash gcc main.c utility.c -o my_app ./my_app

This process tells the compiler to compile each .c file and then link the resulting object files into a single executable.