How make
Reads a Makefile
GNU make does its work in two distinct phases. During the first phase it reads all the makefiles, included makefiles, etc. and internalizes all the variables and their values and implicit and explicit rules, and builds a dependency graph of all the targets and their prerequisites. During the second phase,
make
uses this internalized data to determine which targets need to be updated and run the recipes necessary to update them.It’s important to understand this two-phase approach because it has a direct impact on how variable and function expansion happens; this is often a source of some confusion when writing makefiles.
We say that expansion is immediate if it happens during the first phase:
make
will expand that part of the construct as the makefile is parsed. We say that expansion is deferred if it is not immediate. Expansion of a deferred construct part is delayed until the expansion is used: either when it is referenced in an immediate context, or when it is needed during the second phase.How Makefiles Are Parsed
GNU
make
parses makefiles line-by-line. Parsing proceeds using the following steps:- Read in a full logical line, including backslash-escaped lines.
- Remove comments.
- If the line begins with the recipe prefix character and we are in a rule context, add the line to the current recipe and read the next line.
- Expand elements of the line which appear in an immediate expansion context.
- Scan the line for a separator character, such as ‘:’ or ‘=’, to determine whether the line is a macro assignment or a rule.
- Internalize the resulting operation and read the next line.