Li Dong
Li Dong

Reputation: 1108

How to set environment variables in makefile recipe?

Here is a simplified Makefile:

all:
    @for (( i = 0; i < 5; ++i )); do \
         var="$$var $$i"; \
         echo $$var; \
     done
    @echo $$var

I suppose the value of "var" is "0 1 2 3 4", but the output is:

0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
               <--- NOTHING!!!

As you can see the last echo is "NOTHING". What is wrong?

Upvotes: 6

Views: 4297

Answers (1)

Eldar Abusalimov
Eldar Abusalimov

Reputation: 25503

From here:

When it is time to execute recipes to update a target, they are executed by invoking a new subshell for each line of the recipe...

Please note: this implies that setting shell variables and invoking shell commands such as cd that set a context local to each process will not affect the following lines in the recipe. If you want to use cd to affect the next statement, put both statements in a single recipe line. Then make will invoke one shell to run the entire line, and the shell will execute the statements in sequence.

Try the following:

all:
    @for (( i = 0; i < 5; ++i )); do \
         var="$$var $$i"; \
         echo $$var; \
     done; \
    echo $$var

Upvotes: 12

Related Questions