Makefile:已设置但具有空值的变量的默认值

Por*_*ine 13 bash make shell-script gnu-make variable

我有一个 Makefile,它有一个变量,如果变量未设置或设置但具有空值,则该变量需要具有默认值。

我怎样才能做到这一点?

我需要这个,因为我在 shell 脚本中调用 make 并且 makefile 所需的值可以作为 $1 从 shell 传递。并将其传递给 makefile,我必须将其设置在 bash-script 中。


想法:(不优雅)在 bash 脚本内部,可以检查变量是否已设置但具有空值,在这种情况下可以取消设置。


片段

注意:如果变量未在终端中定义,以下将不起作用,因为它们是在 bash 脚本中设置的。

生成文件

dSourceP?=$(shell pwd)
Source?=$(notdir $(wildcard $(dSourceP)/*.md))
Run Code Online (Sandbox Code Playgroud)

Bash 脚本

make all dSourceP="${1}" Source="${2}"
Run Code Online (Sandbox Code Playgroud)

终端

bash ./MyScript.sh
bash ./MyScript.sh /home/nikhil/MyDocs
bash ./MyScript.sh /home/nikhil/MyDocs index.md
Run Code Online (Sandbox Code Playgroud)

Ste*_*itt 25

由于您使用的GNU make,你可以使用?=操作

FOO ?= bar
Run Code Online (Sandbox Code Playgroud)

但这并不处理预先存在的空(或者更确切地说,空)值。以下处理缺失值和空值:

ifndef FOO
override FOO = bar
endif

test:
    echo "$(FOO)"

.PHONY: test
Run Code Online (Sandbox Code Playgroud)

(确保第 6 行以真实标签开头。)

你会用

make FOO=blah
Run Code Online (Sandbox Code Playgroud)

设置一个值。makemake FOO=将最终设置FOObar; 您需要override 覆盖在命令行上设置的变量