You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 02:12:31