Create comma-separated lists in GNU Make

2019-04-20 00:22发布

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 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?

3条回答
劳资没心,怎么记你
2楼-- · 2019-04-20 01:04

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)
查看更多
老娘就宠你
3楼-- · 2019-04-20 01:13

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')
查看更多
Bombasti
4楼-- · 2019-04-20 01:20

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.

查看更多
登录 后发表回答