aneccodeal
aneccodeal

Reputation: 8913

recursive Makefile: want to run phony target then run the all target

Given this Makefile snippet:

TARGETS =       ${SHARED_LIB_A} ${SHARED_LIB_B}

.PHONY: subdirs $(SUBDIRS) 

subdirs: $(SUBDIRS)

$(SUBDIRS):
    $(MAKE) -C $@

all: $(TARGETS)

I want to modify this Makefile so that TARGETS get built after the PHONY target is run. Ie. TARGETS depends on the code in SUBDIRS being built - TARGETS needs to be run after SUBDIRS. Right now the way this works is that the PHONY target gets run (the subdirs are built), but not the all target (unless I specifically run it like 'make all' - but I want to avoid doing that if possible, I just want to run 'make' and have it build the subdirectories and then build TARGETS.

Upvotes: 0

Views: 359

Answers (1)

MadScientist
MadScientist

Reputation: 100836

First, you should have all as the first rule, not the last one. Unless you specify a specific target on the make command line, it will run the first target in the makefile (here, subdirs).

Second, you should declare subdirs as a prerequisite of $(TARGETS); that will ensure that they are not built until after subdirs is complete:

all: $(TARGETS)

$(TARGETS): subdirs

Now, because subdirs is PHONY it means that $(TARGETS) will always be considered out of date and always be built, even if invoking subdirs didn't change any files. However, there's no other alternative as you've written your makefile here, because make cannot know what files (created by the submakes) you want to use to see if the library is out of date.

Alternatively you can specify that subdirs is an order-only prerequisite:

$(TARGETS): | subdirs

Upvotes: 1

Related Questions