../

Common Patterns for Writing Makefiles

2024-03-17

List all *.c files in the src directory:

SRC = $(shell find src/ -name '*.c')

List all *.c files in the src directory, but exclude main.c:

SRC = $(shell find src/ -name '*.c' -not -name 'main.c')

List the corresponding *.o files for all *.c files:

OBJ = $(SRC:.c=.o)

Compile all *.c files into *.o files and generate header file dependencies (*.d files):

$(OBJ):%.o:%.c
    $(CC) -c $(CFLAGS) $< -MD -MF $@.d -o $@

Include dependencies in the Makefile to facilitate automatic recompilation when header files are modified:

DEPS := $(shell find . -name *.d)

ifneq ($(DEPS),)
include $(DEPS)
endif

Mistivia - https://mistivia.com