Tuesday, 9 July 2019

Makefile variable assign difference between := vs =

makefile difference between := vs =



There are two ways that a variable in GNU make can have a value:

Note: Got the comment as "Can you use early evaluation here with :=", so it will be good to use :=

The Two Flavors of Variables:  recursively expanded

  • The first flavor of variable is a recursively expanded variable.
  • Variables of this sort are defined by lines using ‘=’ or  Defining Multi-Line Variables
  • if it contains references to other variables, these references are expanded whenever this variable is substituted (in the course of expanding some other string). When this happens, it is called recursive expansion.
For Example,

foo = $(bar)
bar = $(ugh)
ugh = Huh?

all:;echo $(foo)

Second flavor of variable: simply expanded variables.

  • Simply expanded variables are defined by lines using ‘:=’ or ‘::=’ (see Setting Variables). Both forms are equivalent in GNU make;
  • The value of a simply expanded variable is scanned once and for all, expanding any references to other variables and functions, when the variable is defined.
  • It does not contain any references to other variables.
  • it contains their values as of the time this variable was defined
  • its value is substituted verbatim.
For example,
       
x := foo
y := $(x) bar
x := later

is equivalent to

y := foo bar
x := later
 

Program:

# Simply expanded variables:
x := foo
# y is assigned with 'foo bar' value, so in future x value changes also won't affect y
# y use value of x not an variable of x.
y := $(x) bar
x := later

# Recursively expanded variable:
a = foo
# y is assgined with '$(a) bar', so in future x value changes also will reflect in y.
# Because y always use variable x not an value of x.
b = $(a) bar
a = later

Test:
        echo $(x)
        echo $(y)
        echo '-----------------------'
        echo $(a)
        echo $(b)

Output:


~/velrajk/sample/makefile/make_:=$ make
echo later
later
echo foo  bar
foo bar
echo '-----------------------'
-----------------------
echo later
later
echo later bar
later bar




Reference: https://www.gnu.org/software/make/manual/make.html#Flavors
 

No comments:

Post a Comment