The preprocessor and multi-file programs
Real C projects are split across many files: one for parsing, one for networking, one for storage. This lesson explains how that works: the preprocessor that runs before the compiler, header files that share declarations between files, and the linker that joins the pieces into one program.
The build pipeline
When you run gcc main.c, four steps happen:
main.c ──preprocess──▶ expanded C ──compile──▶ assembly ──assemble──▶ main.o ──link──▶ program
(#include, (object (joins .o files
#define, #if) file) and libraries)You can stop after any step to look:
#include <stdio.h>
#define GREETING "hi"
int main(void) {
puts(GREETING);
return 0;
}gcc -E tiny.c | wc -l # preprocess only
gcc -E tiny.c | tail -4
gcc -c tiny.c # compile to an object file, don't link
file tiny.o829
int main(void) {
puts("hi");
return 0;
}
tiny.o: ELF 64-bit LSB relocatable#include <stdio.h> pasted hundreds of lines of declarations into the file, and GREETING was replaced by "hi" before the compiler saw anything. The object file tiny.o contains machine code with "holes" where puts will go; the linker fills them in.
#define: macros
#include <stdio.h>
#define PI 3.14159265358979
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define BAD_SQUARE(x) x * x
int main(void) {
printf("area of r=2: %.3f\n", PI * SQUARE(2));
printf("MAX(3, 9) = %d\n", MAX(3, 9));
printf("SQUARE(1 + 2) = %d\n", SQUARE(1 + 2));
printf("BAD_SQUARE(1 + 2) = %d\n", BAD_SQUARE(1 + 2));
return 0;
}area of r=2: 12.566 MAX(3, 9) = 9 SQUARE(1 + 2) = 9 BAD_SQUARE(1 + 2) = 5
Macros are text replacement, not functions. BAD_SQUARE(1 + 2) became 1 + 2 * 1 + 2 = 5. Rules for macros:
- Put parentheses around every parameter and around the whole body.
- Never pass expressions with side effects:
MAX(i++, j)incrementsitwice. - Prefer a
static inlinefunction or aconstexpr/const/enumconstant when one works. Use macros only for what they're uniquely good at: conditional compilation,__FILE__/__LINE__, and generating repetitive code.
Built-in macros
#include <stdio.h>
#define LOG(msg) fprintf(stderr, "[%s:%d %s] %s\n", __FILE__, __LINE__, __func__, msg)
void save(void) {
LOG("saving data");
}
int main(void) {
LOG("starting");
save();
printf("C standard version: %ld\n", __STDC_VERSION__);
return 0;
}[main.c:10 main] starting [main.c:6 save] saving data C standard version: 202311
__FILE__ and __LINE__ are replaced by the current file and line, which makes macros like LOG and assert say exactly where they were called.
Conditional compilation
#if, #ifdef and friends include or skip code before compiling. That's how one codebase supports several operating systems or builds:
#include <stdio.h>
int main(void) {
#ifdef DEBUG
printf("debug build: extra checks on\n");
#else
printf("release build\n");
#endif
#if defined(__linux__)
printf("compiled for Linux\n");
#elif defined(_WIN32)
printf("compiled for Windows\n");
#elif defined(__APPLE__)
printf("compiled for macOS\n");
#endif
return 0;
}gcc -o build build.c && ./build
gcc -DDEBUG -o build build.c && ./buildrelease build compiled for Linux debug build: extra checks on compiled for Linux
-DDEBUG defines DEBUG from the command line (-DLEVEL=3 gives it a value). The standard assert(x) macro from <assert.h> checks a condition in debug builds and disappears when you compile with -DNDEBUG.
Splitting a program into files
Let's build a small project: a statistics module used by a main program.
The header declares what the module offers. It's the module's public interface:
#ifndef STATS_H
#define STATS_H
#include <stddef.h>
typedef struct {
double min, max, mean;
} Summary;
// Summarise n values. Returns 0 on success, -1 if n is 0.
int stats_summary(const double *values, size_t n, Summary *out);
double stats_median(double *values, size_t n); // sorts values in place
#endifThe implementation defines the functions:
#include "stats.h"
#include <stdlib.h>
static int compare(const void *a, const void *b) { // static: private to this file
double x = *(const double *)a, y = *(const double *)b;
return (x > y) - (x < y);
}
int stats_summary(const double *values, size_t n, Summary *out) {
if (n == 0) return -1;
double sum = 0;
out->min = out->max = values[0];
for (size_t i = 0; i < n; i++) {
if (values[i] < out->min) out->min = values[i];
if (values[i] > out->max) out->max = values[i];
sum += values[i];
}
out->mean = sum / n;
return 0;
}
double stats_median(double *values, size_t n) {
qsort(values, n, sizeof *values, compare);
return n % 2 ? values[n / 2] : (values[n / 2 - 1] + values[n / 2]) / 2;
}The program includes the header and uses the module:
#include <stdio.h>
#include "stats.h"
int main(void) {
double response_ms[] = {120, 85, 310, 95, 140, 88};
size_t n = sizeof response_ms / sizeof response_ms[0];
Summary s;
if (stats_summary(response_ms, n, &s) != 0) return 1;
printf("min %.0f ms, max %.0f ms, mean %.1f ms\n", s.min, s.max, s.mean);
printf("median %.1f ms\n", stats_median(response_ms, n));
return 0;
}Compile each .c file to an object file, then link them:
cd stats
gcc -std=c23 -Wall -Wextra -c stats.c # → stats.o
gcc -std=c23 -Wall -Wextra -c main.c # → main.o
gcc -o report main.o stats.o # link
./reportmain.o stats.o min 85 ms, max 310 ms, mean 139.7 ms median 107.5 ms
(Or all in one go: gcc -o report main.c stats.c.) Compiling separately means that after changing one file, only that file is recompiled. In a project with hundreds of files, that's the difference between seconds and minutes. The Make lesson automates it.
#include "…" vs #include <…>
"stats.h": look in the current file's folder first, then the system folders. Use it for your headers.<stdio.h>: look only in the system and-Ifolders. Use it for the standard library and installed libraries.
Include guards
The #ifndef STATS_H / #define STATS_H / #endif lines are an include guard: if the header is included twice (easily done when headers include other headers), the second copy is skipped. Every header needs one. #pragma once at the top does the same and is supported by all major compilers.
What goes where
In the header (.h) |
In the source file (.c) |
|---|---|
| Function declarations (prototypes) | Function definitions (bodies) |
typedefs, struct and enum definitions others need |
static helper functions and variables (private) |
Macros and extern declarations of shared globals |
The one definition of each global |
Never put function bodies or variable definitions in a header (except static inline functions): every file that includes it would get a copy, and the linker would complain about multiple definitions.
Linker errors
When the linker can't find a function, the error looks different from a compiler error:
cd stats
gcc -o report main.c # forgot stats.cld: /tmp/ccXXXX.o: in function `main': main.c:(.text+0x44): undefined reference to `stats_summary' ld: main.c:(.text+0x84): undefined reference to `stats_median' collect2: error: ld returned 1 exit status
undefined reference to 'stats_summary' means: it was declared (the header promised it exists) but no object file defined it. You forgot to compile or link a file, or a library (-lm for math, -lpthread, -lsqlite3).
Using a library
Libraries are collections of object files. Link one with -l (and tell the compiler where its headers and files are with -I and -L if they're not in the standard places). Here, the real SQLite library:
#include <stdio.h>
#include <sqlite3.h>
int main(void) {
printf("SQLite version %s\n", sqlite3_libversion());
sqlite3 *db;
if (sqlite3_open(":memory:", &db) != SQLITE_OK) return 1;
sqlite3_exec(db, "CREATE TABLE t(x); INSERT INTO t VALUES (1), (2), (3);", NULL, NULL, NULL);
sqlite3_stmt *st;
sqlite3_prepare_v2(db, "SELECT sum(x) FROM t", -1, &st, NULL);
if (sqlite3_step(st) == SQLITE_ROW) printf("sum = %d\n", sqlite3_column_int(st, 0));
sqlite3_finalize(st);
sqlite3_close(db);
return 0;
}sudo apt install libsqlite3-dev # the library and its header
gcc -std=c23 -Wall -o db db.c -lsqlite3
./dbSQLite version 3.x sum = 6
pkg-config --cflags --libs sqlite3 prints the right flags for any installed library, so you don't have to guess them.
Practice
- Split one of your earlier programs into
main.c,util.candutil.h, with an include guard. - Make a helper function in
util.cstaticand try to call it frommain.c. Read the linker error. - Write a
DEBUG_PRINT(fmt, ...)macro that prints the file and line, and compiles to nothing unless-DDEBUGis given (look up__VA_ARGS__). - Run
gcc -Eon a file that includes<stdlib.h>and find the declaration ofmallocin the output.
1.What does the preprocessor do with #include "stats.h"?
2.Why does #define DOUBLE(x) x * 2 give the wrong answer for DOUBLE(1 + 1)?
3.What does "undefined reference to stats_summary" mean?
4.What is an include guard for?