我的 Makefile 中的强制重建实际上是如何工作的?

How the forcing rebuild in my Makefile actually work?

How to force make to always rebuild a file from this answer更具体地说,我能够实现作为初学者的目标,所以我更好地评论了一切。

我在一个目录下有这4个文件; ls -F:

iterator  Makefile  test*  test.cpp

这里所有的文件应该都是不言自明的,但是我有点感觉,iterator听起来有点奇怪,所以为了crystal清楚,我想store/show 关于我重新编译了多少次 test.cpp 源代码的信息。

在这里我想礼貌地问一下 rebuild/recompile 的强制实际上是如何工作的?我不是 Makefile 方面的专家,所以总结一下。


这是我的实际 Makefile,完全没有变化:

CXX := g++-10
CXXFLAGS := -O2 -std=c++20 -Wall -Wextra -Werror -Wpedantic -pedantic-errors
APP_NAME := test
SRC_FILE := $(APP_NAME).cpp

# The following works!
# However, I have no idea how? :(
$(APP_NAME): .force_rebuild
.PHONY: .force_rebuild

$(APP_NAME): $(SRC_FILE)
# quickly delete terminal buffer
    @clear
# increase test number
    @expr $$(cat iterator) + 1 > iterator
# print test number description
    @printf '%s' "Test Nr.: "
# set bright cyan color for the number
    @tput bold; tput setaf 6
# print test number
    @cat iterator
# reset to normal terminal color
    @tput sgr0
# compile (always force rebuild)
    @$(CXX) $(CXXFLAGS) $(SRC_FILE) -o $(APP_NAME)
# run my test app
    @./$(APP_NAME)

为了完整起见,我在 Linux Mint 20.2 Cinnamon 上工作,Bash 作为 shell 和 VS Code 作为文本编辑器,使用 GNU Make 4.2.1。

旁注:如果没有语法高亮显示,它看起来很奇怪且可读性较差,这是唯一的原因我还附上了截图:

来自the manual

One file can be the target of several rules. All the prerequisites mentioned in all the rules are merged into one list of prerequisites for the target. If the target is older than any prerequisite from any rule, the recipe is executed.

在您的情况下,您有两个应用目标规则。第一条规则中的先决条件 .force_rebuild 被标记为 .PHONY,这使得您的应用程序目标始终早于 .force_rebuild。这会触发应用程序目标的配方执行。该食谱在第二条规则中。

以防万一,还要指出上面引述之后的段落:

There can only be one recipe to be executed for a file. If more than one rule gives a recipe for the same file, make uses the last one given and prints an error message.