【问题标题】:GNU Make: delegate target creation to external MakefileGNU Make:将目标创建委托给外部 Makefile
【发布时间】:2015-09-09 12:34:22
【问题描述】:

我在项目中使用 Makefile 来自动化工作流程。为了保持它们的可读性,我在每个子目录中都有一个 Makefile。结构如下:

+ a
|- Makefile # with input.txt -> output.txt
|- input.txt
|- output.txt
+ b
|- Makefile # with input.txt -> output.txt
|- input.txt

现在,有一个复杂的情况:将b 中的input.txt 转换为output.txt 的规则也需要output.txt 来自a

我想告诉我的b/Makefile 使用a/Makefile 来构建a/output.txt。有没有办法做到这一点?

这是我尝试过的,出现了哪些问题:

  • b/Makefile 中添加一个规则,该规则执行make -C ../a output.txt:我不能在b/Makefile 中使用%.txt: ../a/%.txt 的模式规则,因为否则它会使用此规则来创建递归定义混乱

  • b/Makefile 中将a/output.txt 标记为.PHONY:每次都重建b 中的目标(只有在a 重建它时才应该重建它)

【问题讨论】:

  • 两个目录中的文件名真的相同吗?在这里不使用多个 makefile 可能实际上更容易。请参阅著名的Recursive Make Considered Harmful 论文(pdf 链接)进行讨论。 (这不是完全你在这里做的,但想法是一样的。)
  • 不,文件名不一定相同 - 但可以。本文中概述的性能问题在我的情况下可以忽略不计,我更担心的是可读性和可维护性(这就是我更喜欢多个 Makefile 的原因)
  • 性能问题到目前为止并不是本文的主要内容。主要的推动力是依赖信息的分裂。要么复制每个目录中构建的目标到其他目录 makefile 中(例如,b/Makefile 包含 ../a/output.txt../a/foo.txt../c/something.o 等的目标),或者您通过手动递归硬编码构建顺序并丢失唯一需要时重建的属性。

标签: gnu-make


【解决方案1】:

a/Makefile:

output.txt: input.txt ../b/output.txt
    cp $< $@

../b/%:
    cd ../b/ && $(MAKE) $*

b/Makefile:

output.txt: input.txt ../a/output.txt
    cp $< $@

../a/%:
    cd ../a/ && $(MAKE) $*

话虽如此,谁没有顶层的 Makefile(在本例中为 ..)来正确处理整个项目?这将使它更加健壮,防止你重复自己,并允许并行执行和其他花哨的技巧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多