How can I have a Makefile automatically rebuild source files that include a modified header file? (In C/C++)

As already pointed out elsewhere on this site, see this page:
Auto-Dependency Generation

In short, gcc can automatically create .d dependency files for you, which are mini makefile fragments containing the dependencies of the .c file you compiled.
Every time you change the .c file and compile it, the .d file will be updated.

Besides adding the -M flag to gcc, you’ll need to include the .d files in the makefile (like Chris wrote above).
There are some more complicated issues in the page which are solved using sed, but you can ignore them and do a “make clean” to clear away the .d files whenever make complains about not being able to build a header file that no longer exists.

Leave a Comment