Makefies : Conditional execution using ifeq

Conditions can be added in makefiles using “if” conditions, to ensure the commands get executed only under certain conditions.

The syntax of if in a makefile is

ifeq(,) statements else statement endif

Let us say we have two files hello1.c and hello2.c which we want to compile using makefile. But the condition for compiling these files is that if the user who is compiling is root then hello_1.c should be compiled,else for any other user hello_2.c should be compiled. We can use the if condition in makefile to achieve this.

This can be done using the following makefile

CC = cc -o pf=hello user = $(shell whoami) ifeq ($(user),root) targets := $(pf)_2 else targets = $(pf)_1 endif $(targets):$(targets).c $(CC) $(targets) $(targets).c

user = $(shell whoami)

Above statement assigns the current user name to the variable “user” using the command “whoami”.

Then we use the “if” condition and check the user name and assign the target based on the result of the condition check.

If we execute the make command as root we will get the following output

$ make cc -o hello_2 hello_2.c

If we do the same as any other user other than root, we will get the following output

$ make cc -o hello_2 hello_2.c


Tags: ,
Copyright 2017. All rights reserved.

Posted November 18, 2012 by Tux Think in category "Linux