Run make in each subdirectory

Alex picture Alex · Jul 24, 2013 · Viewed 65.3k times · Source

I have a directory (root_dir), that contains a number of sub-directories (subdir1, subdir2, ...).

I want to run the make in each directory in root_dir, using a Makefile placed in it. (Obviously supposed that each of subdir... has inside its own Makefile).

So there are essentially two questions:

  1. How to get a list of directories in Makefile (automatically)?
  2. How to run make for each of the directories inside a make file?

As I know in order to run make in a specific directory I need to do the following:

$(MAKE) -C subdir

Answer

MadScientist picture MadScientist · Jul 24, 2013

There are various problems with doing the sub-make inside a for loop in a single recipe. The best way to do multiple subdirectories is like this:

SUBDIRS := $(wildcard */.)

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

.PHONY: all $(SUBDIRS)

(Just to point out this is GNU make specific; you didn't mention any restrictions on the version of make you're using).

ETA Here's a version which supports multiple top-level targets.

TOPTARGETS := all clean

SUBDIRS := $(wildcard */.)

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

.PHONY: $(TOPTARGETS) $(SUBDIRS)