1.12. Makefile with more default convention

As compared to Build using a Makefile, let us extend the Makefile with more default conventions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
all: greeting_en greeting_fr greeting_es

greeting_en:
	@echo Generating greeting_en from main.c and greeting_en.c
	gcc main.c greeting_en.c -Wall -o greeting_en

greeting_fr:
	@echo Generating greeting_fr from main.c and greeting_fr.c
	gcc main.c greeting_fr.c -Wall -o greeting_fr

greeting_es:
	@echo Generating greeting_es from main.c and greeting_es.c
	gcc main.c greeting_es.c -Wall -o greeting_es

clean:
	rm greeting_en greeting_fr greeting_es

run:
	./greeting_en
	./greeting_fr
	./greeting_es

In line no. 1, we have added a default target called all. So running make and make all does exactly the same thing.

In line no. 1, we have all added target dependencies. all depends on greeting_en, greeting_fr and greeting_es. So when we run make all, it’s dependencies (greeting_en, greeting_fr and greeting_es) are build first before building all.

We have also added a target clean and line no. 15 and 16 to remove generated binaries. We just need to run make clean in case we want to remove generated binaries.

And to easily run the generates files with one single command, make run, we have added target at lines 18 to 21.

1.12.1. Compiling using Makefile

To compile all our required binaries, the command would be.

make all

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

Generating greeting_en from main.c and greeting_en.c
gcc main.c greeting_en.c -Wall -o greeting_en
Generating greeting_fr from main.c and greeting_fr.c
gcc main.c greeting_fr.c -Wall -o greeting_fr
Generating greeting_es from main.c and greeting_es.c
gcc main.c greeting_es.c -Wall -o greeting_es

As you can see, running make all also build its dependencies (greeting_en, greeting_fr and greeting_es).

1.12.2. Running generated binaries using Makefile

To execute the binary generated from the source file, the command would as simple as.

make run

As you can see, we do not have to run each file individually. make run does that for us.

If everything went fine, the output would be:

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