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

BashShellMakefileEnvironment Variables

Bash Problem Overview


I am trying to do a simple thing:

TMPDIR ?= /tmp

test:
	@echo $(TMPDIR)

This works if I run:

$ make test
/tmp

It also works if I run:

$ make test -e TMPDIR=~/tmp
/home/user/tmp

What can I do to also have it works for:

$ TMPDIR=~/tmp make test
/home/user/tmp

Bash Solutions


Solution 1 - Bash

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 - Bash

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 - Bash

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.

Solution 4 - Bash

One of the thing you could do is:

TMPDIR := "/tmp"

ifdef $$TMPDIR
TMPDIR := $$TMPDIR
endif

test:
	echo $(TMPDIR)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNatimView Question on Stackoverflow
Solution 1 - BashMadScientistView Answer on Stackoverflow
Solution 2 - BashMaxim EgorushkinView Answer on Stackoverflow
Solution 3 - BashkenorbView Answer on Stackoverflow
Solution 4 - BashNatimView Answer on Stackoverflow