Header Files in C Explained: Split One Program into .h and .c Files
The packing tool reads a file and takes launch instructions, and it all still lives in one .c file. That file keeps growing: scroll, search, scroll back. Professional C programs do not grow this way - they split into pieces, and this part does the split.
This is Part 14 of the C Learning Guide. Part 13 let the user choose the file at launch, and this part organizes the code itself into header files and source files. Every complete program below was compiled and run with gcc -Wall -Wextra -std=c17. The output blocks contain captured output, not predicted results.
One file is getting crowded
A C program of ten lines forgives everything. A tool with structures, file loading and argument parsing does not: finding one function means scrolling past everything else, and two people cannot edit the same file without colliding. C's answer is to split code by job. Files that do the work end in .c (source files). Files that describe what exists end in .h (header files), and any source file that needs those descriptions copies them in with #include.
| Goes in the header (.h) | Goes in the source (.c) |
|---|---|
| Function declarations (prototypes) | Function definitions (the actual code) |
| struct and typedef definitions | main and the program's flow |
| #define constants shared by files | Variables and helpers only this file needs |
| extern declarations of shared variables | The one real definition of each shared variable |
The header is the contract; the source file is the work. Any file that includes the header can call the functions, use the structures and read the constants - without seeing how the work is done.
A declaration promises, a definition delivers
These two lines look similar but say different things. A declaration such as int full_boxes(int items); only promises the compiler that a function with that name and shape exists somewhere. A definition is the function itself, with its body. The promise is enough to check a call; the definition is only needed once, at link time. That is why this program compiles even though main calls full_boxes before its definition appears:
#include <stdio.h>
int full_boxes(int items); /* declaration: the promise, definition comes later */
int main(void) {
int items = 11;
printf("%d items need %d full boxes\n", items, full_boxes(items));
return 0;
}
int full_boxes(int items) { /* definition: the actual work */
return items / 4;
}Verified output:
11 items need 2 full boxes
Delete the declaration line and the compiler can only guess - you will meet that warning later in this part. Headers exist so that no file ever has to guess: the promise is written once and copied everywhere it is needed.
Include guards stop double copies
#include "orders.h" is not a link or a reference - the preprocessor literally copies the header's text into the including file. In a real project the same header can arrive twice in one file: main.c includes orders.h and files.h, and files.h also includes orders.h. Without protection, the struct inside would be defined twice in one translation unit, and the compiler refuses:
noguard.c:11:3: error: conflicting types for 'Order'; have 'struct <anonymous>'
11 | } Order;
| ^~~~~
noguard.c:6:3: note: previous declaration of 'Order' with type 'Order'
6 | } Order;
| ^~~~~
The standard protection is an include guard: the whole header sits inside #ifndef NAME_H / #define NAME_H ... #endif. The first copy defines the macro, so every later copy is skipped as empty. This program proves the pattern by deliberately pasting the same guarded header content twice - it compiles cleanly and runs:
#include <stdio.h>
/* first time the header content arrives */
#ifndef ORDER_H
#define ORDER_H
typedef struct {
int id;
int items;
} Order;
#endif
/* the same header content arrives again through another include chain */
#ifndef ORDER_H
#define ORDER_H
typedef struct {
int id;
int items;
} Order;
#endif
int main(void) {
Order o = {201, 11};
printf("order %d carries %d items\n", o.id, o.items);
return 0;
}Verified output:
order 201 carries 11 items
The second block vanished before the compiler ever saw it - ORDER_H was already defined. Every header you write gets this guard, with a macro name built from the file name.
Split the tool into three files
Here is the packing tool organized the way this part promises. The header orders.h carries the constant, the struct and the two declarations, all inside a guard:
orders.h
#ifndef ORDERS_H
#define ORDERS_H
#define BOX_CAPACITY 4
typedef struct {
int id;
char destination[20];
int items;
} Order;
int full_boxes(int items);
void print_order(Order o);
#endif
The source file orders.c includes its own header - so the compiler checks that the definitions match the promises - and does the work:
orders.c
#include <stdio.h>
#include "orders.h"
int full_boxes(int items) {
return items / BOX_CAPACITY;
}
void print_order(Order o) {
printf("order %d -> %s: %d items, %d full boxes, %d loose\n",
o.id, o.destination, o.items,
full_boxes(o.items), o.items % BOX_CAPACITY);
}
And main.c includes the same header, so it can use Order, print_order and full_boxes without knowing how they are built:
main.c
#include <stdio.h>
#include "orders.h"
int main(void) {
Order orders[] = {
{201, "Delhi", 11},
{202, "Mumbai", 8},
{203, "Jaipur", 24},
};
int total = sizeof orders / sizeof orders[0];
for (int i = 0; i < total; ++i) {
print_order(orders[i]);
}
printf("summary: %d orders packed\n", total);
return 0;
}
Building is one command naming all the .c files; each is compiled, then the linker joins the pieces. "orders.h" in quotes means the header sits next to the source files, unlike <stdio.h> which is looked up in the compiler's own directories:
gcc -Wall -Wextra -std=c17 main.c orders.c -o packing ./packing
Captured output:
order 201 -> Delhi: 11 items, 2 full boxes, 3 loose order 202 -> Mumbai: 8 items, 2 full boxes, 0 loose order 203 -> Jaipur: 24 items, 6 full boxes, 0 loose summary: 3 orders packed
Same tool, same output - but now the record-keeping code and the program flow live in separate, findable pieces.
Try the split tool in one file
The runner compiles a single file, so below is the same three files joined in order - header block first, then the two source parts, with comment lines marking where each file begins and ends. It is exactly the code above, and it produces exactly the same output:
/* the three files of the split tool, joined for a single-file online run:
header block first, then orders.c, then main.c */
#include <stdio.h>
/* ---- orders.h ---- */
#ifndef ORDERS_H
#define ORDERS_H
#define BOX_CAPACITY 4
typedef struct {
int id;
char destination[20];
int items;
} Order;
int full_boxes(int items);
void print_order(Order o);
#endif
/* ---- end of orders.h ---- */
/* ---- orders.c ---- */
int full_boxes(int items) {
return items / BOX_CAPACITY;
}
void print_order(Order o) {
printf("order %d -> %s: %d items, %d full boxes, %d loose\n",
o.id, o.destination, o.items,
full_boxes(o.items), o.items % BOX_CAPACITY);
}
/* ---- end of orders.c ---- */
/* ---- main.c ---- */
int main(void) {
Order orders[] = {
{201, "Delhi", 11},
{202, "Mumbai", 8},
{203, "Jaipur", 24},
};
int total = sizeof orders / sizeof orders[0];
for (int i = 0; i < total; ++i) {
print_order(orders[i]);
}
printf("summary: %d orders packed\n", total);
return 0;
}Verified output (identical to the three-file run):
order 201 -> Delhi: 11 items, 2 full boxes, 3 loose order 202 -> Mumbai: 8 items, 2 full boxes, 0 loose order 203 -> Jaipur: 24 items, 6 full boxes, 0 loose summary: 3 orders packed
Sharing one variable with extern
Functions are not the only things files share. If two source files must see one common variable, the rule mirrors functions: define it once in one .c file, and let other files declare it with extern. An extern declaration says "this variable exists somewhere - use it, and the linker will find it." This single file shows the same arrangement:
#include <stdio.h>
void count_order(int items); /* defined below */
extern int total_items; /* one shared variable, defined somewhere else */
int main(void) {
count_order(11);
count_order(8);
printf("total items counted: %d\n", total_items);
return 0;
}
int total_items = 0; /* the single definition */
void count_order(int items) {
total_items += items;
}Verified output:
total items counted: 19
In the multi-file tool, int total_items = 0; would live in orders.c, and orders.h would carry extern int total_items; so main.c could read it too. One warning from experience: never put a plain variable definition (without extern) in a header - every file that includes it creates its own copy, and the linker then sees the same name defined many times.
The errors this prevents, and what the messages mean
Splitting code creates a new job - keeping promises and definitions matched - and the toolchain reports every mismatch. These three messages were captured from deliberately broken variants of the tool:
Forgetting a file at build time. Compiling main.c alone, without orders.c, passes the compile step but fails at the link step, because the promise was never matched with work:
main.c:(.text+0xf3): undefined reference to `print_order' collect2: error: ld returned 1 exit status
"Undefined reference" is the linker speaking: a declaration was believed, but no definition arrived. The fix is to list every .c file in the build command.
Defining the same thing twice. If full_boxes and print_order are pasted into two different .c files, both compile - then the linker refuses to pick:
multiple definition of `full_boxes'; orders.c:(.text+0x0): first defined here collect2: error: ld returned 1 exit status
One name, one definition, across the whole program. This is also why variable definitions do not belong in headers.
Calling without any declaration. Remove the include and the prototype from main.c, and the compiler can only guess what full_boxes is:
nodecl.c:4:20: warning: implicit declaration of function 'full_boxes' [-Wimplicit-function-declaration]
4 | printf("%d\n", full_boxes(11));
| ^~~~~~~~~~
A guess is not a check: the compiler cannot verify the argument types, and in C23 this guess is an outright error. Always let the compiler see the declaration - which is exactly what including the header provides.
What was checked, and what comes next
All four runnable programs compiled without warnings using gcc with -Wall -Wextra -std=c17, then ran to produce the captured outputs shown; the three error messages come from deliberately broken variants, trimmed only of temporary file names. The runnable examples carry on-demand code runners; the three-file split is shown as listings because the runner compiles one file at a time, and its joined copy runs instead. Next: building with make and a Makefile, so recompiling many files stops being one long typed command.
Continue with the series index, revisit Part 13: command-line arguments, or use the Online Compiler.
Sources and scope
These examples use C17 and gcc on Linux. Captured outputs are real local runs; error texts are real compiler and linker output with temporary object names trimmed. The runner uses OneCompiler: code runs on its servers and its cookies/privacy policy apply. Do not enter secrets.
Comments
Post a Comment