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

Solution 1:

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

T ?= foo
all:
        : '$(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'

Solution 2:

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

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

And then:

make TMPDIR=whatever
whatever

It is generally considered a bad practice for makefiles to depend on environment variables because that may lead to non-reproducible builds. This is why passing variable overrides in make command line explicitly is recommended.

Solution 3:

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.