make wildcard subdirectory targets

Zed picture Zed · Dec 19, 2009 · Viewed 34.7k times · Source

I have a "lib" directory in my applications main directory, which contains an arbitrary number of subdirectories, each having its own Makefile.

I would like to have a single Makefile in the main directory, that calls each subdirectory's Makefile. I know this is possible if I manually list the subdirs, but I would like to have it done automatically.

I was thinking of something like the following, but it obviously does not work. Note that I also have clean, test, etc. targets, so % is probably not a good idea at all.

LIBS=lib/*

all: $(LIBS)

%:
  (cd $@; $(MAKE))

Any help is appreciated!

Answer

mrkj picture mrkj · Dec 19, 2009

The following will work with GNU make:

LIBS=$(wildcard lib/*)
all: $(LIBS)
.PHONY: force
$(LIBS): force
  cd $@ && pwd

If there might be something other than directories in lib, you could alternatively use:

LIBS=$(shell find lib -type d)

To address the multiple targets issue, you can build special targets for each directory, then strip off the prefix for the sub-build:

LIBS=$(wildcard lib/*)
clean_LIBS=$(addprefix clean_,$(LIBS))
all: $(LIBS)
clean: $(clean_LIBS)
.PHONY: force
$(LIBS): force
  echo make -C $@
$(clean_LIBS): force
  echo make -C $(patsubst clean_%,%,$@) clean