oo_miguel
oo_miguel

Reputation: 2379

How to avoid code repetition calling recursive Makefiles?

Is it possible to simplify a Makefile of the following form in order to avoid code repetition:

dir1/foo:
    make -C dir1 foo

dir1/bar:
    make -C dir1 bar

dir2/baz:
    make -C dir2 baz

...

clean: 
    make -C dir1 clean
    make -C dir2 clean
    ...

I imagine I could specify only:

MY_TARGETS=dir1/foo dir1/bar dir2/baz ...

And than have some general rules to derive targets, as presented in the Makefile above.

Upvotes: 0

Views: 213

Answers (1)

Beta
Beta

Reputation: 99094

You haven't given us much information. Recursive Make can be a good solution, if your main makefile is as simple as your example (which I doubt).

You could do this:

%:
    $(MAKE) -C $(dir $@) $(notdir $@)

clean:
    $(MAKE) -C dir1 clean
    $(MAKE) -C dir2 clean
    ...

If that clean recipe is too long, you can simplify it:

DIRS := dir1 dir2 ...

clean:
    @for x in $(DIRS); do $(MAKE) -C $$x clean; done

Or if you don't like having that DIRS list there, you could have Make generate it, depending on whether you want to make clean in all subdirectories, or all that match the dir* pattern, or... you haven't given us enough information.

Upvotes: 2

Related Questions