2012-04-16 209 views
5

CODE:如何通過迭代列表來生成Makefile中的目標?

LIST=0 1 2 3 4 5 
PREFIX=rambo 

# some looping logic to interate over LIST 

預期的結果:

rambo0: 
    sh rambo_script0.sh 

rambo1: 
    sh rambo_script1.sh 

由於我的列表中有6個元素,應該產生6個目標。在將來,如果我想添加更多目標,我希望能夠修改我的LIST,而不是觸及代碼的任何其他部分。

應如何寫入循環邏輯?

回答

9

使用text-transforming functions。通過patsubst,您可以進行相當一般的轉換。爲了構建文件名,addsuffixaddprefix都很方便。

有關規則,請使用pattern rules

總的結果可能會是這個樣子:

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

all: $(targets) 

$(targets): rambo%: rambo%.sh 
    sh $< 
+0

感謝,有什麼辦法以最終生成的形式查看目標? – Lazer 2012-04-16 11:29:09

+0

@Lazer不是我所知道的,但是我遠離一位專家。 '-n'(空轉)選項可能會告訴你你想要什麼。 – 2012-04-16 11:36:59

+1

@Lazer,'$(info目標是$(目標))' – Beta 2012-04-16 12:40:25

12

如果您使用了GNU make,你可以生成在運行時任意目標:

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))))