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

后端 未结 3 799
别那么骄傲
别那么骄傲 2021-02-04 09:44

CODE:

LIST=0 1 2 3 4 5
PREFIX=rambo

# some looping logic to interate over LIST

EXPECTED RESULT:

rambo0:
    sh rambo_script0.s         


        
3条回答
  •  时光说笑
    2021-02-04 10:46

    Just my 2 cents to @Idelic answer, if you need to use some Make $cmd you must escape them using $$ e.g.

    LIST = 0 1 2 3 4 5
    define make-rambo-target
    $(info create target: $(addprefix rambo_script, $(addsuffix .sh, $1)).)
    rambo$1: $$(addprefix rambo_script, $$(addsuffix .sh, $1))
        sh $$<
    endef
    
    all: $(addprefix rambo, $(LIST))
    
    $(foreach element, $(LIST), $(eval $(call make-rambo-target,$(element))))
    

    output:

    $ make
    create target: rambo_script0.sh.
    create target: rambo_script1.sh.
    create target: rambo_script2.sh.
    create target: rambo_script3.sh.
    create target: rambo_script4.sh.
    create target: rambo_script5.sh.
    sh rambo_script0.sh
    sh rambo_script1.sh
    sh rambo_script2.sh
    sh rambo_script3.sh
    sh rambo_script4.sh
    sh rambo_script5.sh
    

    note: here rules "are seen" by Make as

    rambo0: $(addprefix rambo_script, $(addsuffix .sh, 0))
        sh $<
    

    But here we could have written without escaping i.e.

    rambo$1: $(addprefix rambo_script, $(addsuffix .sh, $1))
        sh $$<
    

    So rule "are seen" as:

    rambo0 : rambo_script0.sh
        sh $<
    

    when Make parse it.

提交回复
热议问题