为什么 'touch' ing makefile 连同所有源文件不重建任何东西?我该如何解决这个问题?

Why does 'touch' ing makefile along with all source file does not rebuild anything? How can I solve this?

我有一些源文件,例如 file1file2file3 以及 Makefile:

tar: file1 file2 file3
    @echo hello

现在当我 touch file1 时,它会重建 file1tar

但是当我 touch 所有源文件和 Makefile 时,它不会重建任何东西。它应该重建所有源文件。为什么会这样?

简单的解决方案是 touch 除了 Makefile 之外的所有文件,但是当我说 20 个源文件时就变得困难了。解决方法是什么?

make 的工作方式是比较 target 和源上的时间戳。规则的一般格式为:

target: source(s)
    action(s)        

在这种情况下,当您 运行 make 时,它会查看 target 的时间戳 (tar) 并询问该时间戳是否早于任何来源的时间戳(filefile2file3)。如果 target 比任何源都旧,那么它被认为是过时的,这会触发规则对 运行.

的操作

问题是这条规则除了回显输出外什么都不做。在 运行s 之后,tar 仍然具有与之前相同的时间戳。下次你 运行 make 时,它会做同样的事情,因为 starting 条件(时间戳)没有改变。

您可以通过将规则触摸 tar 文件作为其操作之一来使此工作按预期进行。

tar: file1 file2 file3
    @touch tar
    @echo hello

现在它应该按预期运行。

$ make
make: `tar' is up to date.
$ touch file3    
$ make
hello
$ make
make: `tar' is up to date.

当然,在典型的 Makefile 中,您的规则会做的不仅仅是 echo。如果它正在构建某些东西,通常规则的 target(在本例中为 tar)会因构建操作而被修改,因此通常不需要显式使用 touch