A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
A real C program is not one file. It is a collection of .c files (implementation) and .h files (interface), compiled separately and linked together. The header declares what a module provides. The source file defines how it works. The compiler processes each .c file independently into an object file. The linker combines the object files into an executable. Understanding this pipeline is the difference between writing C scripts and building C software.
/* mathlib.h - the interface */#ifndef MATHLIB_H#define MATHLIB_Hint add(int a, int b);int multiply(int a, int b);double average(const int *arr, int len);#endif
/* mathlib.c - the implementation */#include "mathlib.h"int add(int a, int b) {return a + b;}int multiply(int a, int b) {return a * b;}double average(const int *arr, int len) {if (len <= 0) return 0.0;long sum = 0;for (int i = 0; i < len; i++) {sum += arr[i];}return (double)sum / len;}
/* main.c - the application */#include <stdio.h>#include "mathlib.h"int main(void) {int data[] = {10, 20, 30, 40, 50};int n = 5;printf("add(3, 4) = %d\n", add(3, 4));printf("multiply(6, 7) = %d\n", multiply(6, 7));printf("average = %.1f\n", average(data, n));return 0;}
The -c flag compiles without linking, producing .o files. The final gcc command links the object files into the executable. If you change mathlib.c, you recompile only mathlib.o and relink. main.o is untouched. In a project with a hundred source files, this incremental compilation saves minutes on every edit. A Makefile automates the dependency tracking.
ar rcs creates a static library archive. The -L. flag tells the linker to search the current directory. The -lmathlib flag links against libmathlib.a (the lib prefix and .a suffix are implied). The library's code is copied into the executable at link time. The resulting binary is self-contained. No external library file is needed at runtime.
Multi-file compilation is how real C projects are organized. Headers declare interfaces. Sources implement them. The compiler processes each source independently. The linker combines them. Libraries package reusable code. This pipeline scales from two files to two thousand. Next: static global variables, which limit a variable's visibility to its own file.
Finish the lesson once you have worked through the material. This awards ★ 40 XP.