chiark / gitweb /
41110ce410ac8ca098cff5e28cbd182951fcc4ee
[subdirmk.git] / README
1 subdirmk - assistance for non-recursive use of make
2 ===================================================
3
4 Introduction
5 ------------
6
7 Peter Miller's 1997 essay _Recursive Make Considered Harmful_
8 persuasively argues that it is better to arrange to have a single
9 make invocation with the project's complete dependency tree, rather
10 than the currently conventional `$(MAKE) -C subdirectory' approach.
11
12 However, actually writing a project's build system in a non-recursive
13 style is not very ergonomic.  The main difficulties are:
14   - constantly having to write out long file and directory names
15   - the lack of a per-directory make variable namespace means
16     long make variables (or namespace clashes)
17   - it is difficult to arrange that one can cd to a subdirectory
18     and say `make all' and have something reasonable happen
19     (to wit, build an appropriate subset)
20
21 `subdirmk' is an attempt to solve these problems (and it also slightly
22 alleviates some of the boilerplate needed to support out-of-tree
23 builds well, and helps a bit with metaprogramming and rule writing).
24
25 Basic approach
26 --------------
27
28 The developer is expected to write a makefile fragment, in each
29 relevant subdirectory, called `Dir.sd.mk'.
30
31 These fragments may contain ordinary make language.  Unqualified
32 filenames are relative to the build toplevel, and all commands all run
33 there.
34
35 However, the sigil & is treated specially.  By and large, it refers to
36 `the build directory corresponding to this .sd.mk file', etc.
37 There are a variety of convenient constructions.
38
39 The result is that to a large extent, the Dir.sd.mk has an easy way
40 to namespace its "local" make variables, and an easy way to refer to
41 its "local" filenames (and filenames in general).
42
43 The Dir.sd.mk's are filtered, fed through autoconf in the usual way
44 (for @..@-substitutions) and included by one autogenerated toplevel
45 makefile.
46
47 So all of the input is combined and passed to one make invocation.
48 (A corollary is that there is no enforcement of the namespacing:
49 discipline is required to prefix relevant variable names with &, etc.)
50
51 Each subdirectory is also provided with an autogenerated `Makefile'
52 which exists purely to capture ordinary make invocations and arrange
53 for something suitable to happen.
54
55 Where there are dependencies between subdirectories, each Dir.sd.mk
56 can simply refer to files in other subdirectories directly.
57
58 Invocation, "recursive" per-directory targets
59 ---------------------------------------------
60
61 Arrangements are made so that when you run `make foo' in a
62 subdirectory, it is like running the whole toplevel makefile, from the
63 toplevel, as `make subdir/foo'.  If `subdir/foo' is a file that might
64 be built, that builds it.
65
66 But `foo' can also be a conventional target like `all'.
67
68 Each subdirectory has its own `all' target.  For example a
69 subdirectory `src' has a target `src/all'.  The rules for these are
70 automatically generated from the settings of the per-directory
71 &TARGETS variables.  &TARGETS is magic in this way.  (In
72 src/Dir.sd.mk, &TARGETS of course refers to a make variable called
73 src_TARGETS.)
74
75 The `all' target in a parent directory is taken to imply the `all'
76 targets in all of its subdirectories, recursively.  And in the
77 autogenerated stub Makefiles, `all' is the default target.  So if you
78 just type `make' in the toplevel, you are asking for `&all'
79 (<subdir>/all) for every directory in the project.
80
81 In a parallel build, the rules for all these various subdirectory
82 targets may be in run in parallel: there is only one `make' invocation
83 at a time.  There is no sequencing between subdirectories, only been
84 individual targets (as specified according to their dependencies).
85
86 You can define other per-directory recursive targets too: set the
87 variable &TARGETS_zonk, or whatever (being sure to write &TARGETS_zonk
88 at the start of a line).  This will create a src/zonk target (for
89 appropriate value of src/).  Unlike `all', these other targets only
90 exist in areas of the project where at least something mentions them.
91 So for example, if &TARGETS_zonk is set in src but not lib, `make
92 zonk' in lib will fail.  If you want to make a target exist
93 everywhere, += it with nothing in Prefix.sd.mk or Suffix.sd.mk (see
94 below).
95
96 Prefix.sd.mk, Suffix.sd.mk, Final.sd.mk, inclusion
97 --------------------------------------------------
98
99 The files Prefix.sd.mk and Suffix.sd.mk in the toplevel of the source
100 are automatically processed before and after each individual
101 directory's Dir.sd.mk, and the &-substituted contents therefore
102 appear once for each subdirectory.
103
104 This lets you do per-directory boilerplate.  Some useful boilerplate
105 is already provided in subdirmk, for you to reference like this:
106   &:include subdirmk/cdeps.sd.mk
107   &:include subdirmk/clean.sd.mk
108 For example you could put that in Suffix.sd.mk.
109
110 The top-level Dir.sd.mk is the first makefile included after the
111 autogenerated `main.mk' which merely has some basic settings and
112 includes.  So if you want to get in early and set global variables,
113 put them near the top of Dir.sd.mk.
114
115 The file Final.sd.mk in the toplevel directory is processed and
116 included after all the other files.
117
118 subdirmk's filter script itself sets (only) these variables:
119   top_srcdir
120   abs_top_srcdir
121   SUBDIRMK_MAKEFILES
122   MAKEFILE_TEMPLATES
123 You are likely to want to define $(PWD), and shorter names for
124 top_srdir and abs_top_srcdir (we suggest $(src) and $(abs_src)).
125
126 Global definitions
127 ------------------
128
129 If want to set global variables, such as CC, that should only be done
130 once.  You can put them in your top-level Dir.sd.mk, or a separate
131 file you `include' and declare using SUBDIRMK_MAKEFILES.
132
133 If you need different settings of variables like CC for different
134 subdirectories, you should probably do that with target-specific
135 variable settings.  See the info node `(make) Target-specific'.
136
137 Directory templates `.sd.mk' vs plain autoconf templates `.mk.in'
138 --------------------------------------------------------------------
139
140 There are two kinds of template files.
141
142  Filename                 .sd.mk                  .mk.in
143
144  Processed by             &-substitution,         autoconf only
145                           then autoconf
146
147  Instantiated             Usu. once per subdir    Once only
148
149  Need to be mentioned     No, but Dir.sd.mk       All not in subdirmk/
150  in configure.ac?         via SUBDIRMK_SUBDIRS    via SUBDIRMK_MAKEFILES
151
152  How to include           `&:include foo.sd.mk'   `include foo.mk'
153                           in all relevant .sd.mk  in only one
154                           (but not needed for     Dir.sd.mk
155                            Prefix, Suffix, Final)
156
157 If you `include subdirmk/regen.mk', dependency management and
158 automatic regeneration for all of this template substitution, and for
159 config.status etc. is done for you.
160
161 Substitution syntax
162 -------------------
163
164 In general & expands to the subdirectory name when used for a
165 filename, and to the subdirectory name with / replaced with _ for
166 variable names.  (If your variables start with capital letters and
167 your filenames with lowercase.  Otherwise, use &/ or &_.)
168
169 Note that & is processed *even in makefile comments*.  The substitutor
170 does not understand make syntax, or shell syntax, at all.  However,
171 the substitution rules are chosen to work well with constructs which
172 are common in makefiles.
173
174 In the notation below, we suppose that the substitution is being in
175 done in a subdirectory sub/dir of the source tree.  In the RH column
176 we describe the expansion at the top level, which is often a special
177 case (in general in variable names we call that TOP rather than the
178 empty string).
179
180 &CAPS           =>      sub_dir_CAPS                    or TOP_CAPS
181 &lc             =>      sub/dir/lc                      or lc
182         Here CAPS is any ASCII letter A-Z and lc is a-z.
183         The assumption is that filenames are usually lowercase and
184         variables usually uppercase.  Otherwise, use another syntax:
185
186 &/              =>      sub/dir/                        or nothing
187 &_              =>      sub_dir_                        or TOP_
188 &.              =>      sub/dir                         or .
189         (This implies that `&./' works roughly like `&/', although
190         it can produce a needless `./')
191
192 &=              =>      sub_dir                         or TOP
193
194 &^lc            =>      $(top_srcdir)/sub/dir/lc
195 &^/             =>      $(top_srcdir)/sub/dir/
196 &^.             =>      $(top_srcdir)/sub/dir
197
198 &~lc            =>      $(top_srcdir)/lc
199 &~/             =>      $(top_srcdir)/
200 &~.             =>      $(top_srcdir)
201
202 In general:
203     ^   pathname of this subdirectory in source tree
204     ~   pathname of top level of source tree
205     /   terminates the path escape } needed if next is
206     _   terminates the var escape  } not letter or space)
207     .   terminates path escape giving dir name (excluding /)
208     =   terminates var escape giving only prefix part (rarely needed)
209   lwsp  starts multi-word processing (see below)
210
211 So pathname syntax is a subset of:
212     '&' [ '^' | '~' ] [ lc | '/' | '.' ]
213
214 &&              =>      &&              for convenience in shell runes
215
216 &\&             =>      &               general escaping mechanism
217 &\$             =>      $               provided for $-doubling regimes
218 &\NEWLINE                               eats the newline and vanishes
219
220 &$VARIABLE      =>      $(sub_dir_VARIABLE)     or $(TOP_VARIABLE)
221         VARIABLE is ASCII starting with a letter and matching \w+
222
223 & thing thing... &
224 &^ thing thing... &
225 &~ thing thing... &
226         Convenience syntax for prefixing multiple filenames.
227         Introduced by & followed by lwsp where lc could go.
228         Each lwsp-separated non-ws word is prefixed by &/ etc.
229         etc. respectively.  No other & escapes are recognised.
230         This processing continues until & preceded by lwsp,
231         or until EOL (the end of the line), or \ then EOL.
232
233 &:<directive> <args>....
234         recognised at start of line only (possibly after lwsp)
235
236 &:include filename              filename should usually be [&]foo.sd.mk
237 &:-include filename             tolerate nonexistent file
238         RHS is &-expanded but filenames are relative to the top
239         srcdir.  This implies that unqualified names are like &~/
240         whereas &/ is like &^/.  &^ and &~ do not work here because
241         they expand to constructions involving literally
242         `$(top_srcdir)', but the RHS is not make-expanded.
243
244 &!<lwsp>        disables & until EOL (and then disappears)
245
246 &#      delete everything to end of line
247         (useful if the RHS contains unrecognised & constructions)
248
249 &TARGETS_things
250         Handled specially.  If mentioned at the start of a line
251         (possibly following whitespace), declares that this
252         subdir ought to have a target `things'.  The rule will be
253                 &/things:: $(&TARGETS_things)
254
255         You may extend it by adding more :: rules for the target,
256         but the preferred style is to do things like this:
257                 &TARGETS_check += & test-passed.stamp
258
259         It is important to mention &TARGETS_things at least once in
260         the context of each applicable directory, because doing so
261         arranges that the *parent* will also have a `things' target
262         which recursively implies this directory's `things'.
263
264         Must be spelled exactly &TARGETS_things.  &_TARGETS_things,
265         for example, is not magic.  To make the target exist
266         without providing any prerequisites for it, write a line
267         containing just `&TARGETS_things +='.
268
269         `all' is extra special: every directory has an `all'
270         target, which corresponds to &TARGETS.
271
272 &:warn [!]WARNTAG ...
273         Suppress (with !) or re-enable (without !) warnings tagged
274         WARNTAG (see section `Warnings', below).  The suppression list
275         is reset at the start of processing in each subdirectory.
276         Warnings that appear at the end of processing are controlled
277         by the final warning state after processing all the toplevel
278         input files (including Final.sd.mk).
279
280 &:local+global [&]VARIABLE ...
281         Suppresses the warning about seeing both VARIABLE and
282         &VARIABLE.  Any & specified in the RHS is redundant: this
283         always affects both versions identically.
284
285 &:changequote NEWQUOTE
286         changes the escape sequence from & to literally NEWQUOTE
287         NEWQUOTE may be any series of of non-whitespace characters,
288         and is terminated by EOL or lwsp.  The whole line is
289         discarded.
290
291         After this, write NEWQUOTE instead of &, everywhere.
292         The effect is unscoped and lasts until the next setting,
293         or until the end of the current directory's Suffix.sd.mk.
294         It takes effect on &:include'd files too, so maybe set
295         it back before using &:include.
296
297         Notably
298                 NEWQUOTENEWQUOTE        => NEWQUOTENEWQUOTE
299                 NEWQUOTE\NEWQUOTE       => NEWQUOTE
300                 NEWQUOTE\$              => $
301                 NEWQUOTE:changequote &  set escape back to &
302
303
304 Dollar doubling and macro assistance
305 ------------------------------------
306
307 &$+             Starts dollar-doubling
308 &$-             Stops dollar-doubling
309         Both are idempotent and local to the file or context.
310
311 Sometimes we will show $'s being doubled inside another construct.
312 This means the content of the construct is $-doubled: $-doubling is
313 locally enabled, and restored afterwards.
314
315 &:macro NAME    =>      define NAME
316 STUFF $ THINGS  ..      STUFF $$ THINGS
317 &:endm          ..      endef
318         NAME is processed for &
319
320 &${..$..} =>    ${eval ${call ..$$..}}
321         (matches { } pairs to find the end)
322         content is $-doubled (unless it contains $- to turn that off)
323
324         Together &:macro and &${...} provide a more reasonable macro
325         facility than raw make.  They solve the problem that make
326         expansions cannot directly generate multiple rules, variable,
327         etc.; instead, `$(eval )' must be used, but that re-expands
328         the argument, meaning that all the literal text must be
329         $-doubled.  This applies to the macro text and to the
330         arguments.  Also `$(eval $(call ...))' is an unfortunate syntax.
331         Hence &:macro and &${...}.
332
333 While dollar-doubling:
334 - - - - - - - - - - -
335
336 $       =>      $$      including $'s produced by other
337                          &-expansions not mentioned here
338
339 &\$     =>      $
340 &$NN    =>      $(NN)   where N are digits
341 &$(     =>      $(
342
343 A few contexts do not support $-doubling, such as directive arguments
344 or places where this might imply $-quadrupling.  (There is no way to
345 get $-quadrupling.)
346
347
348 Tables of file reference syntaxes
349 ---------------------------------
350
351 In a nonrecursive makefile supporting out of tree builds there are
352 three separate important distinctions between different file
353 locations:
354
355  (i) In the build tree, or in the source tree ?
356
357  (ii) In (or relative to) the subdirectory to which this Dir.sd.mk
358      relates, or relative to the project's top level ?
359
360  (iii) Absolute or relative pathname ?  Usually relative pathnames
361      suffice.  Where an absolute pathname is needed, it can be built
362      out of &/ and an appropriate make variable such as $(PWD).
363
364 Path construction &-expansions are built from the following:
365
366                       Relative paths in...
367                       build     source
368                                                        
369   This directory      &         &^
370   Top level           .         &~
371
372 In more detail, with all the various options laid out:
373
374       Recommended     Relative paths in...   Absolute paths in...
375              for      build     source       build         source
376                                                        
377   This       lc       &file     &^file       $(PWD)/&file  $(abs_src)/&file
378   directory  any      &/file    &^/file      $(PWD)/&/file $(abs_src)/&/file
379              several  & f g h   &^ f g h     $(addprefix...)
380                                              
381   Top        lc       file      &~file
382   level      any      file      &~/file      $(PWD)/file   $(abs_src)/file
383              .mk.in   file      $(src)/file  $(PWD)/file   $(abs_src)/file
384              several  f g h     &~ f g h     $(addprefix...)
385
386 (This assumes you have appropriate make variables src, PWD and
387 abs_src.)
388
389 Warnings
390 --------
391
392 subdirmk's `generate' program, which does the acual &-substitution,
393 can produce some warnings about your .sd.mk files.  These can be
394 suppressed with the &:warn directive.  The warning tags are:
395
396     local+global
397         The same VARNAME was used both with and without an & prefix.
398         This can be confusing.  Also, if you avoid this then you will
399         get a warning iff you accidentally leave off a needed &.
400         (You can suppress this warning for a particular VARNAME with
401         the &:local+global directive.)
402
403     single-char-var
404         A variable expansion like $FBAR.  make's expansion rules
405         interpret this as $(F)BAR.  It's normally better to write
406         it this way, at least if the variable expansion is followed
407         by more letters.  Note that &$FOO works differently to
408         raw make: it expands to $(sub_dir_FOO).
409
410     unknown-warning
411         &:warn was used to try to enable a warning that this version
412         of subdirmk does not understand.  (Note that an attempt to
413         *dis*able an unknown warning is only reported if some other
414         warning was issued which might have been disabled.)
415
416 Subdirectory and variable naming
417 --------------------------------
418
419 The simple variable decoration scheme does not enforce a strict
420 namespace distinction between parts of variable names which come from
421 subdirectory names, and parts that mean something else.
422
423 So it is a good idea to be a bit careful with your directory naming.
424 `TOP', names that contain `_', and names that are similar to parts of
425 make variables (whether conventional ones, or ones used in your
426 project) are best avoided.
427
428 If you name your variables in ALL CAPS and your subdirectories in
429 lower case with `-' rather than `_', there will be no confusion.
430
431 Incorporating this into your project
432 ------------------------------------
433
434 Use `git-subtree' to merge the subdirmk/ directory.  You may find it
435 useful to symlink the DEVELOPER-CERTIFICATE file (git can store
436 symlinks as symlinks - just `git add' the link).  And you probably
437 want to mention the situation in your top-level COPYING and HACKING.
438
439 Symlink autogen.sh into your project toplevel.
440
441 In your configure.ac, say
442
443   m4_include([subdirmk/subdirmk.ac])
444   SUBDIRMK_SUBDIRS([...list of subdirectories in relative syntax...])
445
446 Write a Dir.sd.mk in each directory.  The toplevel one should
447 probably contain:
448
449   include subdirmk/usual.mk
450   include subdirmk/regen.mk
451
452 Write a Suffix.sd.mk in the toplevel, if you want.  It should probably
453 have:
454
455   &:include subdirmk/cdeps.sd.mk
456   &:include subdirmk/clean.sd.mk
457
458 Hints
459 -----
460
461 You can convert your project incrementally.  Start with the top-level
462 Makefile.in and rename it to Dir.sd.mk, and add the appropriate
463 stuff to configure.ac, and fix everything up.  Leave the existing
464 $(MAKE) -C for your existing subdirectories alone.  Then you can
465 convert individual subdirectories, or classes of subdirectories, at
466 your leisure.  (You must be /sure/ that each recursive (non-subdirmk)
467 subdirectory will be entered only once at a time, but your existing
468 recursive make descent system should already do that or you already
469 have concurrency bugs.)
470
471 Aside from this, be very wary of any invocation of $(MAKE) anywhere.
472 This is a frequent source of concurrency bugs in recursive make build
473 systems.  When combined with nonrecursive make it's all in the same
474 directory and there is nothing stopping the different invocations
475 ending up trying to make the same targets at the same time. That
476 causes hideous racy lossage.  There are ways to get this to work
477 reliably but it is advanced stuff.
478
479 If you make syntax errors, or certain kinds of other errors, in your
480 makefiles, you may find that just `make' is broken now and cannot get
481 far enough to regenerate a working set of makefiles.  If this happens
482 just rerun ./config.status by hand.
483
484 If you go back and forth between different versions of your code you
485 can sometimes find that `make' complains that one of your Subdir.sd.mk
486 files is missing: typically, if iot was used and therefore a
487 dependency in some other version of your code.  If you run `make
488 clean' (or `make realclean') these dependencies are suppressed, which
489 will clear up the problem.
490
491
492 Legal information
493 -----------------
494
495 subdirmk is
496  Copyright 2019 Mark Wooding
497  Copyright 2019 Ian Jackson
498
499     subdirmk and its example is free software; you can redistribute it
500     and/or modify it under the terms of the GNU Library General Public
501     License as published by the Free Software Foundation; either
502     version 2 of the License, or (at your option) any later version.
503
504     This is distributed in the hope that it will be useful, but
505     WITHOUT ANY WARRANTY; without even the implied warranty of
506     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
507     Library General Public License for more details.
508
509     You should have received a copy of the GNU Library General Public
510     License along with this library as the file LGPL-2.
511     If not, see https://www.gnu.org/.
512
513 Individual files generally contain the following tag in the copyright
514 notice, instead of the full licence grant text:
515   SPDX-License-Identifier: LGPL-2.0-or-later
516 As is conventional, this should be read as a licence grant.
517
518 Contributions are accepted based on the git commit Signed-off-by
519 convention, by which the contributors' certify their contributions
520 according to the Developer Certificate of Origin version 1.1 - see
521 the file DEVELOPER-CERTIFICATE.
522
523 Where subdirmk is used by and incorporated into another project (eg
524 via git subtree), the directory subdirmk/ is under GNU LGPL-2.0+, and
525 the rest of the project are under that other project's licence(s).
526 (The project's overall licence must be compatible with LGPL-2.0+.)