我可以让 make 删除中间文件吗?

Can i let make delete intermediate files?

我有点难以理解 make.

中间文件 概念

考虑这个制作过程的例子:

输入文件:

构建步骤:

  1. 剪掉myGraphic.picture
  2. 的边框
  3. 将剪切图形转换为特殊格式
  4. 编译代码,包括转换后的图形。

概念是这样的:

在 Makefile 中,这看起来像这样:

all: myProgram.exe

myProgram.exe: myProgram.code myGraphic.picture.cut.converted
    compiler -code myProgram.code -graphic myGraphic.picture.cut.converted

myGraphic.picture.cut.converted: myGraphic.picture.cut
    converter -in myGraphic.picture.cut -out myGraphic.picture.cut.converted

myGraphic.picture.cut: myGraphic.picture
    cutter -in myGraphic.picture -out myGraphic.picture.cut

据我了解,在运行make之后,我将得到编译后的程序,以及中间文件.cut.converted.cut.

有没有办法自动删除这些文件?如果是这样, make 是否足够聪明,不会在原始图片未更改的情况下重新创建所有这些?

再简单不过了。只需添加 this target:

.INTERMEDIATE: myGraphic.picture.cut myGraphic.picture.cut.converted

如果目标在 Makefile 中明确命名,而不是魔法目标 .INTERMEDIATE 的依赖项,那么它将被保留。

因此添加 .INTERMEDIATE: 行,and/or 将您的转换改写为模式规则:

%.cut.converted: %.cut
    converter -in $< -out $@

%.picture.cut: %.picture
    cutter -in $< -out $@

这还有一个好处,那就是更容易阅读。

当然,如果这些工具可以用作管道中的过滤器,您至少可以消除对某些临时文件的需求。

是的。如果不需要,可以删除文件。例如:

results.txt : testzipf.py isles.dat abyss.dat last.dat
    python $^ *.dat > $@
    rm -f *.dat


.PONY : dats
dats : isles.dat abyss.dat last.dat

%.dat : books/%.txt countwords.py
    python countwords.py $< $@

此文件从 dats 创建一个 results.txt,最后删除 dat 文件 rm -f *.dat

如果您再次 运行 make 命令,它将再次创建中间文件并在使用它们生成目标后删除它们。

你的 make 脚本看起来像

all: myProgram.exe
   rm -f *.cut
myProgram.exe: myProgram.code myGraphic.picture.cut.converted
   compiler -code myProgram.code -graphic        myGraphic.picture.cut.converted

myGraphic.picture.cut.converted: myGraphic.picture.cut
   converter -in myGraphic.picture.cut -out myGraphic.picture.cut.converted

myGraphic.picture.cut: myGraphic.picture
   cutter -in myGraphic.picture -out myGraphic.picture.cut