get a default value when variable is unset in make

后端 未结 4 1866
面向向阳花
面向向阳花 2020-12-31 09:10

(edit: question more accurate based on @Michael feedback)

In bash, I often use parameter expansion: the following commands print \"default value\" when

相关标签:
4条回答
  • 2020-12-31 09:28

    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
    
    0 讨论(0)
  • 2020-12-31 09:35

    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.

    0 讨论(0)
  • 2020-12-31 09:38

    I have a similar case where the result of filtering a shell command could be a single word or empty string. When empty, it should fallback to the default word. In the example below APPLE_LINUX will be 'apple' on macOS or 'linux' on other platforms. MSG will be set to the message for the appropriate platform. The example intentionality avoids using ifeq.

    MACHINE         := $(shell $(COMPILE.cpp) -dumpmachine)
    MACHINE_APPLE   := $(findstring apple,$(MACHINE))
    APPLE_LINUX     := $(firstword $(MACHINE_APPLE) linux)
    apple.MSG       := You are building on macOS
    linux.MSG       := You are building on Linux or another OS
    MSG             := $($(APPLE_LINUX).MSG)
    
    0 讨论(0)
  • 2020-12-31 09:40

    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)
    
    0 讨论(0)
提交回复
热议问题