您可以轻松编写自己的宏“包”来执行此操作。例如,将此文件创建为样板,调用它program.mk
并将其放在树中的中心位置:
lang.c.objs = $(patsubst %.c,%.o,$(1))
lang.c.link = $(CC) $(CFLAGS) $(LDFLAGS) -o $(1) $(2)
lang.c++.objs = $(patsubst %.cpp,%.o,$(1))
lang.c++.link = $(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(1) $(2)
define make-program
program.$(1).lang ?= c
program.$(1).objects ?= $$(call lang.$$(program.$(1).lang).objs,$$(program.$(1).sources))
$$(program.$(1).name): $$(program.$(1).objects) $$(program.$(1).extra-deps)
$$(call lang.$$(program.$(1).lang).link,$$@,$$^ $$(program.$(1).ldlibs))
CLEANABLE += $$(program.$(1).name)
ALL_PROGRAMS += $$(program.$(1).name)
endef
# If the user didn't specify a list of programs, build them all
ifndef PROGRAMS
PROGRAMS = $(foreach p,$(filter program.%.name,$(.VARIABLES)),\
$(patsubst program.%.name,%,$(p)))
endif
# Generate the rule to build each program
$(foreach p,$(PROGRAMS),$(eval $(call make-program,$(p))))
.PHONY: all clean
all: $(ALL_PROGRAMS)
clean: ; rm -f $(CLEANABLE)
.DEFAULT_GOAL := all
现在,在您要构建程序的每个目录中,您的 makefile 可以是:
program.p.name = Program
program.p.sources = Program1.c Program2.c
include path/to/program.mk
类似的library.mk
可以用于库。这种方法非常强大并且很容易扩展。