我有以下makefile,它有多個cp命令將目錄從源復制到目標。
process:
cp dir/level/2000/config.json output/2000/config.json
cp dir/level/2001/config.json output/2001/config.json
cp dir/level/2002/config.json output/2002/config.json
stage:
mkdir -p output/2000 output/2001 output/2002
cp dir/common/2000/esc output/2000/esc
cp dir/common/2001/esc output/2001/esc
cp dir/common/2002/esc output/2002/esc
apply: stage process
我想通過引入一個變數串列來使上述 Makefile 更具動態性,2000 2001 2002然后它將遍歷變數并在每次迭代時運行規則。就像是...
var := 2000 2001 2002
process:
cp dir/level/${var}/config.json output/${var}/config.json
stage:
mkdir -p output/${var}
cp dir/common/${var}/esc output/${var}/esc
apply: stage process
現在,如果我運行make apply它,它應該重新創建與第一個 makefile 相同的步驟。我嘗試使用多個目標 as${var}并且它以我想要的方式作業,但它只能用于代替其中一個目標,不能同時用于stage和process. 我做了
process:
cp dir/level/2000/config.json output/2000/config.json
cp dir/level/2001/config.json output/2001/config.json
cp dir/level/2002/config.json output/2002/config.json
${var}:
mkdir -p output/$@
cp dir/common/$@/esc output/$@/esc
apply: ${var} process
現在,如果我運行 make apply ,它將按預期運行,但是如何使用相同的多個目標來代替process呢?
uj5u.com熱心網友回復:
您最有可能使用模式規則:
apply: stage process
var := 2000 2001 2002
process: $(foreach V,$(var),output/$V/config.json)
stage: $(foreach V,$(var),output/$V/esc)
output/%/config.json: dir/level/%/config.json
cp $< $@
output/%/esc : dir/common/%/esc
mkdir -p $(@D)
cp $< $@
uj5u.com熱心網友回復:
最簡單的解決方案可能是在您的配方中使用 shellfor回圈:
var := 2000 2001 2002
process:
for year in $(var); do \
cp dir/level/$$year/config.json output/$$year/config.json; \
done
請注意,在配方中,我們需要撰寫$$year以參考命名的 shell 變數year,因為單個$會引入 makefile 變數參考。
僅使用make語法,您可以這樣做:
var = 2000 2001 2002
outputs = $(patsubst %,output/%/config.json,$(var))
output/%/config.json: dir/level/%/config.json
echo cp $< $@
all: $(outputs)
這將創建一個outputs具有以下內容的變數:
output/2000/config.json output/2001/config.json output/2002/config.json
然后使用模式規則隱式創建配方,以從相應的輸入創建這些輸出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/433638.html
