414 points · by DarkCrusader2 · 6y ago · 194 comments
foo.o: foo.c ; $(CC) $<
If you find $(@D) hard to remember then do $(dir $@) instead.I wrote a book about GNU Make stuff (https://nostarch.com/gnumake). If (and only if) you've read the GNU Make Manual from the FSF my book may help you. It's not for newbies. Don't want the book? All the articles are here: https://blog.jgc.org/2013/02/updated-list-of-my-gnu-make-art...
https://www.gnu.org/software/make/manual/html_node/One-Shell...
# Borrowed from https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
.PHONY: help
help: ## Display this help section
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z0-9_-]+:.*?## / {printf "\033[36m%-38s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
.DEFAULT_GOAL := help
.PHONY: load-terraform-output
load-terraform-output: ## Request the output JSON from Terraform
some commands
some more
It makes Makefiles a little more self documenting.Now I issue a `make` (or `make help`) to get a listing of the documented tasks. Very helpful.
define newline # a literal \n
endef
# Makefile debugging trick:
# call print-VARIABLE to see the runtime value of any variable
# (hardened a bit against some special characters appearing in the output)
print-%:
@echo '$*=$(subst ','\'',$(subst $(newline),\n,$($*)))'
.PHONY: print-*I eventually did something similar to that and built something alike to `make -p`, by hand, that was also a bit like `./configure` or CMakeCache.txt. It could then be read back into `make` and bypass a fair bit of configuration testing work (it's much faster on cygwin anyways). I got a bit too nervous at the automagical complexity though and never made a pull request (plus I only just fixed it to work on the old version of make that ships with macOS). But I thought perhaps you might find this fascinating for the levels of make hackery to try to untangle: https://github.com/JuliaLang/julia/compare/master...vtjnash:...
As an example, python has doc strings accessible via __doc__
$ python
>>> class foo:
... '''description of foo'''
...
>>> foo.__doc__
'description of foo'
>>> make -p
the main problem is that make itself doesn't support a concept of "hidden files". also a problem is that GNU make comes with lots of implicit rules, so you really need something like make -R -r -p for this to remotely work.I tried that on a small Makefile with 4 simple rules, and it spit out 2436 lines of diagnostic information. Which to be fair is less then `make -p`'s 8687 lines, but it's still completely useless to me.
But to get you started Chris Wellons does have a pretty nice blog post about writing POSIX Makefiles: https://nullprogram.com/blog/2017/08/20/
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/m...
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/m...
If you don't use anything that is not there, or in a manner not covered by a requirement, you will likely have a highly portable result.
Unhappily though, I think there are further portability issues, namely that when I create my BSDmakefile I am not sure that all the features I use would work with the versions of Make that come with OpenBSD, NetBSD, etc.
I mean, largely I don't do anything too crazy or fancy but the feeling is always there and I don't really have time/inclination to test every change with OpenBSD, NetBSD, etc since I don't normally use any of those other operating systems in the BSD family aside from FreeBSD which I do use.
For the last few years I've been using C less though, as I prefer Rust anyway. And for the times when I do end up creating a makefile I now usually create only a GNUmakefile. Supporting only GNU Make feels a little bad but I think in most cases people will have it installed even on FreeBSD, and at least naming it as GNUmakefile like is being suggested and as I am doing, does not waste peoples time trying to run other implementations of Make with those projects even if it might annoy them to install GNU Make.
A suggestion for naming makefiles GNUmakefile is a funny try to borderline, but it is late for around two decades and cannot have effect beyond boring. In technical terms, it is easier to rename BSDmakefiles rather than millions of projects out there.
$ uname -rs
Darwin 18.7.0
$ which make
/usr/bin/make
$ make --version
GNU Make 3.81
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
This program built for i386-apple-darwin11.3.0It's not dissimilar from early C programmers who wanted C to be more like Pascal and put things like this in headers:
#define BEGIN {
#define END }
and then never used curly braces. NO! DON'T DO IT!> Make leans heavily on the shell, and in the shell spaces matter. Hence, the default behavior in Make of using tabs forces you to mix tabs and spaces, and that leads to readability issues.
I agree with you in that replacing TAB with > makes things much less readable.
1) The original creator of Make plainly said that his original choice of tabs over spaces was accidental, and honestly a mistake. He just learned about (at the time) new tools lex and yacc for writing parsers and chose TAB as a line prefix for shell commands. Not much thought given really.
2) Tab in the very beginning of the line determines that the rest of the line is a command. However, the rest of that line goes into shell pretty much verbatim (modulo a few substitutions). Because of that, you may have tabs in the middle of that line, no problem, and they will be passed into the shell to execute!
3) To my knowledge, shells treat '\t' and ' ' the same way as whitespace. If anyone knows such differences, please let me know tho, I will correct myself. On the other hand, ">" is an important shell operator.
Macs don't have GNU make 4, only 3.81, so it's outright not portable with that > thingie.
By default, it’s installed as gmake to not conflict with the existing make 3.81.
[1]: https://brew.sh/
It all depends on the use case, but in some situations a cop out such as "just use Homebrew" is actively user hostile due to the amount of human friction it generates.
As it turns out, I've written bucketloads of portable (GNU and non-GNU) makefiles and never needed a post v3 feature.
Released April 1st, 2004.
That's usually the reason why Macs have outdated tools from Linux land.
Is there any point in supporting a platform which hasn't updated its major version of Make in over 15 years?
macOS Catalina now uses zsh.
steps up to you and whispers in your ear
Or you could, you know... use a real text editor.
I have been working with Makefile’s, with a team, for close to ten years and have never encountered anyone accidentally using spaces. I guess someone editing it via GitHubs web ui or something.
I added a makefile to a project that didn't yet have one, and I didn't have makefile support added in my IDE.
Got some weird, unhelpful errors when trying to run make, and eventually realised spaces were being used instead of tabs.
The solution was to configure my .editorconfig file to use tabs for makefiles, and as a nice-to-have, to also install a makefile plugin in my IDE.
The real solution is to not have your editor silently convert tabs to spaces, ever.
I don't work with make much anymore (or Python or Haskell), but I've come to see the use of invisible characters to express structure as a mistake. It can make code real neat and tidy looking, but I'm not sure the trade off is worth it. In the past I've resorted to actually having my editor show whitespace symbols to make sure code that looks aligned actually is aligned.
IMO, since Makefile has only one-level indentation for commands, this use of significant whitespace is rather benign, compared to Python.
Recently I was working on a project with multiple Makefiles, ie Makefile.{win,nix}. My Emacs config did not load makefile-mode due to the suffixes. As spaces are my default, I got spaces on TAB, iirc even after turning on makefile-mode.
It is your responsibility to let editors know that, be adding that magical first line to your make.
But you notice your mistake very quickly and I've never sent code to code review with spaces instead of tabs.
So, I configured my syntax highlighting to very subtly show whitespace characters. The editor keeps them consistent in every other case. Have never had the problem again since.
If you're going to rely on a fancy shell anyway, why not just throw make out of the loop altogether? That is, unless you're working on a big project where incremental builds really make a difference. (But IME, with a few exceptions, these are the projects that usually outgrow and abandon make anyway)
You can run cc via shell via make, or you can just run cc via shell. In the latter case, there's one less program (with quirks) to fight with, and more flexibility to do stuff that you can't easily bend make to do.
Instead of pushing for makefiles to become shell scripts for the part you mention, I usually implement such things as support scripts (in shell, python, whatever) - who often come in useful on their own - and call those from make targets. IOW using the best tool for each job, with make as the orchestrator.
My core argument is that this rarely matters, and in the cases it does, it is often the case that the project's needs surpass what make provides anyway. Or they're using a very special version of make with very special supporting infrastructure, like bsd.mk.
I'm compiling some 100k lines of legacy C (for a custom operating system) plus compat shims that make the thing run on Linux and my very very trivial build script (plain posix compatible shell) takes less than 5 seconds to run in debug mode. Optimized release builds are a bit slower, but this hardly matters in day to day development. It would be trivial to add some parallelism with xargs.
Fwiw I can compile the same thing with CMake, and it's faster only sometimes. It often happens that a header changes and everything needs to be built anyway. And it often happens that the parallelism bites me back when one file gives an error which scrolls out of sight as a dozen other files are still being compiled in parallel.
I've wasted far more time fighting subtly broken makefiles (that don't pick up some dependencies and thus fail to recompile the things that need to be recompiled), and build systems with fancy declarative languages that don't present an obvious way to do what you do in one line of shell when you don't need to worry about a dependency graph.
That said, I'm not a fan of the CMake scripting language, which is quirky and error-prone. It should be easy to write a new 'Find' module, but it's not. There should be officially documented design patterns to make the task trivial. There still aren't.
CMake gets the job done, but it's surprisingly difficult to work with.
</rant>
That's why /you/ don't need make. But there are plenty of 100k line projects that would take much longer, like nearly anything written in c++ for example.
In my personal experience 90% of Makefiles I come across not only don't take advantage of these, but actually have to actively employ workarounds to avoid these things. If you're taking advantage of the things make has to offer then by all means use make, but if all of your targets are .PHONY and you're having to turn off make features just so you can put all your bash scripts in one file then maybe just put your bash scripts in separate files.
So you are in agreement with your parent? He's suggesting make for these use cases.
The issue is that a lot of times people use Makefiles for putting convenient commands that have little to do with dependencies/incremental builds.
- I forget to add a dependency to the Makefile, I modify said file and notice that `make` doesn't do anything, hinting that something is wrong. If the build system rebuilds everything every time I probably won't notice the problem immediately.
- I edit code in a project but run make in the wrong location (because I'm working on two projects at one for instance). Again, make will tell me that there's nothing to do when I make changes.
- I run the latest build and it behaves in an unexpected way, I'm thinking that maybe I haven't actually built the last version of the source so the code I'm looking at isn't what's being executed. If I run "make" and I see that it starts rebuilding some artifacts I know that I'm out of date and need to try again. If nothing happens then I need to stop looking for excuse and actually start debugging.
- I pull code written by other people (or apply a patch, or unstash old changes). Running make will give me some insight on what parts of the codebase have been impacted. If I see that it's rebuilding something I didn't expect to change it'll probably catch my eye and get me to double check what happened.
So I definitely wouldn't trade a Makefile for a shell script, especially since if you build system can easily be replaced by a simple script you'll probably be able to do just fine with a very basic Makefile.
#!/bin/sh
set -e
case "$1" in
build)
;;
run)
;;
clean)
;;
*)
echo "unknown: $1"; exit 2
;;
esac
OR #!/bin/sh
set -e
test $# -gt 0
build() {
:
}
run() {
:
}
clean() {
:
}
"$@"
Personally, I find makefiles to be ubiquitous and well-understood, and if I want to do anything complex, I can always put that complexity in a shell script that's called by a make target.I think can still add value in that scenario as the standard project entrypoint. Someone completely new to the project should be able to `make help`, `make install`, etc. Even if the make targets are simple wrappers to project specific tooling (npm, pip, sbt, etc). If the Makefile is kept simple, then users can treat it as a form of README and should be able to cherry-pick from it as they see fit.
But yeah, I share your sentiment about quirky, non-portable Makefiles potentially being anti-value.
This is rare these days.. honestly at this point there's so much tooling already around that one can't really ever take that for granted. Almost always, I need to look for some readme or look around and figure out what build system is in use (sometimes it's a common system plus custom stuff so just seeing a name you recognize isn't automatically going to mean the standard invocation will work).
In this case, it hardly matters whether I'm going to run make or ./build or make help or ./build help. A simple script, which I'm advocating for simple projects, can double as a form of README just as a Makefile can.
> And you will never again pull your hair out because some editor swapped a tab for four spaces
How many editors out there in 2019 will automatically replace tabs with spaces by default? Unless you're editing makefiles in Microsoft Word or something, I don't see why a working code editor will do something you didn't tell it to do.
Vim, Emacs, Nano, Sublime Text, Kate/Kdevelop, Visual Studio/Code, Atom, Brackets, Text Mate, Scintilla/SciTE/Geany/etc, Programmers Notepad, CodeBlocks, Eclipse, and JetBrains all know not to mess with your tabs.
Rather than switch away from tabs so you can keep using a broken editor, the correct solution is to switch an editor that works. And if you configured your editor to replace tabs with spaces, and it doesn't give you an option to handle Makefiles differently, then that's a broken editor.
I generally use expandtabs in vim - but I still don't break makefiles. I suspect it's quite possible to force vim to expand tabs in makefiles.. But why would I want to?
> This disables the bewildering array of built in rules ...
Oh, wow, I totally disagree. It's good to be opinionated -- that is, unless you're wrong. ;)
In all seriousness I find it terribly useful to quickly create simple Makefiles and follow idioms like CFLAGS/CXXFLAGS/LDFLAGS/LDLIBS/etc.
https://www.gnu.org/software/make/manual/html_node/Suffix-Ru...
I have tried to teach make, but these implicit rules firing when I'm just trying to do a simple example can mask errors and create a lot of confusion.
Also, not looking at all the VCS versions of the file makes make run much faster, so being modular in what you imported would be a win for bigger systems too.
url_exists(http://example.com/file): file
rsync file example.com:/html
I've had a few attempts at this (most recently in 2013: https://people.redhat.com/~rjones/goaljobs/) but never really arrived at anything satisfactory.I'm using make to build a content graph, part of that is http:// dependencies. The underlying concept is that you can define protocols (https would be one) and then teach my make pre-parser about building them. An example would be:
myfile.js: https://code.jquery.com/jquery-3.4.1.js local.js
uglifyjs $^ -o $@
The 'https://' is rewritten to map to a local cache directory (so it's little more than a glorified variable, but still more intuitive since protocols are so familiar from our use of the web), so the above code is actually something like myfile.js: cache/https/code.jquery.com/jquery-3.4.1.js local.js
uglifyjs $^ -o $@
and that in turn invokes a rule that makes a HEAD request to the URL - if that is outdated against the local copy, that gets renewed. So, in regular make code, something like this: cache/https/%: cache/https/%.head
curl -Ls https://$* > $@
cache/https/%.head: cache/https/%.head.force
rsync --checksum $< $@
cache/https/%.head.force: FORCE
curl -Ls -I https://$* > $@
I could see a way to turn this around, though. The concept of "protocols" is currently only GET in my setup, but I do plan on supporting the idea of POST, eventually. So what you're asking for is that, I guess.I must say, though, that in my now three years of using (or abusing) make, "just make it another file" is surprisingly often the right next step. In the POST situation, it would simply be a local file that has direct or side-effects attached that do what you're expecting it to do.
This way it also often turns out that the "fetch"/"cache" part gets naturally separated from the rest, and that's super useful to track down any permanent or transitory issue.
It does get unwieldy after a certain size, but that's what I'm building tooling for.
My makefiles are beautiful... To me
And they're sure as sh!t not wrong, or they wouldn't work! :)
help: ## Show this help
@fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/##//'
foo: ## foo help
# make help will print the names of the targets with
# the help message following ##
I don't remember the source, I think I saw it in a stackoverflow question.Make's lack of hermeticity means that it's easy to accidentally craft a Makefile where there are dependencies between targets that are not explicitly listed in the Makefile. When this happens, you can't be sure that when you change an input file and run `make`, all the dependent targets will be rebuilt. This means you often have to `make clean; make` to make sure that things get correctly rebuilt.
Bazel also supports things like caching of artifacts so that when you build, switch branches, build, switch back, and build, it can re-use built artifacts from build #1 so that build #3 becomes a no-op. With remote caching, this can happen across computers and users; when user 1 builds at SHA 123, and then user 2 later checks out SHA 123 and does a build, user 2's build will simply copy the cached artifacts over the network and do no local work. (There is some operational overhead to maintaining this shared cache however).
That said, guides like this are really helpful for maintaining and extending existing make-based build systems!
I manage a couple of Yocto Linux-based firmware builds for my employer. Each project has a top-level Makefile that wraps the underlying build tools, so the build process is as easy as cloning the repo and running "make".
Make is also great for all of the post-build orchestration steps like "grab these files, rename this one, generate a little report, and make a tarball of the result". Steps that are each a little snippet of shell-script, and have some ordering dependency.
A 'build.sh' type shell-script would work too, but wouldn't include all of Make's built in features and dependency management. And you'd need to write stuff if you wanted it to parse specific target requests. At which point - why not just use Make?
So I guess I really like Make for the role of "be the top-level glue around other build systems". It includes dependency-management and file-generation rules, works out parallel ordering where possible, and comes with tab-completion on every desktop Linux.
Plus every developer who uses the command-line understands that a Makefile means "stuff can be built from inside this folder". They also probably know that "make" or "make all" is likely to run the build, "make install" will probably install it, and "make clean" will probably clean the folder. These conventions have deep staying power. And builds that follow them can be used by a lot of engineers with no further training or documentation required.
It’s surprisingly good for managing the build process for a web project that various build tools like Gulp, Grunt, etc. have been created to handle.
I finally ended up using npm scripts and it was easy to convert them into a Makefile.
Make is the standard and available everywhere, Bazel is not. Everyone can/should be able to debug Make. Bazel is yet another adhoc solution in a problem space full of adhoc solutions. Which is great if one needs the features that Bazel offers, but I dare say that the vast majority of projects out there do not and are better served by Make.
I love make, but a lot of this advice is targeted at being able to write "better" shell scripts in make. I don't recommend it. If you find yourself writing a shell for loop, you probably want instead to build a list of targets. If you find yourself wanting complex shell variable preparation, you probably instead want target-specific variables. ONESHELL is a good way to accidentally build some invisible dependencies into a recipe, and make it difficult to use custom functions or canned recipes.
If you do find yourself really wanting a shell, you'll probably also want "advanced" features like error traps, and you'll probably want to work with tools like shellcheck (imo critical for any shell script longer than one pipeline). Both are thwarted by baking the invocations into your make recipe. And the recipe still looks great - probably better! - if you extract any logic into a separate script (which then also opens up further possibilities, like including that tool itself in a shell pipeline in a make recipe).
I use it in cases where Makefiles would be a real mess to maintain and in general where I want to paralelize a set of file transforming jobs and have a nice progress indicator and ability to cancel and continue.
I just have a nice PHP generator class for ninja files and I build ninja files programatically in a real programming language based on whatever I like.
With this approach it's possible to fully parallelize builds accross however many different toolchains and SDKs with relative ease and without need to deal with quirks, or limitations of languages of various build systems or build tools that try to be semi-universal (like GNU make) but are not, or have a lot of non-obvious magic integrated.
And I also live how ninja tracks changes in its own build rules and automatically rebuilds targets that would be affected, which is what I always disliked about makefiles. If you change makefile rule you basically have to do `make clean ; make`.
I just wish https://github.com/ninja-build/ninja/pull/1578 would get merged, so I can compose ninjabuild repos seamlessly.
Moreover, Docker's caching implicitly allows to declare dependencies with a lot fewer headaches than make. On the downside, it is all to easy to write something that busts Docker's cache early in the build process, rendering `docker build` super-expensive.
So my opinionated tooling: docker, git (to extract project versions and inject them into the image), bash (to glue everything together). Everything else belongs inside the Docker build.
But yeah, all the actual work is in the Dockerfile.
out/image-id: $(shell find src -type f)
is that if you delete a file from src (without also modifying or adding a file), make won't consider image-id to need rebuilding out/foo:
> mkdir -p $(@D)
> …
I prefer to use this pattern, which lets you have many fewer `mkdir -p …` lines in the make output when you use it a bunch of times: out/foo: | out
> …
out:
> mkdir "$@"
(Here using the > recipe prefix from the article, though you won’t find me doing that in real life—I like my tabs.)No thanks.
If I could rewrite history, I would make those builtin rules nicely, explicitly, importable. No magic when I'm trying to teach make, please.
At most I've had to tinker with existing ones - in which case I wasn't motivated to make them more elegant, as opposed to replacing them with CMake generation.
But the problem is that building software is a lot more than just running a bunch of commands. The commands represent solutions to problems, but if the solutions aren't good enough, you just make more problems for yourself.
The biggest problems I've had with Makefile-based builds are getting everyone using the repository the right version of dependencies, and incrementality. A project I did at work involved protos, and it was great when I was the only person working on it. I had a Makefile that generated them for Go and Typescript (gRPC-Web) and usually an incremental edit to a proto file and a re-run of the Makefile resulted in an incremental update to the generated protos. Perfect. Then other people started working on the project, and sometimes a simple proto change would regenerate the entire proto. Sometimes the protos would compile, but not actually work. The problem was that there is a hidden dependency of the proto compiler, protoc-gen-(go|ts), and the language-specific proto API version that controls the output of the proto compilation process. Make has no real way to say "when I say protoc, I mean protoc from this .tar.gz file with SHA256:abc123def456..." You just kind of yolo it. Yolo-ing it works fine for one person; even if your dev machine gets destroyed, you'll probably get it working again in a day or two. As soon as you have four people working on it, every hidden dependency destroys a day of productivity. I just don't think it's a good idea.
Meanwhile, you can see how well automated dependency management systems work. Things like npm and go modules pretty much always deliver the right version of dependencies to you. With go, the compiler even updates the project definition for you, so you don't even have to manage files. It just works. This is what we should be aiming for for everything.
I have also not had much luck with incremental builds in make. Some projects have a really good set of Makefiles that usually results in an edit resulting in a changed binary. Some don't! You make a change, try out your binary, and see that it decided to cache something that isn't cacheable. How do you debug it? Blow away the cache and wait 20 minutes for a full build. Correctness or speed, choose any 1. I had this problem all the time when I worked on a buildroot project, probably because I never understood what the build system was doing. "Oh yeah, just clean out those dep files." What even are the dep files? I never understood how to make it work for me, even after asking questions and getting little pieces of wisdom that seemed a lot like cargo-culting or religion. Nobody could ever point to "here's the function that computes the dependency graph" and "here's the function that schedules commands to use all your CPUs". The reason is... because it lives in many different modules that don't know about each other. (Some in make itself, some in makefiles, some in the jobs make runs... it's a mess.)
Meanwhile, I've also worked on projects that use a full build system that tracks every dependency required to build every input. You start it up, and it uses 300M of RAM to build a full graph. When it's done it maxes out all your CPUs until you have a binary. You change one file, and 100% of the time, it just builds what depended on that file. You run it in your CI environment and it builds and the tests pass, the first time.
I am really tired of not having that. I started using Bazel for all my personal projects that involve protocol buffers or have files in more than one language. The setup is intense, watching your CPU stress the neighborhood power grid as it builds the proto compiler from scratch is surprising, but once it starts working, it keeps working. There are no magic incantations. The SHA256 of everything you depend on is versioned in the repository. It works with traditional go tools like goimports and gopls. Someone can join your project and contribute code by only installing one piece of software and cloning your repository. It's the way of the future. Makefiles got us far, but I'm done. I am tired of debugging builds. I am tired of helping people install software. "bazel build ..." and get your work done.
But realistically, Linux has captured 75% or more of the entire *nix market. A lot of developers spend their entire careers in Linux these days, and that trend isn't likely to swing back towards other Unix flavors anytime soon.
As long as a developer understands what users will be using their Makefile, it shouldn't matter if they target platform-specific features. The BSD ports tree uses a bunch of BSD Make features that aren't in GNU Make. And that's totally fine, because they know their target users.
Like let's say I'm writing a Makefile that wraps tools which don't run on anything other than Linux. Why would I care about portability across Make implementations?
If a dev doesn't know their users' environments (other than being POSIXy), probably they shouldn't be writing raw Make of any flavor. And if they do know their users, then it isn't a big deal to rely on some platform-specific features.