特定于目标的 make 变量

ben*_*fle 5 make gnu-make

如何强制立即设置特定于目标的变量(第 2 行)?我想要的输出是maketoreleasemake debugto be debug

X = release
debug: X = debug
debug: all

# the rest is included from an external file; cannot be changed
Y := $(X)
BUILD := $(Y)

all:
    @echo $(BUILD)
Run Code Online (Sandbox Code Playgroud)

小智 1

您的问题是由于 GNUMake 如何解析 make 文件造成的。

GNU make 的工作分为两个不同的阶段。在第一阶段,它读取所有 makefile、包含的 makefile 等,并将所有变量及其值、隐式和显式规则内化,并构建所有目标及其先决条件的依赖关系图。在第二阶段,make 使用这些内部结构来确定需要重建哪些目标并调用执行此操作所需的规则。

读取 Makefile

看起来好像当您运行make debug依赖项时,它会all:打印出值,就像您运行一样make all。您需要做的是修改您的 makefile,以便all两者debug都触发相同的依赖关系。你通常会看到类似的东西

all: $(executable)
debug: $(executable)
$(executable): $(objs)
    <compile objects to executable>
Run Code Online (Sandbox Code Playgroud)

debug永远不会触发all,但在任何一种情况下都会编译可执行文件。

至于你的代码:

X = release

debug: X = debug

Y = $(X)
BUILD = $(Y)

.PHONY: print
print:
        @echo $(BUILD)

all: print
debug: print
Run Code Online (Sandbox Code Playgroud)

我必须使 print 成为一个虚假的依赖项,因为它不是正在创建的实际对象。否则,这将是您的依赖项,两者debugall需要,但根据您设置的标志进行不同的编译。