Home > other >  Makefile compare string input
Makefile compare string input

Time:10-02

To understand better string variables in a Makefile, I have tried to do this example :

KEYWORD=Nothing

test:
    $(call myFunc)

define myFunc
ifeq ($(KEYWORD), "Apple")
    echo "You have found the key"
else
    echo "Try again"
endif
endef

But when I'm typing

make test KEYWORD="Fork"

It prints errors

syntax error near unexpected token `Fork,'
`ifeq (Fork, "Apple")'

I have also tried :

  • Put Apple or 'Apple' in ifeq
  • Put a space or not after "," : ifeq ($(KEYWORD), "Apple")
  • Run command with KEYWORD=Fork
  • Did it using shell (if [ ${KEYWORD} -eq "Apple" ])

I'm running out of ideas because I don't understand how Makefille / Shell interpret the assignment KEYWORD="Fork"

Thanks

CodePudding user response:

First, $(call myfunc) is 100% identical to writing $(myfunc). The call function in make merely expands a variable with some other local values (the arguments) bound first. If you don't provide any local values, then you're just expanding the variable.

Expanding a variable just replaces the variable reference with what it expands to. So writing:

FOO = bar
foo:
        echo $(FOO)

is 100% identical to writing:

foo:
        echo bar

So in your situation,

test:
        $(call myFunc)

is the same as:

test:
        $(myFunc)

which is the same as:

test:
        ifeq ($(KEYWORD), "Apple")
            echo "You have found the key"
        else
            echo "Try again"
        endif

which is why you get the output you did: these are not valid shell commands, but since you've expanded the variable as part of a recipe, they are sent to the shell as part of the recipe.

CodePudding user response:

MadScientist identifies the problem. Perhaps the solution you're looking for is simply evaluating the conditional earlier. eg:

KEYWORD ?= NOTHING
...
ifeq ($(KEYWORD), Apple)
define myFunc
        echo "You have found the key"
endef
else
define myFunc
        echo "Try again"
endef
endif
  • Related