Past one file, a C project splits in two. A header (.h) declares what exists - function prototypes, type definitions, constants - and is included by anyone who needs them. A source (.c) defines it. The rule is one definition in one place and as many declarations as you like, and it is the direct consequence of the compiler reading each file independently.
A header included twice in one translation unit would declare its types twice, which is an error. Include guards prevent it: #ifndef, #define, the contents, #endif. #pragma once does the same in one line and is supported everywhere in practice, though it is not in the standard.
Macros are textual substitution and carry textual hazards. Parenthesise every parameter and the whole body, or SQUARE(a + b) expands to a + b * a + b. And a macro that uses an argument twice evaluates it twice, so MAX(i++, j) increments twice. An inline function does the same job with types and without either trap.
Conditional compilation - #ifdef DEBUG - includes or excludes code before the compiler sees it, which is how one source supports several platforms or build types.
A Makefile records what depends on what, so changing one .c recompiles that file and relinks, rather than rebuilding everything. That is the whole point of object files.
/* ---- stack.h : what exists ------------------------------------- */
#ifndef STACK_H /* include guard: ifndef / define / endif */
#define STACK_H
#include <stddef.h>
typedef struct Stack Stack; /* opaque: callers cannot see the fields */
Stack *stack_create(size_t capacity);
int stack_push(Stack *s, int value);
int stack_pop(Stack *s, int *out);
void stack_destroy(Stack *s);
/* Parenthesise EVERY parameter and the whole body, or
SQUARE(a + b) expands to a + b * a + b. */
#define SQUARE(x) ((x) * (x))
/* Still wrong even parenthesised: x is evaluated twice, so
MAX(i++, j) increments twice. An inline function has neither trap. */
#define MAX(a, b) ((a) > (b) ? (a) : (b))
static inline int max_int(int a, int b) { return a > b ? a : b; }
#endif /* STACK_H */
/* ---- stack.c : the definitions ---------------------------------- */
/*
#include "stack.h"
#include <stdlib.h>
struct Stack { int *items; size_t top, capacity; };
Stack *stack_create(size_t capacity) { ... }
*/
/* ---- Makefile : rebuild only what changed ----------------------- */
/*
CC = gcc
CFLAGS = -Wall -Wextra -g -std=c17
OBJECTS = main.o stack.o
program: $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $(OBJECTS)
%.o: %.c stack.h # any .o depends on its .c and the header
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -f $(OBJECTS) program
# The recipe lines must start with a TAB, not spaces.
*/
/* Conditional compilation, decided before the compiler runs:
#ifdef DEBUG
fprintf(stderr, "value = %d\n", value);
#endif
turned on with: gcc -DDEBUG ... */