首页 > 解决方案 > 在不使用目标的情况下,如何防止目标的先决条件扩展?

问题描述

在具有多个目标的 Makefile 中,如何防止扩展未使用的目标的先决条件?请参见以下示例:

thisexpands = $(warning Expanded!)

.PHONY: target1
target1: $(thisexpands)
    @echo Target 1

.PHONY: target2
target2:
    @echo Target 2

呼吁target2力量thisexpands扩大,即使它被懒惰地评估并且它target1从未被使用过。

在我的现实世界中thisexpands,调用时扩展target1是一个问题,因为它是一个 shell 命令,当在 target1 的上下文之外调用时会打印错误,并且它是父目标(此处未显示)。

标签: makefile

解决方案


在运行第一条规则之前,Makefile 已被完全解析。作为解析的一部分,必须扩展所有目标和先决条件。您可以在 GNU make 手册中的How make Reads a Makefile中找到有关 makefile 不同部分何时发生扩展的详细信息。

一种方法是使用递归:

thisexpands = $(warning Expanded!)

target1: ; $(MAKE) target1-recurse T1_DEPS='$(value thisexpands)'

T1_DEPS =
target1-recurse: $(T1_DEPS)
        @echo Target 1

这不起作用:

您可以通过使用辅助扩展来推迟扩展,如下所示:

.SECONDEXPANSION:
target1: $$(thisexpands)

要非常小心,适当地转义先决条件列表。


推荐阅读