IntermediateLesson 13 of 18
Preprocessor, Headers & Multiple Files – C
#define, macros and their pitfalls, include guards, splitting into .h/.c and a Makefile.
Before the compiler starts, the preprocessor runs: it replaces text. #include copies files in, #define defines text substitutions, #if/#ifdef switch parts of the code on or off. Macros know no types – parentheses are therefore mandatory.
#include <stdio.h>
#define PI 3.14159
#define QUADRAT(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define DEBUG 1
int main(void) {
printf("%.2f\n", PI * QUADRAT(2)); // 12.57
printf("%d\n", QUADRAT(1 + 2)); // 9 (thanks to parentheses)
printf("%d\n", MAX(3, 9)); // 9
#if DEBUG
printf("Debug mode\n");
#endif
return 0;
}You split larger programs into parts: the header (.h) contains declarations (what exists), the source file (.c) the definitions (how it works). An include guard prevents a header from being included twice.
// ---- mathe.h ----
#ifndef MATHE_H
#define MATHE_H
#include <stddef.h>
int addiere(int a, int b);
double durchschnitt(const int *werte, size_t n);
#endif
// ---- mathe.c ----
#include "mathe.h"
int addiere(int a, int b) { return a + b; }
double durchschnitt(const int *werte, size_t n) {
long s = 0;
for (size_t i = 0; i < n; i++) s += werte[i];
return n ? (double)s / n : 0.0;
}
// ---- main.c ----
#include <stdio.h>
#include "mathe.h"
int main(void) {
int w[] = {2, 4, 9};
printf("%d %.2f\n", addiere(2, 3), durchschnitt(w, 3)); // 5 5.00
return 0;
}Each .c file is translated individually into an object file, and the linker joins everything together. With several files, a Makefile automates the process and only rebuilds what has changed:
# Compiling without Make:
gcc -Wall -Wextra -std=c17 -c main.c
gcc -Wall -Wextra -std=c17 -c mathe.c
gcc main.o mathe.o -o programm
# Makefile (recipe lines start with a TAB, not with spaces!)
CC = gcc
CFLAGS = -Wall -Wextra -std=c17 -g
OBJ = main.o mathe.o
programm: $(OBJ)
$(CC) $(CFLAGS) -o $@ $(OBJ)
%.o: %.c mathe.h
$(CC) $(CFLAGS) -c $<
clean:
rm -f programm *.oWarningMacros evaluate arguments multiple times:
MAX(i++, 5) may increment i twice. Without parentheses, #define QUAD(x) x*x yields 5 instead of 9 for QUAD(2+1). For constants and small functions, const, enum and static inline functions are safer.Tip
static in front of a global function or variable makes it visible only in this .c file (internal linkage) – C's version of "private". Do not define variables in headers, only declarations (extern int zaehler;).