Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use environment variable if set otherwise use default value in makefile

Tags:

bash

makefile

I can do this:

MY_VAR:=$(myvar)

But what I want is to also define a value for MY_VAR that is used if the environment variable myvar isn't defined. Is this possible?

Something like:

# pseudo code
MY_VAR:=if not $(myvar) then someDefaultValue
like image 368
red888 Avatar asked Nov 19 '18 07:11

red888


People also ask

How do I set an environment variable in makefile?

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.

How do I check if an environment variable is set in makefile?

Check if variable is defined in a Makefilecheck_defined = \ $(strip $(foreach 1,$1, \ $(call __check_defined,$1,$(strip $(value 2))))) __check_defined = \ $(if $(value $1),, \ $(error Undefined $1$(if $2, ($2)))) install: $(call check_defined, var1) $(call check_defined, var2) # do stuff here..

How do I override a makefile variable?

There is one way that the makefile can change a variable that you have overridden. This is to use the override directive, which is a line that looks like this: ' override variable = value ' (see The override Directive).

What is $$ in makefile?

Commands and executionIf you want a string to have a dollar sign, you can use $$ . This is how to use a shell variable in bash or sh . Note the differences between Makefile variables and Shell variables in this next example.


1 Answers

Assuming make is GNU Make, all the environment variable settings inherited by make are automatically registered as make variable settings. See 6.10 Variables from the Environment. So you can just write, e.g.

Makefile (1)

ifdef myvar
MYVAR := $(myvar)
else
MYVAR := default
endif

.PHONY: all

all:
    echo $(MYVAR)

Which runs like:

$ make
echo default
default

when myvar is not defined in the environment; and when it is defined, runs like:

$ export myvar=notDefault
$ make
echo notDefault
notDefault

And in case the environment variable and the make variable are the same - and why not? - it is simpler still.

Makefile (2)

MYVAR ?= default

.PHONY: all

all:
    echo $(MYVAR)

See 6.5 Setting Variables

Then:

$ make
echo default
default
$ export MYVAR=notDefault
$ make
echo notDefault
notDefault
like image 196
Mike Kinghan Avatar answered Oct 14 '22 14:10

Mike Kinghan