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!

Community
  • 1
  • 1
kgbook
  • 388
  • 4
  • 16
  • Exercise: And can you see why `HELLO='hello 3rd'; echo $(HELLO); echo $$HELLO` outputs what it does? – Norman Gray May 17 '17 at 18:56
  • the output is `hello 3rd` and a blank line – kgbook May 18 '17 at 14:44
  • `echo $$HELLO` is equal to `echo $('hello 3rd')` – kgbook May 18 '17 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`. – Norman Gray May 18 '17 at 22:31

2 Answers2

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).

Norman Gray
  • 11,978
  • 2
  • 33
  • 56
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