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

The purpose of header files

The purpose of header files

What you'll learn: How to use header files to share declarations across multiple parts of your program without repeating code.

The "Menu" Analogy

Imagine you walk into a restaurant. The waiter hands you a menu that lists all the dishes the kitchen can prepare. The menu doesn't contain the actual food, nor does it contain the complex recipes used by the chefs. It is simply a list of promises: "If you ask for the Spaghetti, we know how to make it."

In C, a header file (ending in .h) is that menu. It contains declarations—a list of function names, their inputs, and their return types. The source file (ending in .c) is the kitchen; it contains the definitions, which is the actual logic and code that performs the work.

Why not just keep everything in one file?

As your programs grow, putting thousands of lines of code into a single main.c file becomes a nightmare to navigate. You’ll want to move specific tasks, like math functions or database logic, into their own separate files.

However, C is a "top-down" language. If you try to use a function in main.c that is defined in physics.c, the compiler will get confused because it hasn't seen that function yet. Instead of copy-pasting the entire code from one file to another, you simply #include the header file. This tells the compiler, "Don't worry, this function exists elsewhere; here is what its signature looks like."

A simple example

If you had a file named calculator.h, it might look like this:

/* calculator.h - The "Menu" */

// This tells the compiler that a function named 'add' 
// exists and takes two integers.
int add(int a, int b);

Then, in your main program, you can use that "menu" to understand how to call the function:

/* main.c */
#include <stdio.h>
#include "calculator.h" // We include our menu here

int main() {
    // The compiler knows 'add' is valid because of the header
    int result = add(5, 3);
    printf("The sum is: %d", result);
    return 0;
}

By using header files, you keep your project organized, allow different parts of your program to communicate, and ensure that you only have to write your logic once.

Key takeaway

Header files act as a bridge between files, providing a list of available functions so the compiler knows how to use them before the actual work is done.