Neil
Neil

Reputation: 25825

Makefile won't assign variable values in `ifeq` statement within function definition

I'm trying to assign a value to a variable in make when a condition is met, inside a function:

Without $() around the ifeq statements:

VARIABLE=true

define test_ifeq
    FOO := foo
    ifeq (${VARIABLE}, true)
        FOO := true
    else
        FOO := false
    endif

    echo "value: ${FOO}"
endef

all:
    $(call test_ifeq)

Result:

FOO := foo
make: FOO: No such file or directory
make: *** [Makefile:15: all] Error 127

With $() around the ifeq and variable assignment statements:

VARIABLE=true

define test_ifeq
    $(FOO := foo)
    $(ifeq (${VARIABLE}, true)
        FOO := true
    else
        FOO := false
    endif)

    echo "value: ${FOO}"
endef

all:
    $(call test_ifeq)

Result:

echo "value: "
value:

Why does this not work?

Upvotes: 1

Views: 1262

Answers (2)

Beta
Beta

Reputation: 99094

To do it with Make:

VARIABLE=true

define test_ifeq
  FOO := foo
  ifeq (${VARIABLE}, true)
    FOO := true
  else
    FOO := false
  endif

$$(info "value: $${FOO}")

endef

$(eval $(call test_ifeq))

To do it on the command line (assuming bash):

VARIABLE=true; FOO=foo; if [ $VARIABLE = true ]; then FOO=true; else FOO=false; fi; echo $FOO

To do it within a rule in a makefile:

all:
    VARIABLE=true; \                                                                                  
  FOO=foo; \
  if [ $$VARIABLE = true ]; then \
  FOO=true; else \
  FOO=false; \
  fi; \
  echo $$FOO

To do it within a rule, using a function:

VARIABLE=true

define test_ifeq2
  FOO=foo; \
  if [ $(VARIABLE) = true ]; then \
  FOO=true; else \
  FOO=false; \
  fi; \
  echo $$FOO
endef

all:
    $(call test_ifeq2)

Upvotes: 0

igagis
igagis

Reputation: 2079

The ifeq and the likes are evaluated at the moment when make reads the makefile, that means there is no actual ifeq present in the assigned value of your test_ifeq variable.

To achieve what you need you have to use $(if ...) and $(filter ...) built in functions along with $(eval ...).

It should look something like this:

VARIABLE=true

define test_ifeq
    $(eval FOO := $(if $(filter $(VARIABLE),true), true, false))

    echo "value: $(FOO)"
endef

all:
    $(call test_ifeq)

NOTE: I haven't tested it, wrote it straight out of head...

Upvotes: 1

Related Questions