Run make in each subdirectory

2019-01-22 02:32发布

问题:

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 knwow in order to run make in a specific directory I heed to do the following:

$(MAKE) -C subdir

回答1:

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)


回答2:

Try this :

SUBDIRS = foo bar baz

subdirs:
    for dir in $(SUBDIRS); do \
        $(MAKE) -C $$dir; \
    done

This may help you link

Edit : you can also do :

The simplest way is to do:

CODE_DIR = code

.PHONY: project_code

project_code:
       $(MAKE) -C $(CODE_DIR)

The .PHONY rule means that project_code is not a file that needs to be built, and the -C flag indicates a change in directory (equivalent to running cd code before calling make). You can use the same approach for calling other targets in the code Makefile.

For example:

clean:
   $(MAKE) -C $(CODE_DIR) clean

Source



回答3:

There is a library called prorab for GNU make which supports inclusion of standalone makefiles in subdirectories.

Some info on github: https://github.com/igagis/prorab/blob/master/wiki/HomePage.md

Basically, with prorab invoking all makefiles in subdirectories looks like this:

include prorab.mk

$(eval $(prorab-build-subdirs))