Remove item from a Makefile variable?

2019-02-01 04:08发布

问题:

I have a makefile, which includes several other makefiles, which in turn all add to a variable like this:

VAR := Something SomethingElse
VAR += SomeOtherThing

(...)

Now I wish to remove SomethingElse from the VAR variable. What do I put in place of (...) to do this?

I am using GNU Make, and a GNU Make specific solution will be fine.

回答1:

You could use the filter-out text function if you're using GNU Make.

OTHERVAR := $(filter-out SomethingElse,$(VAR))


回答2:

On top of the correct answer above:

VAR = bla1 bla2 bla3 bla4 bla5

TMPVAR := $(VAR)
VAR = $(filter-out bla3, $(TMPVAR))

all:
    @echo "VAR is: $(VAR)"

Output:
VAR is: bla1 bla2 bla4 bla5

Note that this breaks all "recursivity" when filter-out is executed, but that might not matter in your case.



回答3:

As I also have a similar situation, I want to add a new answer. In my case there were also commas into the variable string and, more, I wanted to remove the comma and the last word :

VAR = "bla1, bla2"

In this case filter out is not working (not even in the previous answers, when there are no quotes)

My solution is to use subst :

VAR = "bla1, bla2"

TTT = , bla2
TMPVAR := $(VAR)
SUBST = $(subst $(TTT),, $(TMPVAR))
FILT = $(filter-out $(TTT), $(TMPVAR))

subst:
    @echo "subst : $(SUBST)"

filter:
    @echo "filter-out : $(FILT)"