1.17. Dependencies in a Makefile

In the previous seciton Section 1.16 : Running Make multiple times — After editing a file, we had an issue, even if we modifiled a .c file, a recompilation did not happen.

To ensure that we have these dependencies, let’s update Makefile like this.

 1TARGETS=greeting_en greeting_fr greeting_es
 2
 3all: $(TARGETS)
 4CFLAGS := -Wall
 5
 6$(TARGETS):
 7	gcc main.c $@.c $(CFLAGS) -o $@
 8
 9greeting_en: greeting_en.c main.c greeting.h
10greeting_fr: greeting_fr.c main.c greeting.h
11greeting_es: greeting_es.c main.c greeting.h
12
13clean:
14	-@rm $(TARGETS)
15
16run:
17	$(foreach target,$(TARGETS), ./$(target);)

In line 9 to 11, we are explicitly adding depdendencies of the makefile.

1.17.1. 1st Run

Let’s compile all.

make all

The output is as expected so far:

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

1.17.2. 2nd Run

Let’s touch a .c file.

touch greeting_en.c

Let’s make all.

make all

The output is interesting now. As you can see below, only English got recompiled. French and Spanish did not.

gcc main.c greeting_en.c -Wall -o greeting_en

1.17.3. Anatomoy of the make file - dependencies

Let us extend the understanding of make files even further than what we learned in Section 1.11.3: Anatomy of the Makefile - targets and rules, dependecies:

TARGET: DEPENDENCIES RULES

With depdencies, we bring in a concept of older than.

In other words, we ask make to re-create a target (which is actually a file), if it is older than it’s depdencies. So, if you touch or modify some .c/.h file, it’s timestamp would be newer than the target.

This way, we give a hint when to exercise the rules to create or build a target