How to set a variable in a Makefile to a filename via a file pattern, only if the pattern has ONE match

1k views Asked by At

I have a makefile for GNU make to build documents from markdown text files. The makefile has a variable INPUT I want to set to the filename of the markdown file. All markdown files follow the pattern *.md.

However I want set INPUT only to the filename when there is only one file matching the pattern, if there are more than one markdown file, make should exit with an error.

I tried the obvious choice

INPUT ?= *.md

but this sets INPUT of course to a list of **all* matches. So it works correctly for a directory which contains, say, only file_a.md, but in a directory with

file_a.md
file_b.md

INPUT contains afterwards "file_a.md file_b.md", which messes up my rules expecting INPUT to contain one file or to exit.

Any way to assign INPUT as I want to with makefile syntax?

1

There are 1 answers

1
Etan Reisner On BEST ANSWER

To do what you want you need to use the $(wildcard) function to force the globbing to be done immediately (otherwise make will wait until the variable is used in an appropriate place before expanding the glob).

INPUT ?= $(wildcard *.md)

ifneq (1,$(words $(INPUT)))
    $(error Too many or two few input files found.)
endif