WeCodeAcademy

C Headers and Multiple Files

Real programs are split into files. A header (.h) declares functions; a source file (.c) defines them. #include "name.h" shares the declarations, and include guards stop a header being read twice. Here is a complete tiny project laid out in three files (compile with gcc main.c mathutil.c -o app).

// mathutil.h
#ifndef MATHUTIL_H
#define MATHUTIL_H
int square(int x);
#endif
// mathutil.c
#include "mathutil.h"
int square(int x) { return x * x; }
ExampleC
// main.c: uses square() declared in mathutil.h
#include <stdio.h>

int square(int x) { return x * x; }   // inlined here so this sample runs on its own

int main(void) {
  printf("%d\n", square(7));
  return 0;
}
Output
49

Keep declarations in headers and definitions in source files. Then a change to one .c file only needs that file recompiled.

Quick check

What do include guards (#ifndef ... #define ... #endif) prevent?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.