Header files and multiple source files
How to split a C or C++ program into .h and .c files, what goes where, and how the linker joins them.
Bigger programs are split into several .c files. A header (.h) holds the declarations other files need: function prototypes, struct definitions and constants. The matching .c file holds the definitions.
Each .c file is compiled on its own into an object file, then the linker joins them. "Undefined reference" errors come from the linker: something was declared but its definition wasn't linked in.
Mark helper functions static so they stay private to their file, and protect headers with include guards.
// math_utils.h
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
int clamp(int v, int lo, int hi);
#endif
Example
#include <stdio.h>
/* In a real project this prototype lives in math_utils.h ... */
int clamp(int v, int lo, int hi);
int main(void) {
printf("%d %d\n", clamp(150, 0, 100), clamp(-5, 0, 100));
return 0;
}
/* ... and this definition in math_utils.c */
int clamp(int v, int lo, int hi) {
return v < lo ? lo : v > hi ? hi : v;
}
Output:
100 0