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
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.
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..
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With