188 points · by kiyanwang · 10y ago · 194 comments
From this perspective, a well structured Makefile can be thought of as a pipeline/graph of functions, that derive values (files) from previously known values (files).
Expressing a build process in this kind of way makes it possible to support incremental / distributed build in a fairly natural / obvious way.
It is less obvious how to support incremental / distributed builds for the more general kind of imperative build script that does a bunch of side effects (e.g. the style of build script you'd get using something like ant).
The syntax is simple:
.PHONY: all clean install
marks "all", "clean" and "install" as phony. Even if the file "all" happens to exist, "make all" will still trigger the build. .PHONY: all
all: ...
.PHONY: clean
clean: ...To be clear, they will rebuilt only if they are not already up to date relative to their own dependencies, right?
Phony is only about making sure that 'all' is seen as target, not as file or folder
help:
@grep -P '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'
Assuming that the trimmed Makefile read: build: ## Build the binary
clean: ## Clean the binary and intermediate files
distclean: clean ## Clean dependencies, intermediate files and binary
deps: ## Install dependencies
all: deps build ## Get dependencies and build binary
release: distclean all ## distclean + all
Now issuing make help would display: all Get dependencies and build binary
build Build the binary
clean Clean the binary and intermediate files
deps Install dependencies
distclean Clean dependencies, intermediate files and binary
release distclean + allSecond, if you're on OS X the `-P` flag is going to have problems [1]. Works fine if you just replace `grep -P` with something like `ack`!
help:
@awk -F ':.*##' '$$0 ~ FS \
{printf "%15s%s\n", $$1 ":", $$2}' \
$(MAKEFILE_LIST) | sortSeriously, thanks. You solved a problem I had.
Meanwhile they'll merrily pile up a thousand node modules into a towering pillar of bad, just to run the equivalent of a shell one-liner, and call it a job well done.
Tools that gain traction today are those that can be learned incrementally by doing a google search and copy pasting a solution, one problem at a time.
Out are all those systems that have an underlying theory to them that has to be mastered first. As pointed out elsewhere, there is a perfectly good manual for make[1] that you can read.
My theory is that it has to do with shortened attention spans, and impatience perhaps bred by constant use of technologies with short stimulus response cycles [2].
[1] https://www.gnu.org/software/make/manual/make.html#Introduct... [2] Cellphones.
Now, I've only got one book on my desk and it's more of a coffee-table thing about html and css
Some stuff is genuinely awful.
- Sendmail was ubiquitous, but it was, according to anyone who'd had either fleeting or deep experience with it, a beardy wilderness of byzantine hacks and toxic waste dumps.
- All the WU apps had major exploits every few months.
- SysVinit sucked too, regardless of which replacement you prefer.
- RPM's macro-based .spec file format? Awful.
> pile up a thousand node modules to run the equivalent of a shell one-liner
If you don't like putting small modules together to achieve a task, I have some news for you about shell and Unix...
No, really. The "UNIX way" is not just "Use tons of small things to do a simple task, complexity of managing them be damned".
It is indeed "do one thing and do it well", but that "thing" is usually high level enough and ready to go -- not something you need a whole stack of dependencies, configuration, and lots of extra glue to use.
And of course those unix tools should be standard and evergreen -- not like npm module du jour that gets abandoned 2-3 years later or completely rewritten.
> - SysVinit sucked too, regardless of which replacement you prefer. > - RPM's macro-based .spec file format? Awful.
These are opinions, which is valid.
If you want to have some fun. install centos7 in a vm. Run yum update systemd. Reboot. Your vm is now bricked.
Rpm spec files can be annoying, but what is more annoying to me is the spec behavior changing between rhel/centos 5, 6 and 7.
I doubt it exists. Until then, I'll stick with my Node.js build tools, thank you very much.
Honestly, if anyone has an example of a makefile that can bundle my scripts, insert bundle links into my HTML which is compiled from jade and nunjucks templates, minify the JS, CSS and HTML and optimize my images...I'd love to see that.
Anyway, the point is, everyone likes the smell of their own farts. But, they still stink.
One can argue that it would be better to solve that problem, rather than requiring everybody to sort-of solve it well enough to run one's own build.
Having said that, minimizing .js, .css, .html or .png files conceptually is the same as turning a .c into a .o, and bundling is conceptually the same as tarring or zipping a set of files, so I don't see why it wouldn't be possible to write a makefile that does that.
Windows is the only real challenge there, but with mingw, I can't imagine that it's a serious one.
You'd be surprised. Especially if they work outside C/C++, and do e.g. mostly web development, they neither care much, not know much about makefiles. At best the know to configure, make and make install something on their Linux, but most haven't even tried that.
>Also why is it for hipsters? Or is the article for hipsters?
The article is (supposedly) for hipsters. You seem a little challenged keeping with the latest "culture" (ain't we all), so let me explain.
What he means is that the article is not for seasoned veterans, or unfashionable people who delve in the old-fashioned word of GNU-tools and Make, but for "hipsters", e.g. the new-ish, young-ish developers, usually working with hip languages (and especially web, scripting, etc.), that are not rooted and well versed in the UNIX traditions.
>Why does the author call his own published notes factually inaccurate? Why is it hacky to use a makefile?
It's just a funny wording for the author to convey:
"I'm not a complete authority on Make and Make best practices, I'll just tell you what I know from experience about it. And I expect some Make-gurus to try yell at me about my suggestions being inaccurate/hacky etc, so I try to pre-empt them with this warning".
(Lots of fond memories arguing about the term in europe, where the word seems to lack its snobby, negative feel)
Yes, but this isn't the generic term "hipster", it's applied to a specific context, that is hipster programmers.
>Lots of fond memories arguing about the term in europe, where the word seems to lack its snobby, negative feel
I guess depends on where in Europe. In the place I'm aware of (e.g. not sure about Germany or nordic countries), it is indeed negative. E.g. this is about hipsters from a UK perspective:
https://www.youtube.com/watch?v=lVmmYMwFj1I&feature=youtu.be
I'm feeling cranky every day, but just today this post is at the top of hacker news, and that's frustrating.
I guess this article could be worse: the number of times I see people reimplement poorly thought out clones of make and present them as the new thing that everyone should use is just absurd.
Bah, you just take things too literally, and can't process/appreciate some obvious and light-hearted cultural signs.
A post that makes a joke comment != a post that discredits itself.
A post that warns that its own makefiles might be hacky != a post that calls makefiles inherently hacky (in fact this is obvious, since the post's goal is the inverse: to promote Make to people).
A post that tries to introduce Make to a whole bunch of devs who don't know about it != a post that doesn't notice that Make is used by many people for native programming on unices
If we stopped attacking the authors of articles, then it would be easier for them to write openly and less defensively, but unfortunately if you write anything on the internet, people will call you an idiot.
There are plenty of valid reasons why an established developer would never use Make, namely integration with the rest of their 'ecosystem'. Also, there's plenty of reasons for everyone to get in and use Make where appropriate.
- you've got dependencies on some basic Unix commands (cp, rm etc.) in your tasks, so better rewrite that all to use your cross-platform language's facilities.
- XML, erm, no, JSON, shall be your only file format.
Java also pretty much brought the idea of dependency management (Maven) to mainstream programming languages (although I guess you could argue some of the early Linux did as well (RPM)). It is sort of interesting how Make is sort of like local dependency management.
Or just install that Ubuntu on Windows thingy and be done with it.
So the problem with choice is the number of people who also know that tool who can help you.
For my part, as a Ruby developer, I detest rake and tend to write makefiles for my Ruby projects instead.
i use rake (very superficially) from time to time, and it seems fine. Any insights you have regarding its design after long-term or more indepth use?
And really, my experience with Gulp had been the opposite of the snide "hipster" dismissals. I wish I could find clean examples via googling that weren't useless due to APIs completely changing, or due to using a library that's been deprecated in favor of another library that's been deprecated...because, man, who still uses a library after a year? :P
Somehow, though, I don't see make being a great replacement for my purposes. At the very least, it's not going to be any faster running Babel over a pile of files.
Despite being an obvious usability hole, this has never been fixed. Exacerbating the issue is the poor error message given upon encountering a space-indented line in Make:
Makefile:2: *** missing separator. Stop.
Make is ubiquitous and fairly easy to use, but it's warts like this that remind you that it is fundamentally a build system from the far past. Makefile:2: *** missing separator (did you mean TAB instead of 8 spaces?). Stop.
See 2c64fb221a265f9e7fc93374906b1e7540377561: 1998-09-04 Paul D. Smith <psmith@gnu.org>
* read.c (read_makefile): If we hit the "missing separator" error,
check for the common case of 8 spaces instead of a TAB and give an
extra comment to help people out.
I guess you may have indented it in the modern way with 4 spaces of "tab". Either way, there's also help to be had from your other tools, e.g., vim highlights space-indented make recipes in glaring red error bars. au FileType make setlocal ts=4 sts=4 sw=4 noet
and have vim automatically use "hard" tabs when it detects that you're editing a Makefile. Of course, you can s/4/2/g or whatever your preferred tab width is.Thanks for mentioning, I had no idea this special case was here!
Well, which implementation of make should be fixed? The thing about these truly ubiquitous nix tools is that eventually people discover that there are unixes other than Linux.
…that said, a quick google found that this
is* fixed in GNU make; check the docs for .RECIPEPREFIX here: https://www.gnu.org/software/make/manual/html_node/Special-V...You can now change the prefix for your recipes by setting the .RECIPEPREFIX special variable (https://www.gnu.org/software/make/manual/html_node/Special-V...).
That being said, with a properly configured editor I've actually found that TAB is an ideal character for the recipe prefix.
[Makefile]
indent_style = tab
http://editorconfig.org/https://github.com/aaronbassett/EditorConfig/blob/master/.ed...
My personal preference for everything is spaces
You want a tool that has been around longer than you do stuff your way. I think it is better if learn to work with the tools and accept that there is a reason some things work in certain ways.And, not to sound harsh, but if you always "accept that there is a reason some things work in certain ways" without questioning if there may be a better way, well, you will always be stuck with the status quo!
Anyway, are you saying that accepting a tools established input format is to go with the status quo? I am all for breaking new grounds, but is this one really a priority?
Anyway, my point was, not everything needs to be customizable to your liking. Sometimes things have a set of simple rules you just have to follow. I for one like that we are limited to tabs, otherwise we would have problems with different number of spaces in the same file and by the way exactly how many spaces are a tab? I like 4 but maybe you like 8 or, god forbidden, 2?
https://gist.github.com/zx2c4/11de49b2780c787b3ed5e1ee394857...
That's the Makefile I use on https://www.edgesecurity.com/ if you're interested. It also has in it some very simple ssh/rsync deployment mechanism. Since the deployment relies on the built files, I can simply run:
$ make deploy
And the entire webpage is built and deployed in one step.Every webpage I manage has a variant of this, with all sorts of rules for building and managing things. It turns out to be much easier than grunt or ant or random bash scripts or vagrant or whatever else kids use these days.
You should read the manual, which is shorter than that page!
make is NOT:
alias:
commands
this will bite you when you least expect. Make is: targetfile: inputfiles
commands to get targetfile to exist
and you can use things like %.css_min: %.css
sass stuff
.PHONY: release
# above is needed otherwise you won't build if there is a release/ dir
release: release-min.css
release-min.css: (list *.css_min files, there are helpers for it)
cat *.css_min > release-min.css
anyway. you get the idea. work with files and why you need those files.https://www.gnu.org/software/make/manual/make.html#Introduct...
Also available in print: https://shop.fsf.org/books-docs/gnu-make-version-381
info make
GNU tools often use man pages for a quick reference of the options, return codes, etc. Unfortunately, as info(1) isn't as well known as man(1), it's easy to miss that many GNU tools have detailed manuals.* (cd /path/to/something && make goal)
* You can use .DEFAULT_GOAL := goal_name to set the default target run by 'make' with no target name specified.
* Adding .SILENT will suppress make entering/leaving directory messages. Probably wise to be careful with one until you're 100% sure you're not ending up in an unintended directory doing nasty things.
* You can use $(COLOR) = `tput setaf x' and $(RESET) = `tput sgr0` to add colors to your make output. For example @echo "$(RED)ERROR!$(RESET)"
* Use if ! -f conditionals to start goals that rely on external scripts/programs. Otherwise make will run until it hits the error which will leave you with a partially completed goal.
goal:
@if [ ! -f ./scripts/blah.sh ]; then echo "ERROR: ./scripts/blah.sh not found"; exit 1; fi
@echo "without the if ! -f this command would run"
@echo "and so would this one"
@./scripts/blah.sh $(IMPORTANT_STUFFS)
@echo "but not this one"I had always, perhaps erroneously, thought that the very first goal in the file was the default one.
https://github.com/adewes/gitboard/blob/master/Makefile
Using the inotify tools it's even possible to automatically trigger a rebuild whenever a file changes.
For me, no need to use Gulp anymore, as Makefiles are easier to reason about, more composable and make use of existing infrastructure instead of reinventing the wheel over and over again.
Nope. You can say "make hello" and have make automatically use its default rules - which can be configured - to e.g. compile hello.c into a hello executable. I use this frequently.
Out of curiousity: how do you configure the implicit ruleset? I wasn't able to find documentation on that (the closest I found was https://ftp.gnu.org/old-gnu/Manuals/make-3.79.1/html_chapter..., which explicitly documents the Make implicit rules but says nothing about changing/augmenting them).
Other than that there's not much configuration, but the predefined rules are usually quite simple, so it's pretty easy to just write your own implicit rules if the predefined ones don't suit your needs.
So there's that. Make being such a good idea and a popular standard, there's no shortage of people implementing not quite compatible make-like-systems.
Another fun tip is make your makefile executable and try the first line like
#!/usr/bin/env gmake
or whatever seems appropriate. Or perhaps GNU make is installed as "make" on your OS or you use an "alternatives" link farm or whatever. Some people will flip out if you put arguments on that command line, others will pat you on the back and high-five. So there's that "fun".
include ${DEPENDS}
${DEPDIR}/%.d: ${SRCDIR}/%.${SRCEXT}
@mkdir -p ${shell dirname $@} ; \
$(CC) -MM ${INCLUDE} -mmcu='${AVRTARGET}' $< >> $@
If any file in the "include" line needs updating then it is generated by gcc and included in the same make run. I didn't find a good documentation about this feature and I discovered this with make's pretty verbose -d option. Previously I did something like this using multiple makefiles and recursively calling make which is generally frowned upon (for valid reasons). %.o: %.c
$(CC) $(CFLAGS) -MMD -c $<
-include $(OBJECTS:.o=.d)Also specify -MP on the GCC command line, which causes GCC to emit an empty rule for all the header files, like this:
foo.o: foo.c foo.h bar.h
foo.h:
bar.h:
Alternatively, you can write a generic empty header creation rule: %.h:
Which has the same effect.that gets a 8/10 on my hipsterometer
If you want to see some interesting/convoluted Makefiles, get a very complex, large piece of software (something from Gnome, possibly) and use autoconf & automake to generate the Makefiles, then pour through them to see how they tick.
If you're decent with Make and want to learn advanced tricks, then by all means go right ahead, but 95% of Make users will never need to delve into such details.
Make is fine. Automake is horrific.
https://github.com/oNaiPs/npm-install-changed
http://blog.keithcirkel.co.uk/how-to-use-npm-as-a-build-tool...
[edit: formatting]
For example, Debian's packaging process is heavily optimized towards Makefiles that supply the standard targets, and you can reduce a lot of friction for packagers if you supply a wellbehaving Makefile with your program. (Even if developers would usually `go build` or whatever instead of `make`.)
Their makefiles work with GNU Make and BSD Make, don't know about nmake (AFAIR Windows).
----------------------------------------------------
foo: bar
bar:
----------------------------------------------------
.PHONY: foo
foo:
What I'd really love right now is a program which can look at a Go source tree and write make rules such that I don't have to run go build or go install unless dependencies have actually changed. It's really annoying to be pushing new images when nothing has actually changed.
If "what it does" means "build complex software projects" I think your claim is rather debatable.
GHC is currently switching away from make after having already overhauled its make-based build system two times:
http://research.microsoft.com/en-us/um/people/simonpj/papers...
And Make is terrible.
At least if want have to deal with more than one directory.
All these languages with their half-baked build tools that won't accept that they may have to play nice with other languages and their build tools are not helping.
Of course it is great when you write a language to also throw in a build tool, but in the end if the build tool re-implements 30% or so of make in a broken way I don't see the point.
Make does have its limitations, but most ordinary projects get nowhere close to reaching those.
Well, other build tools sometimes also do a lot more than make ever did. (And in some areas, perhaps less.)
Example: Cabal/cabal-install (for Haskell) can automatically fetch all your project's dependencies and automatically compile them for you.
> Make does have its limitations, but most ordinary projects get nowhere close to reaching those.
I suppose it depends on what you mean by "ordinary", but IME this Makefiles by virtue of being purely file-based is useless for most of my projects. There are a many langauges (e.g. Java/Scala, Haskell) where it just doesn't fit for normal development. As an example: Tracking intra-file dependencies for proper recompilation is really difficult to for Scala code without reimplementing a huge chunk of a Scala compiler. (I'd venture to suggest that you'd be foolish to even try doing this in Make.)
tup (http://gittup.org/tup) has a really nice way of handling interdependencies. They set up some filesystem magic to figure out which files were read while compiling a certain target, and record these files as dependencies for the target.
Another instance of a hard problem ("reimplementing [...] a Scala compiler") that turns into a very easy problem once you look at it from the right angle.
You need to learn the Make build tool (easy) and then you need to learn bash scripting to get anywhere (argh!).
The OP has linked an example Makefile and I wouldn't be able to maintain/debug it without reading plenty of manpages:
https://github.com/Financial-Times/n-makefile/blob/master/Ma...
Also, a lot of the complexity is due to him being new to make:
asset%:
@if [ -e webpack.config.js ]; then ... fiOne of the normal conventions for Daniel J. Bernstein's tinydns is to use make. No "projects" or "builds" are involved. The goal is not to create a program. Rather, make is used to ensure that the binary form of the DNS database is re-built whenever the system administrator has edited the text form. The administrator simply has to remember to run "make", and the Makefile re-builds, and atomically publishes, the new DNS database.
The simplest makefiles are of the scale exhibited at http://cr.yp.to/djbdns/run-server.html
But one can create significantly more ambitious makefiles than those. (-:
Is make the right tool for executing such tasks? Well, it's not bad for some I guess, and ok if this one project is all you have.
Sometimes you've better off having something that does exactly what you need, regardless of speed. Sometimes you need something fast, lightweight, ubiquitous, and reliable despite its quirks.