Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a default value when variable is unset in make

(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?

like image 463
oHo Avatar asked Apr 16 '13 10:04

oHo


People also ask

What is $@ in Makefile?

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.

How can we set default value to the variable?

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.

How do you assign a default value to a variable in UNIX?

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).

What is default var value?

Variables of any "Object" type (which includes all the classes you will write) have a default value of null.


2 Answers

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)
like image 127
MadScientist Avatar answered Sep 25 '22 11:09

MadScientist


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.

like image 41
devnull Avatar answered Sep 22 '22 11:09

devnull