Evert
Evert

Reputation: 99505

Finding the appropriate executable in a Makefile

I'm writing a Makefile that needs to execute the program foo1, which is usually provided by the operating system. Some operating systems provide this binary with a different name, foo2.

I'm trying to figure out how to best test for the correct executable and exist if neither doesn't exist. I've had a few approaches but they all seem ugly and I figured there might be a more appropriate way to do this.

I tried this:

FOO = $(shell which foo foo2)

target:
   @which $(FOO) > /dev/null
   $(FOO)

I don't find this very elegant because if both foo and foo2 exist on the system, which will actually return two lines. It's also weird that I call which twice and that I rely on an error being emitted when I don't pass anything to the second which.

In short, what's a better way?

Upvotes: 1

Views: 578

Answers (1)

MadScientist
MadScientist

Reputation: 100781

How about something like:

FOO := $(firstword $(shell which foo foo1))
ifeq ($(FOO),)
  $(error Cannot find foo or foo1)
endif

target:
        $(FOO)

Or if you don't like using make's error function you can use:

target:
        @[ -n "$(FOO)" ] || { echo "Cannot find foo or foo1"; exit 1; }

Note this will not work if you have any pathnames with spaces in them in your PATH... but that's a much larger problem to solve anyway.

Upvotes: 3

Related Questions