How to ensure Makefile variable is set as a prerequisite

makefile

A Makefile deploy recipe needs an environment variable ENV to be set to properly execute itself, whereas other recipes don't care, e.g.,

ENV = 

.PHONY: deploy hello

deploy:
    rsync . $(ENV).example.com:/var/www/myapp/

hello:
    echo "I don't care about ENV, just saying hello!"

How can I make sure this ENV variable is set? Is there a way to declare this makefile variable as a prerequisite of the deploy recipe? e.g.,

deploy: make-sure-ENV-variable-is-set

Best Answer

This will cause a fatal error if ENV is undefined and something needs it (in GNUMake, anyway).

.PHONY: deploy check-env

deploy: check-env
	...

other-thing-that-needs-env: check-env
	...

check-env:
ifndef ENV
	$(error ENV is undefined)
endif

(Note that ifndef and endif are not indented - they control what make "sees", taking effect before the Makefile is run. "$(error" is indented with a tab so that it only runs in the context of the rule.)