从 Makefile 变量中删除项?

我有一个 makefile,其中包含了其他几个 makefile,这些 makefile 都会添加一个变量,如下所示:

VAR := Something SomethingElse
VAR += SomeOtherThing


(...)

现在我希望从 VAR变量中删除 SomethingElse。我应该用什么来代替 (...)来做这件事?

我正在使用 GNUMake,一个 GNUMake 特定的解决方案将是好的。

61838 次浏览

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

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

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.

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)"