Make expand variables in another variables

387 views Asked by At

I was wondering if it was possible to expand variables themselves in a Makefile. Something to this effect:

VAR1 = var1
VAR2 = var2
ALL_VARS = $(VAR*)

Using the ALL_VARS variable should result in something like:

var1 var2

Is something like this possible?

Thank you in advance

3

There are 3 answers

0
MadScientist On BEST ANSWER

You can't do that in standard make. But if you have GNU make, and your variable names match a (make) pattern, you can use:

VAR1 = var1
VARFoo = varfoo
VAR-big = var-big

ALL_VARS = $(foreach V,$(filter VAR%,$(.VARIABLES)),$($V))

$(info ALL_VARS = $(ALL_VARS))

should get you:

var1 varfoo var-big

although the order is not necessarily guaranteed.

0
Come Raczy On

If you variables do follow a regular pattern (e.g. VAR1, VAR2, etc.) you can generate a sequence for the stems of the variables and use foreach. Something like this:

NUM ?= 2

GENERATE=$(or $(and $(word $(1), $(2)), $(2)), $(call GENERATE, $(1), $(2) $(words 0 $(2))))
sequence=$(call GENERATE, $(NUM))

VAR1 = var1
VAR2 = var2
ALL_VARS = $(foreach n, $(sequence), $(VAR$n))
$(warning $(ALL_VARS))
1
Mike Kinghan On

You can do this fairly simply by using the $(filter ...) builtin function and the special variable .VARIABLES, e.g.

VARX = var1
VARY = var2
ALL_VARS = $(foreach var,$(filter VAR%,$(.VARIABLES)),$($(var)))

all: 
    @echo $(ALL_VARS)