Makefile header dependencies

Suppose foo.c has a line:

#include "something.h"

You’d like a line in the makefile:

foo.o: foo.c something.h

The gcc compiler can construct that line for you. The command

gcc -MMD -c -o foo.o foo.c

will build foo.o and foo.d which contains the line. (Try it.)

So just modify your makefile to produce these *.d files and include them, and you’re done:

$(ODIR)/%.o: %.c $(DEPS)
    $(CC) -MMD -c -o $@ $< $(CFLAGS)

-include $(ODIR)/*.d

(Further refinements are possible, like specifying where the *.d files should go.)

Leave a Comment