如果当前目录中已存在名为 target 的文件,则在没有 .PHONY 的情况下构建目标

May*_*ank 4 makefile

在查看 MakeFiles 时,我发现当名为 target 的文件存在时,即使不使用 .PHONY,目标也会被构建。但是,当我对另一个目标(即 clean)执行相同操作时,目标不会被构建并说“clean 是最新的”,这是可以的。我只想知道当文件存在于当前目录中时为什么要构建另一个目标。

生成文件:

CC:= gcc
CCFLAGS:=-Wall -Wextra
hello: hellomake.o hellofunc.o
        $(CC) $(CCFLAGS) hellomake.c hellofunc.c -o file
hellomake.o : hellomake.c
        $(CC) $(CCFLAGS) -c hellomake.c
hellofunc.o : hellofunc.c
        $(CC) $(CCFLAGS) -c hellofunc.c
clean:
        rm -rf *.o
        rm -rf file
Run Code Online (Sandbox Code Playgroud)

我当前的目录有一个与目标名称相同的文件,如“hello”。它应该给出结果为“hello is up-to-date”,但它没有这样做并将输出给出为:make hello

gcc  -Wall -Wextra  hellomake.c hellofunc.c -o file 
Run Code Online (Sandbox Code Playgroud)

请说明当目标不是 .PHONY 并且名为目标的文件已存在于当前目录中时,为什么要构建目标。

enr*_*cis 5

因为make查看最后修改时间来决定构建什么。从make手册中:

\n\n
\n

make程序使用 makefile 数据库和文件的最后修改时间来决定哪些文件需要更新。

\n
\n\n

该命令make检查目标与其先决条件之间的时间关系。如果在目标之后修改了先决条件,则意味着目标已过期,并且即使文件存在,也会触发重建。因此很可能您的依赖项已在目标之后被修改。

\n\n

为了避免这种行为,您可以:

\n\n
    \n
  • 用于touch更改目标时间戳。
  • \n
  • 在调用之前使用make -t hello或。来自文档make --touch hellomake hello
  • \n
\n\n
\n
\xe2\x80\x98-t\xe2\x80\x99\n\xe2\x80\x98--touch\xe2\x80\x99\nMarks targets as up to date without actually changing them. In other words,\nmake pretends to update the targets but does not really change their\ncontents; instead only their modified times are updated.\n
Run Code Online (Sandbox Code Playgroud)\n
\n