(edit: question more accurate based on @Michael feedback)
In bash, I often use parameter expansion: the following commands print "default value
" when $VARNAME
is unset, otherwise it prints the VARNAME content.
echo ${VARNAME:-default value} #if VARNAME empty => print "default value"
echo ${VARNAME-default value} #if VARNAME empty => print "" (VARNAME string)
I did not find a similar feature on GNU make
.
I finally wrote in my Makefile
:
VARNAME ?= "default value"
all:
echo ${VARNAME}
But I am not happy with this solution: it always creates the variable VARNAME
and this may change the behavior on some makefiles.
Is there a simpler way to get a default value on unset variable?
The file name of the target of the rule. If the target is an archive member, then ' $@ ' is the name of the archive file. In a pattern rule that has multiple targets (see Introduction to Pattern Rules), ' $@ ' is the name of whichever target caused the rule's recipe to be run.
You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.
You can use something called Bash parameter expansion to accomplish this. To get the assigned value, or default if it's missing: FOO="${VARIABLE:-default}" # If variable not set or null, use default. # If VARIABLE was unset or null, it still is after this (no assignment done).
Variables of any "Object" type (which includes all the classes you will write) have a default value of null.
If you want to use the expansion of a GNU make variable if it is non-empty and a default value if it is empty, but not set the variable, you can do something like this:
all:
echo $(or $(VARNAME),default value)
If you want to test if a variable has a non-empty value, you can use:
ifeq ($(VARNAME),)
VARNAME="default value"
else
do_something_else
endif
For checking if a variable has been defined or not, use ifdef
.
Refer to Syntax of Conditionals in the manual for more.
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