Makefile伪目标是什么意思?

看了一些文章,对伪目标的描述也不尽相同,下面有两个示例和解释:

示例1:

.PHONY: install
install:
    cp hello /usr/local/bin/hello

伪目标 install 表示即使当前文件夹内有 install 这个文件,但是 make 执行的仍然是 Makefile 内部的 install,不会使用外部的文件,相当于进行了一个内部封装。

示例2:

all: gotool
    @go build -v .
clean:
    rm -f apiserver
    find . -name "[._]*.s[a-w][a-z]" | xargs -i rm -f {}
gotool:
    gofmt -w .
    go tool vet . |& grep -v vendor;true
ca:
    openssl req -new -nodes -x509 -out conf/server.crt -keyout conf/server.key -days 3650 -subj "/C=DE/ST=NRW/L=Earth/O=Random Company/OU=IT/CN=127.0.0.1/emailAddress=xxxxx@qq.com"

help:
    @echo "make - compile the source code"
    @echo "make clean - remove binary file and vim swp files"
    @echo "make gotool - run go tool 'fmt' and 'vet'"
    @echo "make ca - generate ca files"

.PHONY: clean gotool ca help



上面的 Makefile 文件中,.PHONY 是个伪目标,形式上是一个目标,但是不需要依赖,伪目标一般只是为了执行目标下面的命令(比如 clean 就是伪目标)。

问题:
没有太理解上面说的伪目标,请大佬再帮解释一下,谢谢大佬。

阅读 4.3k
2 个回答

Makefile 默认会认为目标应该对应于一个文件,这会造成什么问题呢?

假设我们有一个 Makefile:

clean:
    ...

假如当前目录下有一个名为 clean 的文件。根据上述规则,该文件存在且没有什么依赖,那么执行 make clean 的时候该文件不需要更新,clean 条目下的命令都不会被执行。

这当然不是我们想要的结果,因此我们给它指定一下 .PHONY: clean 这样 make 不会去根据文件的存在、新旧而考虑是否要跳过它。