make
doesn't support this directly, and trying to do it manually from the makefile is just too difficult, since you need to delete the directory regardless of which rule is run, even if a rule fails, and even if no rules are invoked (because the target is up to date).
The best solution that I've found is to wrap the Makefile in a shell script make.sh
:
#!/bin/bash
TEMPDIR=$(mktemp -d -t) || exit 1
export TEMPDIR
trap "rm -rf $TEMPDIR" 0
make $@
Then, in your Makefile, add a rule to verify that TEMPDIR was set:
ifeq ($(TEMPDIR),)
$(error TEMPDIR environment variable not defined (try running from make.sh))
endif
Then just run make.sh
instead of make
.