简体   繁体   中英

How can I have a Makefile target update dependent on the value of an environment variable?

I have a make target that will have different output depending on the value of an environment variable.

How can I:

  • skip the dependency and not re-make the target if the environment variable has not changed the last run
  • make or re-make the target if the environment variable is not set or has changed

I thought I could create or conditionally update a file with the current environment variable value and then use that file as a make dependency. I couldn't find an elegant way to do that with native tools. ( sed -i always updated the file's timestamp, maybe awk is possible)

How about using a shell script to update a file that holds the variable value?

SHELL = /bin/bash
var_file := var.txt
var_name := NAME

is_var_updated = [[ ! -e $(var_file) ]] || [[ "$$(< $(var_file))" != "$($(var_name))" ]]
update_var_file = echo "$($(var_name))" > $(var_file)

$(shell $(is_var_updated) && $(update_var_file))

output.txt: $(var_file)
    echo "Name is $$NAME" > $@

This works like this.

$ ls
Makefile
$ NAME=foo make
echo "Name is $NAME" > output.txt
$ NAME=foo make
make: `output.txt' is up to date.
$ NAME=bar make
echo "Name is $NAME" > output.txt

Make conditionals could be a starting point:

.PHONY: all

FILE := foobar
ifdef ENV_VAR
OLD_ENV_VAR := $(shell [ -f $(FILE) ] && cat $(FILE))
ifeq ($(ENV_VAR),$(OLD_ENV_VAR))
DONTRUN := 1
endif
endif

ifdef DONTRUN
all:
    @echo 'ENV_VAR unmodified'
else
$(shell printenv ENV_VAR > $(FILE))
all:
    @echo 'ENV_VAR undefined or modified'
endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM