When programming with multiple files/modules, dependency tracking is always a big issue. GNU Make calculates the correct order to compile in, but is only that smart. It does know that if a .cpp file changes, the corresponding .o file needs to be updated. But a change in an included header can go unnoticed.

While debugging a strange problem today, it was exactly that last scenario: A change in a header file did not cause a recompile, which left me debugging an old version of the binary. So I wanted to include the dependencies of .cpp files on the included headers in my Makefile. But since I’m too lazy to do it myself, I wrote a script.

Include these lines into your main Makefile.

	-rm -f $@
	find . -name '*.cpp' | while read s; do echo "$${s%%cpp}o: $${s}" >> $@; done
	find . -name '*.c' | while read s; do echo "$${s%%c}o: $${s}" >> $@; done
	find . -name '*.cpp' -o -name '*.c' -o -name '*.hpp' -o -name '*.h' | while read f; do \
		/bin/echo -n "$$f: " >> $@; \
		D="`dirname "$$f"`/"; \
		grep '^#include "' $$f | sed 's@^#include "\(.*\)"@'$$D'\1@' | tr '\n' ' ' >> $@; \
		echo "" >> $@; \
		echo "	touch \$$@" >> $@; \
.PHONY: Makefile.includes
include Makefile.includes