如何在没有子外壳的情况下进行条件扩展?

How to make conditional expansion without subshell?

我在 GNU Make 中编写了以下函数,它检查第一个参数是否属于某个列表,并相应地扩展到第二个或第三个参数:

FLAGS := foo bar
use = $(shell { echo $(FLAGS) | grep -qw $(1) ; } && echo $(2) || echo $(3))

all:
»   $(info $(call use, foo, have-foo, no-foo))
»   $(info $(call use, baz, have-baz, no-baz))

它的行为如我所愿:

$ make all
have-foo
no-baz
make: 'all' is up to date.

我需要它在没有 Guile 支持的情况下构建的 GNU Make 上工作。

我不确定我是否完全理解,但为什么不呢?

use = $(if $(filter ,$(FLAGS)),,)

??

虽然 MadScientists 的回答可能就是您所需要的,但看起来您正在 make 中进行配置管理。虽然这是 IMO 应该发生的地方,但传统阻止了 make 成为用于该目的的成熟工具。然而,有一个库在这种情况下可以提供帮助:The GNUmake Table Toolkit 允许您从 table 那些满足特定自由定义条件的行中 select(阅读 select 的文档) .

include gmtt/gmtt.mk

# original definition of the flag table
define FLAG-TABLE
2
foo  have-foo-1
foo  have-foo-2
bar  have-bar-1

endef

# GNUmake even allows to write an addendum to a define:
define FLAG-TABLE +=
bar have-bar-2
foo have-foo-3

endef

# the  is where the parameter of the call to MY-SELECTION is placed; the $ is 
# where the first column of the table is put before calling `str-eq`
MY-SELECTION = $(call select,2,$(FLAG-TABLE),$$(call str-eq,$,))

$(info $(FLAG-TABLE))
$(info ------------------)
$(info $(call MY-SELECTION,foo))
$(info ------------------)
$(info $(call MY-SELECTION,bar))

输出:

$ make
2
foo  have-foo-1
foo  have-foo-2
bar  have-bar-1
 bar have-bar-2
foo have-foo-3

------------------
 have-foo-1 have-foo-2 have-foo-3
------------------
 have-bar-1 have-bar-2