Define a Makefile variable using a ENV variable or a default value Define a Makefile variable using a ENV variable or a default value bash bash

Define a Makefile variable using a ENV variable or a default value


To follow up on my comments above, here's an example:

T ?= fooall:        : '$(T)'

Now if I run the Makefile in various ways, it behaves as we expect (I get foo only if I don't set T either on the command line or environment):

$ make: 'foo'$ make T=bar: 'bar'$ T=bar make: 'bar'


Variables specified on make command line override the values assigned in makefile:

TMPDIR := "/tmp"test:    @echo $(TMPDIR)

And then:

make TMPDIR=whateverwhatever

It is generally bad practice for makefiles to depend on environment variables, this is why passing variables in make command line is preferred.


Another way is to use make or function:

X := $(or ${X},${X},abc)all :    @echo ${X}makeabcX=def make def

Actually, you should just stick to using ?= assignment.


Here is a simple solution:

SHELL  := env TMPDIR=$(TMPDIR) $(SHELL)TMPDIR ?= "/tmp"all:  @echo $(TMPDIR)

which works for both scenarios: TMPDIR=new/path make and make TMPDIR=new/path.