代码生成,使规则展开(Code generation and make rule expansion

2019-09-16 13:58发布

假设我有一个规则来实现:

.PHONY:gen
gen: auto.template
        generate-sources auto.template

创建一批文件,例如auto1.srcauto2.srcauto3.src等。

如果我现在有规则,建立从目标*.src文件,如下所示:

$(patsubst %.src,%.target,$(wildcard *.src)): %.target: %.src
        build $< > $@

我怎样才能让make首先执行gen规则,然后展开第二个规则模板的前提条件? GNU扩展的欢迎。

:我想保持它在一个 make调用; 一个不重要的解决方案,这将是摆在次要的第二条规则Makefile.secondrun并调用$(MAKE) -f Makefile.secondrungen进行了处理。 但我不知道是否有一个更好的选择。

Answer 1:

建立关贝塔的答案,这里是如何您可以使用GNU 的makefile再造做,这是不一样的东西递归凑合吧。 相反,它更新使用主生成文件的规则包含的makefile文件,然后重新启动原来的化妆实例。 这是多么*.d相关文件通常是生成和使用。

# Get the list of auto-generated sources.  If this file doesn't exist, or if it is older 
# than auto.template, it will get built using the rule defined below, according to the 
# standard behavior of GNU make.  If autosrcs.mk is rebuilt, GNU make will automatically 
# restart itself after autosrcs.mk is updated.

include autosrcs.mk

# Once we have the list of auto-generated sources, getting the list of targets to build 
# from them is a simple pattern substitution.

TARGETS=$(patsubst %.src,%.target,$(AUTO_SRCS))

all: $(TARGETS)

# Rule describing how to build autosrcs.mk.  This generates the sources, then computes 
# the list of autogenerated sources and writes that to autosrcs.mk in the form of a 
# make variable.  Note that we use *shell* constructs to get the list of sources, not
# make constructs like $(wildcard), which could be expanded at the wrong time relative
# to when the source files are actually created.

autosrcs.mk: auto.template
        ./generate-sources auto.template
        echo "AUTO_SRCS=`echo *.src`" > autosrcs.mk

# How to build *.target files from *.src files.

%.target: %.src
        @echo 'build $< > $@'


Answer 2:

简短的回答:你不能。 做决定这一切将要执行它执行任何规则之前的规则。

较长的回答:或许你可以。 正如你所说,你可以用递归做明确或暗中的,比方说,建立一个文件,你的makefile将include (我看着你,杰克·凯利)。 或者,如果你能以某种方式获得这些文件的列表gen将建立,你可以写周围的规则。 或者你可以采取这样的信仰的飞跃:

%.target: %.src
        build $< > $@

%.src: gen;


文章来源: Code generation and make rule expansion