how.wtf

What does PHONY mean in a Makefile

· Thomas Taylor

What does .PHONY mean in a Makefile? The make manual describes the .PHONY target as,

A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request.

However, what does this mean?

What is .PHONY in a makefile?

By default, targets are “target files”. For the following rule,

1hello.txt: dependency.txt
2	echo "hello world" > hello.txt

make asks: “Is hello.txt out of date?” To determine if it is out of date, it follows the logic:

  1. If hello.txt exists, is dependency.txt more recent than hello.txt? If so, run the instructions.
  2. If hello.txt does not exist, run the instructions.
1> touch dependency.txt
2> make hello.txt
3echo "hello world" > hello.txt
4> make hello.txt
5make: 'hello.txt' is up to date.
6> echo "update" > dependency.txt
7> make hello.txt
8echo "hello world" > hello.txt

However, for targets that do not output files, a .PHONY label is used. In the following rule,

1.PHONY: format
2format:
3	gofmt -s -w .

the format target formats go code. It does not produce a file.

Why is .PHONY important in a makefile?

For some cases, .PHONY is not needed. For example,

1lint:
2	golangci-lint run

the lint target surfaces various code issues. As long as a file named lint does not exist (or will not exist in the future), this command will continue working. From the make perspective, lint will always be out of date since the file will never exist.

The .PHONY is only important if a target’s name can collide with a file name.

#makefile  

Reply to this post by email ↪