cat
cat

Reputation: 4020

Dynamically generating a list of targets

If a file exists, I want to add a target to build. If the file does not exist, I want the target to be skipped.

an example:

FILENAME = f

TARGETS := normal
ifneq($(shell stat test_$(FILENAME).c), "")
  TARGETS += test
endif

all: $(TARGETS)

normal: 
    @echo normal

test: 
    @echo test

I'm not sure the $(shell stat ...) part even works, but the bigger problem is that make with any file test_f.c in the current folder gives:

Makefile:4: *** multiple target patterns.  Stop.

Removing the ifneq ... endif block makes the target normal. How can I only run the target test if test_f.c exists?

Upvotes: 0

Views: 992

Answers (2)

Oo.oO
Oo.oO

Reputation: 13375

You can also iterate over targets with for loop

.PHONY: all

RECIPES = one

all:    RECIPES += $(if $(wildcard test_f.c), two, )
all:
        for RECIPE in ${RECIPES} ; do \
                $(MAKE) $${RECIPE} ; \
        done
one:
        $(warning "One")

two:
        $(warning "Two")

> make
for RECIPE in one   ; do \
        /Applications/Xcode.app/Contents/Developer/usr/bin/make ${RECIPE} ; \
    done
makefile:11: "One"
make[1]: `one' is up to date.

> touch test_f.c

> make
for RECIPE in one  two ; do \
        /Applications/Xcode.app/Contents/Developer/usr/bin/make ${RECIPE} ; \
    done
makefile:11: "One"
make[1]: `one' is up to date.
makefile:14: "Two"
make[1]: `two' is up to date.

Upvotes: 1

Mingjing Zhang
Mingjing Zhang

Reputation: 943

What you can do is generate a string variable (let's call it OPTIONAL) such that when 'test_f.c' exists, OPTIONAL=test; otherwise, OPTIONAL=_nothing_. And then add OPTIONAL as a prerequisite of all. e.g.:

FILENAME = f

TARGETS = normal
OPTIONAL = $(if $(wildcard test_f.c), test, )
all: $(TARGETS) $(OPTIONAL)

normal: 
    @echo normal

test: 
    @echo test

Upvotes: 1

Related Questions