get a default value when variable is unset in make

那年仲夏 提交于 2019-12-18 13:11:44

问题


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


回答1:


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)



回答2:


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.




回答3:


Just remove the colon. If you use :- in your substitution the default value will be used if the variable is null, an empty string or it does not exist, but just using - on its own will only substitute the default value if the variable has not been defined.

# var1=default
# var2=

# echo var2 is ${var2:-$var1}
var2 is something
# echo var3 is ${var3:-$var1}
var3 is something

# echo var2 is ${var2-$var1}
var2 is
# echo var3 is ${var3-$var1}
var3 is something


来源:https://stackoverflow.com/questions/16035247/get-a-default-value-when-variable-is-unset-in-make

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!