-->

Makefile: all vs default targets

2020-08-14 10:09发布

问题:

Talking with respect to GNU make, what is the difference between PHONY targets all: and default:.

CC=g++
default: hello

hello: hello.cpp
     $(CC) -o hello hello.cpp

and

CC=g++
all: hello

hello: hello.cpp
     $(CC) -o hello hello.cpp

Both of them do the same job.

回答1:

You can call them shirley if you like; neither of the labels you mention has any special semantics. The default behavior of make is to run the first target in the Makefile if you don't specify a target as a command-line argument. If you like to override this behavior, there is the .DEFAULT: special target.

There is a convention to have a target named all which builds everything, but this is just human convention, not a special case or a requirement as far as Make is concerned.

Similarly, there is a (weak) convention to call the default target default, but similarly, this is just a human label (and somewhat overlaps and possibly conflicts with the all convention).

So the following Makefile does exactly the same thing:

.PHONY: shirley all default
default: hello
all: hello
shirley: hello

hello: hello.cpp
# (Make already knows how to build an executable out of a .cpp file)

You can omit any or all of the phony targets above, and the only difference will be that humans won't be able to say make shirley when they (effectively) mean make hello.

Bottom line: Construct your Makefile so that make does what a reasonable end-user expects without reading too much README files or inspecting the Makefile. Often that will be make all (and you should probably have a target with this name, just to satisfy human conventions, even if it's not the default) but this obviously depends on your project and your users' expectations.

Don't call me Shirley.



回答2:

The only difference, is that all is recommended in the GNU Make manual, to be the first (default) target, and default has no such special recommendation.



回答3:

One is spelled "all" and the other is spelled "default". There's no other difference between them. Maybe if you explained why you're asking we'd be able to help more.

Note that in your example above neither of the targets are actually phony. You'd have to declare them as such:

.PHONY: all

etc.