1.18. Using GCC to create dependency files for the Makefile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
TARGETS=greeting_en greeting_fr greeting_es
CDEPS=$(foreach target,$(TARGETS), $(target).d)

all: $(TARGETS)

$(TARGETS):%:%.o

$(TARGETS): main.c Makefile
	gcc $< $@.o  $(CFLAGS) -o $@

%.o: %.c Makefile
	gcc -MMD -c -o $@ $< $(CFLAGS)

clean:
	-@rm $(TARGETS)
	-@rm *.d *.o

run:
	$(foreach target,$(TARGETS), ./$(target);)

-include $(CDEPS)

.PHONY: all clean run

To compile that file with GCC, the command would be.

make all

When the above command completes successfully, the compilation output would be:

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

To execute the binary generated from the source file, the command would be as shown below.

make run

If everything went fine, the output would be:

./greeting_en;  ./greeting_fr;  ./greeting_es;
Hello World!
Bonjour le monde!
Hola Mundo!