1.18. Using GCC to create dependency files for the Makefile

Managing depdendencies, especially in a huge project like Section 1.17 Dependencies in a Makefile would be extremely difficult and painful.

GNU C supports creating dependencies automatically on compilation, using the flag -MMD.

 1TARGETS=greeting_en greeting_fr greeting_es
 2CDEPS=$(foreach target,$(TARGETS), $(target).d)
 3
 4all: $(TARGETS)
 5
 6$(TARGETS):%:%.o
 7
 8$(TARGETS): main.c Makefile
 9	gcc $< $@.o  $(CFLAGS) -o $@
10
11%.o: %.c Makefile
12	gcc -MMD -c -o $@ $< $(CFLAGS)
13
14clean:
15	-@rm $(TARGETS)
16	-@rm *.d *.o
17
18run:
19	$(foreach target,$(TARGETS), ./$(target);)
20
21-include $(CDEPS)
22
23.PHONY: all clean run

Note

Flags -M, -MM along with -MMD

If you read https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html, you can see there are other options like -M and -MM as well. In order to keep this book brief, they are not covered here.

1.18.1. 1st Run

Let’s compile that with gcc.

make all

Output would be like this.

gcc -MMD -c -o greeting_en.o greeting_en.c 
gcc main.c greeting_en.o   -o greeting_en
gcc -MMD -c -o greeting_fr.o greeting_fr.c 
gcc main.c greeting_fr.o   -o greeting_fr
gcc -MMD -c -o greeting_es.o greeting_es.c 
gcc main.c greeting_es.o   -o greeting_es

1.18.2. 2nd Run

Let’s touch a core .h file.

touch greeting.h

Let’s make all.

make all

The output is interesting now. As you can see below, Everything got re-compiled because a common header file used by every one was used for compilation.

gcc -MMD -c -o greeting_en.o greeting_en.c 
gcc main.c greeting_en.o   -o greeting_en
gcc -MMD -c -o greeting_fr.o greeting_fr.c 
gcc main.c greeting_fr.o   -o greeting_fr
gcc -MMD -c -o greeting_es.o greeting_es.c 
gcc main.c greeting_es.o   -o greeting_es