1.13.1. Anatomy of the Makefile with variables

Now let us understand the Makefile step by step.

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

In line no. 1, we are declaring a variable TARGETS and adding values greeting_en, greeting_fr and greeting_es. By convention, values are space separated in a Makefile. So essentially, TARGETS is an array.

1TARGETS=greeting_en greeting_fr greeting_es
2
3all: $(TARGETS)
4
5$(TARGETS):

In line no. 3 we are declaring that the target all. The target all depends on the values listed in TARGETS.

Since all is the first target encountered, it is the default target. So, the commands make and make all are semantically same.

$(TARGETS):
	gcc main.c $@.c -Wall -o $@

In lines 5 and 6, we have introduced a new way of declaring/defining a Makefile target. Unlike in previous section, where greeting_en, etc. were declared explicitly, here we are declaring them using the variable TARGETS. Using $ operator, we are expanding the variable. So, $(TARGETS) is expansion of values stored in the variable TARGETS

The $@ in line no. 6 is a special make variable that depends on the current target being executed. For more see Automatic Variables in https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html

clean:
	rm $(TARGETS)

The above lines declare a target called clean. When user executes the make clean, it runs the shell executable rm and removes the files listed as part of TARGETS variable.

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

The above lines declare a target called run. We also introduce a construct of Makefiles, foreach. Using foreach, we are iterating over variables part of TARGETS, and store its value into a new variable called target. Using ./$(target);, we are actually executing each generated file.

To learn more about foreach, see https://www.gnu.org/software/make/manual/html_node/Foreach-Function.html#Foreach-Function