开发者

Create comma-separated lists in GNU Make

开发者 https://www.devze.com 2023-04-07 13:48 出处:网络
I have a Makefile with a set of booleans which must be used to control the flags for an externalapplication. The problem is that the flag must be passed as a comma-separated string.

I have a Makefile with a set of booleans which must be used to control the flags for an external application. The problem is that the flag must be passed as a comma-separated string.

Something like this (non-working pseudo code):

WITH_LIST = ""
WITHOUT_LIST = ""

ifeq ($(BOOL_A),y)
    # Append A 开发者_JS百科to list "WITH_LIST"
else
    # Append A to list "WITHOUT_LIST"
endif

ifeq ($(BOOL_B),y)
    # Append B to list "WITH_LIST"
else
    # Append B to list "WITHOUT_LIST"
endif

ifeq ($(BOOL_C),y)
    # Append C to list "WITH_LIST"
else
    # Append C to list "WITHOUT_LIST"
endif

Now assuming BOOL_A == y, BOOL_B == n and BOOL_C == y, I need to run the following command:

./app --with=A,C --with-out=B

How can I generate these string using Gnu Make?


First you create the two white-space separated lists, either using your method, or thiton's. Then you use the little trick from the end of section 6.2 of the GNU make manual to create a variable holding a single space, and one holding a comma. You can then use these in $(subst ...) to change the two lists to comma-separated.

PARTS  := A B C

BOOL_A := y
BOOL_B := n
BOOL_C := y

WITH_LIST    := $(foreach part, $(PARTS), $(if $(filter y, $(BOOL_$(part))), $(part)))
WITHOUT_LIST := $(filter-out $(WITH_LIST), $(PARTS))

null  :=
space := $(null) #
comma := ,

WITH_LIST    := $(subst $(space),$(comma),$(strip $(WITH_LIST)))
WITHOUT_LIST := $(subst $(space),$(comma),$(strip $(WITHOUT_LIST)))

all:
    ./app --with=$(WITH_LIST) --with-out=$(WITHOUT_LIST)


A construct like

OPTIONS+=$(if $(filter y,$(BOOL_A)),--with=A,--with-out=A)

should work.

Edit: Sorry, overlooked the necessary collation.

PARTS=A B C
YESSES=$(foreach i,$(PARTS),$(if $(filter y,$(BOOL_$(i))),$(i)))

all:
        echo with=$(shell echo $(YESSES) | tr ' ' ',')

The idea is to check for each possible part X whether it's set to yes and insert it into a list if it is yes. This list is whitespace-separated and hard to comma-separate with make, but easy to do this in shell.


Or just use sed: ugly (and untested) but straightforward

WITH_LIST = $(shell echo A$(BOOL_A) B$(BOOL_B) C$(BOOL_C) | sed -e 's/[ABC][^yABC]*//g' -e 's/y//g' -e 's/ /,/g')
WITHOUT_LIST = $(shell echo A$(BOOL_A) B$(BOOL_B) C$(BOOL_C) | sed -e 's/[ABC]y[^ABC]*//g' -e 's/[^ABC ]//g' -e 's/ /,/g')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号