19

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

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

4

4 回答 4

22

至少使用 GNU make,

TMPDIR := $(shell mktemp -d)

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

于 2009-02-26T05:50:03.567 回答
22

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

PACKAGE := "audit"
all:
    $(eval TMP := $(shell mktemp -d))
    @mkdir $(TMP)/$(PACKAGE)
    rm -rf $(TMP)
于 2016-10-18T23:58:20.403 回答
11

有关技巧,请参阅从 makefile中获取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
于 2013-01-30T16:10:29.797 回答
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
于 2009-02-26T05:51:22.533 回答