如何根据条件的输出执行不同的配方?

How to execute different recipes based on the output of a condition?

我正在尝试编译除被排除的源文件之外的所有源文件。

考虑到我既不能控制目标也不能控制先决条件,我只能控制配方。

由于某种原因,if 条件无法正常运行。

即使当源文件位于 custom_c_excludes 变量中的排除文件中时输出为真,第一个条件也始终满足,因此正确的行为应该是 ifep 条件失败并阻止前面的else应该被执行。

(条件输出:true => 不编译)

(条件输出:false => 编译)

$(OBJDIR)/%.$(OBJEXT): %.c
ifeq (false,$(if $(findstring $<,$(custom_c_excludes)),true,false))
    @echo 'This file is included and should be compiled.'
    @echo 'Condition output : $(if $(findstring $<,$(custom_c_excludes)),true,false)'
else
    @echo 'This file is not included  and should not be compiled.'
    @echo 'Condition output : $(if $(findstring $<,$(custom_c_excludes)),true,false)'

endif

预期输出是:

This file is included and should be compiled.

Condition output : false

This file is not included and should not be compiled.

Condition output : true

实际输出为:

This file is included and should be compiled.

Condition output : true

ifeq 在解析 Makefile 期间评估,而不是在执行配方期间评估,因此您的配方将始终生成相同的。您可以使用 make -p:

进行验证
# Implicit Rules

obj/%.o: %.c
#  recipe to execute (from 'Makefile', line 11):
        @echo 'This file is included and should not be compiled.'
        @echo 'Condition output : $(if $(findstring $<,$(custom_c_excludes)),true,false)'

但是,如果您确实知道要对哪些文件进行不同的评估(例如这个 custom_c_excludes 变量),您可以执行 static pattern rule,即:

$ cat Makefile
OBJDIR := obj
OBJEXT := o

custom_c_excludes := foo.c

$(OBJDIR)/%.$(OBJEXT): %.c
        @echo 'This file is included and should be compiled.'

$(patsubst %.c,$(OBJDIR)/%.$(OBJEXT),$(custom_c_excludes)): $(OBJDIR)/%.$(OBJEXT): %.c
        @echo 'This file is not included and should not be compiled.'

输出:

$ make obj/foo.o
This file is not included and should not be compiled.

$ make obj/bar.o
This file is included and should be compiled.