A Basic C Makefile


These days I usually use Meson for building C and C++ code, but for small projects the simplicity and ubiquity of a Makefile can't be beat. In the past I'd write custom Makefile rules to compile each file individually, but with the power of wildcards we can write a generic Makefile that drops in to any project. Simply set the executable name, customize your compiler options, and off you go.

# `make` builds the target
# `make file.o` creates the `file` object file
# `make clean` will rm all object files and the target

TARGET = my-executable

# sample settings
CC = gcc
CFLAGS = -std=c11 -Wall -Wextra -Wpedantic -g
LDLIBS = -lpthread

SOURCES = $(wildcard *.c)
HEADERS = $(wildcard *.h)

# link the object files to create the target
	$(CC) $(CFLAGS) $^ -o $@ $(LDLIBS)

# compile rule for the object files
%.o: %.c $(HEADERS)
	$(CC) $(CFLAGS) -c $< -o $@

.PHONY: clean