Why does gnu make delete this file?

Viewed 86

Consider this Makefile:

.PHONY: all

all: main.txt

main.txt: build/main.txt
    cp build/main.txt .

%/main.txt: %/data.txt
    cp $*/data.txt $*/main.txt

%/data.txt:
    touch $*/data.txt

After running make, build/data.txt is removed automatically. Why is this the case?

I tried adding .PRECIOUS: build/% to the file, but it it not help, the file was still removed. How can I prevent this?

1 Answers

According to the GNU Make documentation

You can also list the target pattern of an implicit rule (such as ‘%.o’) as a prerequisite file of the special target .PRECIOUS to preserve intermediate files created by rules whose target patterns match that file’s name.

the prerequisite for.PRECIOUS needs to be the (exact) target pattern of an existing implicit rule.

In your case this would be %/data.txt instead.

The documentation hints at this, but is not particularly clear about it.

As a side note: As far as I can tell build/main.txt is not automatically deleted since it is explicitly named as a prerequisite for the main.txt target and build/data.txt is automatically deleted since it is never explicitly named.

Related