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