Building Executables with Similar Rules Using GNU Make
As an alternative to Scons, GNU Make can be an efficient solution for your task. GNU Make allows you to define a flexible build process through its dependency resolution system.
GNU Make Approach
We present two makefiles that enable building and cleaning from both the top-level directory (all_lessons) and individual project directories:
project.mk
all : % : forward_ # build any target by forwarding to the main makefile $(MAKE) -C .. project_dirs=$(notdir ${CURDIR}) $@ .PHONY : forward_
Makefile
# one directory per project, one executable per directory project_dirs := $(shell find * -maxdepth 0 -type d ) # executables are named after its directory and go into the same directory exes := $(foreach dir,${project_dirs},${dir}/${dir}) all : ${exes} # the rules .SECONDEXPANSION: objects = $(patsubst %.cpp,%.o,$(wildcard $(dir )*.cpp)) # link ${exes} : % : $$(call objects,$$*) Makefile g++ -o $@ $(filter-out Makefile,$^) ${LDFLAGS} ${LDLIBS} # compile .o and generate dependencies %.o : %.cpp Makefile g++ -c -o $@ -Wall -Wextra ${CPPFLAGS} ${CXXFLAGS} -MD -MP -MF ${@:.o=.d} $< .PHONY: clean clean : rm -f $(foreach exe,${exes},$(call objects,${exe})) $(foreach dir,${project_dirs},$(wildcard ${dir}/*.d)) ${exes} # include auto-generated dependency files -include $(foreach dir,${project_dirs},$(wildcard ${dir}/*.d))
Advantages
Usage
To build from an individual project directory, create a symbolic link to project.mk as Makefile in that directory. Building or cleaning from the all_lessons directory will process all projects, while doing so from a project's directory will only affect that project.
This approach provides a clean and flexible way to build multiple executables with similar rules from various directories.
The above is the detailed content of How can GNU Make be used to efficiently build multiple executables with similar rules from different directories?. For more information, please follow other related articles on the PHP Chinese website!