Part 4 — Chapter 20

Chapter 20: Multi-file Projects

As programs become larger, placing all code inside a single source file becomes difficult to manage. Real-world C projects are usually divided into multiple files to improve organization, readability, and maintainability.

A multi-file project separates core functionality into different source (.c) and header (.h) files.

Why Multi-file Projects?

Splitting programs into multiple files helps:

  • organize code into modules
  • improve readability
  • simplify debugging
  • enable code reuse
  • make large projects easier to maintain

For example:

  • one file may handle GPIO drivers
  • another may handle UART communication
  • another may contain application logic

Basic Project Structure

A standard multi-file hierarchy splits local units into clean-cut twin pairing sets. Visually, the directory is structured exactly like a scalable file system:

Directory Map
📁 firmware_root/
├── 📄 main.c     // Entry Flow
├── 📄 math.c     // Logic Engine
└── 📄 math.h     // API Definitions
Source Code Execution
math.h
Header
#ifndef MATH_H
#define MATH_H

int add(int a, int b); // Function declaration available to others

#endif
math.c
Source
#include "math.h" // Connects declaration and implementation

int add(int a, int b)
{
    return a + b; // Actual function definition
}
main.c
Source
#include <stdio.h>
#include "math.h" // Imports function visibility

int main()
{
    printf("%d", add(10, 20)); // Uses functions without definition bloat

    return 0;
}

Compilation

Multiple source files must be compiled together.

GCC Command

Terminal - gcc
$ gcc main.c math.c -o program

How It Works

  • math.h provides the function declaration
  • math.c contains the function implementation
  • main.c calls the function
  • during compilation, all source files are linked together into one executable program

Compilation Flow

Multi-file generation runs linearly, funneling distinct modules through sequential processing gates:

Header Files (.h)
Source Files (.c)
Compiler
Linker
Executable Program

Important Points

  • Large programs are divided into multiple source files
  • Header files share declarations between files
  • Source files contain implementations
  • Include guards prevent duplicate header inclusion
  • All source files must be linked during compilation

Embedded Focus

Embedded firmware projects are almost always multi-file projects. Drivers, communication protocols, interrupt handlers, middleware, and application logic are usually separated into different modules.

application.c
C
#include "uart_driver.h"
#include "gpio_driver.h"

This modular structure improves scalability, simplifies debugging, and allows multiple developers to work on different parts of the firmware independently.

← Chapter 19: Header Files Chapter 21: Bitwise Operators →