Kalu
Kalu

Reputation: 290

how to change directories from makefile and execute subdirectories make file?

suppose A has two sub directories B and C where each subdirectories has their own make file.The parent A has its own make file.To call the child directories I have to use the below command in the parent makefile :

subB:
   cd B && make
subC:
   cd c && make

Is there a generalized way of calling child directories makefile with a single statement.Beacause in future more 50 to 60 folders may be added.What is the generalized way of writing it

Upvotes: 0

Views: 3412

Answers (3)

Chnossos
Chnossos

Reputation: 10456

List directories, excluding current one (.):

DIRS := $(shell find . -maxdepth 1 ! -path . -type d)

Tell make that directories are not a target and you do want to trigger the associated recipe:

.PHONY: all $(DIRS)

Mandatory non-pattern rule:

all: $(DIRS)

Actual recipe for each directory (the + is important for threading):

$(DIRS):
    +$(MAKE) -C $@

Result:

DIRS := $(shell find -maxdepth 1 ! -path . -type d)

.PHONY: all $(DIRS)

all: $(DIRS)

$(DIRS):
    +$(MAKE) -C $@

Notes:

  • This answer is multi-threaded-friendly (i.e. make -j $(nproc))
  • You can call make with explicit targets like so: make dir1 dir3

Upvotes: 1

Kalu
Kalu

Reputation: 290

DIR:= $(wildcard */.)

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

Upvotes: 0

mooiamaduck
mooiamaduck

Reputation: 2156

I would use a combination of make -C and find.

make -C <directory> runs make like usual, except that it temporarily changes to <directory> before running the command.

find is a command which traverses a directory tree. By default it prints the paths of all files, directories, symlinks, etc. contained within the current working directory. You can also tell find to run a particular command on each of those paths instead of printing them, using the -exec option. In the command passed to -exec, {} stands for the path of the current file/directory, and ; is necessary to mark the end of the command (these are special characters in shell syntax so you need to quote them).

If you wanted, for example, to run the Makefile in all of the directories in the current working directory, then you could do this:

sub:
    find -maxdepth 1 -type d -exec make -C '{}' ';'

-type d tells find to run only on directories. -maxdepth 1 means that only the directories which are directly beneath the current directory will be checked; the sub-directories within them will not.

Upvotes: 1

Related Questions