Search

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.
Syntax:



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.



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



If we run it as "user1" we will get the output



If we run it as any other user we will get the output


No comments:

Post a Comment