How can I automatically create (and remove) a temp directory in a Makefile?

安稳与你 提交于 2019-12-05 01:30:01
paxdiablo

I seem to recall being able to call make recursively, something along the lines of:

all:
    -mkdir $(TEMPDIR)
    $(MAKE) $(MLAGS) old_all
    -rm -rf $(TEMPDIR)

old_all: ... rest of stuff.

I've done similar tricks for making in subdirectories:

all:
    @for i in $(SUBDIRS); do \
        echo "make all in $$i..."; \
        (cd $$i; $(MAKE) $(MLAGS) all); \
    done

Just checked it and this works fine:

$ cat Makefile
all:
    -mkdir tempdir
    -echo hello >tempdir/hello
    -echo goodbye >tempdir/goodbye
    $(MAKE) $(MFLAGS) old_all
    -rm -rf tempdir

old_all:
    ls -al tempdir

$ make all
mkdir tempdir
echo hello >tempdir/hello
echo goodbye >tempdir/goodbye
make  old_all
make[1]: Entering directory '/home/pax'
ls -al tempdir
total 2
drwxr-xr-x+ 2 allachan None 0 Feb 26 15:00 .
drwxrwxrwx+ 4 allachan None 0 Feb 26 15:00 ..
-rw-r--r--  1 allachan None 8 Feb 26 15:00 goodbye
-rw-r--r--  1 allachan None 6 Feb 26 15:00 hello
make[1]: Leaving directory '/home/pax'
rm -rf tempdir

$ ls -al tempdir
ls: cannot access tempdir: No such file or directory

With GNU make, at least,

TMPDIR := $(shell mktemp -d)

will get you your temporary directory. I can't come up with a good way to clean it up at the end, other than the obvious rmdir "$(TMPDIR)" as part of the all target.

These previous answers either didn't work or seemed overly complicated. Here is a far more straight forward example I was able to figure out:

PACKAGE := "audit"
all:
    $(eval TMP := $(shell mktemp -d))
    @mkdir $(TMP)/$(PACKAGE)
    rm -rf $(TMP)
Stefan

See Getting the name of the makefile from the makefile for the $(self) trick

ifeq ($(tmpdir),)

location = $(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
self := $(location)

%:
    @tmpdir=`mktemp --tmpdir -d`; \
    trap 'rm -rf "$$tmpdir"' EXIT; \
    $(MAKE) -f $(self) --no-print-directory tmpdir=$$tmpdir $@

else
# [your real Makefile]
%:
    @echo Running target $@ with $(tmpdir)
endif
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!