Course contentsShow
← C
Lesson 796 of 1,21911. The Preprocessor and BuildFree lesson

Splitting code into `.c` and `.h`

Splitting code into .c and .h

What you'll learn: How to organize your C projects by separating implementation details from public declarations.

As your programs grow, keeping thousands of lines in a single main.c file becomes a nightmare. To stay organized, C programmers split code into two specific types of files: Source files (.c) and Header files (.h).

The Restaurant Analogy

Think of a professional kitchen.

  • The Header file (.h) is the menu. It tells the customer what dishes are available and what ingredients they contain, but it doesn't show how to cook them.
  • The Source file (.c) is the chef in the kitchen. This is where the actual cooking (the logic) happens.

When another part of your program wants to use a function, it just looks at the "menu" to see how to call it. It doesn't need to see the messy kitchen logic.

How to split them

Suppose you have a math function. You divide it like this:

  1. The Header (math_utils.h): Contains the function prototype. This tells the compiler: "A function with this name and these parameters exists somewhere."
  2. The Source (math_utils.c): Contains the function definition. This is the actual code block that does the work.
// math_utils.h - The "Menu"
// Only the signature (the promise)
int add(int a, int b);

// math_utils.c - The "Kitchen"
// The actual implementation
#include "math_utils.h"

int add(int a, int b) {
    return a + b;
}

// main.c - The "Customer"
#include <stdio.h>
#include "math_utils.h" // We include the menu to know how to use 'add'

int main() {
    printf("Result: %d", add(5, 10));
    return 0;
}

Why do this?

By splitting your code, you gain two major advantages. First, readability: you can scan a header file in seconds to see what a library is capable of without scrolling through hundreds of lines of logic. Second, compilation speed: if you change the logic inside one .c file, the compiler usually only needs to reprocess that specific file, rather than your entire project.

Key takeaway

Put your function declarations in .h files to share them, and put the actual logic in .c files to keep the details hidden.