Checking Make Vars
If your make target recipes use make variables you may want to test that they are set before using them. This would look something like this:
test -n '$(varname)' || { echo 'variable not set: varname'; exit 1; }
Rather than sprinkling that sort of code all over your Makefile, you may want to use a dependency instead. If you want to be sure that the variable x
is defined, use the dependency needvar.x
.
foo: needvar.x
echo "This is foo, and x=$(x)"
This should fail if x
is unset or empty (my common use case). So how is the needvar.x
defined? Well that depends.
If you run GNU Make, then it probably looks like this:
needvar.%: .PHONY
Which works for any variable.
In BSD Make like this:
needvar.x: .PHONY
with a loop to define the target for each variable of interest.
The package make-needvar implements this so that you don’t have to. It uses the tricks from make-help to handle both flavors of Make. All you need is to include the top-level file, and for BSD Make set needvars
to the list of variables you will check. After that, the needvar.x
targets are defined, and you can use them in any target that requires a variable setting.
That’s it. Stupid simple, yet effective!