Home >Backend Development >C++ >Can GNU Make streamline building numerous executables with similar rules across a directory structure, allowing compilation from both the main directory and individual project folders?
Building Multiple Executables with Similar Rules Using GNU Make
Question:
Can GNU Make facilitate building multiple executables with similar rules in a directory structure, enabling compilation from both the main directory and individual project directories?
Answer:
Yes, GNU Make can handle this task with a concise and efficient approach. Below are two makefiles that implement the desired functionality:
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))
Usage:
Advantages:
The above is the detailed content of Can GNU Make streamline building numerous executables with similar rules across a directory structure, allowing compilation from both the main directory and individual project folders?. For more information, please follow other related articles on the PHP Chinese website!