Using wildcard in GNU Make pattern rule

gnu-makemake

Assume doc.pdf is the target.

The following rule triggers a regeneration of doc.pdf whenever doc.refer is updated, but is also happy when doc.refer does not exist at all:

doc.pdf: doc.mom $(wildcard doc.refer)
    pdfmom -e -k < $< > $@

However the following pattern rule does not accomplish the same (the PDF is generated correctly, but a rebuild is not triggered when changing doc.refer):

%.pdf: %.mom Makefile $(wildcard %.refer)
    pdfmom -e -k < $< > $@

I suspect that the wildcard command is executed before the % character is expanded. How can I work around this?

Best Answer

The GNU Make function wildcard takes a shell globbing pattern and expands it to the files matching that pattern. The pattern %.refer does not contain any shell globbing patterns.

You probably want something like

%.pdf: %.mom %.refer
        pdfmom -e -k < $< > $@

%.pdf: %.mom
        pdfmom -e -k < $< > $@

The first target will be invoked for making PDF files when there's a .mom and a .refer file available for the base name of the document. The second target will be invoked when there isn't a .refer file available.

The order of these targets is important.

Related Question