Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 135 ยท Advanced C

Build Tools: Make and CMake

Automate C builds - how make decides what to rebuild, writing a real Makefile with automatic header dependencies, CMake targets and build types, and debug versus release flags.

Once a program is split into several source files, building it by hand becomes a chore: compile each .c file into an object file, remember which ones changed, pass the same dozen flags every time, link everything at the end. Forget to recompile one file after editing a header and you get a program built from inconsistent pieces, which fails in baffling ways. Build tools record the steps once and then do the minimum work needed, correctly, every time.

This lesson covers the two tools you'll meet in almost every C project. Make is the classic: small, everywhere, and still the backbone of countless projects. CMake is the modern standard for portable projects: it generates build files for Make, Ninja, Visual Studio or Xcode from one description. You'll also learn the compiler flags that separate a debug build from a release build. Our editor builds single files, so the project files here are read-only, while the runnable examples show the ideas underneath.

What a build tool does

A build is a graph of targets made from prerequisites: main.o is made from main.c and the headers it includes; the program is made from all the object files. A build tool walks this graph and rebuilds a target only if it's missing or older than one of its prerequisites (it compares file modification times). Edit one .c file and only its object file is recompiled, then the program is relinked. Edit a header and every object file that includes it is rebuilt.

That decision is simple enough to write in C. The program below models a small project with made-up timestamps, where parser.h was just edited, and prints the commands a build tool would run:

C How make decides what to rebuild

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first build recompiles main.o and parser.o (both depend on the edited header), skips report.o, and relinks app. The second build does nothing at all, because every output is newer than its inputs. Try setting report.c's time to 400 or main.o's to 0 (deleted) and run it again. Real make adds parallelism, pattern rules and much more, but this comparison of timestamps is its core.

Writing a Makefile

make reads a file named Makefile in the current directory. Its basic unit is the rule:

MAKE
target: prerequisites
	recipe (shell commands)

Warning: Each recipe line must start with a tab character, not spaces. If your editor turns tabs into spaces, make stops with missing separator. This is the most famous wart in Unix tooling, and it's been there since 1976.

Here is a complete, practical Makefile for the temperature project from the previous lesson. Read it once, then the explanations below:

MAKE
# ---- configuration ----
CC      := gcc
CSTD    := -std=c17
WARN    := -Wall -Wextra -Wpedantic -Wshadow
CFLAGS  := $(CSTD) $(WARN) -Iinclude -MMD -MP
LDLIBS  := -lm

BUILD   ?= debug
ifeq ($(BUILD),release)
  CFLAGS += -O2 -DNDEBUG
else
  CFLAGS += -O0 -g3 -fsanitize=address,undefined
  LDFLAGS += -fsanitize=address,undefined
endif

SRC     := $(wildcard src/*.c)
OBJ     := $(SRC:src/%.c=build/%.o)
DEP     := $(OBJ:.o=.d)
BIN     := build/weather

# ---- rules ----
.PHONY: all clean run

all: $(BIN)

$(BIN): $(OBJ)
	$(CC) $(LDFLAGS) $^ $(LDLIBS) -o $@

build/%.o: src/%.c | build
	$(CC) $(CFLAGS) -c $< -o $@

build:
	mkdir -p build

run: $(BIN)
	./$(BIN)

clean:
	rm -rf build

-include $(DEP)

Variables. CC, CFLAGS, LDFLAGS and LDLIBS are conventional names that users expect to override: make CC=clang builds with Clang without editing the file. := assigns immediately; ?= assigns only if the variable isn't already set, so make BUILD=release picks the release flags. $(VAR) expands a variable.

Automatic variables. Inside a recipe, $@ is the target, $< is the first prerequisite and $^ is all prerequisites. So $(CC) $(CFLAGS) -c $< -o $@ compiles one source into its object file.

Pattern rules. build/%.o: src/%.c is one rule for every object file: % matches the same stem on both sides. $(SRC:src/%.c=build/%.o) turns the list of sources into the list of objects, and $(wildcard src/*.c) finds the sources, so adding a new .c file needs no Makefile change.

Header dependencies. A pattern rule only knows that build/main.o depends on src/main.c, not on the headers it includes. The flags -MMD -MP make GCC and Clang write a small .d file next to each object, listing the headers that file actually included, and -include $(DEP) pulls those lists into the Makefile (the - means "don't complain on the first build, when they don't exist yet"). Without this, editing a header doesn't trigger rebuilds, which is the classic source of stale-build bugs. A generated build/main.d looks like:

MAKE
build/main.o: src/main.c include/temp_stats.h
include/temp_stats.h:

Phony targets. all, clean and run aren't files. Declaring them .PHONY tells make to always run them, even if a file named clean happens to exist. The first rule in the file (all) is the default when you type just make.

Order-only prerequisites. | build means "the build directory must exist first, but its timestamp doesn't matter" (a directory's time changes whenever a file inside it does, which would otherwise cause endless rebuilds).

Typical use:

Terminal
make                 # debug build (the default here)
make -j8             # build up to 8 files in parallel
make BUILD=release   # optimized build
make clean           # remove everything that was built
make -n              # print the commands without running them

-j parallelism is free speed: independent object files compile at the same time on different cores. It's also why correct dependencies matter, since a missing prerequisite can make a parallel build race.

Debug and release flags

The same source code is usually built in two ways. A debug build is for development: no optimization (so the debugger shows variables and lines exactly as written), full debug information, assertions enabled, and often sanitizers that catch memory errors at runtime. A release build is what you ship: optimized and with assertions disabled.

Flag Meaning
-std=c17 / -std=c23 Language standard; add -Wpedantic to warn about compiler extensions
-Wall -Wextra The essential warning sets; enable them always
-Werror Treat warnings as errors (great in CI, annoying with new compiler versions)
-O0 No optimization: fastest compile, easiest debugging
-O2 Standard release optimization; -O3 is more aggressive, -Os optimizes for size
-g / -g3 Debug information for gdb/lldb (-g3 includes macros)
-DNDEBUG Defines NDEBUG, which turns every assert into nothing
-DNAME=value Defines any macro from the command line
-fsanitize=address,undefined AddressSanitizer and UBSan: runtime checks for memory errors and undefined behavior
-I dir / -L dir / -l name Header search path / library search path / link library libname

Code can see some of these choices through the preprocessor. -D macros arrive as if #defined at the top of every file, and GCC and Clang define __OPTIMIZE__ whenever optimization is on. Our editor compiles with -O1 and no NDEBUG, so this program reports a mixed setup; the first line simulates -DAPP_VERSION=..., which a build tool would normally pass:

C What the build flags look like from inside

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output shows 202311 for the C23 standard, GCC 15, optimization on and assertions enabled. Add #define NDEBUG as the very first line and the assertion line changes: that's precisely what -DNDEBUG does in a release build. (NDEBUG must be defined before <assert.h> is included, which a command-line -D always is.) More about these macros in Predefined Macros and assert.

Warnings deserve special attention, because they're the cheapest bug detector you'll ever get. This program compiles and runs, but our -Wall -Wextra flags flag three real problems. The warnings are the lesson here:

C Bugs that warning flags catch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC warns that unused_total is unused, that the comparison mixes signed and unsigned integers, and suggests parentheses around an assignment used as a condition. Two of those are real bugs, and the output proves it. limit is converted to an enormous unsigned value, so the program prints within the limit?! even though 5 is clearly greater than โˆ’1 (see Type Conversions and Casts). And count = 0 assigns 0 instead of comparing, so the program prints count is 0 although count started at 3 (see if, else if and else). Fix all three: delete the unused variable, make limit a size_t (or check it for negative values first), and write ==. In a team, -Werror in the continuous-integration build makes sure such warnings never pile up.

CMake

Makefiles are great on Unix, but they're tied to a shell, to GCC-style flags, and to make itself. Windows developers using Visual Studio, macOS developers using Xcode, and fast builders using Ninja would each need their own build files. CMake solves this: you describe the project once in CMakeLists.txt, and CMake generates native build files for whatever toolchain is present. It's the de facto standard for open-source C and C++ projects, and IDEs such as CLion, VS Code and Visual Studio open CMake projects directly.

A minimal project:

CMAKE
cmake_minimum_required(VERSION 3.20)
project(weather VERSION 1.4.0 LANGUAGES C)

set(CMAKE_C_STANDARD 17)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)          # -std=c17, not -std=gnu17

add_executable(weather
    src/main.c
    src/temp_stats.c
    src/csv_reader.c
)
target_include_directories(weather PRIVATE include)
target_link_libraries(weather PRIVATE m)        # the math library on Unix

Modern CMake is organized around targets (executables and libraries) and their properties, instead of global variables. Once a module is reused by several programs or tests, make it a library target; anything that links to it automatically gets its PUBLIC include directories and dependencies:

CMAKE
add_library(temp_stats src/temp_stats.c)
target_include_directories(temp_stats PUBLIC include)

if(MSVC)
    target_compile_options(temp_stats PRIVATE /W4)
else()
    target_compile_options(temp_stats PRIVATE -Wall -Wextra -Wpedantic)
endif()

target_compile_definitions(temp_stats PRIVATE APP_VERSION="${PROJECT_VERSION}")

add_executable(weather src/main.c src/csv_reader.c)
target_link_libraries(weather PRIVATE temp_stats)

enable_testing()
add_executable(test_temp_stats tests/test_temp_stats.c)
target_link_libraries(test_temp_stats PRIVATE temp_stats)
add_test(NAME temp_stats COMMAND test_temp_stats)

PRIVATE means "needed to build this target only", PUBLIC means "needed by this target and by everyone who links to it", and INTERFACE means "needed only by users". Getting these right keeps big builds clean. The compiler-specific branch shows how CMake projects stay portable: MSVC's warning flags differ from GCC's.

Building is a two-step process: configure (generate build files into a separate build directory) and build. Keeping all generated files out of the source tree is called an out-of-source build, and it means "clean" is just deleting a directory:

Terminal
cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug     # configure (once, or after CMakeLists changes)
cmake --build build -j                           # build in parallel
ctest --test-dir build                           # run the tests

cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release
cmake --build build-release

cmake -S . -B build -G Ninja                     # choose a generator explicitly

CMAKE_BUILD_TYPE selects ready-made flag sets: Debug (-g, no optimization), Release (-O3 -DNDEBUG), RelWithDebInfo (-O2 -g -DNDEBUG) and MinSizeRel (-Os -DNDEBUG). Visual Studio and Xcode generators hold all of them at once, and you pick one with cmake --build build --config Release. CMake also tracks header dependencies automatically, and adding set(CMAKE_EXPORT_COMPILE_COMMANDS ON) writes a compile_commands.json that editors and tools like clangd and clang-tidy use to understand your project.

Choosing a build tool

Tool Strengths Typical use
A one-line gcc command Nothing to learn Single files, experiments, this course's editor
Make Everywhere on Unix, simple, flexible Small and medium Unix projects, glue tasks
CMake Cross-platform, IDE support, library ecosystem Most portable C and C++ projects
Ninja Extremely fast at executing builds A backend generated by CMake or Meson, rarely written by hand
Meson Clean syntax, fast, good defaults GNOME, systemd and other Linux projects

Whatever you choose, the same principles apply: describe dependencies completely, keep debug and release configurations separate, turn warnings on, and make a fresh build from a clean checkout work with one or two commands. For catching the bugs these builds expose, see Debugging C Programs; for the threads that -pthread enables, read on.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You edit parser.h, which main.c and parser.c include but report.c does not. With correct dependencies, what does make rebuild?

    Both object files that depend on the header are older than it, so they are recompiled, and the program is relinked because its inputs changed. report.o is skipped.
  2. 2. In the recipe $(CC) $(CFLAGS) -c $< -o $@ for the rule build/main.o: src/main.c, what do $< and $@ expand to?

    $@ is the target being built and $< is its first prerequisite.
  3. 3. What do the flags -MMD -MP add to a Makefile-based build?

    The compiler writes .d files listing each object's real header dependencies, and -include brings them into make.
  4. 4. What does compiling with -DNDEBUG do to assert(ptr != NULL);?

    When NDEBUG is defined before <assert.h> is included, assert expands to nothing. That's why release builds must never rely on side effects inside an assertion.
  5. 5. Why does strlen(word) > limit with int limit = -1 evaluate to false?

    In a comparison between size_t and int, the int is converted to the unsigned type, so -1 becomes SIZE_MAX. -Wsign-compare (part of -Wextra) warns about exactly this.

Summary

  • Build tools model a project as targets and prerequisites and rebuild a target only when it's missing or older than one of its inputs.
  • A Makefile rule is target: prerequisites plus tab-indented recipe lines; use variables (CC, CFLAGS, LDLIBS), automatic variables ($@, $<, $^), pattern rules and .PHONY targets.
  • Generate header dependencies with -MMD -MP and -include the .d files, or edited headers won't trigger rebuilds. Use make -j for parallel builds.
  • Debug builds use -O0 -g and often sanitizers; release builds use -O2 -DNDEBUG. Always compile with -Wall -Wextra, and consider -Werror in CI.
  • CMake describes targets once and generates Make, Ninja, Visual Studio or Xcode builds; use target_* commands with PRIVATE/PUBLIC, out-of-source build directories and CMAKE_BUILD_TYPE.

Next: Multithreading, where your programs start doing several things at once with pthreads and C11 threads.