Previous: , Up: Advanced   [Contents][Index]

6.3.2 Computed Variable Names



x = y
y = z
a := $($(x))

defines a as ‘z’: the ‘$(x)’ inside ‘$($(x))’ expands to ‘y’, so ‘$($(x))’ expands to ‘$(y)’ which in turn expands to ‘z’. Here the name of the variable to reference is not stated explicitly; it is computed by expansion of ‘$(x)’. The reference ‘$(x)’ here is nested within the outer variable reference.


x = y
y = z
z = u

Here the innermost ‘$(x)’ expands to ‘y’, so ‘$($(x))’ expands to ‘$(y)’ which in turn expands to ‘z’; now we have ‘$(z)’, which becomes ‘u’.

References to recursively-expanded variables within a variable name are re-expanded in the usual fashion. For example:

x = $(y)
y = z
z = Hello
a := $($(x))

defines a as ‘Hello’: ‘$($(x))’ becomes ‘$($(y))’ which becomes ‘$(z)’ which becomes ‘Hello’.

Nested variable references can also contain modified references and function invocations (see Functions for Transforming Text), just like any other reference. For example, using the subst function (see Functions for String Substitution and Analysis):

x = variable1
variable2 := Hello
y = $(subst 1,2,$(x))
z = y

eventually defines a as ‘Hello’. It is doubtful that anyone would ever want to write a nested reference as convoluted as this one, but it works: ‘$($($(z)))’ expands to ‘$($(y))’ which becomes ‘$($(subst 1,2,$(x)))’. This gets the value ‘variable1’ from x and changes it by substitution to ‘variable2’, so that the entire string becomes ‘$(variable2)’, a simple variable reference whose value is ‘Hello’.


a_dirs := dira dirb
1_dirs := dir1 dir2
a_files := filea fileb
1_files := file1 file2
ifeq "$(use_a)" "yes"
a1 := a
a1 := 1
ifeq "$(use_dirs)" "yes"
df := dirs
df := files



Computed variable names can also be used in substitution references:

a_objects := a.o b.o c.o
1_objects := 1.o 2.o 3.o


defines sources as either ‘a.c b.c c.c’ or ‘1.c 2.c 3.c’, depending on the value of a1.


ifdef do_sort
func := sort
func := strip
bar := a d b g q c

attempts to give ‘foo’ the value of the variable ‘sort a d b g q c’ or ‘strip a d b g q c’, rather than giving ‘a d b g q c’ as the argument to either the sort or the strip function. This restriction could be removed in the future if that change is shown to be a good idea.


dir = foo
define $(dir)_print =
lpr $($(dir)_sources)

This example defines the variables ‘dir’, ‘foo_sources’, and ‘foo_print’.

Note that nested variable references are quite different from recursively expanded variables (see The Two Flavors of Variables), though both are used together in complex ways when doing makefile programming.

Previous: , Up: Advanced   [Contents][Index]