Invoke directories recursively with GNU make

Hi folks, I guess we all have had this problem and we mostly solve it in a crude way by hardcoding directories into static targets. But since fiddling around with BSD make, here’s a way to make this a bit more flexible for GNU make. Your Makefile will look like this:

SUBDIR= dir1 dir2 dir3

include recurse.mk

Granted this isn’t much, because the logic is hidden in the file recurse.mk, which is put into the project’s root directory:

.PHONY: $(SUBDIR) recurse

regress: TARGET=regress
check: TARGET=check
clean: TARGET=clean
all: TARGET=all

recurse regress check clean all: $(SUBDIR)

$(SUBDIR):
    @exec $(MAKE) -C $@ $(TARGET)

Now, every time you need to recursively access more directories, you put a simple Makefile into the directory and point to the location of recurse.mk. Be careful not to mix subdirectories and source code – your Makefiles will only get more messy again. One small issue remains, though. There should be a better way to automatically pass down the targets, but I haven’t found it yet. Let me know if you can help with that.

Update: Figured it out. Very easy to do it using $(MAKECMDGOALS) to remove the redundancy in recurse.mk. Enjoy!

.PHONY: $(SUBDIR) recurse

$(MAKECMDGOALS) recurse: $(SUBDIR)

$(SUBDIR):
        @exec $(MAKE) -C $@ $(MAKECMDGOALS)

2 thoughts on “Invoke directories recursively with GNU make”

  1. Nice and neat, thanks for this.

    One question though: why do you have ‘recurse’ in your final solution? If both appearances of ‘recurse’ are removed, will it affect anything?

  2. The `recurse’ target forces the evaluation of $(SUBDIR); otherwise GNU make insists that there’s nothing to do, even though .PHONY was used.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.