Pliant AllianceSoftware development notes & tools

How to write a simple Makefile for C projects

A small C program can be compiled with one command, but a project with several source files quickly becomes harder to manage. Repeating compiler commands by hand is slow, and it is easy to forget which files have changed, which libraries are required, or which object files belong to an older version of the code. A Makefile records those relationships in a form that the make utility can follow.

The useful idea is simple: describe the final program, list the files it depends on, and provide the command needed to build it. make then checks file modification times and recompiles only what is necessary. The same approach works on Linux, macOS, BSD, and Windows environments that provide a Unix-like shell, including development setups used by Australian students, hobbyists, and professional teams.

What a Makefile does

A Makefile contains rules. Each rule usually has a target, a list of prerequisites, and one or more shell commands. The target is the file or action you want to produce. A prerequisite is something the target depends on, such as a C source file or header. The command explains how to create the target.

For a project containing main.c, greet.c, and greet.h, the final executable might be called greet. The compiler first turns each .c file into an object file ending in .o, then the linker combines those object files into the executable. This two-stage process matters because changing greet.c should not require recompiling main.c.

A minimal rule looks like this:

greet: main.o greet.o
	cc main.o greet.o -o greet

main.o: main.c greet.h
	cc -c main.c

greet.o: greet.c greet.h
	cc -c greet.c

The indentation before each command must be a tab character, not a group of spaces. This is one of the oldest and most common Makefile mistakes. On a typical Ubuntu installation, make and a C compiler can be installed through the distribution’s package manager. On macOS, Apple’s command-line developer tools provide clang, while Windows developers may use WSL or a Unix-style toolchain.

The command make builds the first target in the file, which is greet in this example. Running it again usually produces no output because the executable and object files are newer than their prerequisites. If greet.c changes, make rebuilds greet.o and then links a fresh executable, while leaving main.o alone.

A practical first Makefile

Hard-coding every filename is acceptable for a tiny example, but variables make a Makefile easier to read and adapt. CC identifies the compiler, CFLAGS contains compiler options, and TARGET names the resulting program. The -Wall and -Wextra options enable useful warnings, while -std=c11 asks for the C11 language standard.

CC = cc
CFLAGS = -Wall -Wextra -std=c11
TARGET = greet

$(TARGET): main.o greet.o
	$(CC) $(CFLAGS) main.o greet.o -o $(TARGET)

main.o: main.c greet.h
	$(CC) $(CFLAGS) -c main.c

greet.o: greet.c greet.h
	$(CC) $(CFLAGS) -c greet.c

clean:
	rm -f $(TARGET) main.o greet.o

The clean rule does not create a file called clean; it performs an action. For that reason, it should be marked as phony:

.PHONY: clean

A phony target tells make that the name is a command rather than a real file. Without this declaration, a file accidentally named clean could cause make clean to do nothing. It is also common to add all as the default target, especially when a project eventually produces more than one program.

.PHONY: all clean

all: $(TARGET)

$(TARGET): main.o greet.o
	$(CC) $(CFLAGS) main.o greet.o -o $(TARGET)

The clean-up command uses rm -f, which avoids an error if one of the files has already been removed. On a shared project, take care that the command names only generated files. A careless rm command can delete source code, test fixtures, or configuration files.

Understanding dependencies and rebuilds

Dependencies are the part of a Makefile that gives it its efficiency. A target is considered out of date when one of its prerequisites has a newer modification time. If greet.h contains a declaration included by both source files, both object files should list that header as a prerequisite. When the header changes, each affected source file is compiled again.

The following arrangement is more maintainable because it stores generated object files in an obj directory and puts the executable in a bin directory:

CC = cc
CPPFLAGS = -Iinclude
CFLAGS = -Wall -Wextra -std=c11
TARGET = bin/greet
SOURCES = src/main.c src/greet.c
OBJECTS = obj/main.o obj/greet.o

.PHONY: all clean

all: $(TARGET)

$(TARGET): $(OBJECTS)
	@mkdir -p bin
	$(CC) $(OBJECTS) -o $@

obj/%.o: src/%.c
	@mkdir -p obj
	$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@

clean:
	rm -rf obj bin

Here, $@ means the current target and $< means the first prerequisite. The pattern rule obj/%.o: src/%.c says that an object file in obj can be made from the matching source file in src. The @ before mkdir hides that command from the terminal; it does not change what the command does.

A header dependency can be written explicitly for a small project:

obj/main.o: include/greet.h
obj/greet.o: include/greet.h

For larger projects, compilers can generate dependency files automatically. With GCC or Clang, adding -MMD -MP to CFLAGS creates a .d file beside each object file. Those files can then be included at the bottom of the Makefile. This is a useful refinement once a project has several headers, although explicit dependencies are easier to understand while learning.

Make feature Purpose Example
Variable Stores a reusable value CC = cc
Target Names a file or action all:
Prerequisite Lists required files main.o greet.o
Recipe Runs the build command $(CC) -c main.c
Pattern rule Describes a family of files obj/%.o: src/%.c
Phony target Marks an action without a file .PHONY: clean
Automatic variable Refers to the current rule $@, $<

The result is a small dependency graph. Source files lead to object files, object files lead to the executable, and a header sits upstream of every object that includes it. Thinking in terms of that graph helps diagnose unexpected rebuilds. If a file is always recompiling, check its timestamps, generated dependency files, and whether a rule names a directory or a broad prerequisite unnecessarily.

Building predictable commands

A good Makefile should make common operations obvious. make builds the default target, make clean removes generated files, and a target such as make run can execute the current program. A test target is also useful when a project has a separate test binary or a shell script that checks expected output.

.PHONY: all clean run test debug

all: $(TARGET)

run: $(TARGET)
	./$(TARGET)

test: $(TARGET)
	./tests/run_tests.sh

debug: CFLAGS += -g -O0
debug: clean all

clean:
	rm -rf obj bin

The debug target demonstrates that variables can be extended for one target. -g adds debugging information and -O0 disables optimisation, making a debugger easier to use. A release build might use -O2, but warning options should generally remain enabled. Treat compiler warnings as feedback rather than noise; they often expose incorrect types, missing declarations, and suspicious control flow before a program fails at runtime.

It is worth keeping commands portable where possible. Use $(CC) instead of assuming GCC, because a macOS system may use Clang behind the cc name. Avoid shell features that exist only in one environment unless the project specifically requires them. Developers moving between Melbourne and Brisbane offices, or contributing from Perth to a Sydney-based repository, benefit when the same make command works without local edits.

Build commands belong alongside source code in version control. This is part of the wider practice of keeping a project’s history reproducible; the version control history should show how source, build instructions, and configuration changed together. A new developer should be able to check out the repository, install the compiler, and understand the expected commands without relying on private notes.

Adapting the file to real projects

As a project grows, replace lists that are difficult to maintain with variables or wildcard functions. For example, $(wildcard src/*.c) can find C source files in one directory, though explicit source lists are often safer because they make additions visible in a code review. A generated list can accidentally include experimental or backup files, so use it with care.

Libraries need to appear in the link command, usually after the object files that use them. A program using the mathematics library might have:

LDLIBS = -lm

$(TARGET): $(OBJECTS)
	$(CC) $(OBJECTS) $(LDLIBS) -o $@

The order can matter with traditional Unix linkers. Put library options after the objects that refer to their functions. For third-party libraries installed through Homebrew, Ubuntu packages, or a project-specific prefix, use CPPFLAGS for include directories and LDFLAGS for library directories. Avoid embedding a single developer’s home directory in the file, since paths differ across machines.

Some C projects generate source files before compiling. In that situation, add a rule for the generated file rather than placing a preparation command in every compile recipe. Generated output should usually be ignored by version control, while the source template or generator remains tracked. The Makefile then documents the sequence clearly and allows a clean rebuild on a new machine.

The same separation of responsibilities is useful outside command-line C. An iOS developer may apply similar thinking to generated assets and compiled source; a UIKit cell example shows how a larger application also benefits from keeping reusable components and their supporting files organised. The tools differ, but the principle is familiar: declare what depends on what, then automate the repeatable work.

Checking and maintaining a simple build

Test a new Makefile from a clean directory. Run make clean, then make, and inspect whether every source file is compiled and the final link succeeds. Run make a second time; it should report that there is nothing to do. Touch one source file with touch src/greet.c, run make again, and verify that only its object file and the final executable are rebuilt.

Next, change a header and confirm that every dependent object is recompiled. If a header change does not trigger the expected rebuild, add the missing prerequisite or enable compiler-generated dependency files. This check catches a subtle class of bugs in which an old object file contains declarations or inline code from a previous version.

Use make -n to preview commands without running them. make -B forces a complete rebuild, which is useful when testing the rules themselves. make -j2 or make -j$(nproc) can build independent targets in parallel, although parallel execution is safest after dependencies are accurate. A missing prerequisite may remain hidden during a serial build and cause intermittent errors during a parallel one.

Keep the finished file short enough that another developer can scan it quickly. A two-file C program does not need a sophisticated build framework. For a small command-line tool developed in Adelaide, a university assignment in Canberra, or a utility maintained by a local business, clear targets, correct header dependencies, and a reliable clean build provide most of the value. When the project outgrows these conventions, the Makefile will already have established the dependency model that a larger build system needs.