makefiledependenciesdiskimage

Makefile Target Dependency on Whether Target Already Exists


I am trying to write a Makefile whose targets depend on the existence of a disk file. The disk file itself merely needs to be created; it does not depend on any other actions that may update it. If I do not give it any dependencies, the file is re-created every time I run make on one of the targets.

Is there a way to have a target depend on whether it exists?

This is part of the Makefile I have. The $(TMPDEV) file only needs to be created if it doesn't exist, otherwise it should be considered up-to-date.

TMPDEV="/tmp/disk.img"

$(TMPDEV):
        fallocate -l 806354944 $(TMPDEV) || dd if=/dev/zero of=$(TMPDEV) bs=1b count=1574912
        sudo parted --script $(TMPDEV) unit s mklabel msdos \
          mkpart primary fat16 2048 526335 \
          mkpart primary fat32 526336 1050623 \
          mkpart primary NTFS 1050624 1574911 \
          quit
        $(eval TMPDISK := $(shell sudo partx --verbose -a $(TMPDEV) | tail -1 | cut -d':' -f1))
        sudo mkfs.fat -F 16 -n FAT16 $(TMPDISK)p1
        sudo mkfs.fat -F 32 -n FAT32 $(TMPDISK)p2
        sudo mkfs.ntfs -L NTFS $(TMPDISK)p3
        sudo partx -d $(TMPDISK)
        sudo losetup -d $(TMPDISK)

testresults: $(TMPDEV)
        touch testresults

analytics: $(TMPDEV)
        touch analytics

Solution

  • Remove the quotes:

    TMPDEV="/tmp/disk.img"
    

    Make doesn't use/need quotes. You are saying that the target here:

    $(TMPDEV):
    

    is, literally, this file including the quotes:

    "/tmp/disk.img":
    

    that file never exists, so the rule is always re-run.