Makefile – Check if a file exists using wildcard function

The following snippet of code can be used to check for the existence of a file from within a Makefile.

ifneq ("$(wildcard $(PATH_TO_FILE))","")
FILE_EXISTS = 1
else
FILE_EXISTS = 0
endif

Quoting from make documentation.

$(wildcard pattern)
The argument pattern is a file name pattern, typically containing
wildcard characters (as in shell file name patterns). The result of
wildcard is a space-separated list of the names of existing files
that match the pattern.

In this present case, we are not using any wildcards, but the absolute path to the file.

2 comments

  1. Be careful, make caches the contents of searched directories, so if a file is created during a makefile stage, ‘wildcard’ may not know about it’s existence, For example, given the following target (and assuming the file myfile.txt doesn’t yet exist), you’ll get the following output (notice the second run produces the correct results):

    wildcard:
    touch myfile.txt
    ifneq (“$(wildcard myfile.txt)”, “”)
    @echo myfile.txt exists
    else
    @echo myfile.txt does not exist
    endif

    prompt> make wildcard
    touch myfile.txt
    myfile.txt does not exist
    prompt> make wildcard
    touch myfile.txt
    myfile.txt exists

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.