haael
haael

Reputation: 1047

Makefile: Setting env var for one build step

I'm using GNU make and Makefiles. Is it possible to set an environment variable for one build step?

Currently I'm doing something like this:

VAR:=valueA
step1:
    echo $(VAR)

Then, "make step1" will print "valueA".

Is it possible to redefine the env var for one build step?

VAR:=valueA
step1:
    echo $(VAR)
step2:
    VAR:=valueB
    echo $(VAR)

I want "make step1" to print "valueA", but "make step1" to print "valueB".

Upvotes: 0

Views: 3827

Answers (2)

MadScientist
MadScientist

Reputation: 100836

First, those are not environment variables, they're make variables. It's really important to understand and remember the difference.

Second, yes, you can do this with target-specific variables:

VAR := valueA
step1:
        echo $(VAR)

step2: VAR := valueB
step2:
        echo $(VAR)

If you really do want the value to be present in the child process's environment, you can use make's export keyword:

export VAR := valueA

step1:
        echo $$VAR

Upvotes: 7

reinierpost
reinierpost

Reputation: 8591

To complement MadScientist's answer: if you actually need to set an environment variable because a command you call expects it to be set, you need to do it within the shell commands that are your recipes:

VAR := value0

all: step1 step2
step1: VAR := value1
step2: VAR := value2

all step1 step2 step3:
        ENVVAR=$(VAR) sh -c 'echo the nested sh for $@ has ENVVAR = $$ENVVAR'

Upvotes: 1

Related Questions