makefileconditional-statements

Export variable in Makefile with ifeq, then access variable elsewhere


Within a Makefile, I am trying to export a variable conditionally using an ifeq block, and then access that variable in a second ifeq block. Here's a sample of my code structure:

ifeq ($(CONDITION),true)
    export RESULT=$$(echo $$ENV_VAR) ; \ 
    echo "$$RESULT" ;
else
    export RESULT=$$(echo $$ENV_VAR_2) ; \
    echo "$$RESULT" ;
endif
ifeq ($CONDITION2),true)
    echo "$$RESULT" ;
endif

In the code above, the first two echo statements (lines 3 and 6) print out correctly, but the third echo (line 9) does not print any output, even when CONDITION2 evaluates to true. I've tried several different tests and format/syntax, but I can't figure out how to get the third echo statement on line 9 to evaluate to print out the value set in the first ifeq block.

Any help is greatly appreciated!


Solution

  • The above is not, by itself, legal makefile content. So, it must be part of a larger context and without seeing that full context we can't be sure of the answer.

    However, most likely you have overlooked the fact that (by default) every line in a makefile is invoked in a separate shell. Thus, shell variables that are set on one line of a recipe will have no effect on the next line. That's why you need the backslash.

    In general I strongly discourage anyone from adding conditional statements (ifeq etc.) into the middle of recipes. It's very confusing and hard to read and work with.

    There are many ways to resolve this issue, but most of them depend on the actual behavior you are using; I doubt the example you provide is very representative of the real makefile you're working with.

    Without knowing the real thing you want to do all I can suggest is setting a make variable to the "second" command then using that variable in the recipe, like this:

    ifeq ($(CONDITION2),true)
      SECOND_CMD = echo "$$RESULT"
    endif
    
    target: ...
    ifeq ($(CONDITION),true)
             export RESULT=$$(echo $$ENV_VAR) ; \ 
             echo "$$RESULT" ; \
             $(SECOND_CMD)
    else
             export RESULT=$$(echo $$ENV_VAR_2) ; \
             echo "$$RESULT" ; \
             $(SECOND_CMD)
    endif
    

    but there are likely cleaner ways to do it.