Building Multiple Executables with Similar Rules Using GNU Make
While Scons is a capable build tool, implementing the desired functionality can be challenging. A more straightforward approach is to utilize GNU Make, which allows for easy building and cleaning from both top-level and individual project directories.
Makefile Setup
The provided makefiles enable building and cleaning from both the all_lessons directory and individual project directories. Each project's executable is named after its directory.
Project Structure
To achieve this, you will need to set up a project structure similar to the example provided:
all_lessons/ helloworld/ lesson.cpp main.cpp even_or_odd/ lesson.cpp main.cpp calculator/ lesson.cpp user_created_add.cpp main.cpp
Makefile Contents
project.mk
all : % : forward_ # build any target by forwarding to the main makefile $(MAKE) -C .. project_dirs=$(notdir ${CURDIR}) $@ .PHONY : forward_
Makefile
# project configuration project_dirs := $(shell find * -maxdepth 0 -type d ) exes := $(foreach dir,${project_dirs},${dir}/${dir}) all : ${exes} # 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 dependency files -include $(foreach dir,${project_dirs},$(wildcard ${dir}/*.d))
Usage
Building from Individual Project Directories
[project_directory]$ ln -s ../project.mk Makefile # create a symlink [project_directory]$ make
Building from the Top-Level Directory
[all_lessons]$ make
Cleaning Individual Project Directories
[project_directory]$ cd .. [all_lessons]$ make clean
Cleaning All Projects
[all_lessons]$ make clean
The above is the detailed content of How to Build Multiple Executables with Similar Rules Using GNU Make?. For more information, please follow other related articles on the PHP Chinese website!