makefile use variable defined in target

Viewed 12268

How can one use the variable defined inside a make target

.PHONY: foo

VAR_GLOBAL=$(shell cat /tmp/global)

foo:
    echo "local" > /tmp/local
    VAR_LOCAL=$(shell cat /tmp/local)
    echo ${VAR_GLOBAL}
    echo ${VAR_LOCAL}

here is the execution output:

$ echo global > /tmp/global
$ make foo
echo "local" > /tmp/local
VAR_LOCAL=local
echo global
global
echo
2 Answers

As @KelvinSherlock pointed out this is a duplicate of another question

here is the specific solution for my question:

.PHONY: foo

VAR_GLOBAL=$(shell cat /tmp/global)

foo:
    echo "local" > /tmp/local
    $(eval VAR_LOCAL := $(shell cat /tmp/local))
    echo ${VAR_GLOBAL}
    echo ${VAR_LOCAL}

You probably want to use the override directive in a target-specific variable assignment, so try:

foo: override LS_LOCAL=$(shell ls /var | tail -1)
    echo ${LS_GLOBAL}
    echo ${LS_LOCAL}

If LS_LOCAL is never defined (even by builtin-rules) you might not need the override keyword.

BTW, you might avoid $(shell ls /var | tail -1) by using the wildcard function combined with the lastword function (perhaps combined with notdir function), so you might code $(lastword $(wildcard /var/*)) or $(notdir $(lastword $(wildcard /var/*))) instead . However, beware of the order of expansion, and of filenames with spaces. At last the shell function probably uses your $PATH variable (so strange things could happen if some weird ls program appears there before /bin/ls). Perhaps using $(shell /bin/ls /var | /usr/bin/tail -1) might be better.

Look also into Guile-extended make; consider perhaps some other build-automation tool like ninja and/or generating your Makefile (or other build configuration) with something like a configure script generated via autoconf or cmake.

Notice also that a command in recipe can be made of several physical backslashed lines (hence executed in the same shell). Maybe you might consider something like

  export MY_VAR=$$(ls /var | tail); \
  dosomething; \
  use $$MY_VAR

inside some recipe.

Related