It is a hassle to have to track which header file is used in which source file. Our Makefile, up to this point, relies on the programmer to correctly describe how the source files use the header files. Any mistake (like omitting an header file from an object file rule) can lead to confusion and frustration.
As lazy programmers, we have a way around this problem, too.
Here is our new and slightly improved Makefile:
Here, we use a a special kind of rule that is more like a template. The target “%.d” is saying “whatever ends with a .d extension”. However, once the % symbol is bound to a particular name, that same name is used in the dependency, “%.c”. This means that every .c file can generate a .d file.
The command to do this is rather complicated. At the core, it uses the -MM option of gcc to generate a dependency file. A dependency file looks just like the dependency part of a rule in a Makefile. Each backslash \ at the end of the line of the command means “I’m not done yet, continue on the next line”. The special variable $^ refers to the all the names in the prerequisite of a rule. $@ refers to the name of the target.
If you run the command “make main.d”, the make program should generate the main.d file. Based on our assumptions, the content of this file should be as follows;
Yep, it says that it also depends on main.c and main.h!