」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 GNU Make 建立具有相似規則的多個可執行檔?

如何使用 GNU Make 建立具有相似規則的多個可執行檔?

發佈於2024-11-07
瀏覽:894

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

使用GNU Make 建立具有類似規則的多個可執行檔

雖然Scons 是一個功能強大的建置工具,但實作所需的功能可能具有挑戰性。更直接的方法是利用 GNU Make,它可以輕鬆地從頂級和單一專案目錄進行建置和清理。

Makefile 設定

提供的 makefile啟用從 all_lessons 目錄和單一專案目錄進行建置和清理。每個項目的可執行檔均以其目錄命名。

專案結構

要實現此目的,您需要設定一個與提供的範例類似的專案結構:

all_lessons/
    helloworld/
        lesson.cpp
        main.cpp
    even_or_odd/
        lesson.cpp
        main.cpp
    calculator/
        lesson.cpp
        user_created_add.cpp
        main.cpp

Makefile 內容

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))

用法

從個人建置專案目錄

[project_directory]$ ln -s ../project.mk Makefile  # create a symlink
[project_directory]$ make

從頂級目錄建立

[all_lessons]$ make

清理各個專案目錄

[project_directory]$ cd ..
[all_lessons]$ make clean

清理所有項目

[all_lessons]$ make clean
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3