代码生成和规则扩展 [英] Code generation and make rule expansion

查看:49
本文介绍了代码生成和规则扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一条制定规则:

Assume I have a make rule:

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

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

that creates a bunch of files, for example auto1.src, auto2.src, auto3.src and so on.

如果我现在有从*.src文件构建目标的规则,像这样:

If I now have rules to build targets from *.src files, like this:

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

如何告诉make首先执行gen规则,然后扩展第二个规则模板的前提条件?欢迎使用GNU扩展.

How can I tell make to first execute the gen rule and then expand the preconditions for the second rule template? GNU extensions are welcome.

注意:我想保留它在 one make调用中;一个简单的解决方案是将第二个规则放在辅助Makefile.secondrun中,并在处理gen之后调用$(MAKE) -f Makefile.secondrun.但是我想知道是否有更好的选择.

Note: I would like to keep it in one make invocation; A trivial solution to this would be to put the second rule in a secondary Makefile.secondrun and call $(MAKE) -f Makefile.secondrun after gen was processed. But I was wondering if there is a better option.

推荐答案

以Beta的答案为基础,这是在GNU make中使用 makefile remaking 来实现的方法,这与递归不同制作.相反,它将使用主makefile中的规则更新包含的makefile,然后重新启动原始的make实例.这就是*.d依赖文件的通常生成和使用方式.

Building off Beta's answer, here's how you can do it using makefile remaking in GNU make, which is not the same thing as recursive make. Rather, it updates an included makefile using a rule in the main makefile, then restarts the original make instance. This is how *.d dependency files are typically generated and used.

# 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 $< > $@'

这篇关于代码生成和规则扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆