make wildcard subdirectory targets

后端 未结 3 899
南笙
南笙 2021-02-02 11:57

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

3条回答
  •  故里飘歌
    2021-02-02 12:32

    What if you want to call different targets than all in an unknown number of subdirectories?

    The following Makefile uses macros so create a forwarding dummy-target for a number of subdirectories to apply the given target from the command line to each of them:

    # all direct directories of this dir. uses "-printf" to get rid of the "./"
    DIRS=$(shell find . -maxdepth 1 -mindepth 1 -type d -not -name ".*" -printf '%P\n')
    # "all" target is there by default, same logic as via the macro
    all: $(DIRS)
    
    $(DIRS):
        $(MAKE) -C $@
    .PHONY: $(DIRS)
    
    # if explcit targets where given: use them in the macro down below. each target will be delivered to each subdirectory contained in $(DIRS).
    EXTRA_TARGETS=$(MAKECMDGOALS)
    
    define RECURSIVE_MAKE_WITH_TARGET
    # create new variable, with the name of the target as prefix. it holds all
    # subdirectories with the target as suffix
    $(1)_DIRS=$$(addprefix $(1)_,$$(DIRS))
    
    # create new target with the variable holding all the subdirectories+suffix as
    # prerequisite
    $(1): $$($1_DIRS)
    
    # use list to create target to fullfill prerequisite. the rule is to call
    # recursive make into the subdir with the target
    $$($(1)_DIRS):
          $$(MAKE) -C $$(patsubst $(1)_%,%,$$@) $(1)
    
    # and make all targets .PHONY
    .PHONY: $$($(1)_DIRS)
    endef
    
    # evaluate the macro for all given list of targets
    $(foreach t,$(EXTRA_TARGETS),$(eval $(call RECURSIVE_MAKE_WITH_TARGET,$(t))))
    

    Hope this helps. Really helpfull when dealing with paralelism: make -j12 clean all in a tree with makefiles having these targets... As always: playing with make is dangerous, different meta-levels of programming are too close together ,-)

提交回复
热议问题