Quiz Entry - updated: 2026.07.10
How do modules and header files work in C?
A module is just a .c file compiled on its own into a .o; its matching .h header lists the declarations (the interface) that other files #include to call into it, and the linker joins them.
1. Define a module (intops.c):
// Implementation file - contains definitions
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
2. Create header file (intops.h):
// Declarations only - the "interface"
// Include guard - prevents double inclusion
#ifndef __intops_h__
#define __intops_h__
int add(int a, int b);
int sub(int a, int b);
int mul(int a, int b);
// __intops_h__
#endif
3. Use the module:
// Get declarations
#include <intops.h>
int foo(int a, int b) {
// Linker connects to intops.o
return add(a, b);
}
Why separate compilation?
- Faster builds (only recompile changed files)
- Hide implementation details
- Share interfaces across multiple files
Compile separately:
# Creates intops.o
gcc -c intops.c
# Creates main.o (uses intops.h)
gcc -c main.c
# Links them together
gcc intops.o main.o
Include guards prevent:
// a.h includes intops.h
#include "a.h"
// b.h also includes intops.h
#include "b.h"
// Without guards, intops.h contents appear twice → errors!
Go deeper:
Include guard — Wikipedia — the double-inclusion problem and #ifndef guards.