views:

206

answers:

1

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!

+2  A: 

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
mrkj
Wow, thanks. Works like a charm!
Zed
@mrkj: Why you haven't defined `$(clean_LIBS)` as phony? E.g. `.PHONY: $(LIBS) $(clean_LIBS)`, then I think you don't need `force`.
dma_k
@dma_k: You make an excellent point. I haven't tested your suggestion, but your reasoning sounds right to me. In fact, it sounds a lot like what the GNU Make manual is suggesting here (see the bit on subdirs): http://www.gnu.org/software/make/manual/make.html#Phony-Targets
mrkj