31

I wrote a Makefile and found out that when executing make command, an unexpected rm was executed, after all command in Mmakefile were done. But I didn't write the rm command in the Makefile.

run-%: d/%.out
    $<

d/%.out: d/%.c
    gcc -o $(subst .c,.out,$<) $<

Output of running make run-a:

gcc -o d/a.out d/a.c
d/a.out
rm d/a.out

Notice the trailing rm d/a.out, which I didn't write.

Under what circumstance will the automatic rm command be added?

Kusalananda
  • 333,661
z.h.
  • 994
  • Related question on SO: https://stackoverflow.com/questions/47447369/gnu-make-removing-intermediate-files – kelvin May 08 '22 at 06:03

1 Answers1

29

When you did make run-a, the file d/a.out was created by an intermediate target (a dependency of run-a) which, when the main target (run-a) has been built and that intermediate target's result is no longer needed, is removed.

You may prevent the removal of d/a.out by declaring it as "precious":

.PRECIOUS: d/%.out

See also "Chains of Implicit Rules" in the GNU Make manual:

Intermediate files are remade using their rules just like all other files. But intermediate files are treated differently in two ways.

The first difference is [...]

The second difference is that if make does create b in order to update something else, it deletes b later on after it is no longer needed. Therefore, an intermediate file which did not exist before make also does not exist after make. make reports the deletion to you by printing a rm -f command showing which file it is deleting.

Kusalananda
  • 333,661
  • 1
    Thank you so much! I have been looking for this solution for more than a week now. I didn't even know it existed. (!) – Henke - Нава́льный П с м Dec 04 '20 at 12:46
  • When did GNU make start doing this? I'll just downgrade to the version of make before they made that change and never upgrade again. – Throw Away Account Jun 17 '21 at 20:13
  • 7
    @ThrowAwayAccount The earliest release available from the GNU git repo (GNU Make release 1) had this behaviour in 1988: https://git.savannah.gnu.org/cgit/make.git/tree/make.texinfo?h=Release1#n3018 – Kusalananda Jun 17 '21 at 20:23
  • @Kusalanandaonstrike, thanks for that. In my case, generated file is getting deleted before being used for the next step. If the above solution is used, does the generated file get deleted ever? – Rao Jul 07 '23 at 05:00
  • @Rao You should ask a separate question about this with an example showing the behaviour you observe. – Kusalananda Aug 03 '23 at 19:13