List 如何使用循环在makefile中附加列表

List 如何使用循环在makefile中附加列表,list,makefile,append,List,Makefile,Append,我试图创建一个仅依赖于一个文件的目标列表。我想要创建的列表非常长,可能需要添加更多的元素,所以我想使用循环来创建目标列表。目标的不同主要在于它们的路径 我想我只需要了解如何在makefile中追加或添加到列表,这样我就可以创建我想要循环中的目标的目标列表 以下是我到目前为止的情况: .PHONY: all dircreate dircreate_sub # Create shortcuts to directories #####################################

我试图创建一个仅依赖于一个文件的目标列表。我想要创建的列表非常长,可能需要添加更多的元素,所以我想使用循环来创建目标列表。目标的不同主要在于它们的路径

我想我只需要了解如何在makefile中追加或添加到列表,这样我就可以创建我想要循环中的目标的目标列表

以下是我到目前为止的情况:

.PHONY: all dircreate dircreate_sub

# Create shortcuts to directories ##############################################
DAT4 = data/4-Year/
DAT2 = data/2-Year/
DEPVARS = a b 

# Create directories ###########################################################
dircreate:
    mkdir -p \
    data/ \
    data/4-Year/ \
    data/2-Year/ 

dircreate_sub:
    for d in $(DEPVARS); do \
        mkdir -p data/4-Year/$$d ; \
        mkdir -p data/2-Year/$$d ; \
    done;

TARGETS = \
    for d in $(DEPVARS); do \
        $(DAT4)$$d/train_index.RDS \
        $(DAT2)$$d/train_index.RDS \
        $(DAT4)$$d/test_index.RDS \
        $(DAT2)$$d/test_index.RDS; \
    done;

$(TARGETS): \
    dataprep.R \
    funcs.R \
    ../core/data/analysis.data.RDS
    Rscript $<

all: dircreate dircreate_sub $(TARGETS)

可能您想要的是:

TARGETS := $(foreach d,$(DEPVARS),\
    $(DAT4)$d/train_index.RDS \
    $(DAT2)$d/train_index.RDS \
    $(DAT4)$d/test_index.RDS \
    $(DAT2)$d/test_index.RDS)

注意:为了提高效率,我使用了:=而不是=。

您需要使用foreach makefile函数:

你可以这样做:

TARGETS := $(foreach depvar,$(DEPVARS),$(DAT4)$$d/train_index.RDS)
TARGETS += $(foreach depvar,$(DEPVARS),$(DAT2)$$d/train_index.RDS)
TARGETS += $(foreach depvar,$(DEPVARS),$(DAT4)$$d/test_index.RDS)
TARGETS += $(foreach depvar,$(DEPVARS),$(DAT2)$$d/test_index.RDS)
TARGETS := $(foreach dat,$(DAT4) $(DAT2),$\
              $(foreach filename,train_index.RDS test_index.RDS,$\
                 $(foreach depvar,$(DEPVARS),$(dat)$(depvar)/$(filename))))
或者像这样:

TARGETS := $(foreach depvar,$(DEPVARS),$(DAT4)$$d/train_index.RDS)
TARGETS += $(foreach depvar,$(DEPVARS),$(DAT2)$$d/train_index.RDS)
TARGETS += $(foreach depvar,$(DEPVARS),$(DAT4)$$d/test_index.RDS)
TARGETS += $(foreach depvar,$(DEPVARS),$(DAT2)$$d/test_index.RDS)
TARGETS := $(foreach dat,$(DAT4) $(DAT2),$\
              $(foreach filename,train_index.RDS test_index.RDS,$\
                 $(foreach depvar,$(DEPVARS),$(dat)$(depvar)/$(filename))))
注意:我使用$\技巧允许在不添加空格的情况下遍历多行,请参见

如果你想做更复杂的事情,你可以使用shell脚本来完成所有的事情

TARGETS := $(shell somescript a b c) 

它起作用了!非常感谢。第二个答案是在最里面的foreach后面缺少了两个parantises。。。修正了,谢谢。这也行得通。我只需要从$$d中删除一个$'s。