Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile If-Then Else and Loops

Tags:

makefile

Can someone explain how to use if-then statements and for loops in Makefiles? I can't seem to find any good documentation with examples.

like image 804
GavinR Avatar asked Oct 07 '08 22:10

GavinR


4 Answers

Conditional Forms

Simple

conditional-directive
text-if-true
endif

Moderately Complex

conditional-directive
text-if-true
else
text-if-false
endif

More Complex

conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif

Conditional Directives

If Equal Syntax

ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"

If Not Equal Syntax

ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"

If Defined Syntax

ifdef variable-name

If Not Defined Syntax

ifndef variable-name  

foreach Function

foreach Function Syntax

$(foreach var, list, text)  

foreach Semantics
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.

like image 58
John Mulder Avatar answered Nov 04 '22 17:11

John Mulder


Here's an example if:

ifeq ($(strip $(OS)),Linux)
        PYTHON = /usr/bin/python
        FIND = /usr/bin/find
endif

Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.

like image 39
Mark Roddy Avatar answered Nov 04 '22 17:11

Mark Roddy


Have you tried the GNU make documentation? It has a whole section about conditionals with examples.

like image 7
Paige Ruten Avatar answered Nov 04 '22 16:11

Paige Ruten


You do see for loops alot of the time, but they are usually not needed. Here is an example of how one might perform a for loop without resorting to the shell

LIST_OF_THINGS_TO_DO = do_this do_that 
$(LIST_OF_THINGS_TO_DO): 
       run $@ > [email protected]

SUBDIRS = snafu fubar
$(SUBDIRS):
     cd $@ && $(MAKE)
like image 5
Kramer Avatar answered Nov 04 '22 17:11

Kramer