Home > Net >  Test a variable in Makefile target
Test a variable in Makefile target

Time:12-10

I am trying to get it to work, but it seems that the variable is not passed correctly to the if statement as it does not "enter" the if loop

apply_test:
                $(eval var=$(shell bash -c "echo 1"))        
                echo $(var)
ifeq ($(var),1)
        echo "inside the stmt"
        $(eval var=$(shell bash -c "echo 2")) 
endif
                echo $(var)

Generally, I try to evaluate the return value of a function, to perform subsequent conditional settings, e.g. set a new variable inside the if-stmt.

What´s wrong with my approach?

CodePudding user response:

I mean, pretty much everything here is problematic :). You haven't given any explanation of why you're trying to do something so convoluted, but pro tips:

  • Any time you're using make conditionals like ifeq etc. inside a recipe it's likely that it won't do what you want, unless you're very sure you completely understand the expansion rules of makefiles.
  • Any time you're using $(shell ...) inside a recipe, it's almost always a bad idea.
  • Any time you're using $(eval ...) inside a recipe, it's almost 100% definitely a bad idea.

However to deal with only your immediate problem: ifeq is processed while the makefile is being parsed. Recipes are not run until after the entire makefile is parsed and make decides which targets to run. So when make is parsing the makefile and looking at ifeq, the variable var has not been set yet and so it evaluates to the empty string and is never equal to 1.

ETA

Without knowing anything else about your requirements I'll say that the "right" way to implement this is using shell operations inside the recipe. That would look like this:

apply_test:
        var=$$(echo 1) ; \       
        echo $$var; \
        if [ $$var = 1 ]; then \
            echo "inside the stmt"; \
            var=$$(echo 2); \
        fi; \
        echo $$var
  • Related