Sharing functions across modules
What you'll learn: How to split your C code into multiple files by using header files to announce functions to the rest of your program.
The Recipe and the Menu
Imagine you are a chef. If you keep every single recipe in one massive book, finding the instructions for "Spicy Salsa" becomes a nightmare. Instead, you put the recipe in its own folder (a source file) and put the name of the dish on a menu (a header file).
In C, as your programs grow, you shouldn't keep everything in main.c. You move logic into separate .c files. However, C is strict: main.c cannot use a function in tools.c unless it has seen a "declaration" (a preview) of that function first. The header file (.h) acts as that preview.
How to Link Them
To share a function, you need three pieces:
- The Source (
tools.c): Where the actual code lives. - The Header (
tools.h): A single line (prototype) telling the compiler the function exists. - The User (
main.c): The file that "includes" the header to gain access to the function.
When you include a header with #include "tools.h", you are telling the compiler: "I'm going to use a function defined elsewhere; trust me, it exists."
Concrete Example
Let's look at how we share a simple addition function across two files:
// --- tools.h (The Menu) ---
// This tells other files: "There is a function called add_numbers"
int add_numbers(int a, int b);
// --- tools.c (The Recipe) ---
#include "tools.h"
int add_numbers(int a, int b) {
return a + b;
}
// --- main.c (The Chef) ---
#include <stdio.h>
#include "tools.h" // Gives us access to add_numbers
int main() {
int result = add_numbers(5, 10);
printf("The sum is: %d", result);
return 0;
}
Notice the quotes in #include "tools.h". We use quotes for files we created ourselves, while <angle brackets> are reserved for built-in system libraries like stdio.h.
Why bother?
By separating the "what" (header) from the "how" (source), you make your code modular. You can give your tools.h and tools.c to a teammate, and they can use your functions without ever needing to read your complex internal logic. They just read the "menu."
Key takeaway
Use .h files to declare function prototypes and #include them in any file where you want to call those functions.