Why use makefiles over shell scripts?
Created
Modified
Published
Are makefiles worth using? Some would say no, it’s better to stick with shell scripts, such as this Hacker News comment about build systems for Node.js:
Why even use Make? I just use shell scripts for automation.
The only case where you really need the incremental behavior of Make is C/C++ builds (and arguably it’s increasingly inappropriate for this domain as well). For all other kinds of automation I just use shell scripts, since Make is mostly a horribly reinvented shell script dialect.
— chubot on Feb 3, 2014
Why indeed? I can remember asking this question myself when I first learned about makefiles. “Ugh, why do I have to learn another tool to build other people’s software? It’s hard enough debugging a shell script.”
Let’s look at the original paper by the author of make:
Consider the plight of a modern programmer. Following the dictates of software engineering, he has divided his project into a number of sensible modules. He makes use of all the tools he can. Common data structure descriptions and constants are entered just once and are shared by the relevant programs. An automatically generated parser analyzes the input. The complicated logic is specified in decision tables. The output is guided by a formatter.
Now he decides to make a small change to a data structure. How does he regenerate his program? One possibility is to “recompile everything in sight”. It may not be easy to put together the monster command sequence he needs. Doing all this work too often will certainly break the budget, since those marvelous tools aren’t free. Alternately, he may think hard and deep, decide exactly which parts are affected by the change, figure out the sub-sequence needed to do the processing, and go to work. He has saved machine time, but if he has forgotten just one module, he now has a bug that may take days to find.
These difficulties affect projects of all sizes. Even in a simple card environment, it is hard to remember which object decks are good and which are bad. In a large project with many people working on related pieces of a product, it is very likely that parts will become inconsistent. What is needed is a mechanism for keeping track of the status of the parts of a program, and for executing an efficient control sequence to ensure that the end product is correctly made from consistent pieces.
[ … ]
The Make program has been in heavy use since 1975. The major implementation runs under the UNIX [2] operating system on PDP-11, VAX-11, and Interdata 8/32 computers, but a version is also available for the Honeywell 6000 GCOS. The following descriptions refer to the version running on UNIX systems, but we also discuss possible implementations in other environments.
— Stuart I. Feldman, “Make – A Program for Maintaining Computer Programs”, 1979
https://doi.org/10.1002/spe.4380090402
Although the word “incremental” does not appear in this paper, Feldman is describing the benefits of what we now call an incremental build, where the programmer can write down the dependency graph and use software to check which dependencies are out of date instead of needing to remember or reconstruct and manually rebuild. This is particularly important for compiled languages like C that generate binary object files and a final executable, in contrast to scripting languages like Python that (in general) run an interpreter directly on the source code. The significance of this problem is laid out colorfully in a quote from Feldman in The Art of Unix Programming:
Make originated with a visit from Steve Johnson (author of yacc, etc.), storming into my office, cursing the Fates that had caused him to waste a morning debugging a correct program (bug had been fixed, file hadn’t been compiled, cc *.o was therefore unaffected). As I had spent a part of the previous evening coping with the same disaster on a project I was working on, the idea of a tool to solve it came up. It began with an elaborate idea of a dependency analyzer, boiled down to something much simpler, and turned into Make that weekend. Use of tools that were still wet was part of the culture. Makefiles were text files, not magically encoded binaries, because that was the Unix ethos: printable, debuggable, understandable stuff.
— Stuart Feldman
http://www.catb.org/esr/writings/taoup/html/ch15s04.html
Feldman also mentions that even in the early 1970s this was not a new idea[1]:
Earlier programs have done related tasks. For example, the Rapid Program Generator [3] on the PDP-10 will automatically recompile if a source file is present but the associated object is either missing or older. However, Make is a more general and complete approach to the problem.
[ … ]
[3] Ralph E. Gorin, ‘RPG Rapid Program Generator’, Stanford Artificial Intelligence Laboratory Operating Note 51.1 (1973).
https://doi.org/10.1002/spe.4380090402
But 1979 was 40 years ago! In 2019, machine time is cheap. For smaller or medium-size projects, we generally can “recompile everything in sight” without waiting too long. Besides, shell languages have become more featureful and portable. We can even run Bash scripts on Windows these days. Have makefiles become superfluous?
I used to think so so, but having familiarized myself with make a little, I’ve changed my mind. While I don’t know enough to discuss make’s merits in comparison with other build systems, I do find makefiles have advantages over shell scripts in many respects.
- A specific example
- Why makefiles are better than shell scripts
- Standard invocation.
- Explicit dependency graph.
- Built-in argument handling.
- Built-in autocompletion.
- Built-in timestamp comparison.
- Shows executed commands by default.
- Halts by default on error.
- Built-in parallelism.
- Delete on error
- Built-in patterns and string processing functions.
- Make builds on top of shell
- Some problems with Make
- Summary
A specific example
Rather than speaking in generalities, let’s look at a specific example. I don’t often need to write a C program from scratch, but I do often need to convert text files written in markup languages to other formats like HTML or PDF. The most basic version of this is using the markdown command to convert a Markdown file to HTML:
markdown example.md > example.html
This follows the same general pattern as generating object files or executables from C source code.
Makefile version
Here is the makefile I use for converting Markdown files to HTML:
MARKDOWN :=$(wildcard *.md) HTML :=$(patsubst %.md,%.html, $(MARKDOWN)) .PHONY : all clean all: $(HTML) %.html: %.md markdown "$<" > "$@" clean: rm -f -- $(HTML)
If you’re unfamiliar with make syntax, this is approximately what the makefile does:
Make a list of files having filenames ending with .md
MARKDOWN :=$(wildcard *.md)
In a directory with three markdown files 01.md, 02.md, and 03.md this is equivalent to
MARKDOWN :=01.md 02.md 03.md
Make a list of HTML filenames, which are the same as the markdown filenames but replacing the .md file extension with .html instead.
HTML :=$(patsubst %.md,%.html, $(MARKDOWN))
Continuing our previous example this is equivalent to
HTML :=01.html 02.html 03.html
Targets all and clean aren’t files, they’re just arbitrary names, so don’t try to find a file called all or clean or compare the modification time with anything.
.PHONY : all clean
By default, generate all HTML files.
all: $(HTML)
This would expand to
all: 01.html 02.html 03.html
To generate an HTML file such as 01.html, replace the .html in the filename with .md and then check if the markdown file is newer.
%.html: %.md
The % is how we use Make feature called a pattern rule that saves us from writing out a different rule for each file like this:
03.html: 03.md markdown 03.md > 03.html 02.html: 02.md markdown 02.md > 02.html 01.html: 01.md markdown 01.md > 01.html
If the HTML file does not exist or the Markdown file is newer, run the markdown command on the Markdown file and send the output to the corresponding HTML file.
%.html: %.md markdown "$<" > "$@"
The second line is the recipe line that is interpreted by the shell, so it’s fine to use shell syntax like > here. However before passing to the shell, Make expands $< to the first dependency (i.e. %.md) and expands $@ to the target (i.e. %.html). (Here we see that makefile syntax can be quite compact but also a bit cryptic.) So for 01.html would be equivalent to
01.html : 01.md markdown "01.md" > "01.html"
To clean generated files, delete all the HTML files with the rm command.
clean: rm -f -- $(HTML)
The -f prevents showing an error if no such files exist. If 01.md, 02.md, and 03.md are present this is equivalent to
clean: rm -f -- 01.html 02.html 03.html
Note $(HTML) is only the HTML files with corresponding markdown files, so this rule will not delete an unpaired HTML file like index.html or tmp.html This is what distinguishes this operation from rm -f -- *.html which uses shell globbing to delete all files ending in .html regardless of whether they are paired with a .md file.
Shell version
The markdown-to-HTML operations map nicely to a shell script: there are no multiple dependencies to check and there are only two explicit targets: all and clean. However, a comparable shell script is still non-trivial to write. I’m using GNU make 4.1 with GNU bash 4.4.19. Here is what a roughly comparable build script could look like in bash:
#! /usr/bin/env bash
function all() {
for markdown_file in *.md
do
local html_file=${markdown_file%.md}.html
if test "$html_file" -ot "$markdown_file"
then
markdown "$markdown_file" > "$html_file"
fi
done
}
function clean() {
declare -a markdown_files
declare -a html_files
markdown_files=(*.md)
html_files=("${markdown_files[@]/%.md/.html}")
rm -f -- "${html_files[@]}"
return $?
}
if test $# -eq 0
then
all
exit $?
elif test "$1" = "all"
then
all
exit $?
elif test "$1" = "clean"
then
clean
exit $?
else
printf "Error: unknown argument(s) '%s'\n" "$*"
exit 1
fi
It’s already considerably longer than the makefile, but on the surface it looks like it provides similar functionality. It also has the upside of correctly handling spaces in filenames, but it has many downsides that the makefile does not.
The first and most glaring problem is that the makefile generates a real dependency graph and accepts arbitary filenames, like this:
$ make 01.html
markdown 01.md > 01.html
The shell script, on the other hand, doesn’t actually know about dependency graphs or filenames. All it can do is build all the files, it can’t build a single requested HTML file:
$ ./build.sh 01.html
Error: unknown argument(s) '01.html'
Actually figuring out what filenames can be built and whether they actually need to be built would be messy, so I skipped it.
Here’s another defect: make prints each command as it is run, like this:
$ make
markdown 02.md > 02.html
markdown 03.md > 03.html
markdown 01.md > 01.html
$ make clean
rm -f -- 02.html 03.html 01.html
Without this output, it can be very difficult to determine what a build script is doing and debug it if something is wrong. Tracing the build script is non-trivial, since we have to decide what gets printed and what doesn’t. One way is to use strategically chosen set -x statements:
function all() {
for markdown_file in *.md
do
local html_file=${markdown_file%.md}.html
if test "$html_file" -ot "$markdown_file"
then
set -x
markdown "$markdown_file" > "$html_file"
{ set +x ;} 2> /dev/null
fi
done
}
function clean() {
declare -a markdown_files
declare -a html_files
markdown_files=(*.md)
html_files=("${markdown_files[@]/%.md/.html}")
set -x
rm -f -- "${html_files[@]}"
{ set +x ;} 2> /dev/null
return $?
}
The output looks like this:
$ ./build.sh
+ markdown 01.md
+ markdown 02.md
+ markdown 03.md
+ markdown 'filename with spaces.md'
$ ./build.sh clean
+ rm -f -- 01.html 02.html 03.html 'filename with spaces.html'
The + signs at the beginning of each line are unavoidable. We could try to manually print the command that is going to be run, but now the onus is on us to do it correctly:
function all() {
for markdown_file in *.md
do
local html_file=${markdown_file%.md}.html
if test "$html_file" -ot "$markdown_file"
then
printf 'markdown %s > %s\n' "$markdown_file" "$html_file"
markdown "$markdown_file" > "$html_file"
fi
done
}
function clean() {
declare -a markdown_files
declare -a html_files
markdown_files=(*.md)
html_files=("${markdown_files[@]/%.md/.html}")
local args
printf -v args '%q ' "${html_files[@]}"
printf 'rm -f -- %s\n' "${args}"
rm -f -- "${html_files[@]}"
return $?
}
The output:
$ ./build.sh
markdown 01.md > 01.html
markdown 02.md > 02.html
markdown 03.md > 03.html
markdown filename with spaces.md > filename with spaces.html
$ ./build.sh clean
rm -f -- 01.html 02.html 03.html filename\ with\ spaces.html
(That last part isn’t really accurate, because we aren’t really using backslashes to escape the filename. Oh well.) Note that we can’t simply use printf on an array. If we write clean like this:
function clean() {
declare -a markdown_files
declare -a html_files
markdown_files=(*.md)
html_files=("${markdown_files[@]/%.md/.html}")
printf 'rm -f -- %s\n' "${html_files[@]}"
rm -f -- "${html_files[@]}"
return $?
}
then we get this output:
$ ./build.sh clean
rm -f -- 01.html
rm -f -- 02.html
rm -f -- 03.html
rm -f -- filename with spaces.html
because of the way printf iterates through arguments, even though the shell is actually only invoking rm once.
Bash has the advantage of built-in arrays, so that these are roughly comparable:
MARKDOWN :=$(wildcard *.md)
HTML :=$(patsubst %.md,%.html, $(MARKDOWN))
markdown_files=(*.md)
html_files=("${markdown_files[@]/%.md/.html}")
The standard POSIX shell does not have arrays, which would make this trickier. But now suppose we also wanted to add parallel execution. In make, this is easy with the -j / --jobs flag. If we want three jobs to run in parallel, we pass -j 3 to make.
$ make -j 3
markdown 02.md > 02.html
markdown 03.md > 03.html
markdown 01.md > 01.html
In bash, using an arbitrary number of jobs is pretty easy, we put a & on the end of a line to make it run in the background and add wait after the for loop:
function all() {
for markdown_file in *.md
do
local html_file=${markdown_file%.md}.html
if test "$html_file" -ot "$markdown_file"
then
set -x
markdown "$markdown_file" > "$html_file" &
{ set +x ;} 2> /dev/null
fi
done
wait
}
but explicitly setting the number of jobs without falling back on e.g. GNU parallel is difficult and would almost certainly be difficult to debug. This won’t matter for a directory containing three markdown files, but it will for a directory containing thousands of markdown files.
Perhaps this is why all but the simplest projects use a build system rather than a shell script. This standardization also has larger benefits.
In 1998 Oracle ported its market-leading database product to Linux, in a move that was rightly seen as a major breakthrough in Linux’s mainstream acceptance. The engineer in charge of the port provided a definitive demonstration that API standards had done their job when he was asked by a reporter what technical challenges Oracle had had to surmount. The engineer’s reply was “We typed ‘make’.”
Why makefiles are better than shell scripts
With this example in mind, let’s write out some ways that makefiles make things easier than plain shell scripts.
Standard invocation.
If I want to compile an unfamiliar code base using its provided shell script, what is it called? Is it make.sh, build.sh, rebuild.sh, compile.sh, run.sh, all.sh, or something else? Does it expect any positional arguments or special environment variables? Does it matter what directory I run it from?
By contrast, with Make I just look for a file called Makefile and then type make. To get back to a “clean” state without any generated files I can use make clean, and to run unit tests make test. These commands are familiar even outside the C/C++ ecosystem and the idioms they represent have become de facto standards.
Explicit dependency graph.
Makefiles provide an explicit dependency graph between files via rule targets and prerequisites. Even when everything can be re-compiled quickly, this is useful for tracking internal and external dependencies, refactoring, and deciding what should be tracked in version control. This explicit dependency graph is especially important in conjunction with other features, such as parallel execution, argument handling, and timestamp comparison.
Built-in argument handling.
For example, make out.html generates out.html and make clean runs the clean recipe without needing to add logic for handling each of those arguments. In even a simple shell script, it is not trivial to properly handle arguments and iterate over them.
Built-in autocompletion.
Bash and other shells with autocompletion have provided scripts to make autocomplete work with arbitrary makefiles, which is not true for arbitrary shell scripts. For example, make c<Tab> autocompletes to make clean, even though the makefile in the current directory doesn’t have its own custom bash autocompletion script. This is a nice tooling and quality of life feature that I find myself using often.
Built-in timestamp comparison.
Shells like Bash do have the -nt flag for “newer than” and the -ot flag for “older than” (e.g. test file1 -ot file2 is true if file1 is older than file2). However these flags are not part of the POSIX standard, and even for shells with this feature it only works for one-to-one comparisons so a lot of additional logic is required for handling an arbitrary number of targets and dependencies.
Shows executed commands by default.
One thing that make does well is it shows exactly what command is run after all the expansions and substitutions are done. This is surprisingly difficult to do in shell. Bash can do tracing with set -x (a.k.a. xtrace), but this will intermingle the executed commands with all the rest of the build script logic.
Halts by default on error.
As soon as one command exits with a non-zero status, make will halt the build process. (Make can also be instructed to ignore the non-zero exit status by prepending a - to the command.) By contrast, shell scripts do not halt on error by default. Bash can be configured to do so with set -e (a.k.a. errexit), but this comes with its own set of caveats.
Built-in parallelism.
Builds can often run faster if independent parts are run in parallel. In part because of the explicit dependency graph, make has this functionality built in. For example, using four cores is as simple as make -j 4.
Delete on error
Make automatically removes a generated file if the command to generate it exits with an error. For example, if you use Ctrl-C to interrupt a process that generates out.txt, it will say make: *** Deleting file 'out.txt'
https://stackoverflow.com/questions/588550/why-does-gnu-make-delete-a-file
If make gets a fatal signal while a shell is executing, it may delete the target file that the recipe was supposed to update. This is done if the target file’s last-modification time has changed since make first checked it.
https://www.gnu.org/software/make/manual/make.html#Interrupts
Usually when a recipe line fails, if it has changed the target file at all, the file is corrupted and cannot be used—or at least it is not completely updated. Yet the file’s time stamp says that it is now up to date, so the next time make runs, it will not try to update that file. The situation is just the same as when the shell is killed by a signal; see Interrupts. So generally the right thing to do is to delete the target file if the recipe fails after beginning to change the file. make will do this if .DELETE_ON_ERROR appears as a target. This is almost always what you want make to do, but it is not historical practice; so for compatibility, you must explicitly request it.
Built-in patterns and string processing functions.
Example: bash does not have a built-in equivalent to filter-out.
https://www.gnu.org/software/make/manual/html_node/Text-Functions.html
Make builds on top of shell
It’s worth pointing out at this point that Make gives us all of its functionality without losing the features the shell gives us. The recipe line for a makefile rule is just a shell script, with full access to shell syntax and behavior. Make doesn’t try to replace shell scripts, it wraps shell scripts in a file with a different syntax that specifies a dependency graph. This means the shell can still be used for all the things its good at, such as pipes, IO redirection, and interactive testing. Make is a widely available (though not quite as widely as shell) and part of the POSIX standard, and permits switching between shells if the default /bin/sh shell is inadequate.
This comes at the cost of syntactic complexity: non-trivial makefiles generally need to interpolate variables into the recipe line, and the mixture of makefile and shell syntax can be confusing. For example, make uses $(VARIABLE) for parameter expansion, whereas Bash uses $VARIABLE or ${VARIABLE} for parameter expansion but $(command) for command substitution. Even more confusing, in a Makefile recipe $@ expands to the target, but in Bash $@ expands to the arguments passed to the script. If we want to save a variable and expand it later things get even more complicated. (I think this is what chubot means by “horribly reinvented shell script dialect”.) However parameter expansion in shell syntax is already complex, so for people already willing to use shell scripts drawing the line at makefile syntax isn’t a very compelling argument.
Some problems with Make
At this point it should be clear that Make is not without flaw. We’ve already noted that mixing makefile variable interpolation with shell syntax can be confusing. I’ll note just a few of the issues that I’ve noticed, but this is by no means complete.
Not installed by default
Bash is available by default on almost all Linux distributions, and a Bourne-compatible shell is always available on other Unix-based operating systems like MacOs and the BSD family. However, Make is not installed by default on most Linux distributions as it is considered a developer tool, not a core utility. (This is why system administrators tend to rely on the lowest common denominator of shell scripts and core utilities like ls and top.)
Mandatory tabs for recipe lines
Makefiles have another common issue that’s unique to their syntax of using tabs to begin recipe lines: distinguishing the whitespace characters like tab characters and space characters is confusing to the uninitiated, and tabs often don’t survive re-typing or pasting into a browser text box. (It was even tricky for me to preserve hard tabs in this blog post.) The tab characters exist in Make today only because of backward compatibility:
Why the tab in column 1? Yacc was new, Lex was brand new. I hadn’t tried either, so I figured this would be a good excuse to learn. After getting myself snarled up with my first stab at Lex, I just did something simple with the pattern newline-tab. It worked, it stayed. And then a few weeks later I had a user population of about a dozen, most of them friends, and I didn’t want to screw up my embedded base. The rest, sadly, is history.
— Stuart Feldman, as quoted in “The Art of Unix Programming”
Can’t handle spaces in filenames
Make still doesn’t handle spaces in filenames, which can be problematic.
Confusing syntax for variable expansion
The interpolation rules are questionable, especially in more complex areas like secondary expansion.
Because dollar signs are used to start make variable references, if you really want a dollar sign in a target or prerequisite you must write two of them, ‘$$’ (see How to Use Variables). If you have enabled secondary expansion (see Secondary Expansion) and you want a literal dollar sign in the prerequisites list, you must actually write four dollar signs (‘$$$$’).
https://www.gnu.org/software/make/manual/html_node/Rule-Syntax.html
Summary
The original motivation for Make was to provide automatic incremental builds, and it remains in widespread use over forty years later. In comparison to an ad hoc shell script, it has several key advantages, both in terms of efficiency and ergonomics. Today there are many alternatives to Make, and the proliferation of these new build systems indicates that make is not ideal for all use cases. Make remains the lowest common denominator, though, especially in the world of Unix-based operating systems.
Further reading:
Makefiles are machine-readable documentation that make your workflow reproducible.
https://bost.ocks.org/mike/make/
When you update some part of the program, it only rebuilds the parts that depend on that. While you could do this with a shell script, it would be a lot more work (explicitly checking the last-modified dates on all the files, etc.) The only obvious alternative with a shell script is to rebuild everything every time
— Jerry Coffin, Sep. 26, 2010
https://stackoverflow.com/questions/3798562/why-use-make-over-a-shell-script
If I worked with just one language, this might be acceptable to me but my work crosses a lot of domains and at the end of the day, only Make seems to pull it all together. I’m not saying it’s perfect (far from!) but the fractured and incomplete landscape of contenders effectively makes them all non-starters.
— u/Steltek, Feb. 24, 2013
https://www.reddit.com/r/programming/comments/195iz1/why_use_make/
Addendum 2019-07-06:
Aside from builds, make is very useful–regardless of language–for running commands according to a dependency graph. Sometimes, it’s even nice to use (without dependencies) as a repository for useful script snippets.
— OhhhhYeaaaaah, 2019-07-05 21:42:28
https://lobste.rs/s/kz20ed/my_experience_learning_make
I got the following impression of it: makefiles define dependencies between generated and manually edited files, and how those dependencies manifest (that is, how you get from the manually written files to the generated ones). The connection to C becomes obvious once you think about C programming in those terms: first you manually edit the C source code, then you generate object files out of that, and then you generate a final executable from those.
https://blog.neon.moe/2019/07/06/make.html
| [1] | There is an HTML version of Ralph E. Gorin’s description of RPG here:
https://www.saildart.org/RPG.REG[S,DOC] The program appears to date back at least to 1968 and also lists Richard Cruen as a contributor:
|