A Small Cookbook of Makefile

2024-03-17

List all *.c files in src/ directory:

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

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

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

List all *.o files for every *.c file.

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

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

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

Add these generated dependencies to Makefile, so that make will automatically recompile source files releated to modified header files:

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

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


Email: i (at) mistivia (dot) com