How does "make" app know default target to build if no target is specified?

Makefile

Makefile Problem Overview


Most Linux apps are compiled with:

make
make install clean

As I understand it, the make command takes names of build targets as arguments. So for example install is usually a target that copies some files to standard locations, and clean is a target that removes temporary files.

But what target will make build if no arguments are specified (e.g. the first command in my example)?

Makefile Solutions


Solution 1 - Makefile

By default, it begins by processing the first target that does not begin with a . aka the default goal; to do that, it may have to process other targets - specifically, ones the first target depends on.

The GNU Make Manual covers all this stuff, and is a surprisingly easy and informative read.

Solution 2 - Makefile

To save others a few seconds, and to save them from having to read the manual, here's the short answer. Add this to the top of your make file:

.DEFAULT_GOAL := mytarget

mytarget will now be the target that is run if "make" is executed and no target is specified.

If you have an older version of make (<= 3.80), this won't work. If this is the case, then you can do what anon mentions, simply add this to the top of your make file:

.PHONY: default
default: mytarget ;

References: https://www.gnu.org/software/make/manual/html_node/How-Make-Works.html

Solution 3 - Makefile

GNU Make also allows you to specify the default make target using a special variable called .DEFAULT_GOAL. You can even unset this variable in the middle of the Makefile, causing the next target in the file to become the default target.

Ref: The Gnu Make manual - Special Variables

Solution 4 - Makefile

bmake's equivalent of GNU Make's .DEFAULT_GOAL is .MAIN:

$ cat Makefile
.MAIN: foo

all:
	@echo all

foo:
	@echo foo
$ bmake
foo

See the bmake(1) manual page.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongrigoryvpView Question on Stackoverflow
Solution 1 - MakefileanonView Answer on Stackoverflow
Solution 2 - MakefileSamuelView Answer on Stackoverflow
Solution 3 - MakefileSandip BhattacharyaView Answer on Stackoverflow
Solution 4 - MakefileMateusz PiotrowskiView Answer on Stackoverflow