Course contentsShow
← C
Lesson 377 of 1,2195. FunctionsFree lesson

Role of the `.h` file

Role of the .h file

What you'll learn: You will understand how header files act as a "menu" that allows different parts of your program to communicate.

The Restaurant Analogy

Imagine you walk into a restaurant. You don't go into the kitchen to see how the chef chops onions or how the stove is wired. Instead, you look at a menu. The menu tells you the name of the dish, what ingredients go into it, and what you get back. It is a "contract" between you and the kitchen.

In C, a .h file (header file) is that menu. It doesn't contain the actual cooking (the logic); it only contains the declarations. It tells the rest of your program, "Hey, a function with this name and these parameters exists somewhere."

Why bother with a separate file?

As your programs grow, putting thousands of lines of code into one main.c file becomes a nightmare. We move functions into separate .c files to keep things organized. However, the C compiler is a bit forgetful. If main.c tries to use a function sitting in math_tools.c, it will complain that it doesn't recognize the function name.

By putting a declaration in a header file and "including" it at the top of your code, you give the compiler a heads-up so it doesn't panic.

What it looks like

A header file typically contains function prototypes. These are just the "headers" of functions followed by a semicolon.

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

// This tells the compiler the function exists. 
// No curly braces {} here, just the signature!
int add_numbers(int a, int b);

When you want to use that function in your main program, you use the #include directive with quotation marks for your own files:

/* main.c */
#include <stdio.h>
#include "math_tools.h" // "Reading the menu"

int main() {
    int sum = add_numbers(5, 10);
    printf("The sum is: %d", sum);
    return 0;
}

Separating "What" from "How"

The .h file defines what a tool does, while the .c file defines how it does it. This modularity means you can share your header file with a teammate so they can use your code without ever needing to read your messy internal logic.

Key takeaway

Header files (.h) act as a public interface or "menu" that allows different code files to share functions safely.