遍历Makefile中的目录列表 [英] Iterating through a list of directories in a Makefile
问题描述
我想在几个目录中执行一个任务,但是到目前为止没有找到类似于makefile的"解决方案.我知道这是一个经常被问到的问题,我知道如何为子makfile等解决它,但是我正在寻找更简单的方法.
I would like to execute a task in several directories but found no "makefile-like" solution up to now. I know this is an often asked question and I know how to solve it for sub-makfiles and so on, but I am looking for something simpler.
代替做
copy:
cd module1 && mkdir foo
cd module2 && mkdir foo
cd module3 && mkdir foo
我想要类似的东西
directories = module1 module2 module3
copy: $(directories)
cd $< && mkdir foo
但这不起作用,因为在第一个目录中,receipe仅被调用一次.我想出了一个可行的解决方案,但可能不是Makefiles风格的
but that does not work, since the receipe is called only once with the first directory. I came up with this solution which works but is probably not in the style of Makefiles:
directories = module1 module2 module3
copy:
for d in $(directories); do cd $$d && mkdir foo && cd ..; done
如何更好地做到这一点?
How can I do this more nicely?
推荐答案
有很多方法可以做到这一点.
There are lots of ways of doing this.
您可以执行Andrew建议的操作而无需对前缀进行硬编码:
You can do what Andrew suggests without hard-coding a prefix:
directories = module1 module2 module2
%/foo: ; mkdir -p -- "$@"
copy: $(addsuffix /foo,$(directories))
给出
$ make -n copy
mkdir -p -- "module1/foo"
mkdir -p -- "module2/foo"
mkdir -p -- "module3/foo"
您还可以从makefile生成 copy
目标:
You can also generate the copy
target from the makefile:
directories = module1 module2 module2
define copy-target
copy:: ; cd $1 && mkdir foo
endef
$(foreach dir,$(directories),$(eval $(call copy-target,$(dir))))
这给出了:
$ make -n copy
cd module1 && mkdir foo
cd module2 && mkdir foo
cd module3 && mkdir foo
您还可以生成命令,而不是目标:
You could also generate the commands, not the target:
directories = module1 module2 module2
copy: ; $(foreach dir,$(directories),(cd $(dir) && mkdir foo) &&) :
结果
$ make -n copy
(cd module1 && mkdir foo) && (cd module2 && mkdir foo) && (cd module3 && mkdir foo) && :
这篇关于遍历Makefile中的目录列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!