Using Makefile to clean subdirectories
Is it possible to perform a make clean from the parent directory which also recursively cleans all sub-directories without having to include a makefile in each sub-directory?
For example, currently in my Makefile, I have something like:
SUBDIRS = src, src1
.PHONY: clean subdirs $(SUBDIRS)
clean: $(SUBDIRS)
rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c
$(SUBDIRS):
$(MAKE) -C $(SUBDIRS) clean
However, this requires me to have a Makefile in both src and src1. Otherwise, I would get the error
No rule to make target clean
Since I only want to run the command "rm -rf *.o ~ core .depend ..cmd *.ko *.mod.c" in each subdirectory anyways, it seems redundant to have to include a Makefile in every subdirectory with the exact same line for clean. Is there no way to simply have the same clean command run in each of the subdirectories?
I agree that you could just have the rm command operate on subdirs. But something like the following allows recursive make using only a single makefile:
SUBDIRS = . src src1
SUBDIRSCLEAN=$(addsuffix clean,$(SUBDIRS))
clean: $(SUBDIRSCLEAN)
clean_curdir:
rm -rfv *.o *~ core .depend .*.cmd *.ko *.mod.c
%clean: %
$(MAKE) -C $< -f $(PWD)/Makefile clean_curdir
除了使用递归之外,您可以通过shell来find
目录列表并执行一次迭代来生成通配符:
SUBDIR_ROOTS := foo bar
DIRS := . $(shell find $(SUBDIR_ROOTS) -type d)
GARBAGE_PATTERNS := *.o *~ core .depend .*.cmd *.ko *.mod.c
GARBAGE := $(foreach DIR,$(DIRS),$(addprefix $(DIR)/,$(GARBAGE_PATTERNS)))
clean:
rm -rf $(GARBAGE)
You cannot without help of an external program. The best is a shell script that does the recursion and calls make in each of the subdirectories (look at my comment to @robert in his response) Something like this will do the work (and does not depend on GNU make features)
#!/bin/sh
ROOTDIR=`/bin/pwd`
for dir in `find . -type d -print`
do
make -C "${dir}" -f "${ROOTDIR}"/Makefile clean
done
of course, you can put this sequence (in target cleanrec
) inside your Makefile
cleanrec:
ROOT=`/bin/pwd`;
for dir in `find . -type d -print`;
do
make -C "$${dir}" -f "$${ROOTDIR}"/Makefile clean;
done
and conserve your clean
target for local cleaning of a single directory. The reason is that Makefile has only static info to do the make, and you have to get some external help to know what subdirectories you have in each directory. So, in case you are going to get external help, you'd better to use a good tool as find(1) and sh(1)
上一篇: r ...但省略(排除)指定的子目录
下一篇: 使用Makefile来清理子目录