如何在Makefile中自动创建(和删除)临时目录?

时间:2009-02-26 05:44:26

标签: makefile temporary-files

是否可以在执行第一个目标之前让make创建临时目录?也许使用一些黑客,一些额外的目标等?

Makefile中的所有命令都可以将自动创建的目录称为$TMPDIR,当make命令结束时,该目录将自动删除。

4 个答案:

答案 0 :(得分:12)

至少使用GNU make,

TMPDIR := $(shell mktemp -d)

将为您提供临时目录。除了作为rmdir "$(TMPDIR)"目标的一部分的明显all之外,我无法想出一个最好的方法来清理它。

答案 1 :(得分:9)

我似乎记得能够递归地调用make,这有点像:

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

old_all: ... rest of stuff.

我在子目录中做了类似的技巧:

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

刚检查过,这很好用:

$ 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

答案 2 :(得分:9)

这些先前的答案要么不起作用,要么看起来过于复杂。这是一个更直接的例子,我能够弄清楚:

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

答案 3 :(得分:6)

请参阅Getting the name of the makefile from the makefile了解$(self)技巧

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