Multi-File Programs & Header Files
Prerequisites: Command-line arguments
A real project splits code across multiple .c files, sharing
declarations through a header:
// math_utils.h
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
int add(int a, int b);
#endif
// math_utils.c
#include "math_utils.h"
int add(int a, int b) {
return a + b;
}
// main.c
#include <stdio.h>
#include "math_utils.h"
int main(void) {
printf("%d\n", add(2, 3));
return 0;
}
gcc main.c math_utils.c -o myprogram
The #ifndef/#define/#endif header guard stops the same
header being pasted in twice if it's #included from more than one
place — without it, the compiler sees int add(int a, int b);
declared twice and errors out.
Common mistakes
- Forgetting to list every
.cfile on thegcccommand line — unlike some languages, nothing "discovers" source files automatically.