Make问题:无法让模式规则对PHONY目标生效
问题:Makefile执行时未输出预期的"Building..."内容
编写了如下Makefile,期望执行make all或make build-target1时能输出“Building...”内容,但实际无对应输出,调试输出如下:
$ make -d all ... Considering target file `all'. File `all' does not exist. Considering target file `build-target1'. File `build-target1' does not exist. Finished prerequisites of target file `build-target1'. Must remake target `build-target1'. Successfully remade target file `build-target1'. Considering target file `build-target2'. File `build-target2' does not exist. Finished prerequisites of target file `build-target2'. Must remake target `build-target2'. Successfully remade target file `build-target2'. Finished prerequisites of target file `all'. Must remake target `all'. Successfully remade target file `all'. make: Nothing to be done for `all'.
对应的原Makefile内容:
# Define a list of targets TARGETS := build-target1 build-target2 # Use a pattern rule to define a generic recipe build-%: echo "Building $*" # Define the default target to build all targets all: $(TARGETS) # Define a phony target to avoid conflicts with file names .PHONY: all $(TARGETS)
解决方案
问题核心是**.PHONY声明与隐式模式规则的兼容性**:GNU Make中,当目标被标记为.PHONY后,会忽略针对该目标的隐式规则(包括你定义的build-%模式规则),仅执行显式指定的配方。
要解决这个问题,推荐使用静态模式规则为phony目标显式绑定配方,调整后的Makefile如下:
# Define a list of targets TARGETS := build-target1 build-target2 # Default target to build all targets all: $(TARGETS) # Static pattern rule to define recipes for each target $(TARGETS): build-%: @echo "Building $*" # Mark targets as phony to avoid file name conflicts .PHONY: all $(TARGETS)
执行修正后的Makefile,运行make all或make build-target1,就能看到预期的Building target1或Building target2输出。
内容的提问来源于stack exchange,提问作者Jeff Saremi
相关产品推荐
相关产品推荐

