4

I want to set a Global variable through a recipe then reference that variable in another independent recipe

The below code is an example code that sets the variable within the recipe but the variable stays with the initial value if referenced outside the recipe

ACTIVE = a

switch:
ifeq ($(ACTIVE),b)
    ACTIVE=$(shell echo 'a')
else
    ACTIVE=$(shell echo 'b')
endif

print:
    $(info acitve = $(ACTIVE))

I know there are ways to broadcast the value of a target-specific variable to dependent targets, but that's not what I want.

Mark Rofail
  • 808
  • 1
  • 8
  • 18

1 Answers1

3

You can use $(eval ...) for this, although it's almost always a bad idea. I have to assume that your real situation is much more complicated because there are many better ways to accomplish what you've actually provided in the sample makefile.

switch:
        $(eval ACTIVE=$(if $(filter-out a,$(ACTIVE)),a,b))
MadScientist
  • 92,819
  • 9
  • 109
  • 136
  • 1
    the eval function works within the scope of the recipe. Upon running `make print` the values is still `a` – Mark Rofail May 25 '18 at 18:26
  • How are you invoking make? If you don't run the `switch` target then `ACTIVE` won't be reset. `eval` modifies the global state of make, so after the `switch` target runs the global value of `ACTIVE` will be different everywhere. – MadScientist May 25 '18 at 21:02
  • `make switch` then `make print` prints `a` still – Mark Rofail May 26 '18 at 13:22
  • 1
    but `make switch print` does the job – Mark Rofail May 26 '18 at 13:39
  • Well sure: running `make switch` changes the value of the `ACTIVE` variable for that invocation of `make`. Once it exits, everything that that invocation of make knew is gone. When you start `make` again, it has gone back to the default. If you want the change to persist across _invocations of make_, not just between targets within a single invocation of make, that's an entirely different thing than your question asked about. To do that, you'll have to persist the "current" value of `ACTIVE` in the filesystem so that the next invocation of `make` can retrieve it. – MadScientist May 26 '18 at 13:44
  • Doing that is simple enough, of course... you just need to put the value in a file. – MadScientist May 26 '18 at 13:45