Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate targets in a Makefile by iterating over a list?

Tags:

shell

makefile

CODE:

LIST=0 1 2 3 4 5
PREFIX=rambo

# some looping logic to interate over LIST

EXPECTED RESULT:

rambo0:
    sh rambo_script0.sh

rambo1:
    sh rambo_script1.sh

Since my LIST has 6 elements, 6 targets should be generated. In future, if I want to add more targets, I want to be able to just modify my LIST and not touch any other part of the code.

How should the looping logic be written?

like image 624
Lazer Avatar asked Apr 16 '12 10:04

Lazer


2 Answers

If you're using GNU make, you can generate arbitrary targets at run-time:

LIST = 0 1 2 3 4 5
define make-rambo-target
  rambo$1:
         sh rambo_script$1.sh
  all:: rambo$1
endef

$(foreach element,$(LIST),$(eval $(call make-rambo-target,$(element))))
like image 164
Idelic Avatar answered Sep 21 '22 22:09

Idelic


Use text-transforming functions. With patsubst you can make quite general transformations. For constructing filenames, addsuffix and addprefix are both convenient.

For the rules, use pattern rules.

The overall result might look something like this:

LIST = 0 1 3 4 5
targets = $(addprefix rambo, $(LIST))

all: $(targets)

$(targets): rambo%: rambo%.sh
    sh $<
like image 32
Michael J. Barber Avatar answered Sep 23 '22 22:09

Michael J. Barber