0

I saw the question:

makefile-variable-assignment

then I did as below:

HELLO='hello 1st'
HELLO_WORLD='$(HELLO) world!'
HELLO='hello 2nd'

all :
    echo $(HELLO_WORLD)
    HELLO='hello 3rd'
    echo $(HELLO_WORLD)
    HELLO='hello 4th'
    echo $(HELLO_WORLD)

the result is that:

root@ubuntu:~# make all -s
hello 2nd world!
hello 2nd world!
hello 2nd world!

I confused, why the value of 'HELLO' was not set to hello 4th but hello 2nd

update:

I update my code :

HELLO='hello 1st'
HELLO_WORLD='$(HELLO) world!'
HELLO='hello 2nd'

all :
    HELLO='hello 3rd' &&  echo $(HELLO_WORLD)
    HELLO='hello 4th' &&  echo $(HELLO_WORLD)

And the result:

root@ubuntu:~# make all -s 
hello 2nd world!
hello 2nd world!

I have realized the sentences like HELLO='hello 3rd' is not variable assignments finally. You two help me a lot. Thanks the answers!

4
  • Exercise: And can you see why HELLO='hello 3rd'; echo $(HELLO); echo $$HELLO outputs what it does? Commented May 17, 2017 at 18:56
  • the output is hello 3rd and a blank line Commented May 18, 2017 at 14:44
  • echo $$HELLO is equal to echo $('hello 3rd') Commented May 18, 2017 at 14:44
  • I meant with your definitions of HELLO first. The first $(HELLO) is a makefile variable, and make expands it to hello 2nd – but the $$HELLO includes the make variable $$, which expands to $, so that make expands this line to HELLO='hello 3rd'; echo hello 2nd; echo $HELLO and that sequence of three commands is what it executes in the shell. At that point, the shell (1) defines the variable HELLO, then (2) echoes the two literal arguments hello and 2nd, then (3) expands the shell variable $HELLO to hello 3rd and prints that. Hence hello 2nd then hello 3rd. Commented May 18, 2017 at 22:31

2 Answers 2

2

The lines like

HELLO='hello 3rd'

are not (make) variable assignments, but lines in the rule action.

The relevant section of the make manual says that the variable has to be at the start of the line.

As you've written it, the HELLO=... lines are simply action lines. In these cases, the command HELLO='hello 3rd' sets the shell variable HELLO in a new shell, which then immediately exits (as the answer form @sergei-kurenkov mentions, each line is executed in a different shell).

Sign up to request clarification or add additional context in comments.

Comments

0

why the terminal print not hello 4th world but hello 2nd world

Each line in recipes is executed in its own shell. So after you have uncommented 4 lines the for the target 'all' you run shell 5 times and enviroment variables in set in first run will not be seen in the second run and so forth.

Source: http://www.gnu.org/software/make/manual/html_node/Execution.html#Execution

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.