Real programs have thousands of lines. Putting them all in one file would be a mess, so C programs are split into several files:
- .h files (headers) list what is available: prototypes, structs,
#defines. - .c files hold the actual code.
Think of it like this: A header file is like the menu in a restaurant: it tells you what dishes exist. The .c file is the kitchen where they are really made.
An example with three files
mathutils.h – the menu:
#ifndef MATHUTILS_H
#define MATHUTILS_H
int square(int n);
int cube(int n);
#endifmathutils.c – the kitchen:
#include "mathutils.h"
int square(int n) {
return n * n;
}
int cube(int n) {
return n * n * n;
}main.c – uses the functions:
#include <stdio.h>
#include "mathutils.h"
int main() {
printf("%d %d\n", square(4), cube(3));
return 0;
}Compile both .c files together:
gcc main.c mathutils.c -o app
./app#include "mathutils.h"uses double quotes for your own files, and< >for C's built-in ones.#ifndef/#define/#endifis an include guard: it stops the same header being pasted in twice.
Remember: Prototypes and types go in
.hfiles; code goes in.cfiles.