Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i pass ENV variables between make targets

I have like this in makefile

target1:
       export var1=test
       $(MAKE) target2

target2:
       echo $(var1)

This is coming as empty

I have other depencies so i want to set variable in first target and then all children dependencies should be able to access that

EDIT:

.ONESHELL:

target1:
        export var1=test
        echo $(var1)

output

make target1
export var1=test
echo
like image 562
Karl Avatar asked Aug 12 '16 22:08

Karl


People also ask

Are makefile variables environment variables?

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment.


1 Answers

By default make invokes a new shell environment for each recipe, the exported variable on the first line isn't in scope for the second.

You can fix this in multiple ways:

Export the variable with make's export directive

target1: export var1 := test
target1:
    $(MAKE) target2

Use make's command line variable assignment

target1:
    $(MAKE) target2 var1=test

Use shell command variable assignment

target1:
    var1=test $(MAKE) target2

Combine the two commands in a single recipe

target1:
    export var1=test; $(MAKE) target2

Force make to pass all recipes to the same shell instance

.ONESHELL:

target1:
    export var1=test
    $(make) target2
like image 60
user657267 Avatar answered Oct 06 '22 14:10

user657267