rubo77
rubo77

Reputation: 20845

combine multiple ifeq and ifneq in a gnu Makefile

How do I add multiple selections if the syntax is like

ifeq ($(VAR1),some-string)

combined with

ifneq ($(VAR2),some-other-string)

combined with some more...

Is there a one liner? Like (fantasycode):

ifeq $VAR1=some-string and not $VAR2=some-other-string

i found this answer which is not clear to me becauser there is no equation in the ifeq statement there.

Upvotes: 7

Views: 19722

Answers (2)

Renaud Pacalet
Renaud Pacalet

Reputation: 29050

No, there is no and operator for the conditionals (but there is a and function that can be used in conditionals). The if, and and or conditional functions consider that the empty string is false and that anything else is true (including strings containing only spaces). The first proposal in the answer you found tests whether variables are the empty string or not. The second tests whether variables are defined or not. In both cases it does not test whether their value is equal to a reference string. This may be the reason why it was not immediately clear to you.

In your (simple) case you can nest the conditionals:

ifeq ($(VAR1),some-string)
  ifneq ($(VAR2),some-other-string)
<do something>
  endif
endif

<do something> will be considered if and only if the two conditionals pass.

For complex situations with many conditions you can compute individual matching variables:

MATCH1 := $(if $(strip $(VAR1)),$(patsubst some-string,,$(VAR1)),NO)

Variable MATCH1 will take value:

  • NO if VAR1 is undefined, is the empty string or a string of spaces,
  • empty string if it is equal to some-string,
  • else the value of VAR1.

So, it will be the empty string if and only if VAR1 == some-string. Same for NOMATCH1:

MOMATCH1 := $(if $(strip $(VAR2)),$(patsubst some-other-string,,$(VAR2)),NO)

NOMATCH1 will be non empty if and only if VAR2 != some-other-string.

Now, your main condition can be expressed using conditional functions:

ifeq ($(or $(MATCH1),$(MATCH2),...),)
  ifneq ($(and $(NOMATCH1),$(NOMATCH2),...),)
<do something>
  endif
endif

Upvotes: 10

Zelnes
Zelnes

Reputation: 433

# Param 1 : Thing to do
# Param 2: VAR VALUE VAR1 VALUE1 VAR2 VALUE2 ...
# Each param VAR/VALUE must be space separated
define rec_check
    $(if $(strip $(2)),$(if $(findstring _$($(word 1,$(2)))_,_$(word 2,$(2))_),$(call rec_check,$(1),$(subst $(word 1,$(2)) $(word 2,$(2)),,$(2)))),$(1))
endef

# Usage :
# MY_VAR=ok
# MY_VAR2=ok
# $(call rec_check,echo "It works",MY_VAR ok MY_VAR2 ok)
# $(call rec_check,echo "It does not work",MY_VAR ok MY_VAR2 ok2)

It is limited to values without any space though, but it works. Also, it only checks AND conditions.

You still can improve to your need

Upvotes: 0

Related Questions