Headers & Multi-File Programs in C
Headers (.h) publish what a .c file provides: function prototypes, struct layouts, macros, and extern declarations — everything another file needs to call in. Sources (.c) define the bodies. This split lets ten files share one interface while compiling independently, joined at the end by the linker.
Hygiene rules keep it working: every header gets include guards, headers include what they use (self-contained), never define functions or non-extern variables in headers (multiple-definition errors), and keep private helpers static in their .c file.
Headers declare, sources define
math.h: int square(int); — math.c: the body. Callers include the header and never see the implementation.
Guard every header
#ifndef MATH_H / #define MATH_H ... #endif (or #pragma once) makes double-inclusion impossible.
Never define in headers
Function bodies and plain globals in headers multiply-define across includers — declare there, define in exactly one .c.
Compile together, link once
gcc main.c math.c -o app — each compiles alone against declarations, the linker resolves everything after.
// math.h:// #ifndef MATH_H// #define MATH_H// int square(int x);// #endif// ---- app built as: gcc main.c math.c -o app#include <stdio.h>#include "math.h"int main(void) { printf("%d\n", square(6)); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.