makefiles: Complex conditional execution
While doing the conditional execution in makefiles, using only if and ifneq allows us to check for one condition but to be able to check multiple conditions one after another, we can use either if or ifneq after the else to check for further conditions.
ifneq(,) statements else statements endif
If the ifneq condition fails then the flow will go to the else and check the condition specified after the else. We can use as many else statements as we require.
Let us say we have three “c” programs, hello_1.c, hello_2.c and hello_3.c. We need to compile them depending on which user is running the make command. hello_1.c should be compiled if we are running make as root, hello_2.c if we are running make as “user1” and for any other user hello_3.c. This can be achieved by the following makefile.
CC = cc -o pf=hello user = $(shell whoami) ifeq ($(user),root) targets := $(pf)_1 else ifeq ($(user),user1) targets = $(pf)_2 else targets = $(pf)_3 endif $(targets):$(targets).c $(CC) $(targets) $(targets).c
In the above makefile, first variable “user” is compared with “root” then with “user1”. If both the conditions turn out to be false then the statements after the final else gets executed, which sets the targets to hello_3.c as required.
If we run the above makefile as root then we will get the output
cc -o hello_1 hello_1.c
If we run it as “user1” we will get the output
cc -o hello_2 hello_2.c
If we run it as any other user we will get the output
cc -o hello_3 hello_3.c