"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Build Multiple Executables with Similar Rules Using GNU Make?

How to Build Multiple Executables with Similar Rules Using GNU Make?

Published on 2024-11-07
Browse:472

 How to Build Multiple Executables with Similar Rules Using GNU Make?

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 ${1})*.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
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3