Debian Codegraph @

doc/autoconf.texi

raw
1 \input texinfo @c -*-texinfo-*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename autoconf.info
5 @include version.texi
6 @settitle Autoconf
7 @documentencoding UTF-8
8 @set txicodequoteundirected
9 @set txicodequotebacktick
10 @set txidefnamenospace
11 @setchapternewpage odd
12 @finalout
13
14 @c @ovar(ARG)
15 @c ----------
16 @c The ARG is an optional argument. To be used for macro arguments in
17 @c their documentation (@defmac).
18 @macro ovar{varname}
19 @r{[}@var{\varname\}@r{]}
20 @end macro
21
22 @c @dvar(ARG, DEFAULT)
23 @c -------------------
24 @c The ARG is an optional argument, defaulting to DEFAULT. To be used
25 @c for macro arguments in their documentation (@defmac).
26 @macro dvar{varname, default}
27 @r{[}@var{\varname\} = @samp{\default\}@r{]}
28 @end macro
29
30 @c @dvarv(ARG, DEFAULT-VAR)
31 @c ------------------------
32 @c Same as @dvar{ARG, DEFAULT-VAR}, but with @var instead of @samp
33 @c around DEFAULT-VAR.
34 @macro dvarv{varname, default}
35 @r{[}@var{\varname\} = @var{\default\}@r{]}
36 @end macro
37
38 @c Handling the indexes with Texinfo yields several different problems.
39 @c
40 @c Because we want to drop out the AC_ part of the macro names in the
41 @c printed manual, but not in the other outputs, we need a layer above
42 @c the usual @acindex{} etc. That's why we first define indexes such as
43 @c acx meant to become the macro @acindex. First of all, using 'ac_'
44 @c does not work with makeinfo, and using 'ac1' doesn't work with TeX.
45 @c So use something more regular 'acx'. Then you finish with a printed
46 @c index saying 'index is not existent'. Of course: you ought to use
47 @c two letters :( So you use capitals.
48 @c
49 @c Second, when defining a macro in the TeX world, following spaces are
50 @c eaten. But then, since we embed @acxindex commands that use the end
51 @c of line as an end marker, the whole things wrecks itself. So make
52 @c sure you do *force* an additional end of line, add a '@c'.
53 @c
54 @c Finally, you might want to get rid of TeX expansion, using --expand
55 @c with texi2dvi. But then you wake up an old problem: we use macros
56 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
57
58 @c Define an environment variable index, for variables users may set
59 @c in their environment or on the configure command line.
60 @defcodeindex ev
61 @c Define an output variable index, for commonly AC_SUBST'ed variables.
62 @defcodeindex ov
63 @c Define a cache variable index, for variables matching *_cv_*.
64 @defcodeindex CA
65 @c Other shell variables not fitting the above categories should be
66 @c listed in the predefined vrindex, which we merge in the concept index.
67 @syncodeindex vr cp
68 @c Define a CPP preprocessor macro index, for #define'd strings.
69 @defcodeindex cv
70 @c Define an Autoconf macro index that @defmac doesn't write to.
71 @defcodeindex AC
72 @c Define an Autotest macro index that @defmac doesn't write to.
73 @defcodeindex AT
74 @c Define an M4sugar macro index that @defmac doesn't write to.
75 @defcodeindex MS
76 @c Define an index for *foreign* programs: 'mv' etc. Used for the
77 @c portability sections and so on.
78 @defindex pr
79
80 @c shortindexflag
81 @c --------------
82 @c Shall we factor AC_ out of the Autoconf macro index etc.?
83 @iftex
84 @set shortindexflag
85 @end iftex
86
87 @c @acindex{MACRO}
88 @c ---------------
89 @c Registering an AC_\MACRO\.
90 @ifset shortindexflag
91 @macro acindex{macro}
92 @ACindex \macro\
93 @c
94 @end macro
95 @end ifset
96 @ifclear shortindexflag
97 @macro acindex{macro}
98 @ACindex AC_\macro\
99 @end macro
100 @end ifclear
101
102 @c @ahindex{MACRO}
103 @c ---------------
104 @c Registering an AH_\MACRO\.
105 @macro ahindex{macro}
106 @ACindex AH_\macro\
107 @c
108 @end macro
109
110 @c @asindex{MACRO}
111 @c ---------------
112 @c Registering an AS_\MACRO\.
113 @ifset shortindexflag
114 @macro asindex{macro}
115 @MSindex \macro\
116 @c
117 @end macro
118 @end ifset
119 @ifclear shortindexflag
120 @macro asindex{macro}
121 @MSindex AS_\macro\
122 @end macro
123 @end ifclear
124
125 @c @atindex{MACRO}
126 @c ---------------
127 @c Registering an AT_\MACRO\.
128 @ifset shortindexflag
129 @macro atindex{macro}
130 @ATindex \macro\
131 @c
132 @end macro
133 @end ifset
134 @ifclear shortindexflag
135 @macro atindex{macro}
136 @ATindex AT_\macro\
137 @end macro
138 @end ifclear
139
140 @c @auindex{MACRO}
141 @c ---------------
142 @c Registering an AU_\MACRO\.
143 @macro auindex{macro}
144 @ACindex AU_\macro\
145 @c
146 @end macro
147
148 @c @hdrindex{MACRO}
149 @c ----------------
150 @c Indexing a header.
151 @macro hdrindex{macro}
152 @prindex @file{\macro\}
153 @c
154 @end macro
155
156 @c @msindex{MACRO}
157 @c ---------------
158 @c Registering an m4_\MACRO\.
159 @ifset shortindexflag
160 @macro msindex{macro}
161 @MSindex \macro\
162 @c
163 @end macro
164 @end ifset
165 @ifclear shortindexflag
166 @macro msindex{macro}
167 @MSindex m4_\macro\
168 @end macro
169 @end ifclear
170
171
172 @c @caindex{VARIABLE}
173 @c ------------------
174 @c Registering an ac_cv_\VARIABLE\ cache variable.
175 @ifset shortindexflag
176 @macro caindex{macro}
177 @CAindex \macro\
178 @end macro
179 @end ifset
180 @ifclear shortindexflag
181 @macro caindex{macro}
182 @CAindex ac_cv_\macro\
183 @end macro
184 @end ifclear
185
186 @c Define an index for functions: 'alloca' etc. Used for the
187 @c portability sections and so on. We can't use 'fn' (aka 'fnindex'),
188 @c since '@defmac' goes into it => we'd get all the macros too.
189
190 @c FIXME: Aaarg! It seems there are too many indices for TeX :(
191 @c
192 @c ! No room for a new @write .
193 @c l.112 @defcodeindex fu
194 @c
195 @c so don't define yet another one :( Just put some tags before each
196 @c @prindex which is actually a @funindex.
197 @c
198 @c @defcodeindex fu
199 @c
200 @c
201 @c @c Put the programs and functions into their own index.
202 @c @syncodeindex fu pr
203
204 @comment %**end of header
205 @comment ========================================================
206
207 @copying
208
209 This manual (@value{UPDATED}) is for GNU Autoconf
210 (version @value{VERSION}),
211 a package for creating scripts to configure source code packages using
212 templates and an M4 macro package.
213
214 Copyright @copyright{} 1992--1996, 1998--2017, 2020--2026 Free Software
215 Foundation, Inc.
216
217 @quotation
218 Permission is granted to copy, distribute and/or modify this document
219 under the terms of the GNU Free Documentation License,
220 Version 1.3 or any later version published by the Free Software
221 Foundation; with no Invariant Sections, no Front-Cover texts, and
222 no Back-Cover Texts. A copy of the license is included in the section
223 entitled ``GNU Free Documentation License.''
224 @end quotation
225 @end copying
226
227
228
229 @dircategory Software development
230 @direntry
231 * Autoconf: (autoconf). Create source code configuration scripts.
232 @end direntry
233
234 @dircategory Individual utilities
235 @direntry
236 * autoscan: (autoconf)autoscan Invocation.
237 Semi-automatic @file{configure.ac} writing
238 * ifnames: (autoconf)ifnames Invocation. Listing conditionals in source.
239 * autoconf-invocation: (autoconf)autoconf Invocation.
240 How to create configuration scripts
241 * autoreconf: (autoconf)autoreconf Invocation.
242 Remaking multiple @command{configure} scripts
243 * autoheader: (autoconf)autoheader Invocation.
244 How to create configuration templates
245 * autom4te: (autoconf)autom4te Invocation.
246 The Autoconf executables backbone
247 * configure: (autoconf)configure Invocation. Configuring a package.
248 * autoupdate: (autoconf)autoupdate Invocation.
249 Automatic update of @file{configure.ac}
250 * config.status: (autoconf)config.status Invocation. Recreating configurations.
251 * testsuite: (autoconf)testsuite Invocation. Running an Autotest test suite.
252 @end direntry
253
254 @titlepage
255 @title Autoconf
256 @subtitle Creating Automatic Configuration Scripts
257 @subtitle for version @value{VERSION}, @value{UPDATED}
258 @author David MacKenzie
259 @author Ben Elliston
260 @author Akim Demaille
261 @page
262 @vskip 0pt plus 1filll
263 @insertcopying
264 @end titlepage
265
266 @contents
267
268
269 @ifnottex
270 @node Top
271 @top Autoconf
272 @insertcopying
273 @end ifnottex
274
275 @c The master menu, created with texinfo-master-menu, goes here.
276
277 @menu
278 * Introduction:: Autoconf's purpose, strengths, and weaknesses
279 * The GNU Build System:: A set of tools for portable software packages
280 * Making configure Scripts:: How to organize and produce Autoconf scripts
281 * Setup:: Initialization and output
282 * Existing Tests:: Macros that check for particular features
283 * Writing Tests:: How to write new feature checks
284 * Results:: What to do with results from feature checks
285 * Programming in M4:: Layers on top of which Autoconf is written
286 * Programming in M4sh:: Shell portability layer
287 * Writing Autoconf Macros:: Adding new macros to Autoconf
288 * Portable Shell:: Shell script portability pitfalls
289 * Portable Make:: Makefile portability pitfalls
290 * Portable C and C++:: C and C++ portability pitfalls
291 * Manual Configuration:: Selecting features that can't be guessed
292 * Site Configuration:: Local defaults for @command{configure}
293 * Running configure Scripts:: How to use the Autoconf output
294 * config.status Invocation:: Recreating a configuration
295 * Obsolete Constructs:: Kept for backward compatibility
296 * Using Autotest:: Creating portable test suites
297 * FAQ:: Frequent Autoconf Questions, with answers
298 * History:: History of Autoconf
299 * GNU Free Documentation License:: License for copying this manual
300 * Indices:: Indices of symbols, concepts, etc.
301
302 @detailmenu
303 --- The Detailed Node Listing ---
304
305 The GNU Build System
306
307 * Automake:: Escaping makefile hell
308 * Gnulib:: The GNU portability library
309 * Libtool:: Building libraries portably
310 * Pointers:: More info on the GNU build system
311
312 Making @command{configure} Scripts
313
314 * Writing Autoconf Input:: What to put in an Autoconf input file
315 * autoscan Invocation:: Semi-automatic @file{configure.ac} writing
316 * ifnames Invocation:: Listing the conditionals in source code
317 * autoconf Invocation:: How to create configuration scripts
318 * autoreconf Invocation:: Remaking multiple @command{configure} scripts
319
320 Writing @file{configure.ac}
321
322 * Shell Script Compiler:: Autoconf as solution of a problem
323 * Autoconf Language:: Programming in Autoconf
324 * Autoconf Input Layout:: Standard organization of @file{configure.ac}
325
326 Initialization and Output Files
327
328 * Initializing configure:: Option processing etc.
329 * Versioning:: Dealing with Autoconf versions
330 * Notices:: Copyright, version numbers in @command{configure}
331 * Input:: Where Autoconf should find files
332 * Output:: Outputting results from the configuration
333 * Configuration Actions:: Preparing the output based on results
334 * Configuration Files:: Creating output files
335 * Makefile Substitutions:: Using output variables in makefiles
336 * Configuration Headers:: Creating a configuration header file
337 * Configuration Commands:: Running arbitrary instantiation commands
338 * Configuration Links:: Links depending on the configuration
339 * Subdirectories:: Configuring independent packages together
340 * Default Prefix:: Changing the default installation prefix
341
342 Substitutions in Makefiles
343
344 * Preset Output Variables:: Output variables that are always set
345 * Installation Directory Variables:: Other preset output variables
346 * Changed Directory Variables:: Warnings about @file{datarootdir}
347 * Build Directories:: Supporting multiple concurrent compiles
348 * Automatic Remaking:: Makefile rules for configuring
349
350 Configuration Header Files
351
352 * Header Templates:: Input for the configuration headers
353 * autoheader Invocation:: How to create configuration templates
354 * Autoheader Macros:: How to specify CPP templates
355
356 Existing Tests
357
358 * Common Behavior:: Macros' standard schemes
359 * Alternative Programs:: Selecting between alternative programs
360 * Files:: Checking for the existence of files
361 * Libraries:: Library archives that might be missing
362 * Library Functions:: C library functions that might be missing
363 * Header Files:: Header files that might be missing
364 * Declarations:: Declarations that may be missing
365 * Structures:: Structures or members that might be missing
366 * Types:: Types that might be missing
367 * Compilers and Preprocessors:: Checking for compiling programs
368 * System Services:: Operating system services
369 * C and POSIX Variants:: Kludges for C and POSIX variants
370 * Erlang Libraries:: Checking for the existence of Erlang libraries
371
372 Common Behavior
373
374 * Standard Symbols:: Symbols defined by the macros
375 * Default Includes:: Includes used by the generic macros
376
377 Alternative Programs
378
379 * Particular Programs:: Special handling to find certain programs
380 * Generic Programs:: How to find other programs
381
382 Library Functions
383
384 * Function Portability:: Pitfalls with usual functions
385 * Particular Functions:: Special handling to find certain functions
386 * Generic Functions:: How to find other functions
387
388 Header Files
389
390 * Header Portability:: Collected knowledge on common headers
391 * Particular Headers:: Special handling to find certain headers
392 * Generic Headers:: How to find other headers
393
394 Declarations
395
396 * Particular Declarations:: Macros to check for certain declarations
397 * Generic Declarations:: How to find other declarations
398
399 Structures
400
401 * Particular Structures:: Macros to check for certain structure members
402 * Generic Structures:: How to find other structure members
403
404 Types
405
406 * Particular Types:: Special handling to find certain types
407 * Generic Types:: How to find other types
408
409 Compilers and Preprocessors
410
411 * Specific Compiler Characteristics:: Some portability issues
412 * Generic Compiler Characteristics:: Language independent tests and features
413 * C Compiler:: Checking its characteristics
414 * C++ Compiler:: Likewise
415 * Objective C Compiler:: Likewise
416 * Objective C++ Compiler:: Likewise
417 * Erlang Compiler and Interpreter:: Likewise
418 * Fortran Compiler:: Likewise
419 * Go Compiler:: Likewise
420 * Algol 68 Compiler:: Likewise
421
422 Writing Tests
423
424 * Language Choice:: Selecting which language to use for testing
425 * Writing Test Programs:: Forging source files for compilers
426 * Running the Preprocessor:: Detecting preprocessor symbols
427 * Running the Compiler:: Detecting language or header features
428 * Running the Linker:: Detecting library features
429 * Runtime:: Testing for runtime features
430 * Multiple Cases:: Tests for several possible values
431
432 Writing Test Programs
433
434 * Guidelines:: General rules for writing test programs
435 * Test Functions:: Avoiding pitfalls in test programs
436 * Generating Sources:: Source program boilerplate
437
438 Results of Tests
439
440 * Defining Symbols:: Defining C preprocessor symbols
441 * Setting Output Variables:: Replacing variables in output files
442 * Special Chars in Variables:: Characters to beware of in variables
443 * Caching Results:: Speeding up subsequent @command{configure} runs
444 * Printing Messages:: Notifying @command{configure} users
445
446 Caching Results
447
448 * Cache Variable Names:: Shell variables used in caches
449 * Cache Files:: Files @command{configure} uses for caching
450 * Cache Checkpointing:: Loading and saving the cache file
451
452 Programming in M4
453
454 * M4 Quotation:: Protecting macros from unwanted expansion
455 * Using autom4te:: The Autoconf executables backbone
456 * Programming in M4sugar:: Convenient pure M4 macros
457 * Debugging via autom4te:: Figuring out what M4 was doing
458
459 M4 Quotation
460
461 * Active Characters:: Characters that change the behavior of M4
462 * One Macro Call:: Quotation and one macro call
463 * Quoting and Parameters:: M4 vs. shell parameters
464 * Quotation and Nested Macros:: Macros calling macros
465 * Changequote is Evil:: Worse than INTERCAL: M4 + changequote
466 * Quadrigraphs:: Another way to escape special characters
467 * Balancing Parentheses:: Dealing with unbalanced parentheses
468 * Quotation Rule Of Thumb:: One parenthesis, one quote
469
470 Using @command{autom4te}
471
472 * autom4te Invocation:: A GNU M4 wrapper
473 * Customizing autom4te:: Customizing the Autoconf package
474
475 Programming in M4sugar
476
477 * Redefined M4 Macros:: M4 builtins changed in M4sugar
478 * Diagnostic Macros:: Diagnostic messages from M4sugar
479 * Diversion support:: Diversions in M4sugar
480 * Conditional constructs:: Conditions in M4
481 * Looping constructs:: Iteration in M4
482 * Evaluation Macros:: More quotation and evaluation control
483 * Text processing Macros:: String manipulation in M4
484 * Number processing Macros:: Arithmetic computation in M4
485 * Set manipulation Macros:: Set manipulation in M4
486 * Forbidden Patterns:: Catching unexpanded macros
487
488 Programming in M4sh
489
490 * Common Shell Constructs:: Portability layer for common shell constructs
491 * Polymorphic Variables:: Support for indirect variable names
492 * Initialization Macros:: Macros to establish a sane shell environment
493 * File Descriptor Macros:: File descriptor macros for input and output
494
495 Writing Autoconf Macros
496
497 * Macro Definitions:: Basic format of an Autoconf macro
498 * Macro Names:: What to call your new macros
499 * Dependencies Between Macros:: What to do when macros depend on other macros
500 * Obsoleting Macros:: Warning about old ways of doing things
501 * Coding Style:: Writing Autoconf macros à la Autoconf
502
503 Dependencies Between Macros
504
505 * Prerequisite Macros:: Ensuring required information
506 * Suggested Ordering:: Warning about possible ordering problems
507 * One-Shot Macros:: Ensuring a macro is called only once
508
509 Portable Shell Programming
510
511 * Systemology:: A zoology of operating systems
512 * Shellology:: A zoology of shells
513 * Invoking the Shell:: Invoking the shell as a command
514 * Here-Documents:: Quirks and tricks
515 * File Descriptors:: FDs and redirections
516 * Signal Handling:: Shells, signals, and headaches
517 * File System Conventions:: File names
518 * Shell Pattern Matching:: Pattern matching
519 * Shell Substitutions:: Variable and command expansions
520 * Assignments:: Varying side effects of assignments
521 * Parentheses:: Parentheses in shell scripts
522 * Special Shell Variables:: Variables you should not change
523 * Shell Functions:: What to look out for if you use them
524 * Limitations of Builtins:: Portable use of not so portable /bin/sh
525 * Limitations of Usual Tools:: Portable use of portable tools
526
527 Portable Make Programming
528
529 * $< in Ordinary Make Rules:: $< in ordinary rules
530 * Failure in Make Rules:: Failing portably in rules
531 * Command Line Prefixes:: What's at the start of makefile command lines
532 * Special Chars in Names:: Special characters in macro names
533 * Backslash-Newline-Empty:: Empty lines after backslash-newline
534 * Backslash-Newline Comments:: Spanning comments across line boundaries
535 * Macros and Submakes:: @code{make macro=value} and submakes
536 * The Make Macro MAKEFLAGS:: @code{$(MAKEFLAGS)} portability issues
537 * The Make Macro SHELL:: @code{$(SHELL)} portability issues
538 * Parallel Make:: Parallel @command{make} quirks
539 * Comments in Make Rules:: Other problems with Make comments
540 * Newlines in Make Rules:: Using literal newlines in rules
541 * Comments in Make Macros:: Other problems with Make comments in macros
542 * Trailing whitespace in Make Macros:: Macro substitution problems
543 * Command-line Macros and whitespace:: Whitespace trimming of values
544 * obj/ and Make:: Don't name a subdirectory @file{obj}
545 * make -k Status:: Exit status of @samp{make -k}
546 * VPATH and Make:: @code{VPATH} woes
547 * Single Suffix Rules:: Single suffix rules and separated dependencies
548 * Timestamps and Make:: Sub-second timestamp resolution
549
550 @code{VPATH} and Make
551
552 * Variables listed in VPATH:: @code{VPATH} must be literal on ancient hosts
553 * VPATH and Double-colon:: Problems with @samp{::} on ancient hosts
554 * $< in Explicit Rules:: @code{$<} does not work in ordinary rules
555 * Automatic Rule Rewriting:: @code{VPATH} goes wild on Solaris
556 * Make Target Lookup:: More details about @code{VPATH} lookup
557
558 Portable C and C++ Programming
559
560 * Varieties of Unportability:: How to make your programs unportable
561 * Integer Overflow:: When integers get too large
562 * Preprocessor Arithmetic:: @code{#if} expression problems
563 * Null Pointers:: Properties of null pointers
564 * Buffer Overruns:: Subscript errors and the like
565 * Volatile Objects:: @code{volatile} and signals
566 * Floating Point Portability:: Portable floating-point arithmetic
567 * Exiting Portably:: Exiting and the exit status
568
569 Integer Overflow
570
571 * Integer Overflow Basics:: Why integer overflow is a problem
572 * Signed Overflow Examples:: Examples of code assuming wraparound
573 * Optimization and Wraparound:: Optimizations that break uses of wraparound
574 * Signed Overflow Advice:: Practical advice for signed overflow issues
575 * Signed Integer Division:: @code{INT_MIN / -1} and @code{INT_MIN % -1}
576
577 Manual Configuration
578
579 * Specifying Target Triplets:: Specifying target triplets
580 * Canonicalizing:: Getting the canonical system type
581 * Using System Type:: What to do with the system type
582
583 Site Configuration
584
585 * Help Formatting:: Customizing @samp{configure --help}
586 * External Software:: Working with other optional software
587 * Package Options:: Selecting optional features
588 * Pretty Help Strings:: Formatting help string
589 * Option Checking:: Controlling checking of @command{configure} options
590 * Site Details:: Configuring site details
591 * Transforming Names:: Changing program names when installing
592 * Site Defaults:: Giving @command{configure} local defaults
593
594 Transforming Program Names When Installing
595
596 * Transformation Options:: @command{configure} options to transform names
597 * Transformation Examples:: Sample uses of transforming names
598 * Transformation Rules:: Makefile uses of transforming names
599
600 Running @command{configure} Scripts
601
602 * Basic Installation:: Instructions for typical cases
603 * Installation Prerequisites:: What you need to install
604 * Compilers and Options:: Selecting compilers and optimization
605 * Multiple Architectures:: Compiling for multiple architectures at once
606 * Installation Names:: Installing in different directories
607 * Optional Features:: Selecting optional features
608 * System Types:: Specifying a system type
609 * Sharing Defaults:: Setting site-wide defaults for @command{configure}
610 * Defining Variables:: Specifying the compiler etc.
611 * configure Invocation:: Changing how @command{configure} runs
612
613 Obsolete Constructs
614
615 * Obsolete config.status Use:: Obsolete convention for @command{config.status}
616 * acconfig Header:: Additional entries in @file{config.h.in}
617 * autoupdate Invocation:: Automatic update of @file{configure.ac}
618 * Obsolete Macros:: Backward compatibility macros
619 * Autoconf 1:: Tips for upgrading your files
620 * Autoconf 2.13:: Some fresher tips
621
622 Upgrading From Version 1
623
624 * Changed File Names:: Files you might rename
625 * Changed Makefiles:: New things to put in @file{Makefile.in}
626 * Changed Macros:: Macro calls you might replace
627 * Changed Results:: Changes in how to check test results
628 * Changed Macro Writing:: Better ways to write your own macros
629
630 Upgrading From Version 2.13
631
632 * Changed Quotation:: Broken code which used to work
633 * New Macros:: Interaction with foreign macros
634 * Hosts and Cross-Compilation:: Bugward compatibility kludges
635 * AC_LIBOBJ vs LIBOBJS:: LIBOBJS is a forbidden token
636 * AC_ACT_IFELSE vs AC_TRY_ACT:: A more generic scheme for testing sources
637
638 Generating Test Suites with Autotest
639
640 * Using an Autotest Test Suite:: Autotest and the user
641 * Writing Testsuites:: Autotest macros
642 * testsuite Invocation:: Running @command{testsuite} scripts
643 * Making testsuite Scripts:: Using autom4te to create @command{testsuite}
644
645 Using an Autotest Test Suite
646
647 * testsuite Scripts:: The concepts of Autotest
648 * Autotest Logs:: Their contents
649
650 Frequent Autoconf Questions, with answers
651
652 * Distributing:: Distributing @command{configure} scripts
653 * Why GNU M4:: Why not use the standard M4?
654 * Bootstrapping:: Autoconf and GNU M4 require each other?
655 * Why Not Imake:: Why GNU uses @command{configure} instead of Imake
656 * Defining Directories:: Passing @code{datadir} to program
657 * Autom4te Cache:: What is it? Can I remove it?
658 * Present But Cannot Be Compiled:: Compiler and Preprocessor Disagree
659 * Expanded Before Required:: Expanded Before Required
660 * Debugging:: Debugging @command{configure} scripts
661
662 History of Autoconf
663
664 * Genesis:: Prehistory and naming of @command{configure}
665 * Exodus:: The plagues of M4 and Perl
666 * Leviticus:: The priestly code of portability arrives
667 * Numbers:: Growth and contributors
668 * Deuteronomy:: Approaching the promises of easy configuration
669
670 Indices
671
672 * Environment Variable Index:: Index of environment variables used
673 * Output Variable Index:: Index of variables set in output files
674 * Preprocessor Symbol Index:: Index of C preprocessor symbols defined
675 * Cache Variable Index:: Index of documented cache variables
676 * Autoconf Macro Index:: Index of Autoconf macros
677 * M4 Macro Index:: Index of M4, M4sugar, and M4sh macros
678 * Autotest Macro Index:: Index of Autotest macros
679 * Program & Function Index:: Index of those with portability problems
680 * Concept Index:: General index
681
682 @end detailmenu
683 @end menu
684
685 @c ============================================================= Introduction.
686
687 @node Introduction
688 @chapter Introduction
689 @cindex Introduction
690
691 @flushright
692 A physicist, an engineer, and a computer scientist were discussing the
693 nature of God. ``Surely a Physicist,'' said the physicist, ``because
694 early in the Creation, God made Light; and you know, Maxwell's
695 equations, the dual nature of electromagnetic waves, the relativistic
696 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
697 before making Light, God split the Chaos into Land and Water; it takes
698 a hell of an engineer to handle that big amount of mud, and orderly
699 separation of solids from liquids@enddots{}'' The computer scientist
700 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
701
702 ---Anonymous
703 @end flushright
704 @c (via François Pinard)
705
706 Autoconf is a tool for producing shell scripts that automatically
707 configure software source code packages to adapt to many kinds of
708 POSIX-like systems. The configuration scripts produced by Autoconf
709 are independent of Autoconf when they are run, so their users do not
710 need to have Autoconf.
711
712 The configuration scripts produced by Autoconf require no manual user
713 intervention when run; they do not normally even need an argument
714 specifying the system type. Instead, they individually test for the
715 presence of each feature that the software package they are for might need.
716 (Before each check, they print a one-line message stating what they are
717 checking for, so the user doesn't get too bored while waiting for the
718 script to finish.) As a result, they deal well with systems that are
719 hybrids or customized from the more common POSIX variants. There is
720 no need to maintain files that list the features supported by each
721 release of each variant of POSIX.
722
723 For each software package that Autoconf is used with, it creates a
724 configuration script from a template file that lists the system features
725 that the package needs or can use. After the shell code to recognize
726 and respond to a system feature has been written, Autoconf allows it to
727 be shared by many software packages that can use (or need) that feature.
728 If it later turns out that the shell code needs adjustment for some
729 reason, it needs to be changed in only one place; all of the
730 configuration scripts can be regenerated automatically to take advantage
731 of the updated code.
732
733 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
734 @c --Henry Spencer, 1987 (see https://en.wikipedia.org/wiki/Unix_philosophy)
735 Those who do not understand Autoconf are condemned to reinvent it, poorly.
736 The primary goal of Autoconf is making the @emph{user's} life easier;
737 making the @emph{maintainer's} life easier is only a secondary goal.
738 Put another way, the primary goal is not to make the generation of
739 @file{configure} automatic for package maintainers (although patches
740 along that front are welcome, since package maintainers form the user
741 base of Autoconf); rather, the goal is to make @file{configure}
742 painless, portable, and predictable for the end user of each
743 @dfn{autoconfiscated} package. And to this degree, Autoconf is highly
744 successful at its goal---most complaints to the Autoconf list are
745 about difficulties in writing Autoconf input, and not in the behavior of
746 the resulting @file{configure}. Even packages that don't use Autoconf
747 will generally provide a @file{configure} script, and the most common
748 complaint about these alternative home-grown scripts is that they fail
749 to meet one or more of the GNU Coding Standards (@pxref{Configuration, , ,
750 standards, The GNU Coding Standards}) that users
751 have come to expect from Autoconf-generated @file{configure} scripts.
752
753 The Metaconfig package is similar in purpose to Autoconf, but the
754 scripts it produces require manual user intervention, which is quite
755 inconvenient when configuring large source trees. Unlike Metaconfig
756 scripts, Autoconf scripts can support cross-compiling, if some care is
757 taken in writing them.
758
759 Autoconf does not solve all problems related to making portable
760 software packages---for a more complete solution, it should be used in
761 concert with other GNU build tools like Automake and
762 Libtool. These other tools take on jobs like the creation of a
763 portable, recursive makefile with all of the standard targets,
764 linking of shared libraries, and so on. @xref{The GNU Build System},
765 for more information.
766
767 Autoconf imposes some restrictions on the names of macros used with
768 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
769
770 Autoconf requires GNU M4 version 1.4.8 or later in order to
771 generate the scripts. It uses features that some versions of M4,
772 including GNU M4 1.3, do not have. Autoconf works better
773 with GNU M4 version 1.4.16 or later, though this is not
774 required.
775
776 @xref{Autoconf 1}, for information about upgrading from version 1.
777 @xref{History}, for the story of Autoconf's development. @xref{FAQ},
778 for answers to some common questions about Autoconf.
779
780 See the @uref{https://@/www.gnu.org/@/software/@/autoconf/,
781 Autoconf web page} for up-to-date information, details on the mailing
782 lists, pointers to a list of known bugs, etc.
783
784 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
785 list}. Past suggestions are
786 @uref{https://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
787
788 Mail bug reports to @email{bug-autoconf@@gnu.org, the
789 Autoconf Bugs mailing list}. Past bug reports are
790 @uref{https://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
791
792 If possible, first check that your bug is
793 not already solved in current development versions, and that it has not
794 been reported yet. Be sure to include all the needed information and a
795 short @file{configure.ac} that demonstrates the problem.
796
797 Autoconf's development tree is accessible via @command{git}; see the
798 @uref{https://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
799 Summary} for details, or view
800 @uref{https://@/git.savannah.gnu.org/@/cgit/@/autoconf.git, the actual
801 repository}. Patches relative to the current @command{git} version can
802 be sent for review to the @email{autoconf-patches@@gnu.org, Autoconf
803 Patches mailing list}, with discussion on prior patches
804 @uref{https://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
805 archived}; and all commits are posted in the read-only
806 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
807 also @uref{https://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
808 archived}.
809
810 Because of its mission, the Autoconf package itself
811 includes only a set of often-used
812 macros that have already demonstrated their usefulness. Nevertheless,
813 if you wish to share your macros, or find existing ones, see the
814 @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
815 Archive}, which is kindly run by @email{simons@@cryp.to,
816 Peter Simons}.
817
818
819 @c ================================================= The GNU Build System
820
821 @node The GNU Build System
822 @chapter The GNU Build System
823 @cindex GNU build system
824
825 Autoconf solves an important problem---reliable discovery of
826 system-specific build and runtime information---but this is only one
827 piece of the puzzle for the development of portable software. To this
828 end, the GNU project has developed a suite of integrated
829 utilities to finish the job Autoconf started: the GNU build
830 system, whose most important components are Autoconf, Automake, and
831 Libtool. In this chapter, we introduce you to those tools, point you
832 to sources of more information, and try to convince you to use the
833 entire GNU build system for your software.
834
835 @menu
836 * Automake:: Escaping makefile hell
837 * Gnulib:: The GNU portability library
838 * Libtool:: Building libraries portably
839 * Pointers:: More info on the GNU build system
840 @end menu
841
842 @node Automake
843 @section Automake
844
845 The ubiquity of @command{make} means that a makefile is almost the
846 only viable way to distribute automatic build rules for software, but
847 one quickly runs into its numerous limitations. Its lack of
848 support for automatic dependency tracking, recursive builds in
849 subdirectories, reliable timestamps (e.g., for network file systems), and
850 so on, mean that developers must painfully (and often incorrectly)
851 reinvent the wheel for each project. Portability is non-trivial, thanks
852 to the quirks of @command{make} on many systems. On top of all this is the
853 manual labor required to implement the many standard targets that users
854 have come to expect (@code{make install}, @code{make distclean},
855 @code{make uninstall}, etc.). Since you are, of course, using Autoconf,
856 you also have to insert repetitive code in your @file{Makefile.in} to
857 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
858 provided by @command{configure}. Into this mess steps @dfn{Automake}.
859 @cindex Automake
860
861 Automake allows you to specify your build needs in a @file{Makefile.am}
862 file with a vastly simpler and more powerful syntax than that of a plain
863 makefile, and then generates a portable @file{Makefile.in} for
864 use with Autoconf. For example, the @file{Makefile.am} to build and
865 install a simple ``Hello world'' program might look like:
866
867 @example
868 bin_PROGRAMS = hello
869 hello_SOURCES = hello.c
870 @end example
871
872 @noindent
873 The resulting @file{Makefile.in} (~400 lines) automatically supports all
874 the standard targets, the substitutions provided by Autoconf, automatic
875 dependency tracking, @code{VPATH} building, and so on. @command{make}
876 builds the @code{hello} program, and @code{make install} installs it
877 in @file{/usr/local/bin} (or whatever prefix was given to
878 @command{configure}, if not @file{/usr/local}).
879
880 The benefits of Automake increase for larger packages (especially ones
881 with subdirectories), but even for small programs the added convenience
882 and portability can be substantial. And that's not all@enddots{}
883
884 @node Gnulib
885 @section Gnulib
886
887 GNU software has a well-deserved reputation for running on
888 many different types of systems. While our primary goal is to write
889 software for the GNU system, many users and developers have
890 been introduced to us through the systems that they were already using.
891
892 @cindex Gnulib
893 Gnulib is a central location for common GNU code, intended to
894 be shared among free software packages. Its components are typically
895 shared at the source level, rather than being a library that gets built,
896 installed, and linked against. The idea is to copy files from Gnulib
897 into your own source tree. There is no distribution tarball; developers
898 should just grab source modules from the repository. The source files
899 are available online, under various licenses, mostly GNU
900 GPL or GNU LGPL.
901
902 Gnulib modules typically contain C source code along with Autoconf
903 macros used to configure the source code. For example, the Gnulib
904 @code{stdckdint} module implements a @file{stdckdint.h} header that nearly
905 conforms to C23, even on older hosts that lack @file{stdckdint.h}.
906 This module contains a source file for the replacement header, along
907 with an Autoconf macro that arranges to use the replacement header on
908 older systems.
909
910 For more information, consult the Gnulib website,
911 @uref{https://@/www.gnu.org/@/software/@/gnulib/}.
912
913 @node Libtool
914 @section Libtool
915
916 Often, one wants to build not only programs, but libraries, so that
917 other programs can benefit from the fruits of your labor. Ideally, one
918 would like to produce @emph{shared} (dynamically linked) libraries,
919 which can be used by multiple programs without duplication on disk or in
920 memory and can be updated independently of the linked programs.
921 Producing shared libraries portably, however, is the stuff of
922 nightmares---each system has its own incompatible tools, compiler flags,
923 and magic incantations. Fortunately, GNU provides a solution:
924 @dfn{Libtool}.
925 @cindex Libtool
926
927 Libtool handles all the requirements of building shared libraries for
928 you, and at this time seems to be the @emph{only} way to do so with any
929 portability. It also handles many other headaches, such as: the
930 interaction of Make rules with the variable suffixes of
931 shared libraries, linking reliably with shared libraries before they are
932 installed by the superuser, and supplying a consistent versioning system
933 (so that different versions of a library can be installed or upgraded
934 without breaking binary compatibility). Although Libtool, like
935 Autoconf, can be used without Automake, it is most simply utilized in
936 conjunction with Automake---there, Libtool is used automatically
937 whenever shared libraries are needed, and you need not know its syntax.
938
939 @node Pointers
940 @section Pointers
941
942 Developers who are used to the simplicity of @command{make} for small
943 projects on a single system might be daunted at the prospect of
944 learning to use Automake and Autoconf. As your software is
945 distributed to more and more users, however, you otherwise
946 quickly find yourself putting lots of effort into reinventing the
947 services that the GNU build tools provide, and making the
948 same mistakes that they once made and overcame. (Besides, since
949 you're already learning Autoconf, Automake is a piece of cake.)
950
951 There are a number of places that you can go to for more information on
952 the GNU build tools.
953
954 @itemize @minus
955
956 @item Web
957
958 The project home pages for
959 @uref{https://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
960 @uref{https://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
961 @uref{https://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
962 @uref{https://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
963
964 @item Automake Manual
965
966 @xref{Top, , Automake, automake, GNU Automake}, for more
967 information on Automake.
968
969 @item Books
970
971 The book @cite{GNU Autoconf, Automake and
972 Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
973 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor. SAMS (originally
974 New Riders), 2000, ISBN 1578701902.} describes the complete GNU
975 build environment. You can also find
976 @uref{https://@/www.sourceware.org/@/autobook/, the entire book on-line}.
977
978 @end itemize
979
980 @c ================================================= Making configure Scripts.
981
982 @node Making configure Scripts
983 @chapter Making @command{configure} Scripts
984 @cindex @file{aclocal.m4}
985 @cindex @command{configure}
986
987 The configuration scripts that Autoconf produces are by convention
988 called @command{configure}. When run, @command{configure} creates several
989 files, replacing configuration parameters in them with appropriate
990 values. The files that @command{configure} creates are:
991
992 @itemize @minus
993 @item
994 one or more @file{Makefile} files, usually one in each subdirectory of the
995 package (@pxref{Makefile Substitutions});
996
997 @item
998 optionally, a C header file, the name of which is configurable,
999 containing @code{#define} directives (@pxref{Configuration Headers});
1000
1001 @item
1002 a shell script called @file{config.status} that, when run, recreates
1003 the files listed above (@pxref{config.status Invocation});
1004
1005 @item
1006 an optional shell script normally called @file{config.cache}
1007 (created when using @samp{configure --config-cache}) that
1008 saves the results of running many of the tests (@pxref{Cache Files});
1009
1010 @item
1011 a file called @file{config.log} containing any messages produced by
1012 compilers, to help debugging if @command{configure} makes a mistake.
1013 @end itemize
1014
1015 @cindex @file{configure.ac}
1016 To create a @command{configure} script with Autoconf, you need
1017 to write an Autoconf input file @file{configure.ac} and run
1018 @command{autoconf} on it. If you write your own feature tests to
1019 supplement those that come with Autoconf, you might also write files
1020 called @file{aclocal.m4} and @file{acsite.m4}. If you use a C header
1021 file to contain @code{#define} directives, you might also run
1022 @command{autoheader}, and you can distribute the generated file
1023 @file{config.h.in} with the package.
1024
1025 Here is a diagram showing how the files that can be used in
1026 configuration are produced. Programs that are executed are suffixed by
1027 @samp{*}. Optional files are enclosed in square brackets (@samp{[]}).
1028 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1029 macro files (by reading @file{autoconf.m4}).
1030
1031 @noindent
1032 Files used in preparing a software package for distribution, when using
1033 just Autoconf:
1034 @example
1035 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1036
1037 @group
1038 configure.ac --.
1039 | .------> autoconf* -----> configure
1040 [aclocal.m4] --+---+
1041 | `-----> [autoheader*] --> [config.h.in]
1042 [acsite.m4] ---'
1043 @end group
1044
1045 Makefile.in
1046 @end example
1047
1048 @noindent
1049 Additionally, if you use Automake, the following additional productions
1050 come into play:
1051
1052 @example
1053 @group
1054 [acinclude.m4] --.
1055 |
1056 [local macros] --+--> aclocal* --> aclocal.m4
1057 |
1058 configure.ac ----'
1059 @end group
1060
1061 @group
1062 configure.ac --.
1063 +--> automake* --> Makefile.in
1064 Makefile.am ---'
1065 @end group
1066 @end example
1067
1068 @noindent
1069 Files used in configuring a software package:
1070 @example
1071 @group
1072 .-------------> [config.cache]
1073 configure* ------------+-------------> config.log
1074 |
1075 [config.h.in] -. v .-> [config.h] -.
1076 +--> config.status* -+ +--> make*
1077 Makefile.in ---' `-> Makefile ---'
1078 @end group
1079 @end example
1080
1081 @menu
1082 * Writing Autoconf Input:: What to put in an Autoconf input file
1083 * autoscan Invocation:: Semi-automatic @file{configure.ac} writing
1084 * ifnames Invocation:: Listing the conditionals in source code
1085 * autoconf Invocation:: How to create configuration scripts
1086 * autoreconf Invocation:: Remaking multiple @command{configure} scripts
1087 @end menu
1088
1089 @node Writing Autoconf Input
1090 @section Writing @file{configure.ac}
1091
1092 To produce a @command{configure} script for a software package, create a
1093 file called @file{configure.ac} that contains invocations of the
1094 Autoconf macros that test the system features your package needs or can
1095 use. Autoconf macros already exist to check for many features; see
1096 @ref{Existing Tests}, for their descriptions. For most other features,
1097 you can use Autoconf template macros to produce custom checks; see
1098 @ref{Writing Tests}, for information about them. For especially tricky
1099 or specialized features, @file{configure.ac} might need to contain some
1100 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1101 Programming}. The @command{autoscan} program can give you a good start
1102 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1103 information).
1104
1105 @cindex @file{configure.in}
1106 Previous versions of Autoconf promoted the name @file{configure.in},
1107 which is somewhat ambiguous (the tool needed to process this file is not
1108 described by its extension), and introduces a slight confusion with
1109 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1110 processed by @command{configure}''). Using @file{configure.ac} is now
1111 preferred, while the use of @file{configure.in} will cause warnings
1112 from @command{autoconf}.
1113
1114 @menu
1115 * Shell Script Compiler:: Autoconf as solution of a problem
1116 * Autoconf Language:: Programming in Autoconf
1117 * Autoconf Input Layout:: Standard organization of @file{configure.ac}
1118 @end menu
1119
1120 @node Shell Script Compiler
1121 @subsection A Shell Script Compiler
1122
1123 Just as for any other computer language, in order to properly program
1124 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1125 the language tries to address and @emph{how} it does so.
1126
1127 The problem Autoconf addresses is that the world is a mess. After all,
1128 you are using Autoconf in order to have your package compile easily on
1129 all sorts of different systems, some of them being extremely hostile.
1130 Autoconf itself bears the price for these differences: @command{configure}
1131 must run on all those systems, and thus @command{configure} must limit itself
1132 to their lowest common denominator of features.
1133
1134 Naturally, you might then think of shell scripts; who needs
1135 @command{autoconf}? A set of properly written shell functions is enough to
1136 make it easy to write @command{configure} scripts by hand. Sigh!
1137 Unfortunately, even in 2008, where shells without any function support are
1138 far and few between, there are pitfalls to avoid when making use of them.
1139 Also, finding a Bourne shell that accepts shell functions is not trivial,
1140 even though there is almost always one on interesting porting targets.
1141
1142 So, what is really needed is some kind of compiler, @command{autoconf},
1143 that takes an Autoconf program, @file{configure.ac}, and transforms it
1144 into a portable shell script, @command{configure}.
1145
1146 How does @command{autoconf} perform this task?
1147
1148 There are two obvious possibilities: creating a brand new language or
1149 extending an existing one. The former option is attractive: all
1150 sorts of optimizations could easily be implemented in the compiler and
1151 many rigorous checks could be performed on the Autoconf program
1152 (e.g., rejecting any non-portable construct). Alternatively, you can
1153 extend an existing language, such as the @code{sh} (Bourne shell)
1154 language.
1155
1156 Autoconf does the latter: it is a layer on top of @code{sh}. It was
1157 therefore most convenient to implement @command{autoconf} as a macro
1158 expander: a program that repeatedly performs @dfn{macro expansions} on
1159 text input, replacing macro calls with macro bodies and producing a pure
1160 @code{sh} script in the end. Instead of implementing a dedicated
1161 Autoconf macro expander, it is natural to use an existing
1162 general-purpose macro language, such as M4, and implement the extensions
1163 as a set of M4 macros.
1164
1165
1166 @node Autoconf Language
1167 @subsection The Autoconf Language
1168 @cindex quotation
1169
1170 The Autoconf language differs from many other computer
1171 languages because it treats actual code the same as plain text. Whereas
1172 in C, for instance, data and instructions have different syntactic
1173 status, in Autoconf their status is rigorously the same. Therefore, we
1174 need a means to distinguish literal strings from text to be expanded:
1175 quotation.
1176
1177 When calling macros that take arguments, there must not be any white
1178 space between the macro name and the open parenthesis.
1179
1180 @example
1181 AC_INIT ([oops], [1.0]) # incorrect
1182 AC_INIT([hello], [1.0]) # good
1183 @end example
1184
1185 Arguments should
1186 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1187 separated by commas. Any leading blanks or newlines in arguments are ignored,
1188 unless they are quoted. You should always quote an argument that
1189 might contain a macro name, comma, parenthesis, or a leading blank or
1190 newline. This rule applies recursively for every macro
1191 call, including macros called from other macros. For more details on
1192 quoting rules, see @ref{Programming in M4}.
1193
1194 For instance:
1195
1196 @example
1197 AC_CHECK_HEADER([stdio.h],
1198 [AC_DEFINE([HAVE_STDIO_H], [1],
1199 [Define to 1 if you have <stdio.h>.])],
1200 [AC_MSG_ERROR([sorry, can't do anything for you])])
1201 @end example
1202
1203 @noindent
1204 is quoted properly. You may safely simplify its quotation to:
1205
1206 @example
1207 AC_CHECK_HEADER([stdio.h],
1208 [AC_DEFINE([HAVE_STDIO_H], 1,
1209 [Define to 1 if you have <stdio.h>.])],
1210 [AC_MSG_ERROR([sorry, can't do anything for you])])
1211 @end example
1212
1213 @noindent
1214 because @samp{1} cannot contain a macro call. Here, the argument of
1215 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1216 interpreted as an argument separator. Also, the second and third arguments
1217 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1218 macro calls. The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1219 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1220 if you unwisely defined a macro with a name like @samp{Define} or
1221 @samp{stdio} then they would need quoting. Cautious Autoconf users
1222 would keep the quotes, but many Autoconf users find such precautions
1223 annoying, and would rewrite the example as follows:
1224
1225 @example
1226 AC_CHECK_HEADER(stdio.h,
1227 [AC_DEFINE(HAVE_STDIO_H, 1,
1228 [Define to 1 if you have <stdio.h>.])],
1229 [AC_MSG_ERROR([sorry, can't do anything for you])])
1230 @end example
1231
1232 @noindent
1233 This is safe, so long as you adopt good naming conventions and do not
1234 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1235 @samp{h}. Though it is also safe here to omit the quotes around
1236 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1237 message strings are more likely to inadvertently contain commas.
1238
1239 The following example is wrong and dangerous, as it is underquoted:
1240
1241 @example
1242 AC_CHECK_HEADER(stdio.h,
1243 AC_DEFINE(HAVE_STDIO_H, 1,
1244 Define to 1 if you have <stdio.h>.),
1245 AC_MSG_ERROR([sorry, can't do anything for you]))
1246 @end example
1247
1248 In other cases, you may want to use text that also resembles a macro
1249 call. You must quote that text (whether just the potential problem, or
1250 the entire line) even when it is not passed as a macro argument; and you
1251 may also have to use @code{m4_pattern_allow} (@pxref{Forbidden
1252 Patterns}), to declare your intention that the resulting configure file
1253 will have a literal that resembles what would otherwise be reserved for
1254 a macro name. For example:
1255
1256 @example
1257 dnl Simulate a possible future autoconf macro
1258 m4_define([AC_DC], [oops])
1259 dnl Underquoted:
1260 echo "Hard rock was here! --AC_DC"
1261 dnl Correctly quoted:
1262 m4_pattern_allow([AC_DC])
1263 echo "Hard rock was here! --[AC_DC]"
1264 [echo "Hard rock was here! --AC_DC"]
1265 @end example
1266
1267 @noindent
1268 which results in this text in @file{configure}:
1269
1270 @example
1271 echo "Hard rock was here! --oops"
1272 echo "Hard rock was here! --AC_DC"
1273 echo "Hard rock was here! --AC_DC"
1274 @end example
1275
1276 @noindent
1277 When you use the same text in a macro argument, you must therefore have
1278 an extra quotation level (since one is stripped away by the macro
1279 substitution). In general, then, it is a good idea to @emph{use double
1280 quoting for all literal string arguments}, either around just the
1281 problematic portions, or over the entire argument:
1282
1283 @example
1284 m4_pattern_allow([AC_DC])
1285 AC_MSG_WARN([[AC_DC] stinks --Iron Maiden])
1286 AC_MSG_WARN([[AC_DC stinks --Iron Maiden]])
1287 @end example
1288
1289 It is also possible to avoid the problematic patterns in the first
1290 place, by the use of additional escaping (either a quadrigraph, or
1291 creative shell constructs), in which case it is no longer necessary to
1292 use @code{m4_pattern_allow}:
1293
1294 @example
1295 echo "Hard rock was here! --AC""_DC"
1296 AC_MSG_WARN([[AC@@&t@@_DC stinks --Iron Maiden]])
1297 @end example
1298
1299 You are now able to understand one of the constructs of Autoconf that
1300 has been continually misunderstood@enddots{} The rule of thumb is that
1301 @emph{whenever you expect macro expansion, expect quote expansion};
1302 i.e., expect one level of quotes to be lost. For instance:
1303
1304 @example
1305 AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [],
1306 [AC_MSG_ERROR([you lose])])
1307 @end example
1308
1309 @noindent
1310 is incorrect: here, the first argument of @code{AC_LANG_SOURCE} is
1311 @samp{char b[10];} and is expanded once, which results in
1312 @samp{char b10;}; and the @code{AC_LANG_SOURCE} is also expanded prior
1313 to being passed to @code{AC_COMPILE_IFELSE}. (There was an idiom common
1314 in Autoconf's past to
1315 address this issue via the M4 @code{changequote} primitive, but do not
1316 use it!) Let's take a closer look: the author meant the first argument
1317 to be understood as a literal, and therefore it must be quoted twice;
1318 likewise, the intermediate @code{AC_LANG_SOURCE} macro should be quoted
1319 once so that it is only expanded after the rest of the body of
1320 @code{AC_COMPILE_IFELSE} is in place:
1321
1322 @example
1323 AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [],
1324 [AC_MSG_ERROR([you lose])])
1325 @end example
1326
1327 @noindent
1328 Voilà, you actually produce @samp{char b[10];} this time!
1329
1330 On the other hand, descriptions (e.g., the last parameter of
1331 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1332 are subject to line breaking, for example---and should not be double quoted.
1333 Even if these descriptions are short and are not actually broken, double
1334 quoting them yields weird results.
1335
1336 Some macros take optional arguments, which this documentation represents
1337 as @ovar{arg} (not to be confused with the quote characters). You may
1338 just leave them empty, or use @samp{[]} to make the emptiness of the
1339 argument explicit, or you may simply omit the trailing commas. The
1340 three lines below are equivalent:
1341
1342 @example
1343 AC_CHECK_HEADERS([stdio.h], [], [], [])
1344 AC_CHECK_HEADERS([stdio.h],,,)
1345 AC_CHECK_HEADERS([stdio.h])
1346 @end example
1347
1348 It is best to put each macro call on its own line in
1349 @file{configure.ac}. Most of the macros don't add extra newlines; they
1350 rely on the newline after the macro call to terminate the commands.
1351 This approach makes the generated @command{configure} script a little
1352 easier to read by not inserting lots of blank lines. It is generally
1353 safe to set shell variables on the same line as a macro call, because
1354 the shell allows assignments without intervening newlines.
1355
1356 You can include comments in @file{configure.ac} files by starting them
1357 with the @samp{#}. For example, it is helpful to begin
1358 @file{configure.ac} files with a line like this:
1359
1360 @example
1361 # Process this file with autoconf to produce a configure script.
1362 @end example
1363
1364 @node Autoconf Input Layout
1365 @subsection Standard @file{configure.ac} Layout
1366
1367 The order in which @file{configure.ac} calls the Autoconf macros is not
1368 important, with a few exceptions. Every @file{configure.ac} must
1369 contain a call to @code{AC_INIT} before the checks, and a call to
1370 @code{AC_OUTPUT} at the end (@pxref{Output}). Additionally, some macros
1371 rely on other macros having been called first, because they check
1372 previously set values of some variables to decide what to do. These
1373 macros are noted in the individual descriptions (@pxref{Existing
1374 Tests}), and they also warn you when @command{configure} is created if they
1375 are called out of order.
1376
1377 To encourage consistency, here is a suggested order for calling the
1378 Autoconf macros. Generally speaking, the things near the end of this
1379 list are those that could depend on things earlier in it. For example,
1380 library functions could be affected by types and libraries.
1381
1382 @display
1383 @group
1384 Autoconf requirements
1385 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1386 information on the package
1387 checks for programs
1388 checks for libraries
1389 checks for header files
1390 checks for types
1391 checks for structures
1392 checks for compiler characteristics
1393 checks for library functions
1394 checks for system services
1395 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1396 @code{AC_OUTPUT}
1397 @end group
1398 @end display
1399
1400
1401 @node autoscan Invocation
1402 @section Using @command{autoscan} to Create @file{configure.ac}
1403 @cindex @command{autoscan}
1404
1405 The @command{autoscan} program can help you create and/or maintain a
1406 @file{configure.ac} file for a software package. @command{autoscan}
1407 examines source files in the directory tree rooted at a directory given
1408 as a command line argument, or the current directory if none is given.
1409 It searches the source files for common portability problems and creates
1410 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1411 for that package, and checks a possibly existing @file{configure.ac} for
1412 completeness.
1413
1414 When using @command{autoscan} to create a @file{configure.ac}, you
1415 should manually examine @file{configure.scan} before renaming it to
1416 @file{configure.ac}; it probably needs some adjustments.
1417 Occasionally, @command{autoscan} outputs a macro in the wrong order
1418 relative to another macro, so that @command{autoconf} produces a warning;
1419 you need to move such macros manually. Also, if you want the package to
1420 use a configuration header file, you must add a call to
1421 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}). You might
1422 also have to change or add some @code{#if} directives to your program in
1423 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1424 information about a program that can help with that job).
1425
1426 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1427 consider adding its suggestions. The file @file{autoscan.log}
1428 contains detailed information on why a macro is requested.
1429
1430 @command{autoscan} uses several data files (installed along with Autoconf)
1431 to determine which macros to output when it finds particular symbols in
1432 a package's source files. These data files all have the same format:
1433 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1434 output if that symbol is encountered. Lines starting with @samp{#} are
1435 comments.
1436
1437 @command{autoscan} accepts the following options:
1438
1439 @table @option
1440 @item --help
1441 @itemx -h
1442 Print a summary of the command line options and exit.
1443
1444 @item --version
1445 @itemx -V
1446 Print the version number of Autoconf and exit.
1447
1448 @item --verbose
1449 @itemx -v
1450 Print the names of the files it examines and the potentially interesting
1451 symbols it finds in them. This output can be voluminous.
1452
1453 @item --debug
1454 @itemx -d
1455 Don't remove temporary files.
1456
1457 @item --include=@var{dir}
1458 @itemx -I @var{dir}
1459 Append @var{dir} to the include path. Multiple invocations accumulate.
1460
1461 @item --prepend-include=@var{dir}
1462 @itemx -B @var{dir}
1463 Prepend @var{dir} to the include path. Multiple invocations accumulate.
1464 @end table
1465
1466 @node ifnames Invocation
1467 @section Using @command{ifnames} to List Conditionals
1468 @cindex @command{ifnames}
1469
1470 @command{ifnames} can help you write @file{configure.ac} for a software
1471 package. It prints the identifiers that the package already uses in C
1472 preprocessor conditionals. If a package has already been set up to have
1473 some portability, @command{ifnames} can thus help you figure out what its
1474 @command{configure} needs to check for. It may help fill in some gaps in a
1475 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1476 Invocation}).
1477
1478 @command{ifnames} scans all of the C source files named on the command line
1479 (or the standard input, if none are given) and writes to the standard
1480 output a sorted list of all the identifiers that appear in those files
1481 in @code{#if}, @code{#ifdef}, @code{#ifndef}, @code{#elif},
1482 @code{#elifdef}, or @code{#elifndef} directives.
1483 It prints each identifier on a line, followed by a
1484 space-separated list of the files in which that identifier occurs.
1485
1486 @noindent
1487 @command{ifnames} accepts the following options:
1488
1489 @table @option
1490 @item --help
1491 @itemx -h
1492 Print a summary of the command line options and exit.
1493
1494 @item --version
1495 @itemx -V
1496 Print the version number of Autoconf and exit.
1497 @end table
1498
1499 @node autoconf Invocation
1500 @section Using @command{autoconf} to Create @command{configure}
1501 @cindex @command{autoconf}
1502
1503 To create @command{configure} from @file{configure.ac}, run the
1504 @command{autoconf} program with no arguments. @command{autoconf} processes
1505 @file{configure.ac} with the M4 macro processor, using the
1506 Autoconf macros. If you give @command{autoconf} an argument, it reads that
1507 file instead of @file{configure.ac} and writes the configuration script
1508 to the standard output instead of to @command{configure}. If you give
1509 @command{autoconf} the argument @option{-}, it reads from the standard
1510 input instead of @file{configure.ac} and writes the configuration script
1511 to the standard output.
1512
1513 The Autoconf macros are defined in several files. Some of the files are
1514 distributed with Autoconf; @command{autoconf} reads them first. Then it
1515 looks for the optional file @file{acsite.m4} in the directory that
1516 contains the distributed Autoconf macro files, and for the optional file
1517 @file{aclocal.m4} in the current directory. Those files can contain
1518 your site's or the package's own Autoconf macro definitions
1519 (@pxref{Writing Autoconf Macros}, for more information). If a macro is
1520 defined in more than one of the files that @command{autoconf} reads, the
1521 last definition it reads overrides the earlier ones.
1522
1523 @command{autoconf} accepts the following options:
1524
1525 @table @option
1526 @item --help
1527 @itemx -h
1528 Print a summary of the command line options and exit.
1529
1530 @item --version
1531 @itemx -V
1532 Print the version number of Autoconf and exit.
1533
1534 @item --verbose
1535 @itemx -v
1536 Report processing steps.
1537
1538 @item --debug
1539 @itemx -d
1540 Don't remove the temporary files.
1541
1542 @item --force
1543 @itemx -f
1544 Remake @file{configure} even if newer than its input files.
1545
1546 @item --include=@var{dir}
1547 @itemx -I @var{dir}
1548 Append @var{dir} to the include path. Multiple invocations accumulate.
1549
1550 @item --prepend-include=@var{dir}
1551 @itemx -B @var{dir}
1552 Prepend @var{dir} to the include path. Multiple invocations accumulate.
1553
1554 @item --output=@var{file}
1555 @itemx -o @var{file}
1556 Save output (script or trace) to @var{file}. The file @option{-} stands
1557 for the standard output.
1558
1559 @item --warnings=@var{category}[,@var{category}...]
1560 @itemx -W@var{category}[,@var{category}...]
1561 @evindex WARNINGS
1562 Enable or disable warnings related to each @var{category}.
1563 @xref{m4_warn}, for a comprehensive list of categories.
1564 Special values include:
1565
1566 @table @samp
1567 @item all
1568 Enable all categories of warnings.
1569
1570 @item none
1571 Disable all categories of warnings.
1572
1573 @item error
1574 Treat all warnings as errors.
1575
1576 @item no-@var{category}
1577 Disable warnings falling into @var{category}.
1578 @end table
1579
1580 The environment variable @env{WARNINGS} may also be set to a
1581 comma-separated list of warning categories to enable or disable.
1582 It is interpreted exactly the same way as the argument of
1583 @option{--warnings}, but unknown categories are silently ignored.
1584 The command line takes precedence; for instance, if @env{WARNINGS}
1585 is set to @code{obsolete}, but @option{-Wnone} is given on the
1586 command line, no warnings will be issued.
1587
1588 Some categories of warnings are on by default.
1589 Again, for details see @ref{m4_warn}.
1590
1591 @item --trace=@var{macro}[:@var{format}]
1592 @itemx -t @var{macro}[:@var{format}]
1593 Do not create the @command{configure} script, but list the calls to
1594 @var{macro} according to the @var{format}. Multiple @option{--trace}
1595 arguments can be used to list several macros. Multiple @option{--trace}
1596 arguments for a single macro are not cumulative; instead, you should
1597 just make @var{format} as long as needed.
1598
1599 The @var{format} is a regular string, with newlines if desired, and
1600 several special escape codes. It defaults to @samp{$f:$l:$n:$%}; see
1601 @ref{autom4te Invocation}, for details on the @var{format}.
1602
1603 @item --initialization
1604 @itemx -i
1605 By default, @option{--trace} does not trace the initialization of the
1606 Autoconf macros (typically the @code{AC_DEFUN} definitions). This
1607 results in a noticeable speedup, but can be disabled by this option.
1608 @end table
1609
1610
1611 It is often necessary to check the content of a @file{configure.ac}
1612 file, but parsing it yourself is extremely fragile and error-prone. It
1613 is suggested that you rely upon @option{--trace} to scan
1614 @file{configure.ac}. For instance, to find the list of variables that
1615 are substituted, use:
1616
1617 @example
1618 @group
1619 $ @kbd{autoconf -t AC_SUBST}
1620 configure.ac:28:AC_SUBST:SHELL
1621 configure.ac:28:AC_SUBST:PATH_SEPARATOR
1622 @i{More traces deleted}
1623 @end group
1624 @end example
1625
1626 @noindent
1627 The example below highlights the difference between @samp{$@@},
1628 @samp{$*}, and @samp{$%}.
1629
1630 @example
1631 @group
1632 $ @kbd{cat configure.ac}
1633 AC_DEFINE(This, is, [an
1634 [example]])
1635 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1636 *: $*
1637 %: $%'
1638 @@: [This],[is],[an
1639 [example]]
1640 *: This,is,an
1641 [example]
1642 %: This:is:an [example]
1643 @end group
1644 @end example
1645
1646 @noindent
1647 The @var{format} gives you a lot of freedom:
1648
1649 @example
1650 @group
1651 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1652 $ac_subst@{"SHELL"@} = "configure.ac:28";
1653 $ac_subst@{"PATH_SEPARATOR"@} = "configure.ac:28";
1654 @i{More traces deleted}
1655 @end group
1656 @end example
1657
1658 @noindent
1659 A long @var{separator} can be used to improve the readability of complex
1660 structures, and to ease their parsing (for instance when no single
1661 character is suitable as a separator):
1662
1663 @example
1664 @group
1665 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1666 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1667 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1668 AUTOMAKE|:::::|automake|:::::|$missing_dir
1669 @i{More traces deleted}
1670 @end group
1671 @end example
1672
1673 @node autoreconf Invocation
1674 @section Using @command{autoreconf} to Update @command{configure} Scripts
1675 @cindex @command{autoreconf}
1676
1677 Installing the various components of the GNU Build System can be
1678 tedious: running @command{autopoint} for Gettext, @command{automake} for
1679 @file{Makefile.in} etc.@: in each directory. It may be needed either
1680 because some tools such as @command{automake} have been updated on your
1681 system, or because some of the sources such as @file{configure.ac} have
1682 been updated, or finally, simply in order to install the GNU Build
1683 System in a fresh tree.
1684
1685 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1686 @command{aclocal}, @command{automake}, @command{libtoolize}, @command{intltoolize},
1687 @command{gtkdocize}, and @command{autopoint} (when appropriate) repeatedly
1688 to update the GNU Build System in the specified directories and their
1689 subdirectories (@pxref{Subdirectories}). By default, it only remakes
1690 those files that are older than their sources.
1691
1692 If you install a new version of some tool, you can make
1693 @command{autoreconf} remake @emph{all} of the files by giving it the
1694 @option{--force} option.
1695
1696 The environment variables @env{AUTOM4TE}, @env{AUTOCONF},
1697 @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL}, @env{AUTOPOINT},
1698 @env{LIBTOOLIZE}, @env{INTLTOOLIZE}, @env{GTKDOCIZE}, @env{M4}, and
1699 @env{MAKE} may be used to override the invocation of the respective
1700 tools.
1701
1702 Except for @env{AUTOM4TE} and @env{M4}, setting any of these enviroment
1703 variables to @samp{true}, @samp{false}, @samp{:}, or the empty string
1704 has the same effect as passing @samp{--exclude=@var{cmd}} on the command
1705 line, where @var{cmd} is the lowercased version of the command's name;
1706 see the description of the @option{--exclude} option, below.
1707
1708 @xref{Automatic Remaking}, for Make rules to automatically
1709 rebuild @command{configure} scripts when their source files change. That
1710 method handles the timestamps of configuration header templates
1711 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1712 @option{--localdir=@var{dir}}.
1713
1714 @cindex Gettext
1715 @cindex @command{autopoint}
1716 Gettext supplies the @command{autopoint} command to add translation
1717 infrastructure to a source package. If you use @command{autopoint},
1718 your @file{configure.ac} should invoke @code{AM_GNU_GETTEXT} and
1719 one of @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})} or
1720 @code{AM_GNU_GETTEXT_REQUIRE_VERSION(@var{min-gettext-version})}.
1721 @xref{autopoint Invocation, , Invoking the @code{autopoint} Program,
1722 gettext, GNU @code{gettext} utilities}, for further details.
1723
1724 @noindent
1725 @command{autoreconf} accepts the following options:
1726
1727 @table @option
1728 @item --help
1729 @itemx -h
1730 Print a summary of the command line options and exit.
1731
1732 @item --version
1733 @itemx -V
1734 Print the version number of Autoconf and exit.
1735
1736 @item --verbose
1737 @itemx -v
1738 Print the name of each directory @command{autoreconf} examines and the
1739 commands it runs. If given two or more times, pass @option{--verbose}
1740 to subordinate tools that support it.
1741
1742 @item --debug
1743 @itemx -d
1744 Don't remove the temporary files.
1745
1746 @item --force
1747 @itemx -f
1748 Consider all generated and standard auxiliary files to be obsolete.
1749 This remakes even @file{configure} scripts and configuration headers
1750 that are newer than their input files (@file{configure.ac} and, if
1751 present, @file{aclocal.m4}).
1752
1753 If deemed appropriate, this option triggers calls to @samp{automake
1754 --force-missing}. Passing both @option{--force} and @option{--install}
1755 to @command{autoreconf} will in turn undo any customizations to standard
1756 files. Note that the macro @code{AM_INIT_AUTOMAKE} has some options
1757 which change the set of files considered to be standard.
1758
1759 @item --replace-handwritten
1760 @itemx -R
1761 Replace files that @emph{could} be generated but appear to have been
1762 written by hand. Currently this only affects the treatment of the
1763 primary configuration header template (usually @file{config.h.in};
1764 @pxref{Header Templates}). In the future it may also affect
1765 @file{aclocal.m4} and others.
1766
1767 @item --install
1768 @itemx -i
1769 Install any missing standard auxiliary files in the package. By
1770 default, files are copied; this can be changed with @option{--symlink}.
1771
1772 If deemed appropriate, this option triggers calls to
1773 @samp{automake --add-missing},
1774 @samp{libtoolize}, @samp{autopoint}, etc.
1775
1776 @item --no-recursive
1777 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1778 macro @code{AC_CONFIG_SUBDIRS}).
1779
1780 @item --symlink
1781 @itemx -s
1782 When used with @option{--install}, install symbolic links to the missing
1783 auxiliary files instead of copying them.
1784
1785 @item --make
1786 @itemx -m
1787 When the directories were configured, update the configuration by
1788 running @samp{./config.status --recheck && ./config.status}, and then
1789 run @samp{make}.
1790
1791 @item --exclude=@var{cmd}[,@var{cmd}...]
1792 @itemx -x @var{cmd}[,@var{cmd}...]
1793 Do not run any @var{cmd} in the list, even if it seems to be needed.
1794 @var{cmd} can be @samp{autoconf}, @samp{autoheader}, @samp{automake},
1795 @samp{aclocal}, @samp{autopoint}, @samp{libtoolize}, @samp{intltoolize},
1796 @samp{gtkdocize}, or @samp{make}.
1797
1798 @samp{--exclude make} has priority over @samp{--make}.
1799
1800 @item --include=@var{dir}
1801 @itemx -I @var{dir}
1802 Append @var{dir} to the include path. Multiple invocations accumulate.
1803 Passed on to @command{aclocal}, @command{autoconf} and
1804 @command{autoheader} internally.
1805
1806 @item --prepend-include=@var{dir}
1807 @itemx -B @var{dir}
1808 Prepend @var{dir} to the include path. Multiple invocations accumulate.
1809 Passed on to @command{autoconf} and @command{autoheader} internally.
1810
1811 @item --warnings=@var{category}[,@var{category}...]
1812 @itemx -W@var{category}[,@var{category}...]
1813 @evindex WARNINGS
1814 Enable or disable warnings related to each @var{category}.
1815 @xref{m4_warn}, for a comprehensive list of categories.
1816 Special values include:
1817
1818 @table @samp
1819 @item all
1820 Enable all categories of warnings.
1821
1822 @item none
1823 Disable all categories of warnings.
1824
1825 @item error
1826 Treat all warnings as errors.
1827
1828 @item no-@var{category}
1829 Disable warnings falling into @var{category}.
1830 @end table
1831
1832 The environment variable @env{WARNINGS} may also be set to a
1833 comma-separated list of warning categories to enable or disable.
1834 It is interpreted exactly the same way as the argument of
1835 @option{--warnings}, but unknown categories are silently ignored.
1836 The command line takes precedence; for instance, if @env{WARNINGS}
1837 is set to @code{obsolete}, but @option{-Wnone} is given on the
1838 command line, no warnings will be issued.
1839
1840 Some categories of warnings are on by default.
1841 Again, for details see @ref{m4_warn}.
1842 @end table
1843
1844 If you want @command{autoreconf} to pass flags that are not listed here
1845 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1846 Due to a limitation in the Autoconf implementation these flags currently
1847 must be set on a single line in @file{Makefile.am}, without any
1848 backslash-newlines or makefile comments.
1849 Also, be aware that future Automake releases might
1850 start flagging @code{ACLOCAL_AMFLAGS} as obsolescent, or even remove
1851 support for it.
1852
1853 @c ========================================= Initialization and Output Files.
1854
1855 @node Setup
1856 @chapter Initialization and Output Files
1857
1858 Autoconf-generated @command{configure} scripts need some information about
1859 how to initialize, such as how to find the package's source files and
1860 about the output files to produce. The following sections describe the
1861 initialization and the creation of output files.
1862
1863 @menu
1864 * Initializing configure:: Option processing etc.
1865 * Versioning:: Dealing with Autoconf versions
1866 * Notices:: Copyright, version numbers in @command{configure}
1867 * Input:: Where Autoconf should find files
1868 * Output:: Outputting results from the configuration
1869 * Configuration Actions:: Preparing the output based on results
1870 * Configuration Files:: Creating output files
1871 * Makefile Substitutions:: Using output variables in makefiles
1872 * Configuration Headers:: Creating a configuration header file
1873 * Configuration Commands:: Running arbitrary instantiation commands
1874 * Configuration Links:: Links depending on the configuration
1875 * Subdirectories:: Configuring independent packages together
1876 * Default Prefix:: Changing the default installation prefix
1877 @end menu
1878
1879 @node Initializing configure
1880 @section Initializing @command{configure}
1881
1882 Every @command{configure} script must call @code{AC_INIT} before doing
1883 anything else that produces output. Calls to silent macros, such as
1884 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1885 are generally used via @file{aclocal.m4}, since that is implicitly
1886 included before the start of @file{configure.ac}. The only other
1887 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1888
1889 @anchor{AC_INIT}
1890 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1891 @ovar{tarname}, @ovar{url})
1892 @acindex{INIT}
1893 Process any command-line arguments and perform initialization
1894 and verification.
1895
1896 Set the name of the @var{package} and its @var{version}. These are
1897 typically used in @option{--version} support, including that of
1898 @command{configure}. The optional argument @var{bug-report} should be
1899 the email to which users should send bug reports. The package
1900 @var{tarname} differs from @var{package}: the latter designates the full
1901 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1902 distribution tar ball names (e.g., @samp{autoconf}). It defaults to
1903 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1904 other than alphanumerics and underscores are changed to @samp{-}. If
1905 provided, @var{url} should be the home page for the package.
1906
1907 Leading and trailing whitespace is stripped from all the arguments to
1908 @code{AC_INIT}, and interior whitespace is collapsed to a single space.
1909 This means that, for instance, if you want to put several email
1910 addresses in @var{bug-report}, you can put each one on its own line:
1911
1912 @smallexample
1913 @group
1914 # We keep having problems with the mail hosting for
1915 # gnomovision.example, so give people an alternative.
1916 AC_INIT([Gnomovision], [17.0.1], [
1917 bugs@@gnomovision.example
1918 or gnomo-bugs@@reliable-email.example
1919 ])
1920 @end group
1921 @end smallexample
1922
1923 The arguments to @code{AC_INIT} may be computed by M4, when
1924 @command{autoconf} is run. For instance, if you want to include the
1925 package's version number in the @var{tarname}, but you don't want to
1926 repeat it, you can use a helper macro:
1927
1928 @smallexample
1929 @group
1930 m4_define([gnomo_VERSION], [17.0.1])
1931 AC_INIT([Gnomovision],
1932 m4_defn([gnomo_VERSION]),
1933 [bugs@@gnomovision.example],
1934 [gnomo-]m4_defn([gnomo_VERSION]))
1935 @end group
1936 @end smallexample
1937
1938 This uses @code{m4_defn} to produce the expansion of
1939 @code{gnomo_VERSION} @emph{as a quoted string}, so that if there happen
1940 to be any more M4 macro names in @code{gnomo_VERSION}, they will not be
1941 expanded. @xref{Defn,,Renaming Macros,m4,GNU m4 macro processor}.
1942
1943 Continuing this example, if you don't want to embed the version number
1944 in @file{configure.ac} at all, you can use @code{m4_esyscmd} to look it
1945 up somewhere else when @command{autoconf} is run:
1946
1947 @smallexample
1948 @group
1949 m4_define([gnomo_VERSION],
1950 m4_esyscmd([build-aux/git-version-gen .tarball-version]))
1951 AC_INIT([Gnomovision],
1952 m4_defn([gnomo_VERSION]),
1953 [bugs@@gnomovision.example],
1954 [gnomo-]m4_defn([gnomo_VERSION]))
1955 @end group
1956 @end smallexample
1957
1958 This uses the utility script @command{git-version-gen} to look up
1959 the package's version in its version control metadata. This script
1960 is part of Gnulib (@pxref{Gnulib}).
1961
1962 The arguments to @code{AC_INIT} are written into @file{configure} in
1963 several different places. Therefore, we strongly recommend that you
1964 write any M4 logic in @code{AC_INIT} arguments to be evaluated
1965 @emph{before} @code{AC_INIT} itself is evaluated. For instance, in the
1966 above example, the second argument to @code{m4_define} is @emph{not}
1967 quoted, so the @code{m4_esyscmd} is evaluated only once, and
1968 @code{gnomo_VERSION} is defined to the output of the command. If the
1969 second argument to @code{m4_define} were quoted, @code{m4_esyscmd} would
1970 be evaluated each time the @var{version} or @var{tarname} arguments were
1971 written to @file{configure}, and the command would be run repeatedly.
1972
1973 In some of the places where the arguments to @code{AC_INIT} are used,
1974 within @file{configure}, shell evaluation cannot happen. Therefore, the
1975 arguments to @code{AC_INIT} may @emph{not} be computed when
1976 @command{configure} is run. If they contain any construct that isn't
1977 always treated as literal by the shell (e.g.@: variable expansions),
1978 @command{autoconf} will issue an error.
1979
1980 The @var{tarname} argument is used to construct filenames. It should
1981 not contain wildcard characters, white space, or anything else that
1982 could be troublesome as part of a file or directory name.
1983
1984 Some of M4's active characters (notably parentheses, square brackets,
1985 @samp{,} and @samp{#}) commonly appear in URLs and lists of email
1986 addresses. If any of these characters appear in an argument to AC_INIT,
1987 that argument will probably need to be double-quoted to avoid errors
1988 and mistranscriptions. @xref{M4 Quotation}.
1989
1990 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1991 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1992 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1993
1994 @table @asis
1995 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1996 @acindex{PACKAGE_NAME}
1997 @ovindex PACKAGE_NAME
1998 @cvindex PACKAGE_NAME
1999 Exactly @var{package}.
2000
2001 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
2002 @acindex{PACKAGE_TARNAME}
2003 @ovindex PACKAGE_TARNAME
2004 @cvindex PACKAGE_TARNAME
2005 Exactly @var{tarname}, possibly generated from @var{package}.
2006
2007 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
2008 @acindex{PACKAGE_VERSION}
2009 @ovindex PACKAGE_VERSION
2010 @cvindex PACKAGE_VERSION
2011 Exactly @var{version}.
2012
2013 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
2014 @acindex{PACKAGE_STRING}
2015 @ovindex PACKAGE_STRING
2016 @cvindex PACKAGE_STRING
2017 Exactly @samp{@var{package} @var{version}}.
2018
2019 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
2020 @acindex{PACKAGE_BUGREPORT}
2021 @ovindex PACKAGE_BUGREPORT
2022 @cvindex PACKAGE_BUGREPORT
2023 Exactly @var{bug-report}, if one was provided. Typically an email
2024 address, or URL to a bug management web page.
2025
2026 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
2027 @acindex{PACKAGE_URL}
2028 @ovindex PACKAGE_URL
2029 @cvindex PACKAGE_URL
2030 Exactly @var{url}, if one was provided. If @var{url} was empty, but
2031 @var{package} begins with @samp{GNU }, then this defaults to
2032 @samp{https://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
2033 assumed.
2034 @end table
2035 @end defmac
2036
2037 If your @command{configure} script does its own option processing, it
2038 should inspect @samp{$@@} or @samp{$*} immediately after calling
2039 @code{AC_INIT}, because other Autoconf macros liberally use the
2040 @command{set} command to process strings, and this has the side effect
2041 of updating @samp{$@@} and @samp{$*}. However, we suggest that you use
2042 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
2043 implement your own option processing. @xref{Site Configuration}.
2044
2045 @node Versioning
2046 @section Dealing with Autoconf versions
2047 @cindex Autoconf version
2048 @cindex version, Autoconf
2049
2050 The following optional macros can be used to help choose the minimum
2051 version of Autoconf that can successfully compile a given
2052 @file{configure.ac}.
2053
2054 @defmac AC_PREREQ (@var{version})
2055 @acindex{PREREQ}
2056 @cindex Version
2057 Ensure that a recent enough version of Autoconf is being used. If the
2058 version of Autoconf being used to create @command{configure} is
2059 earlier than @var{version}, print an error message to the standard
2060 error output and exit with failure (exit status is 63). For example:
2061
2062 @example
2063 AC_PREREQ([@value{VERSION}])
2064 @end example
2065
2066 This macro may be used before @code{AC_INIT}.
2067 @end defmac
2068
2069 @defmac AC_AUTOCONF_VERSION
2070 @acindex{AUTOCONF_VERSION}
2071 This macro was introduced in Autoconf 2.62. It identifies the version
2072 of Autoconf that is currently parsing the input file, in a format
2073 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
2074 other words, for this release of Autoconf, its value is
2075 @samp{@value{VERSION}}. One potential use of this macro is for writing
2076 conditional fallbacks based on when a feature was added to Autoconf,
2077 rather than using @code{AC_PREREQ} to require the newer version of
2078 Autoconf. However, remember that the Autoconf philosophy favors feature
2079 checks over version checks.
2080
2081 You should not expand this macro directly; use
2082 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead. This is because some
2083 users might
2084 have a beta version of Autoconf installed, with arbitrary letters
2085 included in its version string. This means it is possible for the
2086 version string to contain the name of a defined macro, such that
2087 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
2088 macro during rescanning, and change the version string to be different
2089 than what you intended to check.
2090 @end defmac
2091
2092 @node Notices
2093 @section Notices in @command{configure}
2094 @cindex Notices in @command{configure}
2095
2096 The following macros manage version numbers for @command{configure}
2097 scripts. Using them is optional.
2098
2099 @defmac AC_COPYRIGHT (@var{copyright-notice})
2100 @acindex{COPYRIGHT}
2101 @cindex Copyright Notice
2102 State that, in addition to the Free Software Foundation's copyright on
2103 the Autoconf macros, parts of your @command{configure} are covered by the
2104 @var{copyright-notice}.
2105
2106 The @var{copyright-notice} shows up in both the head of
2107 @command{configure} and in @samp{configure --version}.
2108 @end defmac
2109
2110
2111 @defmac AC_REVISION (@var{revision-info})
2112 @acindex{REVISION}
2113 @cindex Revision
2114 Copy revision stamp @var{revision-info} into the @command{configure}
2115 script, with any dollar signs or double-quotes removed. This macro lets
2116 you put a revision stamp from @file{configure.ac} into @command{configure}
2117 that the traditional version control systems RCS and CVS can update,
2118 without these systems changing it again when you check in the resulting
2119 @command{configure}. That way, you can determine easily which revision of
2120 @file{configure.ac} a particular @command{configure} corresponds to.
2121
2122 For example, this line in @file{configure.ac}:
2123
2124 @example
2125 AC_REVISION([$Revision: 1.30 $])
2126 @end example
2127
2128 @noindent
2129 produces this in @command{configure}:
2130
2131 @example
2132 #!/bin/sh
2133 # From configure.ac Revision: 1.30
2134 @end example
2135 @end defmac
2136
2137
2138 @node Input
2139 @section Configure Input: Source Code, Macros, and Auxiliary Files
2140
2141 The following macros help you manage the contents of your source tree.
2142
2143 @anchor{AC_CONFIG_SRCDIR}
2144 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2145 @acindex{CONFIG_SRCDIR}
2146 Distinguish this package's source directory from other source
2147 directories that might happen to exist in the file system.
2148 @var{unique-file-in-source-dir} should name a file that is unique to
2149 this package. @command{configure} will verify that this file exists in
2150 @file{@var{srcdir}}, before it runs any other checks.
2151
2152 Use of this macro is strongly recommended. It protects against people
2153 accidentally specifying the wrong directory with @option{--srcdir}.
2154 @xref{configure Invocation}, for more information.
2155 @end defmac
2156
2157 Packages that use @command{aclocal} to generate @file{aclocal.m4}
2158 should declare where local macros can be found using
2159 @code{AC_CONFIG_MACRO_DIRS}.
2160
2161 @defmac AC_CONFIG_MACRO_DIRS (@var{dir1} [@var{dir2} ... @var{dirN}])
2162 @defmacx AC_CONFIG_MACRO_DIR (@var{dir})
2163 @acindex{CONFIG_MACRO_DIRS}
2164 @acindex{CONFIG_MACRO_DIR}
2165 @acindex{CONFIG_MACRO_DIR_TRACE}
2166 Specify the given directories as the location of additional local Autoconf
2167 macros. These macros are intended for use by commands like
2168 @command{autoreconf} or @command{aclocal} that trace macro calls; they should
2169 be called directly from @file{configure.ac} so that tools that install
2170 macros for @command{aclocal} can find the macros' declarations. Tools
2171 that want to learn which directories have been selected should trace
2172 @code{AC_CONFIG_MACRO_DIR_TRACE}, which will be called once per directory.
2173
2174 AC_CONFIG_MACRO_DIRS is the preferred form, and can be called multiple
2175 times and with multiple arguments; in such cases, directories in earlier
2176 calls are expected to be searched before directories in later calls, and
2177 directories appearing in the same call are expected to be searched in
2178 the order in which they appear in the call. For historical reasons, the
2179 macro AC_CONFIG_MACRO_DIR can also be used once, if it appears first,
2180 for tools such as older @command{libtool} that weren't prepared to
2181 handle multiple directories. For example, a usage like
2182
2183 @smallexample
2184 AC_CONFIG_MACRO_DIR([dir1])
2185 AC_CONFIG_MACRO_DIRS([dir2])
2186 AC_CONFIG_MACRO_DIRS([dir3 dir4])
2187 @end smallexample
2188
2189 will cause the trace of AC_CONFIG_MACRO_DIR_TRACE to appear four times,
2190 and should cause the directories to be searched in this order:
2191 @samp{dir1 dir2 dir3 dir4}.
2192
2193 Note that if you use @command{aclocal} from an Automake release prior to
2194 1.13 to generate @file{aclocal.m4}, you must also set
2195 @code{ACLOCAL_AMFLAGS = -I @var{dir1} [-I @var{dir2} ... -I @var{dirN}]}
2196 in your top-level @file{Makefile.am}. Due to a limitation in
2197 the Autoconf implementation of @command{autoreconf}, these include
2198 directives currently must be set on a single line in @file{Makefile.am},
2199 without any backslash-newlines or makefile comments.
2200 @end defmac
2201
2202 @prindex @command{config.guess}
2203 @prindex @command{config.sub}
2204 @prindex @command{install-sh}
2205
2206 Some Autoconf macros require auxiliary scripts. @code{AC_PROG_INSTALL}
2207 (@pxref{Particular Programs}) requires a
2208 fallback implementation of @command{install} called @file{install-sh},
2209 and the @code{AC_CANONICAL} macros (@pxref{Manual Configuration})
2210 require the system-identification scripts @file{config.sub} and
2211 @file{config.guess}. Third-party tools, such as Automake and Libtool,
2212 may require additional auxiliary scripts.
2213
2214 By default, @command{configure} looks for these scripts next to itself,
2215 in @file{@var{srcdir}}. For convenience when working with subdirectories
2216 with their own configure scripts (@pxref{Subdirectories}), if the
2217 scripts are not in @file{@var{srcdir}} it will also look in
2218 @file{@var{srcdir}/..} and @file{@var{srcdir}/../..}. All of the
2219 scripts must be found in the same directory.
2220
2221 If these default locations are not adequate, or simply to reduce clutter
2222 at the top level of the source tree, packages can use
2223 @code{AC_CONFIG_AUX_DIR} to declare where to look for auxiliary scripts.
2224
2225 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2226 @acindex{CONFIG_AUX_DIR}
2227 Look for auxiliary scripts in @var{dir}. Normally, @var{dir} should be a
2228 relative path, which is taken as relative to @file{@var{srcdir}}.
2229 If @var{dir} is an absolute path or contains shell variables, however,
2230 it is used as-is.
2231
2232 When the goal of using @code{AC_CONFIG_AUX_DIR} is to reduce clutter at
2233 the top level of the source tree, the conventional name for @var{dir} is
2234 @file{build-aux}. If you need portability to DOS variants, do not name
2235 the auxiliary directory @file{aux}. @xref{File System Conventions}.
2236 @end defmac
2237
2238 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2239 @acindex{REQUIRE_AUX_FILE}
2240 @vrindex ac_aux_dir
2241 Declare that @var{file} is an auxiliary script needed by this configure
2242 script, and set the shell variable @code{ac_aux_dir} to the directory
2243 where it can be found. The value of @code{ac_aux_dir} is guaranteed to
2244 end with a @samp{/}.
2245
2246 Macros that need auxiliary scripts must use this macro to register each
2247 script they need.
2248 @end defmac
2249
2250 @command{configure} checks for all the auxiliary scripts it needs on
2251 startup, and exits with an error if any are missing.
2252
2253 @command{autoreconf} also detects missing auxiliary scripts. When used
2254 with the @option{--install} option, @command{autoreconf} will try to add
2255 missing scripts to the directory specified by @code{AC_CONFIG_AUX_DIR},
2256 or to the top level of the source tree if @code{AC_CONFIG_AUX_DIR} was
2257 not used. It can always do this for the scripts needed by Autoconf core
2258 macros: @file{install-sh}, @file{config.sub}, and @file{config.guess}.
2259 Many other commonly-needed scripts are installed by the third-party
2260 tools that @command{autoreconf} knows how to run, such as @file{missing}
2261 for Automake and @file{ltmain.sh} for Libtool.
2262
2263 If you are using Automake, auxiliary scripts will automatically be
2264 included in the tarball created by @command{make dist}. If you are
2265 not using Automake you will need to arrange for auxiliary scripts to
2266 be included in tarballs yourself. Auxiliary scripts should normally
2267 @emph{not} be checked into a version control system, for the same
2268 reasons that @command{configure} shouldn't be.
2269
2270 The scripts needed by Autoconf core macros can be found in
2271 @file{$(datadir)/autoconf/build-aux} of the Autoconf installation
2272 (@pxref{Installation Directory Variables}).
2273 @file{install-sh} can be downloaded from
2274 @url{https://git.savannah.gnu.org/cgit/automake.git/plain/lib/install-sh}.
2275 @file{config.sub} and @file{config.guess} can be downloaded from
2276 @url{https://git.savannah.gnu.org/cgit/config.git/tree/}.
2277
2278 @node Output
2279 @section Outputting Files
2280 @cindex Outputting files
2281
2282 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2283 calling @code{AC_OUTPUT}. That is the macro that generates and runs
2284 @file{config.status}, which in turn creates the makefiles and any
2285 other files resulting from configuration. This is the only required
2286 macro besides @code{AC_INIT} (@pxref{Input}).
2287
2288 @anchor{AC_OUTPUT}
2289 @defmac AC_OUTPUT
2290 @acindex{OUTPUT}
2291 @cindex Instantiation
2292 Generate @file{config.status} and launch it. Call this macro once, at
2293 the end of @file{configure.ac}.
2294
2295 @file{config.status} performs all the configuration actions: all the
2296 output files (see @ref{Configuration Files}, macro
2297 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2298 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2299 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2300 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2301 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2302 are honored.
2303
2304 The location of your @code{AC_OUTPUT} invocation is the exact point
2305 where configuration actions are taken: any code afterwards is
2306 executed by @command{configure} once @command{config.status} was run. If
2307 you want to bind actions to @command{config.status} itself
2308 (independently of whether @command{configure} is being run), see
2309 @ref{Configuration Commands, , Running Arbitrary Configuration
2310 Commands}.
2311 @end defmac
2312
2313 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2314 @xref{Obsolete Macros}, for a description of the arguments that
2315 @code{AC_OUTPUT} used to support.
2316
2317
2318 If you run @command{make} in subdirectories, you should run it using the
2319 @command{make} variable @code{MAKE}. Most versions of @command{make} set
2320 @code{MAKE} to the name of the @command{make} program plus any options it
2321 was given. (But many do not include in it the values of any variables
2322 set on the command line, so those are not passed on automatically.)
2323 Some old versions of @command{make} do not set this variable. The
2324 following macro allows you to use it even with those versions.
2325
2326 @anchor{AC_PROG_MAKE_SET}
2327 @defmac AC_PROG_MAKE_SET
2328 @acindex{PROG_MAKE_SET}
2329 @ovindex SET_MAKE
2330 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2331 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2332 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2333 @code{$(MAKE)}, such as @samp{MAKE=make}. Calls @code{AC_SUBST} for
2334 @code{SET_MAKE}.
2335 @end defmac
2336
2337 If you use this macro, place a line like this in each @file{Makefile.in}
2338 that runs @command{MAKE} on other directories:
2339
2340 @example
2341 @@SET_MAKE@@
2342 @end example
2343
2344
2345
2346 @node Configuration Actions
2347 @section Performing Configuration Actions
2348 @cindex Configuration actions
2349
2350 @file{configure} is designed so that it appears to do everything itself,
2351 but there is actually a hidden slave: @file{config.status}.
2352 @file{configure} is in charge of examining your system, but it is
2353 @file{config.status} that actually takes the proper actions based on the
2354 results of @file{configure}. The most typical task of
2355 @file{config.status} is to @emph{instantiate} files.
2356
2357 @acindex{CONFIG_@var{ITEMS}}
2358 This section describes the common behavior of the four standard
2359 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2360 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}. They all
2361 have this prototype:
2362
2363 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2364 @c awful.
2365 @example
2366 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2367 @end example
2368
2369 @noindent
2370 where the arguments are:
2371
2372 @table @var
2373 @item tag@dots{}
2374 A blank-or-newline-separated list of tags, which are typically the names of
2375 the files to instantiate.
2376
2377 You are encouraged to use literals as @var{tags}. In particular, you
2378 should avoid
2379
2380 @example
2381 AS_IF([@dots{}], [my_foos="$my_foos fooo"])
2382 AS_IF([@dots{}], [my_foos="$my_foos foooo"])
2383 AC_CONFIG_@var{ITEMS}([$my_foos])
2384 @end example
2385
2386 @noindent
2387 and use this instead:
2388
2389 @example
2390 AS_IF([@dots{}], [AC_CONFIG_@var{ITEMS}([fooo])])
2391 AS_IF([@dots{}], [AC_CONFIG_@var{ITEMS}([foooo])])
2392 @end example
2393
2394 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2395 special @var{tag} values: they may have the form @samp{@var{output}} or
2396 @samp{@var{output}:@var{inputs}}. The file @var{output} is instantiated
2397 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2398
2399 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2400 for example, asks for
2401 the creation of the file @file{Makefile} that contains the expansion of the
2402 output variables in the concatenation of @file{boiler/top.mk} and
2403 @file{boiler/bot.mk}.
2404
2405 The special value @samp{-} might be used to denote the standard output
2406 when used in @var{output}, or the standard input when used in the
2407 @var{inputs}. You most probably don't need to use this in
2408 @file{configure.ac}, but it is convenient when using the command line
2409 interface of @file{./config.status}, see @ref{config.status Invocation},
2410 for more details.
2411
2412 The @var{inputs} may be absolute or relative file names. In the latter
2413 case they are first looked for in the build tree, and then in the source
2414 tree. Input files should be text files, and a line length below 2000
2415 bytes should be safe.
2416
2417 @item commands
2418 Shell commands output literally into @file{config.status}, and
2419 associated with a tag that the user can use to tell @file{config.status}
2420 which commands to run. The commands are run each time a @var{tag}
2421 request is given to @file{config.status}, typically each time the file
2422 @file{@var{tag}} is created.
2423
2424 The variables set during the execution of @command{configure} are
2425 @emph{not} available here: you first need to set them via the
2426 @var{init-cmds}. Nonetheless the following variables are pre-computed:
2427
2428 @table @code
2429 @item srcdir
2430 @vrindex srcdir
2431 The name of the top source directory, assuming that the working
2432 directory is the top build directory. This
2433 is what @command{configure}'s @option{--srcdir} option sets.
2434
2435 @item ac_top_srcdir
2436 @vrindex ac_top_srcdir
2437 The name of the top source directory, assuming that the working
2438 directory is the current build directory.
2439
2440 @item ac_top_build_prefix
2441 @vrindex ac_top_build_prefix
2442 The name of the top build directory, assuming that the working
2443 directory is the current build directory.
2444 It can be empty, or else ends with a slash, so that you may concatenate
2445 it.
2446
2447 @item ac_srcdir
2448 @vrindex ac_srcdir
2449 The name of the corresponding source directory, assuming that the
2450 working directory is the current build directory.
2451
2452 @item tmp
2453 @vrindex tmp
2454 The name of a temporary directory within the build tree, which you
2455 can use if you need to create additional temporary files. The
2456 directory is cleaned up when @command{config.status} is done or
2457 interrupted. Please use package-specific file name prefixes to
2458 avoid clashing with files that @command{config.status} may use
2459 internally.
2460 @end table
2461
2462 @noindent
2463 The @dfn{current} directory refers to the directory (or
2464 pseudo-directory) containing the input part of @var{tags}. For
2465 instance, running
2466
2467 @example
2468 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2469 @end example
2470
2471 @noindent
2472 with @option{--srcdir=../package} produces the following values:
2473
2474 @example
2475 # Argument of --srcdir
2476 srcdir='../package'
2477 # Reversing deep/dir
2478 ac_top_build_prefix='../../'
2479 # Concatenation of $ac_top_build_prefix and srcdir
2480 ac_top_srcdir='../../../package'
2481 # Concatenation of $ac_top_srcdir and deep/dir
2482 ac_srcdir='../../../package/deep/dir'
2483 @end example
2484
2485 @noindent
2486 independently of @samp{in/in.in}.
2487
2488 @item init-cmds
2489 Shell commands output @emph{unquoted} near the beginning of
2490 @file{config.status}, and executed each time @file{config.status} runs
2491 (regardless of the tag). Because they are unquoted, for example,
2492 @samp{$var} is output as the value of @code{var}. @var{init-cmds}
2493 is typically used by @file{configure} to give @file{config.status} some
2494 variables it needs to run the @var{commands}.
2495
2496 You should be extremely cautious in your variable names: all the
2497 @var{init-cmds} share the same name space and may overwrite each other
2498 in unpredictable ways. Sorry@enddots{}
2499 @end table
2500
2501 All these macros can be called multiple times, with different
2502 @var{tag} values, of course!
2503
2504
2505 @node Configuration Files
2506 @section Creating Configuration Files
2507 @cindex Creating configuration files
2508 @cindex Configuration file creation
2509
2510 Be sure to read the previous section, @ref{Configuration Actions}.
2511
2512 @anchor{AC_CONFIG_FILES}
2513 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2514 @acindex{CONFIG_FILES}
2515 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2516 file (by default @file{@var{file}.in}), substituting the output variable
2517 values.
2518 @c Before we used to have this feature, which was later rejected
2519 @c because it complicates the writing of makefiles:
2520 @c If the file would be unchanged, it is left untouched, to preserve
2521 @c timestamp.
2522 This macro is one of the instantiating macros; see @ref{Configuration
2523 Actions}. @xref{Makefile Substitutions}, for more information on using
2524 output variables. @xref{Setting Output Variables}, for more information
2525 on creating them. This macro creates the directory that the file is in
2526 if it doesn't exist. Usually, makefiles are created this way,
2527 but other files, such as @file{.gdbinit}, can be specified as well.
2528
2529 Typical calls to @code{AC_CONFIG_FILES} look like this:
2530
2531 @example
2532 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2533 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2534 @end example
2535
2536 You can override an input file name by appending to @var{file} a
2537 colon-separated list of input files. Examples:
2538
2539 @example
2540 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2541 [lib/Makefile:boiler/lib.mk])
2542 @end example
2543
2544 @noindent
2545 Doing this allows you to keep your file names acceptable to
2546 DOS variants, or
2547 to prepend and/or append boilerplate to the file.
2548
2549 The @var{file} names should not contain shell metacharacters.
2550 @xref{Special Chars in Variables}.
2551 @end defmac
2552
2553
2554
2555 @node Makefile Substitutions
2556 @section Substitutions in Makefiles
2557 @cindex Substitutions in makefiles
2558 @cindex Makefile substitutions
2559
2560 Each subdirectory in a distribution that contains something to be
2561 compiled or installed should come with a file @file{Makefile.in}, from
2562 which @command{configure} creates a file @file{Makefile} in that directory.
2563 To create @file{Makefile}, @command{configure} performs a simple variable
2564 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2565 @file{Makefile.in} with the value that @command{configure} has determined
2566 for that variable. Variables that are substituted into output files in
2567 this way are called @dfn{output variables}. They are ordinary shell
2568 variables that are set in @command{configure}. To make @command{configure}
2569 substitute a particular variable into the output files, the macro
2570 @code{AC_SUBST} must be called with that variable name as an argument.
2571 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2572 left unchanged. @xref{Setting Output Variables}, for more information
2573 on creating output variables with @code{AC_SUBST}.
2574
2575 A software package that uses a @command{configure} script should be
2576 distributed with a file @file{Makefile.in}, but no makefile; that
2577 way, the user has to properly configure the package for the local system
2578 before compiling it.
2579
2580 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2581 GNU Coding Standards}, for more information on what to put in
2582 makefiles.
2583
2584 @menu
2585 * Preset Output Variables:: Output variables that are always set
2586 * Installation Directory Variables:: Other preset output variables
2587 * Changed Directory Variables:: Warnings about @file{datarootdir}
2588 * Build Directories:: Supporting multiple concurrent compiles
2589 * Automatic Remaking:: Makefile rules for configuring
2590 @end menu
2591
2592 @node Preset Output Variables
2593 @subsection Preset Output Variables
2594 @cindex Output variables
2595
2596 Some output variables are preset by the Autoconf macros. Some of the
2597 Autoconf macros set additional output variables, which are mentioned in
2598 the descriptions for those macros. @xref{Output Variable Index}, for a
2599 complete list of output variables. @xref{Installation Directory
2600 Variables}, for the list of the preset ones related to installation
2601 directories. Below are listed the other preset ones, many of which are
2602 precious variables (@pxref{Setting Output Variables},
2603 @code{AC_ARG_VAR}).
2604
2605 The preset variables which are available during @file{config.status}
2606 (@pxref{Configuration Actions}) may also be used during
2607 @command{configure} tests. For example, it is permissible to reference
2608 @samp{$srcdir} when constructing a list of directories to pass via
2609 the @option{-I} option during a compiler feature check. When used in this
2610 manner, coupled with the fact that @command{configure} is always run
2611 from the top build directory, it is sufficient to use just
2612 @samp{$srcdir} instead of @samp{$top_srcdir}.
2613
2614 @c Just say no to ASCII sorting! We're humans, not computers.
2615 @c These variables are listed as they would be in a dictionary:
2616 @c actor
2617 @c Actress
2618 @c actress
2619
2620 @defvar CFLAGS
2621 @evindex CFLAGS
2622 @ovindex CFLAGS
2623 Debugging and optimization options for the C compiler. If it is not set
2624 in the environment when @command{configure} runs, the default value is set
2625 when you call @code{AC_PROG_CC} (or empty if you don't). @command{configure}
2626 uses this variable when compiling or linking programs to test for C features.
2627
2628 If a compiler option affects only the behavior of the preprocessor
2629 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2630 instead. If it affects only the linker (e.g., @option{-L@var{directory}}),
2631 it should be put into @code{LDFLAGS} instead. If it
2632 affects only the compiler proper, @code{CFLAGS} is the natural home for
2633 it. If an option affects multiple phases of the compiler, though,
2634 matters get tricky:
2635
2636 @itemize @bullet
2637 @item
2638 If an option selects a 32-bit or 64-bit build on a bi-arch system, it
2639 must be put direcly into @code{CC}, e.g., @code{CC='gcc -m64'}. This is
2640 necessary for @code{config.guess} to work right.
2641 @item
2642 Otherwise one approach is to put the option into @code{CC}. Another is
2643 to put it into both @code{CPPFLAGS} and @code{LDFLAGS}, but not into
2644 @code{CFLAGS}.
2645 @end itemize
2646
2647 However, remember that some @file{Makefile} variables are reserved by
2648 the GNU Coding Standards for the use of the ``user''---the person
2649 building the package. For instance, @code{CFLAGS} is one such variable.
2650
2651 Sometimes package developers are tempted to set user variables such as
2652 @code{CFLAGS} because it appears to make their job easier. However, the
2653 package itself should never set a user variable, particularly not to
2654 include switches that are required for proper compilation of the
2655 package. Since these variables are documented as being for the package
2656 builder, that person rightfully expects to be able to override any of
2657 these variables at build time. If the package developer needs to add
2658 switches without interfering with the user, the proper way to do that is
2659 to introduce an additional variable. Automake makes this easy by
2660 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2661 automake, GNU Automake}), but the concept is the same even if
2662 Automake is not used.
2663 @end defvar
2664
2665 @defvar configure_input
2666 @ovindex configure_input
2667 A comment saying that the file was generated automatically by
2668 @command{configure} and giving the name of the input file.
2669 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2670 of every makefile it creates. For other files, you should
2671 reference this variable in a comment at the top of each input file. For
2672 example, an input shell script should begin like this:
2673
2674 @example
2675 #!/bin/sh
2676 # @@configure_input@@
2677 @end example
2678
2679 @noindent
2680 The presence of that line also reminds people editing the file that it
2681 needs to be processed by @command{configure} in order to be used.
2682 @end defvar
2683
2684 @defvar CPPFLAGS
2685 @evindex CPPFLAGS
2686 @ovindex CPPFLAGS
2687 Preprocessor options for the C, C++, Objective C, and Objective C++
2688 preprocessors and compilers. If
2689 it is not set in the environment when @command{configure} runs, the default
2690 value is empty. @command{configure} uses this variable when preprocessing
2691 or compiling programs to test for C, C++, Objective C, and Objective C++
2692 features.
2693
2694 This variable's contents should contain options like @option{-I},
2695 @option{-D}, and @option{-U} that affect only the behavior of the
2696 preprocessor. Please see the explanation of @code{CFLAGS} for what you
2697 can do if an option affects other phases of the compiler as well.
2698
2699 Currently, @command{configure} always links as part of a single
2700 invocation of the compiler that also preprocesses and compiles, so it
2701 uses this variable also when linking programs. However, it is unwise to
2702 depend on this behavior because the GNU Coding Standards do
2703 not require it and many packages do not use @code{CPPFLAGS} when linking
2704 programs.
2705
2706 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2707 might run into.
2708 @end defvar
2709
2710 @defvar CXXFLAGS
2711 @evindex CXXFLAGS
2712 @ovindex CXXFLAGS
2713 Debugging and optimization options for the C++ compiler. It acts like
2714 @code{CFLAGS}, but for C++ instead of C.
2715 @end defvar
2716
2717 @defvar DEFS
2718 @ovindex DEFS
2719 @option{-D} options to pass to the C compiler. If @code{AC_CONFIG_HEADERS}
2720 is called, @command{configure} replaces @samp{@@DEFS@@} with
2721 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}). This
2722 variable is not defined while @command{configure} is performing its tests,
2723 only when creating the output files. @xref{Setting Output Variables}, for
2724 how to check the results of previous tests.
2725 @end defvar
2726
2727 @defvar ECHO_C
2728 @defvarx ECHO_N
2729 @defvarx ECHO_T
2730 @ovindex ECHO_C
2731 @ovindex ECHO_N
2732 @ovindex ECHO_T
2733 These obsolescent variables let you suppress the trailing newline from
2734 @command{echo} for question-answer message pairs.
2735 Nowadays it is better to use @code{AS_ECHO_N}.
2736 @end defvar
2737
2738 @defvar ERLCFLAGS
2739 @evindex ERLCFLAGS
2740 @ovindex ERLCFLAGS
2741 Debugging and optimization options for the Erlang compiler. If it is not set
2742 in the environment when @command{configure} runs, the default value is empty.
2743 @command{configure} uses this variable when compiling
2744 programs to test for Erlang features.
2745 @end defvar
2746
2747 @defvar FCFLAGS
2748 @evindex FCFLAGS
2749 @ovindex FCFLAGS
2750 Debugging and optimization options for the Fortran compiler. If it
2751 is not set in the environment when @command{configure} runs, the default
2752 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2753 @command{configure} uses this variable when compiling or linking
2754 programs to test for Fortran features.
2755 @end defvar
2756
2757 @defvar FFLAGS
2758 @evindex FFLAGS
2759 @ovindex FFLAGS
2760 Debugging and optimization options for the Fortran 77 compiler. If it
2761 is not set in the environment when @command{configure} runs, the default
2762 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2763 @command{configure} uses this variable when compiling or linking
2764 programs to test for Fortran 77 features.
2765 @end defvar
2766
2767 @defvar LDFLAGS
2768 @evindex LDFLAGS
2769 @ovindex LDFLAGS
2770 Options for the linker. If it is not set
2771 in the environment when @command{configure} runs, the default value is empty.
2772 @command{configure} uses this variable when linking programs to test for
2773 features in C, C++, Objective C, Objective C++, Fortran, Go, and Algol 68.
2774
2775 This variable's contents should contain options like @option{-s} and
2776 @option{-L} that affect only the behavior of the linker. Please see the
2777 explanation of @code{CFLAGS} for what you can do if an option also
2778 affects other phases of the compiler.
2779
2780 Don't use this variable to pass library names
2781 (@option{-l}) to the linker; use @code{LIBS} instead.
2782 @end defvar
2783
2784 @defvar LIBS
2785 @evindex LIBS
2786 @ovindex LIBS
2787 @option{-l} options to pass to the linker. The default value is empty,
2788 but some Autoconf macros may prepend extra libraries to this variable if
2789 those libraries are found and provide necessary functions, see
2790 @ref{Libraries}. @command{configure} uses this variable when linking
2791 programs to test for C, C++, Objective C, Objective C++, Fortran, and Go
2792 features.
2793 @end defvar
2794
2795 @defvar OBJCFLAGS
2796 @evindex OBJCFLAGS
2797 @ovindex OBJCFLAGS
2798 Debugging and optimization options for the Objective C compiler. It
2799 acts like @code{CFLAGS}, but for Objective C instead of C.
2800 @end defvar
2801
2802 @defvar OBJCXXFLAGS
2803 @evindex OBJCXXFLAGS
2804 @ovindex OBJCXXFLAGS
2805 Debugging and optimization options for the Objective C++ compiler. It
2806 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2807 @end defvar
2808
2809 @defvar GOFLAGS
2810 @evindex GOFLAGS
2811 @ovindex GOFLAGS
2812 Debugging and optimization options for the Go compiler. It acts like
2813 @code{CFLAGS}, but for Go instead of C.
2814 @end defvar
2815
2816 @defvar A68FLAGS
2817 @evindex A68FLAGS
2818 @ovindex A68FLAGS
2819 Debugging and optimization options for the Algol 68 compiler. It acts
2820 like @code{CFLAGS}, but for Algol 68 instead of C.
2821 @end defvar
2822
2823 @defvar builddir
2824 @ovindex builddir
2825 Rigorously equal to @samp{.}. Added for symmetry only.
2826 @end defvar
2827
2828 @defvar abs_builddir
2829 @ovindex abs_builddir
2830 Absolute name of @code{builddir}.
2831 @end defvar
2832
2833 @defvar top_builddir
2834 @ovindex top_builddir
2835 The relative name of the top level of the current build tree. In the
2836 top-level directory, this is the same as @code{builddir}.
2837 @end defvar
2838
2839 @defvar top_build_prefix
2840 @ovindex top_build_prefix
2841 The relative name of the top level of the current build tree with final
2842 slash if nonempty. This is the same as @code{top_builddir}, except that
2843 it contains zero or more runs of @code{../}, so it should not be
2844 appended with a slash for concatenation. This helps for @command{make}
2845 implementations that otherwise do not treat @file{./file} and @file{file}
2846 as equal in the top-level build directory.
2847 @end defvar
2848
2849 @defvar abs_top_builddir
2850 @ovindex abs_top_builddir
2851 Absolute name of @code{top_builddir}.
2852 @end defvar
2853
2854 @defvar srcdir
2855 @ovindex srcdir
2856 The name of the directory that contains the source code for
2857 that makefile.
2858 @end defvar
2859
2860 @defvar abs_srcdir
2861 @ovindex abs_srcdir
2862 Absolute name of @code{srcdir}.
2863 @end defvar
2864
2865 @defvar top_srcdir
2866 @ovindex top_srcdir
2867 The name of the top-level source code directory for the
2868 package. In the top-level directory, this is the same as @code{srcdir}.
2869 @end defvar
2870
2871 @defvar abs_top_srcdir
2872 @ovindex abs_top_srcdir
2873 Absolute name of @code{top_srcdir}.
2874 @end defvar
2875
2876 @node Installation Directory Variables
2877 @subsection Installation Directory Variables
2878 @cindex Installation directories
2879 @cindex Directories, installation
2880
2881 The following variables specify the directories for
2882 package installation, see @ref{Directory Variables, , Variables for
2883 Installation Directories, standards, The GNU Coding
2884 Standards}, for more information. Each variable corresponds to an
2885 argument of @command{configure}; trailing slashes are stripped so that
2886 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2887 between directory names. See the end of this section for
2888 details on when and how to use these variables.
2889
2890 @defvar bindir
2891 @ovindex bindir
2892 The directory for installing executables that users run.
2893 @end defvar
2894
2895 @defvar datadir
2896 @ovindex datadir
2897 The directory for installing idiosyncratic read-only
2898 architecture-independent data.
2899 @end defvar
2900
2901 @defvar datarootdir
2902 @ovindex datarootdir
2903 The root of the directory tree for read-only architecture-independent
2904 data files.
2905 @end defvar
2906
2907 @defvar docdir
2908 @ovindex docdir
2909 The directory for installing documentation files (other than Info and
2910 man).
2911 @end defvar
2912
2913 @defvar dvidir
2914 @ovindex dvidir
2915 The directory for installing documentation files in DVI format.
2916 @end defvar
2917
2918 @defvar exec_prefix
2919 @ovindex exec_prefix
2920 The installation prefix for architecture-dependent files. By default
2921 it's the same as @code{prefix}. You should avoid installing anything
2922 directly to @code{exec_prefix}. However, the default value for
2923 directories containing architecture-dependent files should be relative
2924 to @code{exec_prefix}.
2925 @end defvar
2926
2927 @defvar htmldir
2928 @ovindex htmldir
2929 The directory for installing HTML documentation.
2930 @end defvar
2931
2932 @defvar includedir
2933 @ovindex includedir
2934 The directory for installing C header files.
2935 @end defvar
2936
2937 @defvar infodir
2938 @ovindex infodir
2939 The directory for installing documentation in Info format.
2940 @end defvar
2941
2942 @defvar libdir
2943 @ovindex libdir
2944 The directory for installing object code libraries.
2945 @end defvar
2946
2947 @defvar libexecdir
2948 @ovindex libexecdir
2949 The directory for installing executables that other programs run.
2950 @end defvar
2951
2952 @defvar localedir
2953 @ovindex localedir
2954 The directory for installing locale-dependent but
2955 architecture-independent data, such as message catalogs. This directory
2956 usually has a subdirectory per locale.
2957 @end defvar
2958
2959 @defvar localstatedir
2960 @ovindex localstatedir
2961 The directory for installing modifiable single-machine data. Content in
2962 this directory typically survives a reboot.
2963 @end defvar
2964
2965 @defvar runstatedir
2966 @ovindex runstatedir
2967 The directory for installing temporary modifiable single-machine data.
2968 Content in this directory survives as long as the process is running
2969 (such as pid files), as contrasted with @file{/tmp} that may be
2970 periodically cleaned. Conversely, this directory is typically cleaned
2971 on a reboot. By default, this is a subdirectory of
2972 @code{localstatedir}.
2973 @end defvar
2974
2975 @defvar mandir
2976 @ovindex mandir
2977 The top-level directory for installing documentation in man format.
2978 @end defvar
2979
2980 @defvar oldincludedir
2981 @ovindex oldincludedir
2982 The directory for installing C header files for non-GCC compilers.
2983 @end defvar
2984
2985 @defvar pdfdir
2986 @ovindex pdfdir
2987 The directory for installing PDF documentation.
2988 @end defvar
2989
2990 @defvar prefix
2991 @ovindex prefix
2992 The common installation prefix for all files. If @code{exec_prefix}
2993 is defined to a different value, @code{prefix} is used only for
2994 architecture-independent files.
2995 @end defvar
2996
2997 @defvar psdir
2998 @ovindex psdir
2999 The directory for installing PostScript documentation.
3000 @end defvar
3001
3002 @defvar sbindir
3003 @ovindex sbindir
3004 The directory for installing executables that system
3005 administrators run.
3006 @end defvar
3007
3008 @defvar sharedstatedir
3009 @ovindex sharedstatedir
3010 The directory for installing modifiable architecture-independent data.
3011 @end defvar
3012
3013 @defvar sysconfdir
3014 @ovindex sysconfdir
3015 The directory for installing read-only single-machine data.
3016 @end defvar
3017
3018
3019 Most of these variables have values that rely on @code{prefix} or
3020 @code{exec_prefix}. It is deliberate that the directory output
3021 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
3022 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
3023 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
3024
3025 This behavior is mandated by the GNU Coding Standards, so that when
3026 the user runs:
3027
3028 @table @samp
3029 @item make
3030 she can still specify a different prefix from the one specified to
3031 @command{configure}, in which case, if needed, the package should hard
3032 code dependencies corresponding to the make-specified prefix.
3033
3034 @item make install
3035 she can specify a different installation location, in which case the
3036 package @emph{must} still depend on the location which was compiled in
3037 (i.e., never recompile when @samp{make install} is run). This is an
3038 extremely important feature, as many people may decide to install all
3039 the files of a package grouped together, and then install links from
3040 the final locations to there.
3041 @end table
3042
3043 In order to support these features, it is essential that
3044 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
3045 so that its value can be expanded based
3046 on the current value of @code{prefix}.
3047
3048 A corollary is that you should not use these variables except in
3049 makefiles. For instance, instead of trying to evaluate @code{datadir}
3050 in @file{configure} and hard-coding it in makefiles using
3051 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
3052 you should add
3053 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
3054 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
3055
3056 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
3057 @code{bindir} and friends in your shell scripts and other files; instead,
3058 let @command{make} manage their replacement. For instance Autoconf
3059 ships templates of its shell scripts ending with @samp{.in}, and uses a
3060 makefile snippet similar to the following to build scripts like
3061 @command{autoheader} and @command{autom4te}:
3062
3063 @example
3064 @group
3065 edit = sed \
3066 -e 's|@@bindir[@@]|$(bindir)|g' \
3067 -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
3068 -e 's|@@prefix[@@]|$(prefix)|g'
3069 @end group
3070
3071 @group
3072 autoheader autom4te: Makefile
3073 rm -f $@@ $@@.tmp
3074 srcdir=''; \
3075 test -f ./$@@.in || srcdir=$(srcdir)/; \
3076 $(edit) $$@{srcdir@}$@@.in >$@@.tmp
3077 @c $$ restore font-lock
3078 chmod +x $@@.tmp
3079 chmod a-w $@@.tmp
3080 mv $@@.tmp $@@
3081 @end group
3082
3083 @group
3084 autoheader: $(srcdir)/autoheader.in
3085 autom4te: $(srcdir)/autom4te.in
3086 @end group
3087 @end example
3088
3089 Some details are noteworthy:
3090
3091 @table @asis
3092 @item @samp{@@bindir[@@]}
3093 The brackets prevent @command{configure} from replacing
3094 @samp{@@bindir@@} in the Sed expression itself.
3095 Brackets are preferable to a backslash here, since
3096 POSIX says @samp{\@@} is not portable.
3097
3098 @item @samp{$(bindir)}
3099 Don't use @samp{@@bindir@@}! Use the matching makefile variable
3100 instead.
3101
3102 @item @samp{$(pkgdatadir)}
3103 The example takes advantage of the variable @samp{$(pkgdatadir)}
3104 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
3105
3106 @item @samp{/}
3107 Don't use @samp{/} in the Sed expressions that replace file names since
3108 most likely the
3109 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
3110 Use a shell metacharacter instead, such as @samp{|}.
3111
3112 @item special characters
3113 File names, file name components, and the value of @code{VPATH} should
3114 not contain shell metacharacters or white
3115 space. @xref{Special Chars in Variables}.
3116
3117 @item dependency on @file{Makefile}
3118 Since @code{edit} uses values that depend on the configuration specific
3119 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
3120 the output depends on @file{Makefile}, not @file{configure.ac}.
3121
3122 @item @samp{$@@}
3123 The main rule is generic, and uses @samp{$@@} extensively to
3124 avoid the need for multiple copies of the rule.
3125
3126 @item Separated dependencies and single suffix rules
3127 You can't use them! The above snippet cannot be (portably) rewritten
3128 as:
3129
3130 @example
3131 autoconf autoheader: Makefile
3132 @group
3133 .in:
3134 rm -f $@@ $@@.tmp
3135 $(edit) $< >$@@.tmp
3136 chmod +x $@@.tmp
3137 mv $@@.tmp $@@
3138 @end group
3139 @end example
3140
3141 @xref{Single Suffix Rules}, for details.
3142
3143 @item @samp{$(srcdir)}
3144 Be sure to specify the name of the source directory,
3145 otherwise the package won't support separated builds.
3146 @end table
3147
3148 For the more specific installation of Erlang libraries, the following variables
3149 are defined:
3150
3151 @defvar ERLANG_INSTALL_LIB_DIR
3152 @ovindex ERLANG_INSTALL_LIB_DIR
3153 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
3154 The common parent directory of Erlang library installation directories.
3155 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
3156 macro in @file{configure.ac}.
3157 @end defvar
3158
3159 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
3160 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
3161 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3162 The installation directory for Erlang library @var{library}.
3163 This variable is set by using the
3164 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3165 macro in @file{configure.ac}.
3166 @end defvar
3167
3168 @xref{Erlang Libraries}, for details.
3169
3170
3171 @node Changed Directory Variables
3172 @subsection Changed Directory Variables
3173 @cindex @file{datarootdir}
3174
3175 In Autoconf 2.60, the set of directory variables has changed, and the
3176 defaults of some variables have been adjusted
3177 (@pxref{Installation Directory Variables}) to changes in the
3178 GNU Coding Standards. Notably, @file{datadir}, @file{infodir}, and
3179 @file{mandir} are now expressed in terms of @file{datarootdir}. If you are
3180 upgrading from an earlier Autoconf version, you may need to adjust your files
3181 to ensure that the directory variables are substituted correctly
3182 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
3183 in place. For example, in a @file{Makefile.in}, adding
3184
3185 @example
3186 datarootdir = @@datarootdir@@
3187 @end example
3188
3189 @noindent
3190 is usually sufficient. If you use Automake to create @file{Makefile.in},
3191 it will add this for you.
3192
3193 To help with the transition, Autoconf warns about files that seem to use
3194 @code{datarootdir} without defining it. In some cases, it then expands
3195 the value of @code{$datarootdir} in substitutions of the directory
3196 variables. The following example shows such a warning:
3197
3198 @example
3199 $ @kbd{cat configure.ac}
3200 AC_INIT
3201 AC_CONFIG_FILES([Makefile])
3202 AC_OUTPUT
3203 $ @kbd{cat Makefile.in}
3204 prefix = @@prefix@@
3205 datadir = @@datadir@@
3206 $ @kbd{autoconf}
3207 $ @kbd{configure}
3208 configure: creating ./config.status
3209 config.status: creating Makefile
3210 config.status: WARNING:
3211 Makefile.in seems to ignore the --datarootdir setting
3212 $ @kbd{cat Makefile}
3213 prefix = /usr/local
3214 datadir = $@{prefix@}/share
3215 @end example
3216
3217 Usually one can easily change the file to accommodate both older and newer
3218 Autoconf releases:
3219
3220 @example
3221 $ @kbd{cat Makefile.in}
3222 prefix = @@prefix@@
3223 datarootdir = @@datarootdir@@
3224 datadir = @@datadir@@
3225 $ @kbd{configure}
3226 configure: creating ./config.status
3227 config.status: creating Makefile
3228 $ @kbd{cat Makefile}
3229 prefix = /usr/local
3230 datarootdir = $@{prefix@}/share
3231 datadir = $@{datarootdir@}
3232 @end example
3233
3234 @acindex{DATAROOTDIR_CHECKED}
3235 In some cases, however, the checks may not be able to detect that a suitable
3236 initialization of @code{datarootdir} is in place, or they may fail to detect
3237 that such an initialization is necessary in the output file. If, after
3238 auditing your package, there are still spurious @file{configure} warnings about
3239 @code{datarootdir}, you may add the line
3240
3241 @example
3242 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3243 @end example
3244
3245 @noindent
3246 to your @file{configure.ac} to disable the warnings. This is an exception
3247 to the usual rule that you should not define a macro whose name begins with
3248 @code{AC_} (@pxref{Macro Names}).
3249
3250
3251
3252 @node Build Directories
3253 @subsection Build Directories
3254 @cindex Build directories
3255 @cindex Directories, build
3256
3257 You can support compiling a software package for several architectures
3258 simultaneously from the same copy of the source code. The object files
3259 for each architecture are kept in their own directory.
3260
3261 To support doing this, @command{make} uses the @code{VPATH} variable to
3262 find the files that are in the source directory. GNU Make
3263 can do this. Most other recent @command{make} programs can do this as
3264 well, though they may have difficulties and it is often simpler to
3265 recommend GNU @command{make} (@pxref{VPATH and Make}). Older
3266 @command{make} programs do not support @code{VPATH}; when using them, the
3267 source code must be in the same directory as the object files.
3268
3269 If you are using GNU Automake, the remaining details in this
3270 section are already covered for you, based on the contents of your
3271 @file{Makefile.am}. But if you are using Autoconf in isolation, then
3272 supporting @code{VPATH} requires the following in your
3273 @file{Makefile.in}:
3274
3275 @example
3276 srcdir = @@srcdir@@
3277 VPATH = @@srcdir@@
3278 @end example
3279
3280 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3281 listed in VPATH}.
3282
3283 @command{configure} substitutes the correct value for @code{srcdir} when
3284 it produces @file{Makefile}.
3285
3286 Do not use the @command{make} variable @code{$<}, which expands to the
3287 file name of the file in the source directory (found with @code{VPATH}),
3288 except in implicit rules. (An implicit rule is one such as @samp{.c.o},
3289 which tells how to create a @file{.o} file from a @file{.c} file.) Some
3290 versions of @command{make} do not set @code{$<} in explicit rules; they
3291 expand it to an empty value.
3292
3293 Instead, Make command lines should always refer to source
3294 files by prefixing them with @samp{$(srcdir)/}. It's safer
3295 to quote the source directory name, in case it contains characters that
3296 are special to the shell. Because @samp{$(srcdir)} is expanded by Make,
3297 single-quoting works and is safer than double-quoting. For example:
3298
3299 @example
3300 time.info: time.texinfo
3301 $(MAKEINFO) '$(srcdir)/time.texinfo'
3302 @end example
3303
3304 @node Automatic Remaking
3305 @subsection Automatic Remaking
3306 @cindex Automatic remaking
3307 @cindex Remaking automatically
3308
3309 You can put rules like the following in the top-level @file{Makefile.in}
3310 for a package to automatically update the configuration information when
3311 you change the configuration files. This example includes all of the
3312 optional files, such as @file{aclocal.m4} and those related to
3313 configuration header files. Omit from the @file{Makefile.in} rules for
3314 any of these files that your package does not use.
3315
3316 The @samp{$(srcdir)/} prefix is included because of limitations in the
3317 @code{VPATH} mechanism.
3318
3319 The @file{stamp-} files are necessary because the timestamps of
3320 @file{config.h.in} and @file{config.h} are not changed if remaking
3321 them does not change their contents. This feature avoids unnecessary
3322 recompilation. You should include the file @file{stamp-h.in} in your
3323 package's distribution, so that @command{make} considers
3324 @file{config.h.in} up to date. Don't use @command{touch}
3325 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3326 @command{echo} (using
3327 @command{date} would cause needless output differences).
3328
3329 @example
3330 @group
3331 $(srcdir)/configure: configure.ac aclocal.m4
3332 cd '$(srcdir)' && autoconf
3333
3334 # autoheader might not change config.h.in, so touch a stamp file.
3335 $(srcdir)/config.h.in: stamp-h.in ;
3336 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3337 cd '$(srcdir)' && autoheader
3338 echo timestamp > '$(srcdir)/stamp-h.in'
3339
3340 config.h: stamp-h ;
3341 stamp-h: config.h.in config.status
3342 ./config.status
3343
3344 Makefile: Makefile.in config.status
3345 ./config.status
3346
3347 config.status: configure
3348 ./config.status --recheck
3349 @end group
3350 @end example
3351
3352 @noindent
3353 (Be careful if you copy these lines directly into your makefile, as you
3354 need to convert the indented lines to start with the tab character.)
3355
3356 In addition, you should use
3357
3358 @example
3359 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3360 @end example
3361
3362 @noindent
3363 so @file{config.status} ensures that @file{config.h} is considered up to
3364 date. @xref{Output}, for more information about @code{AC_OUTPUT}.
3365
3366 @xref{config.status Invocation}, for more examples of handling
3367 configuration-related dependencies.
3368
3369 @node Configuration Headers
3370 @section Configuration Header Files
3371 @cindex Configuration Header
3372 @cindex @file{config.h}
3373
3374 When a package contains more than a few tests that define C preprocessor
3375 symbols, the command lines to pass @option{-D} options to the compiler
3376 can get quite long. This causes two problems. One is that the
3377 @command{make} output is hard to visually scan for errors. More
3378 seriously, the command lines can exceed the length limits of some
3379 operating systems. As an alternative to passing @option{-D} options to
3380 the compiler, @command{configure} scripts can create a C header file
3381 containing @samp{#define} directives. The @code{AC_CONFIG_HEADERS}
3382 macro selects this kind of output. Though it can be called anywhere
3383 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3384 it right after @code{AC_INIT}.
3385
3386 The package should @samp{#include} the configuration header file before
3387 any other header files, to prevent inconsistencies in declarations (for
3388 example, if it redefines @code{const}, or if it defines a macro like
3389 @code{_FILE_OFFSET_BITS} that affects the behavior of system
3390 headers). Note that it is okay to only include @file{config.h} from
3391 @file{.c} files; the project's @file{.h} files can rely on
3392 @file{config.h} already being included first by the corresponding
3393 @file{.c} file.
3394
3395 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3396 option (or @option{-I..}; whichever directory contains @file{config.h}).
3397 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3398 the directory of the currently read file, i.e., the source directory, not
3399 the build directory.
3400
3401 With the appropriate @option{-I} option, you can use
3402 @samp{#include <config.h>}. Actually, it's a good habit to use it,
3403 because in the rare case when the source directory contains another
3404 @file{config.h}, the build directory should be searched first.
3405
3406
3407 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3408 @acindex{CONFIG_HEADERS}
3409 @cvindex HAVE_CONFIG_H
3410 This macro is one of the instantiating macros; see @ref{Configuration
3411 Actions}. Make @code{AC_OUTPUT} create the file(s) in the
3412 blank-or-newline-separated list @var{header} containing C preprocessor
3413 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3414 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3415 The usual name for @var{header} is @file{config.h};
3416 @var{header} should not contain shell metacharacters.
3417 @xref{Special Chars in Variables}.
3418
3419 If @var{header} already exists and its contents are identical to what
3420 @code{AC_OUTPUT} would put in it, it is left alone. Doing this allows
3421 making some changes in the configuration without needlessly causing
3422 object files that depend on the header file to be recompiled.
3423
3424 Usually the input file is named @file{@var{header}.in}; however, you can
3425 override the input file name by appending to @var{header} a
3426 colon-separated list of input files. For example, you might need to make
3427 the input file name acceptable to DOS variants:
3428
3429 @example
3430 AC_CONFIG_HEADERS([config.h:config.hin])
3431 @end example
3432
3433 @end defmac
3434
3435 @defmac AH_HEADER
3436 @ahindex{HEADER}
3437 This macro is defined as the name of the first declared config header
3438 and undefined if no config headers have been declared up to this point.
3439 A third-party macro may, for example, require use of a config header
3440 without invoking AC_CONFIG_HEADERS twice, like this:
3441
3442 @example
3443 AC_CONFIG_COMMANDS_PRE(
3444 [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3445 @end example
3446
3447 @end defmac
3448
3449 @xref{Configuration Actions}, for more details on @var{header}.
3450
3451 @menu
3452 * Header Templates:: Input for the configuration headers
3453 * autoheader Invocation:: How to create configuration templates
3454 * Autoheader Macros:: How to specify CPP templates
3455 @end menu
3456
3457 @node Header Templates
3458 @subsection Configuration Header Templates
3459 @cindex Configuration Header Template
3460 @cindex Header templates
3461 @cindex @file{config.h.in}
3462
3463 Your distribution should contain a template file that looks as you want
3464 the final header file to look, including comments, with @code{#undef}
3465 statements which are used as hooks. For example, suppose your
3466 @file{configure.ac} makes these calls:
3467
3468 @example
3469 AC_CONFIG_HEADERS([conf.h])
3470 AC_CHECK_HEADERS([unistd.h])
3471 @end example
3472
3473 @noindent
3474 Then you could have code like the following in @file{conf.h.in}.
3475 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3476 to 1, if and only if the system has @file{unistd.h}.
3477
3478 @example
3479 @group
3480 /* Define as 1 if you have unistd.h. */
3481 #undef HAVE_UNISTD_H
3482 @end group
3483 @end example
3484
3485 The format of the template file is stricter than what the C preprocessor
3486 is required to accept. A directive line should contain only whitespace,
3487 @samp{#undef}, and @samp{HAVE_UNISTD_H}. The use of @samp{#define}
3488 instead of @samp{#undef}, or of comments on the same line as
3489 @samp{#undef}, is strongly discouraged. Each hook should only be listed
3490 once. Other preprocessor lines, such as @samp{#ifdef} or
3491 @samp{#include}, are copied verbatim from the template into the
3492 generated header.
3493
3494 Since it is a tedious task to keep a template header up to date, you may
3495 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3496
3497 During the instantiation of the header, each @samp{#undef} line in the
3498 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3499 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3500 been executed during the @command{configure} run, the @samp{#undef} line is
3501 commented out. (This is important, e.g., for @samp{_POSIX_SOURCE}:
3502 on many systems, it can be implicitly defined by the compiler, and
3503 undefining it in the header would then break compilation of subsequent
3504 headers.)
3505
3506 Currently, @emph{all} remaining @samp{#undef} lines in the header
3507 template are commented out, whether or not there was a corresponding
3508 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3509 for future releases of Autoconf.
3510
3511 Generally speaking, since you should not use @samp{#define}, and you
3512 cannot guarantee whether a @samp{#undef} directive in the header
3513 template will be converted to a @samp{#define} or commented out in the
3514 generated header file, the template file cannot be used for conditional
3515 definition effects. Consequently, if you need to use the construct
3516
3517 @example
3518 @group
3519 #ifdef THIS
3520 # define THAT
3521 #endif
3522 @end group
3523 @end example
3524
3525 @noindent
3526 you must place it outside of the template.
3527 If you absolutely need to hook it to the config header itself, please put
3528 the directives to a separate file, and @samp{#include} that file from the
3529 config header template. If you are using @command{autoheader}, you would
3530 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3531
3532
3533 @node autoheader Invocation
3534 @subsection Using @command{autoheader} to Create @file{config.h.in}
3535 @cindex @command{autoheader}
3536
3537 The @command{autoheader} program can create a template file of C
3538 @samp{#define} statements for @command{configure} to use.
3539 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3540 @file{configure} sources to determine the name of the template.
3541 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3542 input file name, @command{autoheader} uses the first one.)
3543
3544 It is recommended that only one input file is used. If you want to append
3545 a boilerplate code, it is preferable to use
3546 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3547 File @file{conf_post.h} is not processed during the configuration then,
3548 which make things clearer. Analogically, @code{AH_TOP} can be used to
3549 prepend a boilerplate code.
3550
3551 In order to do its job, @command{autoheader} needs you to document all
3552 of the symbols that you might use. Typically this is done via an
3553 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3554 is a literal symbol and whose third argument describes the symbol
3555 (@pxref{Defining Symbols}). Alternatively, you can use
3556 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3557 suitable input file for a subsequent configuration header file.
3558 Symbols defined by Autoconf's builtin tests are already documented properly;
3559 you need to document only those that you
3560 define yourself.
3561
3562 You might wonder why @command{autoheader} is needed: after all, why
3563 would @command{configure} need to ``patch'' a @file{config.h.in} to
3564 produce a @file{config.h} instead of just creating @file{config.h} from
3565 scratch? Well, when everything rocks, the answer is just that we are
3566 wasting our time maintaining @command{autoheader}: generating
3567 @file{config.h} directly is all that is needed. When things go wrong,
3568 however, you'll be thankful for the existence of @command{autoheader}.
3569
3570 The fact that the symbols are documented is important in order to
3571 @emph{check} that @file{config.h} makes sense. The fact that there is a
3572 well-defined list of symbols that should be defined (or not) is
3573 also important for people who are porting packages to environments where
3574 @command{configure} cannot be run: they just have to @emph{fill in the
3575 blanks}.
3576
3577 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3578
3579 If you give @command{autoheader} an argument, it uses that file instead
3580 of @file{configure.ac} and writes the header file to the standard output
3581 instead of to @file{config.h.in}. If you give @command{autoheader} an
3582 argument of @option{-}, it reads the standard input instead of
3583 @file{configure.ac} and writes the header file to the standard output.
3584
3585 @command{autoheader} accepts the following options:
3586
3587 @table @option
3588 @item --help
3589 @itemx -h
3590 Print a summary of the command line options and exit.
3591
3592 @item --version
3593 @itemx -V
3594 Print the version number of Autoconf and exit.
3595
3596 @item --verbose
3597 @itemx -v
3598 Report processing steps.
3599
3600 @item --debug
3601 @itemx -d
3602 Don't remove the temporary files.
3603
3604 @item --force
3605 @itemx -f
3606 Remake the template file even if newer than its input files.
3607
3608 @item --replace-handwritten
3609 @itemx -R
3610 Remake the template file even if it appears not to have been generated
3611 by @command{autoheader}.
3612
3613 @item --include=@var{dir}
3614 @itemx -I @var{dir}
3615 Append @var{dir} to the include path. Multiple invocations accumulate.
3616
3617 @item --prepend-include=@var{dir}
3618 @itemx -B @var{dir}
3619 Prepend @var{dir} to the include path. Multiple invocations accumulate.
3620
3621 @item --warnings=@var{category}[,@var{category}...]
3622 @itemx -W@var{category}[,@var{category}...]
3623 @evindex WARNINGS
3624 Enable or disable warnings related to each @var{category}.
3625 @xref{m4_warn}, for a comprehensive list of categories.
3626 Special values include:
3627
3628 @table @samp
3629 @item all
3630 Enable all categories of warnings.
3631
3632 @item none
3633 Disable all categories of warnings.
3634
3635 @item error
3636 Treat all warnings as errors.
3637
3638 @item no-@var{category}
3639 Disable warnings falling into @var{category}.
3640 @end table
3641
3642 The environment variable @env{WARNINGS} may also be set to a
3643 comma-separated list of warning categories to enable or disable.
3644 It is interpreted exactly the same way as the argument of
3645 @option{--warnings}, but unknown categories are silently ignored.
3646 The command line takes precedence; for instance, if @env{WARNINGS}
3647 is set to @code{obsolete}, but @option{-Wnone} is given on the
3648 command line, no warnings will be issued.
3649
3650 Some categories of warnings are on by default.
3651 Again, for details see @ref{m4_warn}.
3652 @end table
3653
3654
3655
3656 @node Autoheader Macros
3657 @subsection Autoheader Macros
3658 @cindex Autoheader macros
3659
3660 @command{autoheader} scans @file{configure.ac} and figures out which C
3661 preprocessor symbols it might define. It knows how to generate
3662 templates for symbols defined by @code{AC_CHECK_HEADERS},
3663 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3664 symbol, you must define a template for it. If there are missing
3665 templates, @command{autoheader} fails with an error message.
3666
3667 The template for a @var{symbol} is created
3668 by @command{autoheader} from
3669 the @var{description} argument to an @code{AC_DEFINE};
3670 see @ref{Defining Symbols}.
3671
3672 For special needs, you can use the following macros.
3673
3674
3675 @defmac AH_TEMPLATE (@var{key}, @var{description})
3676 @ahindex{TEMPLATE}
3677 Tell @command{autoheader} to generate a template for @var{key}. This macro
3678 generates standard templates just like @code{AC_DEFINE} when a
3679 @var{description} is given.
3680
3681 For example:
3682
3683 @example
3684 AH_TEMPLATE([NULL_DEVICE],
3685 [Name of the file to open to get
3686 a null file, or a data sink.])
3687 @end example
3688
3689 @noindent
3690 generates the following template, with the description properly
3691 justified.
3692
3693 @example
3694 /* Name of the file to open to get a null file, or a data sink. */
3695 #undef NULL_DEVICE
3696 @end example
3697 @end defmac
3698
3699
3700 @defmac AH_VERBATIM (@var{key}, @var{template})
3701 @ahindex{VERBATIM}
3702 Tell @command{autoheader} to include the @var{template} as-is in the header
3703 template file. This @var{template} is associated with the @var{key},
3704 which is used to sort all the different templates and guarantee their
3705 uniqueness. It should be a symbol that can be defined via @code{AC_DEFINE}.
3706 @end defmac
3707
3708
3709 @defmac AH_TOP (@var{text})
3710 @ahindex{TOP}
3711 Include @var{text} at the top of the header template file.
3712 @end defmac
3713
3714
3715 @defmac AH_BOTTOM (@var{text})
3716 @ahindex{BOTTOM}
3717 Include @var{text} at the bottom of the header template file.
3718 @end defmac
3719
3720
3721 Please note that @var{text} gets included ``verbatim'' to the template file,
3722 not to the resulting config header, so it can easily get mangled when the
3723 template is processed. There is rarely a need for something other than
3724
3725 @example
3726 AH_BOTTOM([#include <custom.h>])
3727 @end example
3728
3729
3730
3731 @node Configuration Commands
3732 @section Running Arbitrary Configuration Commands
3733 @cindex Configuration commands
3734 @cindex Commands for configuration
3735
3736 You can execute arbitrary commands before, during, and after
3737 @file{config.status} is run. The three following macros accumulate the
3738 commands to run when they are called multiple times.
3739 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3740 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3741
3742 @anchor{AC_CONFIG_COMMANDS}
3743 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3744 @acindex{CONFIG_COMMANDS}
3745 Specify additional shell commands to run at the end of
3746 @file{config.status}, and shell commands to initialize any variables
3747 from @command{configure}. Associate the commands with @var{tag}.
3748 Since typically the @var{cmds} create a file, @var{tag} should
3749 naturally be the name of that file. If needed, the directory hosting
3750 @var{tag} is created. The @var{tag} should not contain shell
3751 metacharacters. @xref{Special Chars in Variables}.
3752 This macro is one of the instantiating macros;
3753 see @ref{Configuration Actions}.
3754
3755 Here is an unrealistic example:
3756 @example
3757 fubar=42
3758 AC_CONFIG_COMMANDS([fubar],
3759 [AS_ECHO(["this is extra $fubar, and so on."])],
3760 [fubar=$fubar])
3761 @end example
3762
3763 Here is a better one:
3764 @example
3765 AC_CONFIG_COMMANDS([timestamp], [echo >timestamp])
3766 @end example
3767 @end defmac
3768
3769 The following two macros look similar, but in fact they are not of the same
3770 breed: they are executed directly by @file{configure}, so you cannot use
3771 @file{config.status} to rerun them.
3772
3773 @c Yet it is good to leave them here. The user sees them together and
3774 @c decides which best fits their needs.
3775
3776 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3777 @acindex{CONFIG_COMMANDS_PRE}
3778 Execute the @var{cmds} right before creating @file{config.status}.
3779
3780 This macro presents the last opportunity to call @code{AC_SUBST},
3781 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3782 @end defmac
3783
3784 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3785 @acindex{CONFIG_COMMANDS_POST}
3786 Execute the @var{cmds} right after creating @file{config.status}.
3787 @end defmac
3788
3789
3790
3791
3792 @node Configuration Links
3793 @section Creating Configuration Links
3794 @cindex Configuration links
3795 @cindex Links for configuration
3796
3797 You may find it convenient to create links whose destinations depend upon
3798 results of tests. One can use @code{AC_CONFIG_COMMANDS} but the
3799 creation of relative symbolic links can be delicate when the package is
3800 built in a directory different from the source directory.
3801
3802 @anchor{AC_CONFIG_LINKS}
3803 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3804 @ovar{init-cmds})
3805 @acindex{CONFIG_LINKS}
3806 @cindex Links
3807 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3808 the corresponding link name @var{dest}. Makes a symbolic link if
3809 possible, otherwise a hard link if possible, otherwise a copy. The
3810 @var{dest} and @var{source} names should be relative to the top level
3811 source or build directory, and should not contain shell metacharacters.
3812 @xref{Special Chars in Variables}.
3813
3814 This macro is one of the instantiating
3815 macros; see @ref{Configuration Actions}.
3816
3817 For example, this call:
3818
3819 @example
3820 AC_CONFIG_LINKS([host.h:config/$machine.h
3821 object.h:config/$obj_format.h])
3822 @end example
3823
3824 @noindent
3825 creates in the current directory @file{host.h} as a link to
3826 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3827 link to @file{@var{srcdir}/config/$obj_format.h}.
3828
3829 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3830 impossible for @samp{config.status} to guess the links to establish.
3831
3832 One can then run:
3833 @example
3834 ./config.status host.h object.h
3835 @end example
3836 @noindent
3837 to create the links.
3838 @end defmac
3839
3840
3841
3842 @node Subdirectories
3843 @section Configuring Other Packages in Subdirectories
3844 @cindex Configure subdirectories
3845 @cindex Subdirectory configure
3846
3847 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3848 makefiles in subdirectories. However, @command{configure} scripts
3849 that control more than one independent package can use
3850 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3851 packages in subdirectories.
3852
3853 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3854 @acindex{CONFIG_SUBDIRS}
3855 @ovindex subdirs
3856 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3857 @var{dir} in the given blank-or-newline-separated list. Each @var{dir} should
3858 be a literal, i.e., please do not use:
3859
3860 @example
3861 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3862 if test "x$package_foo_enabled" = xyes; then
3863 my_subdirs="$my_subdirs foo"
3864 fi
3865 AC_CONFIG_SUBDIRS([$my_subdirs])
3866 @end example
3867
3868 @noindent
3869 because this prevents @samp{./configure --help=recursive} from
3870 displaying the options of the package @code{foo}. Instead, you should
3871 write:
3872
3873 @example
3874 AS_IF([test "x$package_foo_enabled" = xyes],
3875 [AC_CONFIG_SUBDIRS([foo])])
3876 @end example
3877
3878 If a given @var{dir} is not found at @command{configure} run time, a
3879 warning is reported; if the subdirectory is optional, write:
3880
3881 @example
3882 AS_IF([test -d "$srcdir/foo"],
3883 [AC_CONFIG_SUBDIRS([foo])])
3884 @end example
3885
3886 These examples use @code{AS_IF} instead of ordinary shell @code{if} to
3887 avoid problems that Autoconf has with macro calls in shell conditionals
3888 outside macro definitions. @xref{Common Shell Constructs}.
3889
3890 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3891 of @command{configure}. This is for packages that might use a
3892 non-Autoconf script @command{Configure}, which can't be called through a
3893 wrapper @command{configure} since it would be the same file on
3894 case-insensitive file systems.
3895
3896 The subdirectory @command{configure} scripts are given the same command
3897 line options that were given to this @command{configure} script, with minor
3898 changes if needed, which include:
3899
3900 @itemize @minus
3901 @item
3902 adjusting a relative name for the cache file;
3903
3904 @item
3905 adjusting a relative name for the source directory;
3906
3907 @item
3908 propagating the current value of @code{$prefix}, including if it was
3909 defaulted, and if the default values of the top level and of the subdirectory
3910 @file{configure} differ.
3911 @end itemize
3912
3913 This macro also sets the output variable @code{subdirs} to the list of
3914 directories @samp{@var{dir} @dots{}}. Make rules can use
3915 this variable to determine which subdirectories to recurse into.
3916
3917 This macro may be called multiple times.
3918 @end defmac
3919
3920 @node Default Prefix
3921 @section Default Prefix
3922 @cindex Install prefix
3923 @cindex Prefix for install
3924
3925 By default, @command{configure} sets the prefix for files it installs to
3926 @file{/usr/local}. The user of @command{configure} can select a different
3927 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3928 There are two ways to change the default: when creating
3929 @command{configure}, and when running it.
3930
3931 Some software packages might want to install in a directory other than
3932 @file{/usr/local} by default. To accomplish that, use the
3933 @code{AC_PREFIX_DEFAULT} macro.
3934
3935 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3936 @acindex{PREFIX_DEFAULT}
3937 Set the default installation prefix to @var{prefix} instead of
3938 @file{/usr/local}.
3939 @end defmac
3940
3941 It may be convenient for users to have @command{configure} guess the
3942 installation prefix from the location of a related program that they
3943 have already installed. If you wish to do that, you can call
3944 @code{AC_PREFIX_PROGRAM}.
3945
3946 @anchor{AC_PREFIX_PROGRAM}
3947 @defmac AC_PREFIX_PROGRAM (@var{program})
3948 @acindex{PREFIX_PROGRAM}
3949 If the user did not specify an installation prefix (using the
3950 @option{--prefix} option), guess a value for it by looking for
3951 @var{program} in @env{PATH}, the way the shell does. If @var{program}
3952 is found, set the prefix to the parent of the directory containing
3953 @var{program}, else default the prefix as described above
3954 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}). For example, if
3955 @var{program} is @code{gcc} and the @env{PATH} contains
3956 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3957 @end defmac
3958
3959
3960
3961 @c ======================================================== Existing tests
3962
3963 @node Existing Tests
3964 @chapter Existing Tests
3965
3966 These macros test for particular system features that packages might
3967 need or want to use. If you need to test for a kind of feature that
3968 none of these macros check for, you can probably do it by calling
3969 primitive test macros with appropriate arguments (@pxref{Writing
3970 Tests}).
3971
3972 These tests print messages telling the user which feature they're
3973 checking for, and what they find. They cache their results for future
3974 @command{configure} runs (@pxref{Caching Results}).
3975
3976 Some of these macros set output variables. @xref{Makefile
3977 Substitutions}, for how to get their values. The phrase ``define
3978 @var{name}'' is used below as a shorthand to mean ``define the C
3979 preprocessor symbol @var{name} to the value 1''. @xref{Defining
3980 Symbols}, for how to get those symbol definitions into your program.
3981
3982 @menu
3983 * Common Behavior:: Macros' standard schemes
3984 * Alternative Programs:: Selecting between alternative programs
3985 * Files:: Checking for the existence of files
3986 * Libraries:: Library archives that might be missing
3987 * Library Functions:: C library functions that might be missing
3988 * Header Files:: Header files that might be missing
3989 * Declarations:: Declarations that may be missing
3990 * Structures:: Structures or members that might be missing
3991 * Types:: Types that might be missing
3992 * Compilers and Preprocessors:: Checking for compiling programs
3993 * System Services:: Operating system services
3994 * C and POSIX Variants:: Kludges for C and POSIX variants
3995 * Erlang Libraries:: Checking for the existence of Erlang libraries
3996 @end menu
3997
3998 @node Common Behavior
3999 @section Common Behavior
4000 @cindex Common autoconf behavior
4001
4002 Much effort has been expended to make Autoconf easy to learn. The most
4003 obvious way to reach this goal is simply to enforce standard interfaces
4004 and behaviors, avoiding exceptions as much as possible. Because of
4005 history and inertia, unfortunately, there are still too many exceptions
4006 in Autoconf; nevertheless, this section describes some of the common
4007 rules.
4008
4009 @menu
4010 * Standard Symbols:: Symbols defined by the macros
4011 * Default Includes:: Includes used by the generic macros
4012 @end menu
4013
4014 @node Standard Symbols
4015 @subsection Standard Symbols
4016 @cindex Standard symbols
4017
4018 All the generic macros that @code{AC_DEFINE} a symbol as a result of
4019 their test transform their @var{argument} values to a standard alphabet.
4020 First, @var{argument} is converted to upper case and any asterisks
4021 (@samp{*}) are each converted to @samp{P}. Any remaining characters
4022 that are not alphanumeric are converted to underscores.
4023
4024 For instance,
4025
4026 @example
4027 AC_CHECK_TYPES([struct $Expensive*])
4028 @end example
4029
4030 @noindent
4031 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
4032 succeeds.
4033
4034
4035 @node Default Includes
4036 @subsection Default Includes
4037 @cindex Default includes
4038 @cindex Includes, default
4039 @hdrindex{assert.h}
4040 @hdrindex{ctype.h}
4041 @hdrindex{errno.h}
4042 @hdrindex{float.h}
4043 @hdrindex{iso646.h}
4044 @hdrindex{limits.h}
4045 @hdrindex{locale.h}
4046 @hdrindex{math.h}
4047 @hdrindex{setjmp.h}
4048 @hdrindex{signal.h}
4049 @hdrindex{stdarg.h}
4050 @hdrindex{stddef.h}
4051 @hdrindex{stdio.h}
4052 @hdrindex{stdlib.h}
4053 @hdrindex{string.h}
4054 @hdrindex{time.h}
4055 @hdrindex{wchar.h}
4056 @hdrindex{wctype.h}
4057
4058 Test programs frequently need to include headers that may or may not be
4059 available on the system whose features are being tested. Each test can
4060 use all the preprocessor macros that have been @code{AC_DEFINE}d by
4061 previous tests, so for example one may write
4062
4063 @example
4064 @group
4065 #include <time.h>
4066 #ifdef HAVE_SYS_TIME_H
4067 # include <sys/time.h>
4068 #endif
4069 @end group
4070 @end example
4071
4072 @noindent
4073 if @file{sys/time.h} has already been tested for.
4074
4075 All hosted environments that are still of interest for portable code
4076 provide all of the headers specified in C89 (as amended in 1995):
4077 @file{assert.h}, @file{ctype.h}, @file{errno.h}, @file{float.h},
4078 @file{iso646.h}, @file{limits.h}, @file{locale.h}, @file{math.h},
4079 @file{setjmp.h}, @file{signal.h}, @file{stdarg.h}, @file{stddef.h},
4080 @file{stdio.h}, @file{stdlib.h}, @file{string.h}, @file{time.h},
4081 @file{wchar.h}, and @file{wctype.h}. Most programs can safely include
4082 these headers unconditionally. A program not intended to be portable to
4083 C89 can also safely include the C99-specified header @file{stdbool.h}.
4084 Other headers, including headers from C99 and later revisions of the C
4085 standard, might need to be tested for (@pxref{Header Files}) or their
4086 bugs may need to be worked around (@pxref{Gnulib}).
4087
4088 If your program needs to be portable to a @emph{freestanding}
4089 environment, such as an embedded OS that doesn't provide all of the
4090 facilities of the C89 standard library, you may need to test for some of
4091 the above headers as well. Note that many Autoconf macros internally
4092 assume that the complete set of C89 headers are available.
4093
4094 Most generic macros use the following macro to provide a default set
4095 of includes:
4096
4097 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
4098 @acindex{INCLUDES_DEFAULT}
4099 Expand to @var{include-directives} if present and nonempty, otherwise to:
4100
4101 @example
4102 @group
4103 #include <stddef.h>
4104 #ifdef HAVE_STDIO_H
4105 # include <stdio.h>
4106 #endif
4107 #ifdef HAVE_STDLIB_H
4108 # include <stdlib.h>
4109 #endif
4110 #ifdef HAVE_STRING_H
4111 # include <string.h>
4112 #endif
4113 #ifdef HAVE_INTTYPES_H
4114 # include <inttypes.h>
4115 #endif
4116 #ifdef HAVE_STDINT_H
4117 # include <stdint.h>
4118 #endif
4119 #ifdef HAVE_STRINGS_H
4120 # include <strings.h>
4121 #endif
4122 #ifdef HAVE_SYS_TYPES_H
4123 # include <sys/types.h>
4124 #endif
4125 #ifdef HAVE_SYS_STAT_H
4126 # include <sys/stat.h>
4127 #endif
4128 #ifdef HAVE_UNISTD_H
4129 # include <unistd.h>
4130 #endif
4131 @end group
4132 @end example
4133
4134 Using this macro without @var{include-directives} has the side effect of
4135 checking for @file{stdio.h}, @file{stdlib.h}, @file{string.h},
4136 @file{inttypes.h}, @file{stdint.h}, @file{strings.h},
4137 @file{sys/types.h}, @file{sys/stat.h}, and @file{unistd.h}, as if by
4138 @code{AC_CHECK_HEADERS_ONCE}. For backward compatibility, the macro
4139 @code{STDC_HEADERS} will be defined when both @file{stdlib.h} and
4140 @file{string.h} are available.
4141
4142 @strong{Portability Note:} It is safe for most programs to assume the
4143 presence of all of the headers required by the original 1990 C standard.
4144 @code{AC_INCLUDES_DEFAULT} checks for @file{stdio.h}, @file{stdlib.h},
4145 and @file{string.h}, even though they are in that list, because they
4146 might not be available when compiling for a ``freestanding environment''
4147 (in which most of the features of the C library are optional). You
4148 probably do not need to write @samp{#ifdef HAVE_STDIO_H} in your own
4149 code.
4150
4151 @file{inttypes.h} and @file{stdint.h} were added to C in the 1999
4152 revision of the standard, and @file{strings.h}, @file{sys/types.h},
4153 @file{sys/stat.h}, and @file{unistd.h} are POSIX extensions. You
4154 @emph{should} guard uses of these headers with appropriate conditionals.
4155 @end defmac
4156
4157 @defmac AC_CHECK_INCLUDES_DEFAULT
4158 @acindex{CHECK_INCLUDES_DEFAULT}
4159 Check for all the headers that @code{AC_INCLUDES_DEFAULT} would check
4160 for as a side-effect, if this has not already happened.
4161
4162 This macro mainly exists so that @code{autoupdate} can replace certain
4163 obsolete constructs with it. You should not need to use it yourself; in
4164 fact, it is likely to be safe to delete it from any script in which it
4165 appears. (@code{autoupdate} does not know whether preprocessor macros
4166 such as @code{HAVE_STDINT_H} are used in the program, nor whether they
4167 would get defined as a side-effect of other checks.)
4168 @end defmac
4169
4170 @node Alternative Programs
4171 @section Alternative Programs
4172 @cindex Programs, checking
4173
4174 These macros check for the presence or behavior of particular programs.
4175 They are used to choose between several alternative programs and to
4176 decide what to do once one has been chosen. If there is no macro
4177 specifically defined to check for a program you need, and you don't need
4178 to check for any special properties of it, then you can use one of the
4179 general program-check macros.
4180
4181 @menu
4182 * Particular Programs:: Special handling to find certain programs
4183 * Generic Programs:: How to find other programs
4184 @end menu
4185
4186 @node Particular Programs
4187 @subsection Particular Program Checks
4188
4189 These macros check for particular programs---whether they exist, and
4190 in some cases whether they support certain features.
4191
4192 @defmac AC_PROG_AR
4193 @acindex{PROG_AR}
4194 @ovindex AR
4195 @c @caindex prog_AR
4196 @c @caindex prog_ac_ct_AR
4197 Set output variable @code{AR} to @samp{ar} if @code{ar} is found, and
4198 otherwise to @samp{:} (do nothing).
4199 @end defmac
4200
4201 @defmac AC_PROG_AWK
4202 @acindex{PROG_AWK}
4203 @ovindex AWK
4204 @caindex prog_AWK
4205 Check for the commands @command{gawk}, @command{mawk},
4206 @command{nawk}, @command{awk}, and @code{busybox awk}, in that
4207 order, and set output variable @code{AWK} to the first one that is found.
4208 Try @code{gawk} first because that is reported to be the
4209 best implementation. The result can be overridden by setting the
4210 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
4211
4212 Using this macro avoids some pitfalls of older systems that have both
4213 traditional @command{awk} (@pxref{awk, , Limitations of Usual Tools})
4214 and better alternatives like @command{gawk}.
4215 It also can help port to stripped-down systems that have only
4216 @code{busybox awk}, although these systems could well have problems
4217 with other build components that use plain @command{awk}.
4218 @end defmac
4219
4220 @defmac AC_PROG_GREP
4221 @acindex{PROG_GREP}
4222 @ovindex GREP
4223 @caindex prog_GREP
4224 Look for the best available @code{grep} or @code{ggrep} that accepts the
4225 longest input lines possible, and that supports multiple @option{-e} options.
4226 Set the output variable @code{GREP} to whatever is chosen.
4227 @xref{grep, , Limitations of Usual Tools}, for more information about
4228 portability problems with the @command{grep} command family. The result
4229 can be overridden by setting the @code{GREP} variable and is cached in the
4230 @code{ac_cv_path_GREP} variable.
4231 @end defmac
4232
4233 @defmac AC_PROG_EGREP
4234 @acindex{PROG_EGREP}
4235 @ovindex EGREP
4236 @caindex prog_EGREP
4237 Check whether @code{$GREP -E} works, or else look for the best available
4238 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
4239 Set the output variable @code{EGREP} to whatever is chosen. The result
4240 can be overridden by setting the @code{EGREP} variable and is cached in the
4241 @code{ac_cv_path_EGREP} variable.
4242 @end defmac
4243
4244 @defmac AC_PROG_FGREP
4245 @acindex{PROG_FGREP}
4246 @ovindex FGREP
4247 @caindex prog_FGREP
4248 Check whether @code{$GREP -F} works, or else look for the best available
4249 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
4250 Set the output variable @code{FGREP} to whatever is chosen. The result
4251 can be overridden by setting the @code{FGREP} variable and is cached in the
4252 @code{ac_cv_path_FGREP} variable.
4253 @end defmac
4254
4255 @defmac AC_PROG_INSTALL
4256 @acindex{PROG_INSTALL}
4257 @ovindex INSTALL
4258 @ovindex INSTALL_PROGRAM
4259 @ovindex INSTALL_DATA
4260 @ovindex INSTALL_SCRIPT
4261 @caindex path_install
4262 @prindex @command{install-sh}
4263 Set output variable @code{INSTALL} to the name of a BSD-compatible
4264 @command{install} program, if one is found in the current @env{PATH}.
4265 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
4266 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
4267 default directories) to determine @var{dir} (@pxref{Output}). Also set
4268 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
4269 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
4270
4271 @samp{@@INSTALL@@} is special, as its value may vary for different
4272 configuration files.
4273
4274 This macro screens out various instances of @command{install} known not to
4275 work. It prefers to find a C program rather than a shell script, for
4276 speed. Instead of @file{install-sh}, it can also use @file{install.sh},
4277 but that name is obsolete because some @command{make} programs have a rule
4278 that creates @file{install} from it if there is no makefile. Further, this
4279 macro requires @command{install} to be able to install multiple files into a
4280 target directory in a single invocation.
4281
4282 Autoconf comes with a copy of @file{install-sh} that you can use.
4283 If you use @code{AC_PROG_INSTALL}, you must include @file{install-sh} in
4284 your distribution; otherwise @command{autoreconf} and @command{configure}
4285 will produce an error message saying they can't find it---even if the
4286 system you're on has a good @command{install} program. This check is a
4287 safety measure to prevent you from accidentally leaving that file out,
4288 which would prevent your package from installing on systems that don't
4289 have a BSD-compatible @command{install} program.
4290
4291 If you need to use your own installation program because it has features
4292 not found in standard @command{install} programs, there is no reason to use
4293 @code{AC_PROG_INSTALL}; just put the file name of your program into your
4294 @file{Makefile.in} files.
4295
4296 The result of the test can be overridden by setting the variable
4297 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4298 @end defmac
4299
4300 @defmac AC_PROG_MKDIR_P
4301 @acindex{PROG_MKDIR_P}
4302 @ovindex MKDIR_P
4303 @caindex path_mkdir
4304 @prindex @command{install-sh}
4305 Set output variable @code{MKDIR_P} to a program that ensures that for
4306 each argument, a directory named by this argument exists, creating it
4307 and its parent directories if needed, and without race conditions when
4308 two instances of the program attempt to make the same directory at
4309 nearly the same time.
4310
4311 This macro uses the equivalent of the @samp{mkdir -p} command. Ancient
4312 versions of @command{mkdir} are vulnerable to race conditions, so if you
4313 want to support parallel installs from different packages into the same
4314 directory you should use a non-ancient @command{mkdir}.
4315
4316 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4317 in M4sh}), but it sets an output variable intended for use in other
4318 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4319 @command{configure}. Also, @code{AS_MKDIR_P} does not accept options,
4320 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4321 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4322 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4323 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4324
4325 The result of the test can be overridden by setting the variable
4326 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4327 @end defmac
4328
4329 @anchor{AC_PROG_LEX}
4330 @defmac AC_PROG_LEX (@var{options})
4331 @acindex{PROG_LEX}
4332 @ovindex LEX
4333 @ovindex LEXLIB
4334 @cvindex YYTEXT_POINTER
4335 @ovindex LEX_OUTPUT_ROOT
4336 @caindex prog_LEX
4337 Search for a lexical analyzer generator, preferring @code{flex}
4338 to plain @code{lex}. Output variable @code{LEX} is set to whichever
4339 program is available. If neither program is available, @code{LEX}
4340 is set to @samp{:};
4341 for packages that ship the generated @file{file.yy.c}
4342 alongside the source @file{file.l}, this default allows users without a
4343 lexer generator to still build the package even if the timestamp for
4344 @file{file.l} is inadvertently changed.
4345
4346 The name of the program to use can be overridden by setting the
4347 output variable @code{LEX} or the cache variable @code{ac_cv_prog_LEX}
4348 when running @command{configure}.
4349
4350 If a lexical analyzer generator is found, this macro performs additional
4351 checks for common portability pitfalls. If these additional checks
4352 fail, @code{LEX} is reset to @samp{:}; otherwise the following
4353 additional macros and variables are provided.
4354
4355 Preprocessor macro @code{YYTEXT_POINTER} is defined if the lexer
4356 skeleton, by default, declares @code{yytext} as a @samp{@w{char *}}
4357 rather than a @samp{@w{char []}}.
4358
4359 Output variable @code{LEX_OUTPUT_ROOT} is set to the base of the file
4360 name that the lexer generates; this is usually either @file{lex.yy} or
4361 @file{lexyy}.
4362
4363 If generated lexers need a library to work, output variable
4364 @code{LEXLIB} is set to a link option for that library (e.g.,
4365 @option{-ll}), otherwise it is set to empty.
4366
4367 The @var{options} argument modifies the behavior of @code{AC_PROG_LEX}.
4368 It should be a whitespace-separated list of options. Currently there
4369 are only two options, and they are mutually exclusive:
4370
4371 @table @code
4372 @item yywrap
4373 Indicate that the library in @code{LEXLIB} needs to define the function
4374 @code{yywrap}. If a library that defines this function cannot be found,
4375 @code{LEX} will be reset to @samp{:}.
4376
4377 @item noyywrap
4378 Indicate that the library in @code{LEXLIB} does not need to define the
4379 function @code{yywrap}. @command{configure} will not search for it at
4380 all.
4381 @end table
4382
4383 Prior to Autoconf 2.70, @code{AC_PROG_LEX} did not take any arguments,
4384 and its behavior was different from either of the above possibilities:
4385 it would search for a library that defines @code{yywrap}, and would set
4386 @code{LEXLIB} to that library if it finds one. However, if a library
4387 that defines this function could not be found, @code{LEXLIB} would be
4388 left empty and @code{LEX} would @emph{not} be reset. This behavior was
4389 due to a bug, but several packages came to depend on it, so
4390 @code{AC_PROG_LEX} still does this if neither the @code{yywrap} nor the
4391 @code{noyywrap} option is given.
4392
4393 Usage of @code{AC_PROG_LEX} without choosing one of the @code{yywrap}
4394 or @code{noyywrap} options is deprecated. It is usually better to
4395 use @code{noyywrap} and define the @code{yywrap} function yourself,
4396 as this almost always renders the @code{LEXLIB} unnecessary.
4397
4398 @strong{Caution:} As a side-effect of the test, this macro may delete
4399 any file in the configure script's current working directory named
4400 @file{lex.yy.c} or @file{lexyy.c}.
4401
4402 @strong{Caution:} Packages that ship a generated @file{lex.yy.c}
4403 cannot assume that the definition of @code{YYTEXT_POINTER} matches
4404 the code in that file. They also cannot assume that @code{LEXLIB}
4405 provides the library routines required by the code in that file.
4406
4407 If you use Flex to generate @file{lex.yy.c}, you can work around these
4408 limitations by defining @code{yywrap} and @code{main} yourself
4409 (rendering @code{-lfl} unnecessary), and by using either the
4410 @option{--array} or @option{--pointer} options to control how
4411 @code{yytext} is declared. The code generated by Flex is also more
4412 portable than the code generated by historical versions of Lex.
4413
4414 If you have used Flex to generate @file{lex.yy.c}, and especially if
4415 your scanner depends on Flex features, we recommend you use this
4416 Autoconf snippet to prevent the scanner being regenerated with
4417 historical Lex:
4418
4419 @example
4420 AC_PROG_LEX
4421 AS_IF([test "x$LEX" != xflex],
4422 [LEX="$SHELL $missing_dir/missing flex"
4423 AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4424 AC_SUBST([LEXLIB], [''])])
4425 @end example
4426
4427 The shell script @command{missing} can be found in the Automake
4428 distribution.
4429
4430 Remember that the user may have supplied an alternate location in
4431 @env{LEX}, so if Flex is required, it is better to check that the user
4432 provided something sufficient by parsing the output of @samp{$LEX
4433 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4434 @end defmac
4435
4436 @anchor{AC_PROG_LN_S}
4437 @defmac AC_PROG_LN_S
4438 @acindex{PROG_LN_S}
4439 @ovindex LN_S
4440 If @samp{ln -s} works on the current file system (the operating system
4441 and file system support symbolic links), set the output variable
4442 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4443 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -pR}.
4444
4445 If you make a link in a directory other than the current directory, its
4446 meaning depends on whether @samp{ln} or @samp{ln -s} is used. To safely
4447 create links using @samp{$(LN_S)}, either find out which form is used
4448 and adjust the arguments, or always invoke @code{ln} in the directory
4449 where the link is to be created.
4450
4451 In other words, it does not work to do:
4452 @example
4453 $(LN_S) foo /x/bar
4454 @end example
4455
4456 Instead, do:
4457
4458 @example
4459 (cd /x && $(LN_S) foo bar)
4460 @end example
4461 @end defmac
4462
4463 @defmac AC_PROG_RANLIB
4464 @acindex{PROG_RANLIB}
4465 @ovindex RANLIB
4466 @c @caindex prog_RANLIB
4467 @c @caindex prog_ac_ct_RANLIB
4468 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4469 is found, and otherwise to @samp{:} (do nothing).
4470 @end defmac
4471
4472 @defmac AC_PROG_SED
4473 @acindex{PROG_SED}
4474 @ovindex SED
4475 @caindex path_SED
4476 Set output variable @code{SED} to a Sed implementation that conforms to
4477 POSIX and does not have arbitrary length limits. Report an error if no
4478 acceptable Sed is found. @xref{sed, , Limitations of Usual Tools}.
4479
4480 The result of this test can be overridden by setting the @code{SED} variable
4481 and is cached in the @code{ac_cv_path_SED} variable.
4482 @end defmac
4483
4484 @defmac AC_PROG_YACC
4485 @acindex{PROG_YACC}
4486 @evindex YACC
4487 @evindex YFLAGS
4488 @ovindex YACC
4489 @caindex prog_YACC
4490 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4491 -y}. Otherwise, if @code{byacc} is found, set @code{YACC} to
4492 @samp{byacc}. Otherwise set @code{YACC} to @samp{yacc}.
4493 The result of this test can be influenced by setting the variable
4494 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4495 @end defmac
4496
4497 @node Generic Programs
4498 @subsection Generic Program and File Checks
4499
4500 These macros are used to find programs not covered by the ``particular''
4501 test macros. If you need to check the behavior of a program as well as
4502 find out whether it is present, you have to write your own test for it
4503 (@pxref{Writing Tests}). By default, these macros use the environment
4504 variable @env{PATH}. If you need to check for a program that might not
4505 be in the user's @env{PATH}, you can pass a modified path to use
4506 instead, like this:
4507
4508 @example
4509 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4510 [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4511 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4512 @end example
4513
4514 You are strongly encouraged to declare the @var{variable} passed to
4515 @code{AC_CHECK_PROG} etc.@: as precious. @xref{Setting Output Variables},
4516 @code{AC_ARG_VAR}, for more details.
4517
4518 @anchor{AC_CHECK_PROG}
4519 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4520 @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4521 @ovar{reject})
4522 @acindex{CHECK_PROG}
4523 @caindex prog_@var{variable}
4524 Check whether program @var{prog-to-check-for} exists in @var{path}. If
4525 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4526 @var{value-if-not-found}, if given. Always pass over @var{reject} (an
4527 absolute file name) even if it is the first found in the search path; in
4528 that case, set @var{variable} using the absolute file name of the
4529 @var{prog-to-check-for} found that is not @var{reject}. If
4530 @var{variable} was already set, do nothing. Calls @code{AC_SUBST} for
4531 @var{variable}. The result of this test can be overridden by setting the
4532 @var{variable} variable or the cache variable
4533 @code{ac_cv_prog_@var{variable}}.
4534 @end defmac
4535
4536 @anchor{AC_CHECK_PROGS}
4537 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4538 @ovar{value-if-not-found}, @dvar{path, $PATH})
4539 @acindex{CHECK_PROGS}
4540 @caindex prog_@var{variable}
4541 Check for each program in the blank-separated list
4542 @var{progs-to-check-for} existing in the @var{path}. If one is found, set
4543 @var{variable} to the name of that program. Otherwise, continue
4544 checking the next program in the list. If none of the programs in the
4545 list are found, set @var{variable} to @var{value-if-not-found}; if
4546 @var{value-if-not-found} is not specified, the value of @var{variable}
4547 is not changed. Calls @code{AC_SUBST} for @var{variable}. The result of
4548 this test can be overridden by setting the @var{variable} variable or the
4549 cache variable @code{ac_cv_prog_@var{variable}}.
4550 @end defmac
4551
4552 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4553 @ovar{value-if-not-found}, @dvar{path, $PATH})
4554 @acindex{CHECK_TARGET_TOOL}
4555 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4556 with a prefix of the target type as determined by
4557 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4558 If the tool cannot be found with a prefix, and if the build and target
4559 types are equal, then it is also searched for without a prefix.
4560
4561 As noted in @ref{Specifying Target Triplets}, the
4562 target is rarely specified, because most of the time it is the same
4563 as the host: it is the type of system for which any compiler tool in
4564 the package produces code. What this macro looks for is,
4565 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4566 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4567 uses to produce objects, archives or executables}.
4568 @end defmac
4569
4570 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4571 @ovar{value-if-not-found}, @dvar{path, $PATH})
4572 @acindex{CHECK_TOOL}
4573 @c @caindex prog_@var{VARIABLE}
4574 @c @caindex prog_ac_ct_@var{VARIABLE}
4575 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4576 with a prefix of the host type as specified by @option{--host}, followed by a
4577 dash. For example, if the user runs
4578 @samp{configure --build=x86_64-gnu --host=aarch64-linux-gnu}, then this call:
4579 @example
4580 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4581 @end example
4582 @noindent
4583 sets @code{RANLIB} to @file{aarch64-linux-gnu-ranlib} if that program exists in
4584 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4585 @var{path}, or to @samp{:} if neither program exists.
4586
4587 When cross-compiling, this macro will issue a warning if no program
4588 prefixed with the host type could be found.
4589 For more information, see @ref{Specifying Target Triplets}.
4590 @end defmac
4591
4592 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4593 @ovar{value-if-not-found}, @dvar{path, $PATH})
4594 @acindex{CHECK_TARGET_TOOLS}
4595 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4596 @var{progs-to-check-for} are checked with a prefix of the target type as
4597 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4598 (@pxref{Canonicalizing}). If none of the tools can be found with a
4599 prefix, and if the build and target types are equal, then the first one
4600 without a prefix is used. If a tool is found, set @var{variable} to
4601 the name of that program. If none of the tools in the list are found,
4602 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4603 is not specified, the value of @var{variable} is not changed. Calls
4604 @code{AC_SUBST} for @var{variable}.
4605 @end defmac
4606
4607 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4608 @ovar{value-if-not-found}, @dvar{path, $PATH})
4609 @acindex{CHECK_TOOLS}
4610 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4611 @var{progs-to-check-for} are checked with a prefix of the host type as
4612 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4613 (@pxref{Canonicalizing}). If none of the tools can be found with a
4614 prefix, then the first one without a prefix is used. If a tool is found,
4615 set @var{variable} to the name of that program. If none of the tools in
4616 the list are found, set @var{variable} to @var{value-if-not-found}; if
4617 @var{value-if-not-found} is not specified, the value of @var{variable}
4618 is not changed. Calls @code{AC_SUBST} for @var{variable}.
4619
4620 When cross-compiling, this macro will issue a warning if no program
4621 prefixed with the host type could be found.
4622 For more information, see @ref{Specifying Target Triplets}.
4623 @end defmac
4624
4625 @anchor{AC_PATH_PROG}
4626 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4627 @ovar{value-if-not-found}, @dvar{path, $PATH})
4628 @acindex{PATH_PROG}
4629 @caindex path_@var{variable}
4630 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4631 name of @var{prog-to-check-for} if found. The result of this test
4632 can be overridden by setting the @var{variable} variable. A positive
4633 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4634 variable.
4635 @end defmac
4636
4637 @anchor{AC_PATH_PROGS}
4638 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4639 @ovar{value-if-not-found}, @dvar{path, $PATH})
4640 @acindex{PATH_PROGS}
4641 @caindex path_@var{variable}
4642 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4643 are found, set @var{variable} to the absolute name of the program
4644 found. The result of this test can be overridden by setting the
4645 @var{variable} variable. A positive result of this test is cached in
4646 the @code{ac_cv_path_@var{variable}} variable.
4647 @end defmac
4648
4649 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4650 @var{progs-to-check-for}, @var{feature-test}, @
4651 @ovar{action-if-not-found}, @dvar{path, $PATH})
4652 @acindex{PATH_PROGS_FEATURE_CHECK}
4653 @caindex path_@var{variable}
4654 @vrindex ac_path_@var{variable}
4655 @vrindex ac_path_@var{variable}_found
4656 This macro was introduced in Autoconf 2.62. If @var{variable} is not
4657 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4658 its value. Otherwise, check for each program in the blank-separated
4659 list @var{progs-to-check-for} existing in @var{path}. For each program
4660 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4661 set to the absolute name of the candidate program. If no invocation of
4662 @var{feature-test} sets the shell variable
4663 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4664 executed. @var{feature-test} will be run even when
4665 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4666 choose a better candidate found later in @var{path}; to accept the
4667 current setting and bypass all further checks, @var{feature-test} can
4668 execute @code{ac_path_@var{variable}_found=:}.
4669
4670 Note that this macro has some subtle differences from
4671 @code{AC_CHECK_PROGS}. It is designed to be run inside
4672 @code{AC_CACHE_VAL}, therefore, it should have no side effects. In
4673 particular, @var{variable} is not set to the final value of
4674 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4675 run. Also, on failure, any action can be performed, whereas
4676 @code{AC_CHECK_PROGS} only performs
4677 @code{@var{variable}=@var{value-if-not-found}}.
4678
4679 Here is an example that searches for an implementation of @command{m4} that
4680 supports the @code{indir} builtin, even if it goes by the name
4681 @command{gm4} or is not the first implementation on @env{PATH}.
4682
4683 @example
4684 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4685 [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4686 [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4687 test "x$m4out" = x0 \
4688 && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4689 [AC_MSG_ERROR([could not find m4 that supports indir])])])
4690 AC_SUBST([M4], [$ac_cv_path_M4])
4691 @end example
4692 @end defmac
4693
4694 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4695 @ovar{value-if-not-found}, @dvar{path, $PATH})
4696 @acindex{PATH_TARGET_TOOL}
4697 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4698 name of the program if it is found.
4699 @end defmac
4700
4701 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4702 @ovar{value-if-not-found}, @dvar{path, $PATH})
4703 @acindex{PATH_TOOL}
4704 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4705 name of the program if it is found.
4706
4707 When cross-compiling, this macro will issue a warning if no program
4708 prefixed with the host type could be found.
4709 For more information, see @ref{Specifying Target Triplets}.
4710 @end defmac
4711
4712
4713 @node Files
4714 @section Files
4715 @cindex File, checking
4716
4717 You might also need to check for the existence of files. Before using
4718 these macros, ask yourself whether a runtime test might not be a better
4719 solution. Be aware that, like most Autoconf macros, they test a feature
4720 of the host machine, and therefore, they die when cross-compiling.
4721
4722 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4723 @ovar{action-if-not-found})
4724 @acindex{CHECK_FILE}
4725 @caindex file_@var{file}
4726 Check whether file @var{file} exists on the native system. If it is
4727 found, execute @var{action-if-found}, otherwise do
4728 @var{action-if-not-found}, if given. Cache the result of this test
4729 in the @code{ac_cv_file_@var{file}} variable, with characters not
4730 suitable for a variable name mapped to underscores.
4731 @end defmac
4732
4733 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4734 @ovar{action-if-not-found})
4735 @acindex{CHECK_FILES}
4736 @caindex file_@var{file}
4737 For each file listed in @var{files}, execute @code{AC_CHECK_FILE}
4738 and perform either @var{action-if-found} or @var{action-if-not-found}.
4739 Like @code{AC_CHECK_FILE}, this defines @samp{HAVE_@var{file}}
4740 (@pxref{Standard Symbols}) for each file found and caches the results of
4741 each test in the @code{ac_cv_file_@var{file}} variable, with characters
4742 not suitable for a variable name mapped to underscores.
4743 @end defmac
4744
4745
4746 @node Libraries
4747 @section Library Files
4748 @cindex Library, checking
4749
4750 The following macros check for the presence of certain C, C++, Fortran,
4751 or Go library archive files.
4752
4753 @anchor{AC_CHECK_LIB}
4754 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4755 @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4756 @acindex{CHECK_LIB}
4757 @caindex lib_@var{library}_@var{function}
4758 Test whether the library @var{library} is available by trying to link
4759 a test program that calls function @var{function} with the library.
4760 @var{function} should be a function provided by the library.
4761 Use the base
4762 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4763 the @var{library} argument.
4764
4765 @var{action-if-found} is a list of shell commands to run if the link
4766 with the library succeeds; @var{action-if-not-found} is a list of shell
4767 commands to run if the link fails. If @var{action-if-found} is not
4768 specified, the default action prepends @option{-l@var{library}} to
4769 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4770 capitals). This macro is intended to support building @code{LIBS} in
4771 a right-to-left (least-dependent to most-dependent) fashion such that
4772 library dependencies are satisfied as a natural side effect of
4773 consecutive tests. Linkers are sensitive to library ordering
4774 so the order in which @code{LIBS} is generated is important to reliable
4775 detection of libraries.
4776
4777 If linking with @var{library} results in unresolved symbols that would
4778 be resolved by linking with additional libraries, give those libraries
4779 as the @var{other-libraries} argument, separated by spaces:
4780 e.g., @option{-lXt -lX11}. Otherwise, this macro may fail to detect
4781 that @var{library} is present, because linking the test program can
4782 fail with unresolved symbols. The @var{other-libraries} argument
4783 should be limited to cases where it is desirable to test for one library
4784 in the presence of another that is not already in @code{LIBS}.
4785
4786 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4787 in some common cases. Many standard functions like @code{gethostbyname}
4788 appear in the standard C library on some hosts, and in special libraries
4789 like @code{nsl} on other hosts. On some hosts the special libraries
4790 contain variant implementations that you may not want to use. These
4791 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4792 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4793
4794 The result of this test is cached in the
4795 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4796 @end defmac
4797
4798 @anchor{AC_SEARCH_LIBS}
4799 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4800 @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4801 @acindex{SEARCH_LIBS}
4802 @caindex search_@var{function}
4803 Search for a library defining @var{function} if it's not already
4804 available. This equates to calling
4805 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4806 no libraries, then for each library listed in @var{search-libs}.
4807
4808 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4809 to contain @var{function}, and run @var{action-if-found}. If the
4810 function is not found, run @var{action-if-not-found}.
4811
4812 If linking with @var{library} results in unresolved symbols that would
4813 be resolved by linking with additional libraries, give those libraries
4814 as the @var{other-libraries} argument, separated by spaces:
4815 e.g., @option{-lXt -lX11}. Otherwise, this macro fails to detect
4816 that @var{function} is present, because linking the test program
4817 always fails with unresolved symbols.
4818
4819 The result of this test is cached in the
4820 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4821 @var{function} is already available, as @samp{no} if no library
4822 containing @var{function} was found, otherwise as the
4823 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4824 @end defmac
4825
4826
4827
4828 @node Library Functions
4829 @section Library Functions
4830
4831 The following macros check for particular C library functions.
4832 If there is no macro specifically defined to check for a function you need,
4833 and you don't need to check for any special properties of
4834 it, then you can use one of the general function-check macros.
4835
4836 @menu
4837 * Function Portability:: Pitfalls with usual functions
4838 * Particular Functions:: Special handling to find certain functions
4839 * Generic Functions:: How to find other functions
4840 @end menu
4841
4842 @node Function Portability
4843 @subsection Portability of C Functions
4844 @cindex Portability of C functions
4845 @cindex C function portability
4846
4847 Most usual functions can either be missing, or be buggy, or be limited
4848 on some architectures. This section tries to make an inventory of these
4849 portability issues. By definition, this list always requires
4850 additions. A much more complete list is maintained by the Gnulib
4851 project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4852 Current POSIX Functions, gnulib, Gnulib}, @ref{Legacy Function
4853 Substitutes, , Legacy Functions, gnulib, Gnulib}, and @ref{Glibc
4854 Function Substitutes, , Glibc Functions, gnulib, Gnulib}. Please
4855 help us keep the Gnulib list as complete as possible.
4856
4857 @table @asis
4858 @item @code{exit}
4859 @c @fuindex exit
4860 @prindex @code{exit}
4861 On ancient hosts, @code{exit} returned @code{int}.
4862 This is because @code{exit} predates @code{void}, and there was a long
4863 tradition of it returning @code{int}.
4864
4865 On current hosts, the problem more likely is that @code{exit} is not
4866 declared, due to C++ problems of some sort or another. For this reason
4867 we suggest that test programs not invoke @code{exit}, but return from
4868 @code{main} instead.
4869
4870 @item @code{malloc}
4871 @c @fuindex malloc
4872 @prindex @code{malloc}
4873 The C standard says a successful call @code{malloc (0)} is implementation
4874 dependent. It can return either @code{NULL} or a new non-null pointer.
4875 The latter is more common (e.g., the GNU C Library) but is by
4876 no means universal. @code{AC_FUNC_MALLOC}
4877 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4878
4879 @item @code{putenv}
4880 @c @fuindex putenv
4881 @prindex @code{putenv}
4882 POSIX prefers @code{setenv} to @code{putenv}; among other things,
4883 @code{putenv} is not required of all POSIX implementations, but
4884 @code{setenv} is.
4885
4886 POSIX specifies that @code{putenv} puts the given string directly in
4887 @code{environ}, but some systems make a copy of it instead (e.g.,
4888 glibc 2.0, or BSD). And when a copy is made, @code{unsetenv} might
4889 not free it, causing a memory leak (e.g., FreeBSD 4).
4890
4891 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4892 environment, but this is not standard usage and it dumps core
4893 on some systems (e.g., AIX).
4894
4895 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4896 environment, rather than inserting it with an empty value.
4897
4898 @item @code{realloc}
4899 @c @fuindex realloc
4900 @prindex @code{realloc}
4901 It is problematic to call @code{realloc} with a zero size.
4902 The C standard says @code{realloc (NULL, 0)} is equivalent to
4903 @code{malloc (0)}, which means one cannot portably tell whether the call
4904 has succeeded if it returns a null pointer. If @code{ptr} is non-null,
4905 the C standard says @code{realloc (ptr, 0)} has undefined behavior.
4906
4907 The @code{AC_FUNC_REALLOC} macro avoids some of these portability issues.
4908 @xref{Particular Functions}.
4909
4910 @item @code{signal} handler
4911 @c @fuindex signal
4912 @prindex @code{signal}
4913 @prindex @code{sigaction}
4914 In most cases, it is more robust to use @code{sigaction} when it is
4915 available, rather than @code{signal}.
4916
4917 @item @code{snprintf}
4918 @c @fuindex snprintf
4919 @prindex @code{snprintf}
4920 @c @fuindex vsnprintf
4921 @prindex @code{vsnprintf}
4922 In C99 and later, if the output array isn't big enough
4923 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4924 truncate the output and return the number of bytes that ought to have
4925 been produced. Some older systems, notably Microsoft Windows before
4926 Visual Studio 2015 and Windows 10, do not null-terminate the output
4927 and return @minus{}1 instead.
4928
4929 Portable code can check the return value of @code{snprintf (buf, sizeof
4930 buf, ...)}: if the value is negative or is not less than @code{sizeof
4931 buf}, an error occurred and the contents of @code{buf} can be ignored.
4932 Alternatively, one of the Gnulib modules related to @code{snprintf} can
4933 be used. @xref{Gnulib}.
4934
4935 @item @code{strerror_r}
4936 @c @fuindex strerror_r
4937 @prindex @code{strerror_r}
4938 POSIX specifies that @code{strerror_r} returns an @code{int}, but many
4939 systems (e.g., the GNU C Library) provide a
4940 different version returning a @code{char *}. @code{AC_FUNC_STRERROR_R}
4941 can detect which is in use (@pxref{Particular Functions}).
4942
4943 @item @code{strnlen}
4944 @c @fuindex strnlen
4945 @prindex @code{strnlen}
4946 Android 5.0's strnlen was broken, because it assumed the addressed array
4947 always had at least the specified number of bytes. For example,
4948 @code{strnlen ("", SIZE_MAX)} should return 0 but on Android 5.0 it
4949 crashed.
4950
4951 AIX 4.3 provided a broken version which produces the
4952 following results:
4953
4954 @example
4955 strnlen ("foobar", 0) = 0
4956 strnlen ("foobar", 1) = 3
4957 strnlen ("foobar", 2) = 2
4958 strnlen ("foobar", 3) = 1
4959 strnlen ("foobar", 4) = 0
4960 strnlen ("foobar", 5) = 6
4961 strnlen ("foobar", 6) = 6
4962 strnlen ("foobar", 7) = 6
4963 strnlen ("foobar", 8) = 6
4964 strnlen ("foobar", 9) = 6
4965 @end example
4966
4967 @item @code{sysconf}
4968 @c @fuindex sysconf
4969 @prindex @code{sysconf}
4970 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4971 9) have @code{_SC_PAGE_SIZE} instead. This can be tested with
4972 @code{#ifdef}.
4973
4974 @item @code{unlink}
4975 @c @fuindex unlink
4976 @prindex @code{unlink}
4977 The POSIX spec says that @code{unlink} causes the given file to be
4978 removed only after there are no more open file handles for it. Some
4979 non-POSIX hosts have trouble with this requirement, though,
4980 and some DOS variants even corrupt the file system.
4981
4982 @item @code{unsetenv}
4983 @c @fuindex unsetenv
4984 @prindex @code{unsetenv}
4985 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4986 can be removed with a call @code{putenv ("FOO=")}, as described under
4987 @code{putenv} above.
4988
4989 @item @code{va_copy}
4990 @c @fuindex va_copy
4991 @prindex @code{va_copy}
4992 C99 and later provide @code{va_copy} for copying
4993 @code{va_list} variables. It may be available in older environments
4994 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4995 pre-C99 mode). These can be tested with @code{#ifdef}. A fallback to
4996 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4997 portability.
4998
4999 @item @code{va_list}
5000 @c @fuindex va_list
5001 @prindex @code{va_list}
5002 @code{va_list} is not necessarily just a pointer. It can be a
5003 @code{struct}, which means @code{NULL} is not portable.
5004 Or it can be an array, which means as a function parameter it can be
5005 effectively call-by-reference and library routines might modify the
5006 value back in the caller.
5007
5008 @item Signed @code{>>}
5009 Normally the C @code{>>} right shift of a signed type replicates the
5010 high bit, giving a so-called ``arithmetic'' shift. But care should be
5011 taken since Standard C doesn't require that behavior. On a few platforms
5012 (e.g., Cray C by default) zero bits are shifted in, the same as a shift of an
5013 unsigned type.
5014
5015 @item Integer @code{/}
5016 C divides signed integers by truncating their quotient toward zero,
5017 yielding the same result as Fortran. However, before C99 the standard
5018 allowed C implementations to take the floor or ceiling of the quotient
5019 in some cases. Hardly any implementations took advantage of this
5020 freedom, though, and it's probably not worth worrying about this issue
5021 nowadays.
5022 @end table
5023
5024
5025 @node Particular Functions
5026 @subsection Particular Function Checks
5027 @cindex Function, checking
5028
5029 These macros check for particular C functions---whether they exist, and
5030 in some cases how they respond when given certain arguments.
5031
5032 @anchor{AC_FUNC_ALLOCA}
5033 @defmac AC_FUNC_ALLOCA
5034 @acindex{FUNC_ALLOCA}
5035 @cvindex C_ALLOCA
5036 @cvindex HAVE_ALLOCA_H
5037 @ovindex ALLOCA
5038 @c @fuindex alloca
5039 @prindex @code{alloca}
5040 @hdrindex{alloca.h}
5041 @c @caindex working_alloca_h
5042 Check for the @code{alloca} function. Define @code{HAVE_ALLOCA_H} if
5043 @file{alloca.h} defines a working @code{alloca}. If not, look for a
5044 builtin alternative. If either method succeeds, define
5045 @code{HAVE_ALLOCA}. Otherwise, set the output variable @code{ALLOCA} to
5046 @samp{$@{LIBOBJDIR@}alloca.o} and define
5047 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
5048 garbage collect). This variable is separate from @code{LIBOBJS} so
5049 multiple programs can share the value of @code{ALLOCA} without needing
5050 to create an actual library, in case only some of them use the code in
5051 @code{LIBOBJS}. The @samp{$@{LIBOBJDIR@}} prefix serves the same
5052 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
5053
5054 Source files that use @code{alloca} should start with a piece of code
5055 like the following, to declare it properly.
5056
5057 @example
5058 @group
5059 #include <stdlib.h>
5060 #include <stddef.h>
5061 #ifdef HAVE_ALLOCA_H
5062 # include <alloca.h>
5063 #elif !defined alloca
5064 # ifdef __GNUC__
5065 # define alloca __builtin_alloca
5066 # elif defined _MSC_VER
5067 # include <malloc.h>
5068 # define alloca _alloca
5069 # elif !defined HAVE_ALLOCA
5070 # ifdef __cplusplus
5071 extern "C"
5072 # endif
5073 void *alloca (size_t);
5074 # endif
5075 #endif
5076 @end group
5077 @end example
5078
5079 If you don't want to maintain this piece of code in your package manually,
5080 you can instead use the Gnulib module @code{alloca-opt} or @code{alloca}.
5081 @xref{Gnulib}.
5082 @end defmac
5083
5084 @defmac AC_FUNC_CHOWN
5085 @acindex{FUNC_CHOWN}
5086 @cvindex HAVE_CHOWN
5087 @c @fuindex chown
5088 @prindex @code{chown}
5089 @caindex func_chown_works
5090 If the @code{chown} function is available and works (in particular, it
5091 should accept @option{-1} for @code{uid} and @code{gid}), define
5092 @code{HAVE_CHOWN}. The result of this macro is cached in the
5093 @code{ac_cv_func_chown_works} variable.
5094
5095 If you want a workaround, that is, a @code{chown} function that is
5096 available and works, you can use the Gnulib module @code{chown}.
5097 @xref{Gnulib}.
5098 @end defmac
5099
5100 @anchor{AC_FUNC_CLOSEDIR_VOID}
5101 @defmac AC_FUNC_CLOSEDIR_VOID
5102 @acindex{FUNC_CLOSEDIR_VOID}
5103 @cvindex CLOSEDIR_VOID
5104 @c @fuindex closedir
5105 @prindex @code{closedir}
5106 @caindex func_closedir_void
5107 If the @code{closedir} function does not return a meaningful value,
5108 define @code{CLOSEDIR_VOID}. Otherwise, callers ought to check its
5109 return value for an error indicator.
5110
5111 Currently this test is implemented by running a test program. When
5112 cross compiling the pessimistic assumption that @code{closedir} does not
5113 return a meaningful value is made.
5114
5115 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
5116 variable.
5117
5118 This macro is obsolescent, as @code{closedir} returns a meaningful value
5119 on current systems. New programs need not use this macro.
5120 @end defmac
5121
5122 @defmac AC_FUNC_ERROR_AT_LINE
5123 @acindex{FUNC_ERROR_AT_LINE}
5124 @c @fuindex error_at_line
5125 @prindex @code{error_at_line}
5126 @caindex lib_error_at_line
5127 If the @code{error_at_line} function is not found, require an
5128 @code{AC_LIBOBJ} replacement of @samp{error}.
5129
5130 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
5131 variable.
5132
5133 The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent. New programs
5134 should use Gnulib's @code{error} module. @xref{Gnulib}.
5135 @end defmac
5136
5137 @defmac AC_FUNC_FNMATCH
5138 @acindex{FUNC_FNMATCH}
5139 @c @fuindex fnmatch
5140 @prindex @code{fnmatch}
5141 @caindex func_fnmatch_works
5142 If the @code{fnmatch} function conforms to POSIX, define
5143 @code{HAVE_FNMATCH}.
5144
5145 Unlike the other specific
5146 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
5147 broken/missing @code{fnmatch}. This is for historical reasons.
5148 See @code{AC_REPLACE_FNMATCH} below.
5149
5150 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
5151 variable.
5152
5153 This macro is obsolescent. New programs should use Gnulib's
5154 @code{fnmatch-posix} module. @xref{Gnulib}.
5155 @end defmac
5156
5157 @defmac AC_FUNC_FNMATCH_GNU
5158 @acindex{FUNC_FNMATCH_GNU}
5159 @c @fuindex fnmatch
5160 @prindex @code{fnmatch}
5161 @caindex func_fnmatch_gnu
5162 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
5163 whether @code{fnmatch} supports GNU extensions. Detect common
5164 implementation bugs, for example, the bugs in the GNU C
5165 Library 2.1.
5166
5167 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
5168 variable.
5169
5170 This macro is obsolescent. New programs should use Gnulib's
5171 @code{fnmatch-gnu} module. @xref{Gnulib}.
5172 @end defmac
5173
5174 @anchor{AC_FUNC_FORK}
5175 @defmac AC_FUNC_FORK
5176 @acindex{FUNC_FORK}
5177 @cvindex HAVE_VFORK_H
5178 @cvindex HAVE_WORKING_FORK
5179 @cvindex HAVE_WORKING_VFORK
5180 @cvindex vfork
5181 @c @fuindex fork
5182 @prindex @code{fork}
5183 @c @fuindex vfork
5184 @prindex @code{vfork}
5185 @hdrindex{vfork.h}
5186 @c @caindex func_fork
5187 @c @caindex func_fork_works
5188 This macro checks for the @code{fork} and @code{vfork} functions. If a
5189 working @code{fork} is found, define @code{HAVE_WORKING_FORK}. This macro
5190 checks whether @code{fork} is just a stub by trying to run it.
5191
5192 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}. If a working
5193 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}. Otherwise,
5194 define @code{vfork} to be @code{fork} for backward compatibility with
5195 previous versions of @command{autoconf}. This macro checks for several known
5196 errors in implementations of @code{vfork} and considers the system to not
5197 have a working @code{vfork} if it detects any of them.
5198
5199 Since this macro defines @code{vfork} only for backward compatibility with
5200 previous versions of @command{autoconf} you're encouraged to define it
5201 yourself in new code:
5202 @example
5203 @group
5204 #ifndef HAVE_WORKING_VFORK
5205 # define vfork fork
5206 #endif
5207 @end group
5208 @end example
5209
5210 The results of this macro are cached in the @code{ac_cv_func_fork_works}
5211 and @code{ac_cv_func_vfork_works} variables. In order to override the
5212 test, you also need to set the @code{ac_cv_func_fork} and
5213 @code{ac_cv_func_vfork} variables.
5214 @end defmac
5215
5216 @anchor{AC_FUNC_FSEEKO}
5217 @defmac AC_FUNC_FSEEKO
5218 @acindex{FUNC_FSEEKO}
5219 @cvindex _LARGEFILE_SOURCE
5220 @cvindex HAVE_FSEEKO
5221 @c @fuindex fseeko
5222 @prindex @code{fseeko}
5223 @c @fuindex ftello
5224 @prindex @code{ftello}
5225 @c @caindex sys_largefile_source
5226 If the @code{fseeko} and @code{ftello} functions are available, define
5227 @code{HAVE_FSEEKO}. Define @code{_LARGEFILE_SOURCE} if necessary to
5228 make the prototype visible.
5229
5230 Configure scripts that use @code{AC_FUNC_FSEEKO} should normally also
5231 use @code{AC_SYS_LARGEFILE} to ensure that @code{off_t} can represent
5232 all supported file sizes. @xref{AC_SYS_LARGEFILE}.
5233
5234 The Gnulib module @code{fseeko} invokes @code{AC_FUNC_FSEEKO}
5235 and also contains workarounds for other portability problems of
5236 @code{fseeko}. @xref{Gnulib}.
5237 @end defmac
5238
5239 @defmac AC_FUNC_GETGROUPS
5240 @acindex{FUNC_GETGROUPS}
5241 @cvindex HAVE_GETGROUPS
5242 @ovindex GETGROUPS_LIB
5243 @c @fuindex getgroups
5244 @prindex @code{getgroups}
5245 @caindex func_getgroups_works
5246 Perform all the checks performed by @code{AC_TYPE_GETGROUPS}
5247 (@pxref{AC_TYPE_GETGROUPS}).
5248 Then, if the @code{getgroups} function is available
5249 and known to work correctly, define @code{HAVE_GETGROUPS}.
5250 Set the output variable @code{GETGROUPS_LIB} to any libraries
5251 needed to get that function.
5252
5253 This macro relies on a list of systems with known, serious bugs in
5254 @code{getgroups}. If this list mis-identifies your system's
5255 @code{getgroups} as buggy, or as not buggy, you can override it by
5256 setting the cache variable @code{ac_cv_func_getgroups_works} in a
5257 @file{config.site} file (@pxref{Site Defaults}). Please also report the
5258 error to @email{bug-autoconf@@gnu.org, the Autoconf Bugs mailing list}.
5259
5260 The Gnulib module @code{getgroups} provides workarounds for additional,
5261 less severe portability problems with this function.
5262 @end defmac
5263
5264 @anchor{AC_FUNC_GETLOADAVG}
5265 @defmac AC_FUNC_GETLOADAVG
5266 @acindex{FUNC_GETLOADAVG}
5267 @cvindex SVR4
5268 @cvindex DGUX
5269 @cvindex UMAX
5270 @cvindex UMAX4_3
5271 @cvindex HAVE_NLIST_H
5272 @cvindex NLIST_NAME_UNION
5273 @cvindex GETLOADAVG_PRIVILEGED
5274 @cvindex NEED_SETGID
5275 @cvindex C_GETLOADAVG
5276 @ovindex LIBOBJS
5277 @ovindex NEED_SETGID
5278 @ovindex KMEM_GROUP
5279 @ovindex GETLOADAVG_LIBS
5280 @c @fuindex getloadavg
5281 @prindex @code{getloadavg}
5282 Check how to get the system load averages. To perform its tests
5283 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5284 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5285 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5286
5287 If the system has the @code{getloadavg} function, define
5288 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5289 necessary to get that function. Also add @code{GETLOADAVG_LIBS} to
5290 @code{LIBS}. Otherwise, require an @code{AC_LIBOBJ} replacement for
5291 @samp{getloadavg} and possibly define several other C preprocessor
5292 macros and output variables:
5293
5294 @enumerate
5295 @item
5296 Define @code{C_GETLOADAVG}.
5297
5298 @item
5299 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5300 those systems.
5301
5302 @item
5303 @hdrindex{nlist.h}
5304 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5305
5306 @item
5307 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5308 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}. The obsolete symbol
5309 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5310
5311 @item
5312 Programs may need to be installed set-group-ID (or set-user-ID) for
5313 @code{getloadavg} to work. In this case, define
5314 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5315 to @samp{true} (and otherwise to @samp{false}), and set
5316 @code{KMEM_GROUP} to the name of the group that should own the installed
5317 program.
5318 @end enumerate
5319
5320 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent. New programs should
5321 use Gnulib's @code{getloadavg} module. @xref{Gnulib}.
5322 @end defmac
5323
5324 @anchor{AC_FUNC_GETMNTENT}
5325 @defmac AC_FUNC_GETMNTENT
5326 @acindex{FUNC_GETMNTENT}
5327 @cvindex HAVE_GETMNTENT
5328 @c @fuindex getmntent
5329 @prindex @code{getmntent}
5330 @caindex search_getmntent
5331 Check for @code{getmntent} in the standard C library, and then in the
5332 @file{sun}, @file{seq}, and @file{gen} libraries. Then, if
5333 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5334 @code{ac_cv_func_getmntent} to @code{yes}. Otherwise set
5335 @code{ac_cv_func_getmntent} to @code{no}.
5336
5337 The result of this macro can be overridden by setting the cache variable
5338 @code{ac_cv_search_getmntent}.
5339
5340 The @code{AC_FUNC_GETMNTENT} macro is obsolescent. New programs should
5341 use Gnulib's @code{mountlist} module. @xref{Gnulib}.
5342 @end defmac
5343
5344 @defmac AC_FUNC_GETPGRP
5345 @acindex{FUNC_GETPGRP}
5346 @cvindex GETPGRP_VOID
5347 @c @fuindex getpgid
5348 @c @fuindex getpgrp
5349 @prindex @code{getpgid}
5350 @prindex @code{getpgrp}
5351 @caindex func_getpgrp_void
5352 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5353 @code{getpgrp}; this is the POSIX behavior. On older BSD
5354 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5355 behaves like POSIX's @code{getpgid}.
5356
5357 @example
5358 #ifdef GETPGRP_VOID
5359 pid = getpgrp ();
5360 #else
5361 pid = getpgrp (0);
5362 #endif
5363 @end example
5364
5365 This macro does not check whether
5366 @code{getpgrp} exists at all; if you need to work in that situation,
5367 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5368
5369 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5370 variable.
5371
5372 This macro is obsolescent, as current systems have a @code{getpgrp}
5373 whose signature conforms to POSIX@. New programs need not use this macro.
5374 @end defmac
5375
5376 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5377 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5378 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5379 @c @fuindex lstat
5380 @prindex @code{lstat}
5381 @caindex func_lstat_dereferences_slashed_symlink
5382 If @file{link} is a symbolic link, then @code{lstat} should treat
5383 @file{link/} the same as @file{link/.}. However, many older
5384 @code{lstat} implementations incorrectly ignore trailing slashes.
5385
5386 It is safe to assume that if @code{lstat} incorrectly ignores
5387 trailing slashes, then other symbolic-link-aware functions like
5388 @code{unlink} also incorrectly ignore trailing slashes.
5389
5390 If @code{lstat} behaves properly, define
5391 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5392 @code{AC_LIBOBJ} replacement of @code{lstat}.
5393
5394 The result of this macro is cached in the
5395 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5396
5397 The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5398 New programs should use Gnulib's @code{lstat} module. @xref{Gnulib}.
5399 @end defmac
5400
5401 @defmac AC_FUNC_MALLOC
5402 @acindex{FUNC_MALLOC}
5403 @cvindex HAVE_MALLOC
5404 @cvindex malloc
5405 @c @fuindex malloc
5406 @prindex @code{malloc}
5407 @caindex func_malloc_0_nonnull
5408 If the @code{malloc} function is compatible with the GNU C
5409 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5410 pointer), define @code{HAVE_MALLOC} to 1. Otherwise define
5411 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5412 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5413 native @code{malloc} is not used in the main project.
5414
5415 Typically, the replacement file @file{malloc.c} should look like (note
5416 the @samp{#undef malloc}):
5417
5418 @verbatim
5419 #include <config.h>
5420 #undef malloc
5421
5422 #include <stdlib.h>
5423
5424 /* Allocate an N-byte block of memory from the heap.
5425 If N is zero, allocate a 1-byte block. */
5426
5427 void *
5428 rpl_malloc (size_t n)
5429 {
5430 if (n == 0)
5431 n = 1;
5432 return malloc (n);
5433 }
5434 @end verbatim
5435
5436 The result of this macro is cached in the
5437 @code{ac_cv_func_malloc_0_nonnull} variable.
5438 The result might contain spaces, e.g., @code{guessing yes}.
5439
5440 If you don't want to maintain a @code{malloc.c} file in your package
5441 manually, you can instead use the Gnulib module @code{malloc-gnu}.
5442 @end defmac
5443
5444 @defmac AC_FUNC_MBRTOWC
5445 @acindex{FUNC_MBRTOWC}
5446 @cvindex HAVE_MBRTOWC
5447 @c @fuindex mbrtowc
5448 @prindex @code{mbrtowc}
5449 @caindex func_mbrtowc
5450 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5451 type @code{mbstate_t} are properly declared.
5452
5453 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5454 variable.
5455
5456 The Gnulib module @code{mbrtowc} not only ensures that the
5457 function is declared, but also works around other portability
5458 problems of this function.
5459 @end defmac
5460
5461 @defmac AC_FUNC_MEMCMP
5462 @acindex{FUNC_MEMCMP}
5463 @ovindex LIBOBJS
5464 @c @fuindex memcmp
5465 @prindex @code{memcmp}
5466 @caindex func_memcmp_working
5467 If the @code{memcmp} function is not available or does not work, require an
5468 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5469
5470 The result of this macro is cached in the
5471 @code{ac_cv_func_memcmp_working} variable.
5472
5473 This macro is obsolescent, as current systems have a working
5474 @code{memcmp}. New programs need not use this macro.
5475 @end defmac
5476
5477 @defmac AC_FUNC_MKTIME
5478 @acindex{FUNC_MKTIME}
5479 @ovindex LIBOBJS
5480 @c @fuindex mktime
5481 @prindex @code{mktime}
5482 @caindex func_working_mktime
5483 If the @code{mktime} function is not available, or does not work
5484 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5485 For the purposes of this test, @code{mktime} should conform to the
5486 POSIX standard and should be the inverse of
5487 @code{localtime}.
5488
5489 The result of this macro is cached in the
5490 @code{ac_cv_func_working_mktime} variable.
5491
5492 The @code{AC_FUNC_MKTIME} macro is obsolescent. New programs should
5493 use Gnulib's @code{mktime} module. @xref{Gnulib}.
5494 @end defmac
5495
5496 @anchor{AC_FUNC_MMAP}
5497 @defmac AC_FUNC_MMAP
5498 @acindex{FUNC_MMAP}
5499 @cvindex HAVE_MMAP
5500 @c @fuindex mmap
5501 @prindex @code{mmap}
5502 @caindex func_mmap_fixed_mapped
5503 If the @code{mmap} function exists and works correctly, define
5504 @code{HAVE_MMAP}. This checks only private fixed mapping of already-mapped
5505 memory.
5506
5507 The result of this macro is cached in the
5508 @code{ac_cv_func_mmap_fixed_mapped} variable.
5509
5510 Note: This macro asks for more than what an average program needs from
5511 @code{mmap}. In particular, the use of @code{MAP_FIXED} fails on
5512 HP-UX 11, whereas @code{mmap} otherwise works fine on this platform.
5513 @end defmac
5514
5515 @defmac AC_FUNC_OBSTACK
5516 @acindex{FUNC_OBSTACK}
5517 @cvindex HAVE_OBSTACK
5518 @cindex obstack
5519 @caindex func_obstack
5520 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5521 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5522
5523 The result of this macro is cached in the @code{ac_cv_func_obstack}
5524 variable.
5525
5526 The @code{AC_FUNC_OBSTACK} macro is obsolescent. New programs should use
5527 Gnulib's @code{obstack} module. @xref{Gnulib}.
5528 @end defmac
5529
5530 @defmac AC_FUNC_REALLOC
5531 @acindex{FUNC_REALLOC}
5532 @cvindex HAVE_REALLOC
5533 @cvindex realloc
5534 @c @fuindex realloc
5535 @prindex @code{realloc}
5536 @caindex func_realloc_0_nonnull
5537 If a successful call to @samp{realloc (NULL, 0)} returns a
5538 non-null pointer, define @code{HAVE_REALLOC} to 1. Otherwise define
5539 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5540 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5541 the native @code{realloc} is not used in the main project. See
5542 @code{AC_FUNC_MALLOC} for details.
5543
5544 The result of this macro is cached in the
5545 @code{ac_cv_func_realloc_0_nonnull} variable.
5546 The result might contain spaces, e.g., @code{guessing yes}.
5547
5548 This macro does not check compatibility with glibc @code{realloc (@var{p}, 0)}
5549 when @var{p} is non-null, as glibc 1--2.1 behaves differently from glibc
5550 2.1.1--2.40 (at least), and the C standard says behavior is undefined.
5551 @end defmac
5552
5553 @defmac AC_FUNC_SELECT_ARGTYPES
5554 @acindex{FUNC_SELECT_ARGTYPES}
5555 @cvindex SELECT_TYPE_ARG1
5556 @cvindex SELECT_TYPE_ARG234
5557 @cvindex SELECT_TYPE_ARG5
5558 @c @fuindex select
5559 @prindex @code{select}
5560 @c @caindex func_select_args
5561 Determines the correct type to be passed for each of the
5562 @code{select} function's arguments, and defines those types
5563 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5564 @code{SELECT_TYPE_ARG5} respectively. @code{SELECT_TYPE_ARG1} defaults
5565 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5566 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5567
5568 This macro is obsolescent, as current systems have a @code{select} whose
5569 signature conforms to POSIX@. New programs need not use this macro.
5570 @end defmac
5571
5572 @defmac AC_FUNC_SETPGRP
5573 @acindex{FUNC_SETPGRP}
5574 @cvindex SETPGRP_VOID
5575 @c @fuindex setpgrp
5576 @prindex @code{setpgrp}
5577 @caindex func_setpgrp_void
5578 If @code{setpgrp} takes no argument (the POSIX version), define
5579 @code{SETPGRP_VOID}. Otherwise, it is the BSD version, which takes
5580 two process IDs as arguments. This macro does not check whether
5581 @code{setpgrp} exists at all; if you need to work in that situation,
5582 first call @code{AC_CHECK_FUNC} for @code{setpgrp}. This macro also
5583 does not check for the Solaris variant of @code{setpgrp}, which returns
5584 a @code{pid_t} instead of an @code{int}; portable code should only use
5585 the return value by comparing it against @code{-1} to check for errors.
5586
5587 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5588 variable.
5589
5590 This macro is obsolescent, as all forms of @code{setpgrp} are also
5591 obsolescent. New programs should use the POSIX function @code{setpgid},
5592 which takes two process IDs as arguments (like the BSD @code{setpgrp}).
5593 @end defmac
5594
5595 @defmac AC_FUNC_STAT
5596 @defmacx AC_FUNC_LSTAT
5597 @acindex{FUNC_STAT}
5598 @acindex{FUNC_LSTAT}
5599 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5600 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5601 @c @fuindex stat
5602 @prindex @code{stat}
5603 @c @fuindex lstat
5604 @prindex @code{lstat}
5605 @caindex func_stat_empty_string_bug
5606 @caindex func_lstat_empty_string_bug
5607 Determine whether @code{stat} or @code{lstat} have the bug that it
5608 succeeds when given the zero-length file name as argument.
5609
5610 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5611 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5612 replacement of it.
5613
5614 The results of these macros are cached in the
5615 @code{ac_cv_func_stat_empty_string_bug} and the
5616 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5617
5618 These macros are obsolescent, as no current systems have the bug.
5619 New programs need not use these macros.
5620 @end defmac
5621
5622 @anchor{AC_FUNC_STRCOLL}
5623 @defmac AC_FUNC_STRCOLL
5624 @acindex{FUNC_STRCOLL}
5625 @cvindex HAVE_STRCOLL
5626 @c @fuindex strcoll
5627 @prindex @code{strcoll}
5628 @caindex func_strcoll_works
5629 If the @code{strcoll} function exists and works correctly, define
5630 @code{HAVE_STRCOLL}. This does a bit more than
5631 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5632 definitions of @code{strcoll} that should not be used. But it does
5633 not check against a known bug of this function on Solaris 10.
5634
5635 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5636 variable.
5637 @end defmac
5638
5639 @defmac AC_FUNC_STRERROR_R
5640 @acindex{FUNC_STRERROR_R}
5641 @cvindex HAVE_STRERROR_R
5642 @cvindex HAVE_DECL_STRERROR_R
5643 @cvindex STRERROR_R_CHAR_P
5644 @c @fuindex strerror_r
5645 @caindex func_strerror_r_char_p
5646 @prindex @code{strerror_r}
5647 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5648 it is declared, define @code{HAVE_DECL_STRERROR_R}. If it returns a
5649 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5650 returns an @code{int} error number. The Thread-Safe Functions option of
5651 POSIX requires @code{strerror_r} to return @code{int}, but
5652 many systems (including, for example, the GNU C
5653 Library) return a @code{char *} value that is not necessarily equal to
5654 the buffer argument.
5655
5656 The result of this macro is cached in the
5657 @code{ac_cv_func_strerror_r_char_p} variable.
5658
5659 The Gnulib module @code{strerror_r} not only ensures that the function
5660 has the return type specified by POSIX, but also works around other
5661 portability problems of this function.
5662 @end defmac
5663
5664 @anchor{AC_FUNC_STRFTIME}
5665 @defmac AC_FUNC_STRFTIME
5666 @acindex{FUNC_STRFTIME}
5667 @cvindex HAVE_STRFTIME
5668 @c @fuindex strftime
5669 @prindex @code{strftime}
5670 Check for @code{strftime} in the @file{intl} library.
5671 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5672
5673 This macro is obsolescent, as no current systems require the @file{intl}
5674 library for @code{strftime}. New programs need not use this macro.
5675 @end defmac
5676
5677 @defmac AC_FUNC_STRTOD
5678 @acindex{FUNC_STRTOD}
5679 @ovindex POW_LIB
5680 @c @fuindex strtod
5681 @prindex @code{strtod}
5682 @caindex func_strtod
5683 @caindex func_pow
5684 If the @code{strtod} function does not exist or doesn't work correctly,
5685 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}. In this case,
5686 because @file{strtod.c} is likely to need @samp{pow}, set the output
5687 variable @code{POW_LIB} to the extra library needed.
5688
5689 This macro caches its result in the @code{ac_cv_func_strtod} variable
5690 and depends upon the result in the @code{ac_cv_func_pow} variable.
5691
5692 The @code{AC_FUNC_STRTOD} macro is obsolescent. New programs should
5693 use Gnulib's @code{strtod} module. @xref{Gnulib}.
5694 @end defmac
5695
5696 @defmac AC_FUNC_STRTOLD
5697 @acindex{FUNC_STRTOLD}
5698 @cvindex HAVE_STRTOLD
5699 @prindex @code{strtold}
5700 @caindex func_strtold
5701 If the @code{strtold} function exists and conforms to C99 or later, define
5702 @code{HAVE_STRTOLD}.
5703
5704 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5705
5706 The Gnulib module @code{strtold} not only ensures that the
5707 function exists, but also works around other portability
5708 problems of this function.
5709 @end defmac
5710
5711 @defmac AC_FUNC_STRNLEN
5712 @acindex{FUNC_STRNLEN}
5713 @cvindex HAVE_STRNLEN
5714 @c @fuindex strnlen
5715 @prindex @code{strnlen}
5716 @caindex func_strnlen_working
5717 If the @code{strnlen} function is not available, or is buggy (like the one
5718 from Android 5.0 or AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5719
5720 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5721 variable.
5722
5723 The @code{AC_FUNC_STRNLEN} macro is obsolescent. New programs should
5724 use Gnulib's @code{strnlen} module. @xref{Gnulib}.
5725 @end defmac
5726
5727 @anchor{AC_FUNC_UTIME_NULL}
5728 @defmac AC_FUNC_UTIME_NULL
5729 @acindex{FUNC_UTIME_NULL}
5730 @cvindex HAVE_UTIME_NULL
5731 @c @fuindex utime
5732 @prindex @code{utime}
5733 @caindex func_utime_null
5734 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5735 the present, define @code{HAVE_UTIME_NULL}.
5736
5737 This macro caches its result in the @code{ac_cv_func_utime_null}
5738 variable.
5739
5740 This macro is obsolescent, as all current systems have a @code{utime}
5741 that behaves this way. New programs need not use this macro.
5742 @end defmac
5743
5744 @anchor{AC_FUNC_VPRINTF}
5745 @defmac AC_FUNC_VPRINTF
5746 @acindex{FUNC_VPRINTF}
5747 @cvindex HAVE_VPRINTF
5748 @cvindex HAVE_DOPRNT
5749 @c @fuindex vprintf
5750 @prindex @code{vprintf}
5751 @c @fuindex vsprintf
5752 @prindex @code{vsprintf}
5753 If @code{vprintf} is found, define @code{HAVE_VPRINTF}. Otherwise, if
5754 @code{_doprnt} is found, define @code{HAVE_DOPRNT}. (If @code{vprintf}
5755 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5756 are also available.)
5757
5758 This macro is obsolescent, as all current systems have @code{vprintf}.
5759 New programs need not use this macro.
5760 @end defmac
5761
5762 @defmac AC_REPLACE_FNMATCH
5763 @acindex{REPLACE_FNMATCH}
5764 @c @fuindex fnmatch
5765 @prindex @code{fnmatch}
5766 @hdrindex{fnmatch.h}
5767 @caindex func_fnmatch_works
5768 If the @code{fnmatch} function does not conform to POSIX (see
5769 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5770
5771 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5772 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5773 copy of the source code of GNU @code{fnmatch}. If necessary,
5774 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5775 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5776 included in place of the system @code{<fnmatch.h>}.
5777
5778 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5779 variable.
5780
5781 This macro is obsolescent, as it assumes the use of particular source
5782 files. New programs should use Gnulib's @code{fnmatch-posix} module,
5783 which provides this macro along with the source files. @xref{Gnulib}.
5784 @end defmac
5785
5786
5787
5788 @node Generic Functions
5789 @subsection Generic Function Checks
5790
5791 These macros are used to find functions not covered by the ``particular''
5792 test macros. If the functions might be in libraries other than the
5793 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5794 If you need to check the behavior of a function as well as find out
5795 whether it is present, you have to write your own test for
5796 it (@pxref{Writing Tests}).
5797
5798 @anchor{AC_CHECK_FUNC}
5799 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5800 @ovar{action-if-not-found})
5801 @acindex{CHECK_FUNC}
5802 @caindex func_@var{function}
5803 If C function @var{function} is available, run shell commands
5804 @var{action-if-found}, otherwise @var{action-if-not-found}. If you just
5805 want to define a symbol if the function is available, consider using
5806 @code{AC_CHECK_FUNCS} instead. This macro checks for functions with C
5807 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5808 standardized than C++. (@pxref{Language Choice}, for more information
5809 about selecting the language for checks.)
5810
5811 This macro caches its result in the @code{ac_cv_func_@var{function}}
5812 variable.
5813 @end defmac
5814
5815 @anchor{AC_CHECK_FUNCS}
5816 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5817 @ovar{action-if-not-found})
5818 @acindex{CHECK_FUNCS}
5819 @cvindex HAVE_@var{function}
5820 For each @var{function} enumerated in the blank-or-newline-separated argument
5821 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5822 If @var{action-if-found} is given, it is additional shell code to
5823 execute when one of the functions is found. You can give it a value of
5824 @samp{break} to break out of the loop on the first match. If
5825 @var{action-if-not-found} is given, it is executed when one of the
5826 functions is not found.
5827
5828 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5829 @end defmac
5830
5831 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5832 @acindex{CHECK_FUNCS_ONCE}
5833 @cvindex HAVE_@var{function}
5834 For each @var{function} enumerated in the blank-or-newline-separated argument
5835 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5836 This is a once-only variant of @code{AC_CHECK_FUNCS}. It generates the
5837 checking code at most once, so that @command{configure} is smaller and
5838 faster; but the checks cannot be conditionalized and are always done once,
5839 early during the @command{configure} run.
5840 @end defmac
5841
5842 @sp 1
5843
5844 Autoconf follows a philosophy that was formed over the years by those
5845 who have struggled for portability: isolate the portability issues in
5846 specific files, and then program as if you were in a POSIX
5847 environment. Some functions may be missing or unfixable, and your
5848 package must be ready to replace them.
5849
5850 Suitable replacements for many such problem functions are available from
5851 Gnulib (@pxref{Gnulib}).
5852
5853 @defmac AC_LIBOBJ (@var{function})
5854 @acindex{LIBOBJ}
5855 @ovindex LIBOBJS
5856 Specify that @samp{@var{function}.c} must be included in the executables
5857 to replace a missing or broken implementation of @var{function}.
5858
5859 @vrindex ac_objext
5860 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5861 variable @code{LIBOBJS} if it is not already in, and calls
5862 @code{AC_LIBSOURCE} for @samp{@var{function}.c}. You should not
5863 directly change @code{LIBOBJS}, since this is not traceable.
5864 @end defmac
5865
5866 @defmac AC_LIBSOURCE (@var{file})
5867 @acindex{LIBSOURCE}
5868 Specify that @var{file} might be needed to compile the project. If you
5869 need to know what files might be needed by a @file{configure.ac}, you
5870 should trace @code{AC_LIBSOURCE}. @var{file} must be a literal.
5871
5872 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5873 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}. In
5874 that case, since shell variables cannot be traced statically, you must
5875 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5876 might cause @code{AC_LIBOBJ} to need. For example, if you want to pass
5877 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5878 @code{"foo"} or @code{"bar"}, you should do:
5879
5880 @example
5881 AC_LIBSOURCE([foo.c])
5882 AC_LIBSOURCE([bar.c])
5883 AC_LIBOBJ([$foo_or_bar])
5884 @end example
5885
5886 @noindent
5887 There is usually a way to avoid this, however, and you are encouraged to
5888 simply call @code{AC_LIBOBJ} with literal arguments.
5889
5890 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5891 slightly different semantics: the old macro took the function name,
5892 e.g., @code{foo}, as its argument rather than the file name.
5893 @end defmac
5894
5895 @defmac AC_LIBSOURCES (@var{files})
5896 @acindex{LIBSOURCES}
5897 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5898 comma-separated M4 list. Thus, the above example might be rewritten:
5899
5900 @example
5901 AC_LIBSOURCES([foo.c, bar.c])
5902 AC_LIBOBJ([$foo_or_bar])
5903 @end example
5904 @end defmac
5905
5906 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5907 @acindex{CONFIG_LIBOBJ_DIR}
5908 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5909 @var{directory}, a name relative to the top level of the
5910 source tree. The replacement directory defaults to @file{.}, the top
5911 level directory, and the most typical value is @file{lib}, corresponding
5912 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5913
5914 @command{configure} might need to know the replacement directory for the
5915 following reasons: (i) some checks use the replacement files, (ii) some
5916 macros bypass broken system headers by installing links to the
5917 replacement headers (iii) when used in conjunction with Automake,
5918 within each makefile, @var{directory} is used as a relative path
5919 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5920 @code{LTLIBOBJS}, etc.
5921 @end defmac
5922
5923 @sp 1
5924
5925 It is common to merely check for the existence of a function, and ask
5926 for its @code{AC_LIBOBJ} replacement if missing. The following macro is
5927 a convenient shorthand.
5928
5929 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5930 @acindex{REPLACE_FUNCS}
5931 @cvindex HAVE_@var{function}
5932 @ovindex LIBOBJS
5933 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5934 @var{action-if-not-found}. You can declare your replacement function by
5935 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}. If the
5936 system has the function, it probably declares it in a header file you
5937 should be including, so you shouldn't redeclare it lest your declaration
5938 conflict.
5939 @end defmac
5940
5941 @node Header Files
5942 @section Header Files
5943 @cindex Header, checking
5944
5945 The following macros check for the presence of certain C header files.
5946 If there is no macro specifically defined to check for a header file you need,
5947 and you don't need to check for any special properties of
5948 it, then you can use one of the general header-file check macros.
5949
5950 @menu
5951 * Header Portability:: Collected knowledge on common headers
5952 * Particular Headers:: Special handling to find certain headers
5953 * Generic Headers:: How to find other headers
5954 @end menu
5955
5956 @node Header Portability
5957 @subsection Portability of Headers
5958 @cindex Portability of headers
5959 @cindex Header portability
5960
5961 This section documents some collected knowledge about common headers,
5962 and the problems they cause. By definition, this list always requires
5963 additions. A much more complete list is maintained by the Gnulib
5964 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5965 POSIX Headers, gnulib, Gnulib} and @ref{Glibc Header File
5966 Substitutes, , Glibc Headers, gnulib, Gnulib}. Please help us keep
5967 the Gnulib list as complete as possible.
5968
5969 When we say that a header ``may require'' some set of other headers, we
5970 mean that it may be necessary for you to manually include those other
5971 headers first, or the contents of the header under test will fail to
5972 compile. When checking for these headers, you must provide the
5973 potentially-required headers in the @var{includes} argument to
5974 @code{AC_CHECK_HEADER} or @code{AC_CHECK_HEADERS}, or the check will
5975 fail spuriously. @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes})
5976 arranges to include a number of common requirements and should normally
5977 come first in your @var{includes}. For example, @file{net/if.h} may
5978 require @file{sys/types.h}, @file{sys/socket.h}, or both, and
5979 @code{AC_INCLUDES_DEFAULT} handles @file{sys/types.h} but not
5980 @file{sys/socket.h}, so you should check for it like this:
5981
5982 @example
5983 AC_CHECK_HEADERS([sys/socket.h])
5984 AC_CHECK_HEADERS([net/if.h], [], [],
5985 [AC_INCLUDES_DEFAULT[
5986 #ifdef HAVE_SYS_SOCKET_H
5987 # include <sys/socket.h>
5988 #endif
5989 ]])
5990 @end example
5991
5992 Note that the example mixes single quoting (for@code{AC_INCLUDES_DEFAULT},
5993 so that it gets expanded) and double quoting (to ensure that each
5994 preprocessor @code{#} gets treated as a literal string rather than a
5995 comment).
5996
5997 @table @asis
5998
5999 @item @file{limits.h}
6000 In C99 and later, @file{limits.h} defines @code{LLONG_MIN},
6001 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
6002 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
6003 define them.
6004
6005 @item @file{memory.h}
6006 @hdrindex{memory.h}
6007 This header file is obsolete; use @file{string.h} instead.
6008
6009 @item @file{strings.h}
6010 @hdrindex{strings.h}
6011 On some systems, this is the only header that declares
6012 @code{strcasecmp}, @code{strncasecmp}, and @code{ffs}.
6013
6014 This header may or may not include @file{string.h} for you. However, on
6015 all recent systems it is safe to include both @file{string.h} and
6016 @file{strings.h}, in either order, in the same source file.
6017
6018 @item @file{inttypes.h} vs.@: @file{stdint.h}
6019 @hdrindex{inttypes.h}
6020 @hdrindex{stdint.h}
6021 C99 specifies that @file{inttypes.h} includes @file{stdint.h}, so there's
6022 no need to include @file{stdint.h} separately in a standard environment.
6023 However, some implementations have @file{stdint.h} but not @file{inttypes.h}
6024 (e.g. MSVC 2012). Therefore, it is necessary to check for each and include
6025 each only if available.
6026
6027 @item @file{linux/irda.h}
6028 @hdrindex{linux/irda.h}
6029 This header may require @file{linux/types.h} and/or @file{sys/socket.h}.
6030
6031 @item @file{linux/random.h}
6032 @hdrindex{linux/random.h}
6033 This header may require @file{linux/types.h}.
6034
6035 @item @file{net/if.h}
6036 @hdrindex{net/if.h}
6037 This header may require @file{sys/types.h} and/or @file{sys/socket.h}.
6038
6039 @item @file{netinet/if_ether.h}
6040 @hdrindex{netinet/if_ether.h}
6041 This header may require some combination of @file{sys/types.h},
6042 @file{sys/socket.h}, @file{netinet/in.h}, and @file{net/if.h}.
6043
6044 @item @file{sys/mount.h}
6045 @hdrindex{sys/mount.h}
6046 This header may require @file{sys/params.h}.
6047
6048 @item @file{sys/ptem.h}
6049 @hdrindex{sys/ptem.h}
6050 This header may require @file{sys/stream.h}.
6051
6052 @item @file{sys/socket.h}
6053 @hdrindex{sys/socket.h}
6054 This header may require @file{sys/types.h}.
6055
6056 @item @file{sys/ucred.h}
6057 @hdrindex{sys/ucred.h}
6058 This header may require @file{sys/types.h}.
6059
6060 @item @file{X11/extensions/scrnsaver.h}
6061 @hdrindex{X11/extensions/scrnsaver.h}
6062 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
6063 so required that you might not even consider looking for it.
6064
6065 @end table
6066
6067
6068 @node Particular Headers
6069 @subsection Particular Header Checks
6070
6071 These macros check for particular system header files---whether they
6072 exist, and in some cases whether they declare certain symbols.
6073
6074 @defmac AC_CHECK_HEADER_STDBOOL
6075 @acindex{CHECK_HEADER_STDBOOL}
6076 @cvindex HAVE__BOOL
6077 @hdrindex{stdbool.h}
6078 @caindex header_stdbool_h
6079 Check whether @file{stdbool.h} exists and conforms to C99 or later,
6080 and cache the result in the @code{ac_cv_header_stdbool_h} variable.
6081 If the type @code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
6082
6083 This macro is obsolescent, as all current C compilers have @file{stdbool.h},
6084 a header that is itself obsolescent as of C23.
6085
6086 This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
6087 packages that supply a substitute @file{stdbool.h} on platforms lacking
6088 a conforming one. The @code{AC_HEADER_STDBOOL} macro is better for code
6089 that explicitly checks for @file{stdbool.h}.
6090 @end defmac
6091
6092 @defmac AC_HEADER_ASSERT
6093 @acindex{HEADER_ASSERT}
6094 @cvindex NDEBUG
6095 @hdrindex{assert.h}
6096 Check whether to enable assertions in the style of @file{assert.h}.
6097 Assertions are enabled by default, but the user can override this by
6098 invoking @command{configure} with the @option{--disable-assert} option.
6099 @end defmac
6100
6101 @anchor{AC_HEADER_DIRENT}
6102 @defmac AC_HEADER_DIRENT
6103 @acindex{HEADER_DIRENT}
6104 @cvindex HAVE_DIRENT_H
6105 @cvindex HAVE_NDIR_H
6106 @cvindex HAVE_SYS_DIR_H
6107 @cvindex HAVE_SYS_NDIR_H
6108 @hdrindex{dirent.h}
6109 @hdrindex{sys/ndir.h}
6110 @hdrindex{sys/dir.h}
6111 @hdrindex{ndir.h}
6112 Check for the following header files. For the first one that is
6113 found and defines @samp{DIR}, define the listed C preprocessor macro:
6114
6115 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
6116 @item @file{dirent.h} @tab @code{HAVE_DIRENT_H}
6117 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
6118 @item @file{sys/dir.h} @tab @code{HAVE_SYS_DIR_H}
6119 @item @file{ndir.h} @tab @code{HAVE_NDIR_H}
6120 @end multitable
6121
6122 The directory-library declarations in your source code should look
6123 something like the following:
6124
6125 @example
6126 @group
6127 #include <sys/types.h>
6128 #ifdef HAVE_DIRENT_H
6129 # include <dirent.h>
6130 # define NAMLEN(dirent) strlen ((dirent)->d_name)
6131 #else
6132 # define dirent direct
6133 # define NAMLEN(dirent) ((dirent)->d_namlen)
6134 # ifdef HAVE_SYS_NDIR_H
6135 # include <sys/ndir.h>
6136 # endif
6137 # ifdef HAVE_SYS_DIR_H
6138 # include <sys/dir.h>
6139 # endif
6140 # ifdef HAVE_NDIR_H
6141 # include <ndir.h>
6142 # endif
6143 #endif
6144 @end group
6145 @end example
6146
6147 Using the above declarations, the program would declare variables to be
6148 of type @code{struct dirent}, not @code{struct direct}, and would access
6149 the length of a directory entry name by passing a pointer to a
6150 @code{struct dirent} to the @code{NAMLEN} macro.
6151
6152 This macro also checks for the obsolete @file{dir} and @file{x} libraries.
6153
6154 This macro is obsolescent, as all current systems with directory
6155 libraries have @code{<dirent.h>}. New programs need not use this macro.
6156
6157 Also see @code{AC_STRUCT_DIRENT_D_INO} and
6158 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
6159 @end defmac
6160
6161 @anchor{AC_HEADER_MAJOR}
6162 @defmac AC_HEADER_MAJOR
6163 @acindex{HEADER_MAJOR}
6164 @cvindex MAJOR_IN_MKDEV
6165 @cvindex MAJOR_IN_SYSMACROS
6166 @hdrindex{sys/mkdev.h}
6167 @hdrindex{sys/sysmacros.h}
6168 Detect the headers required to use @code{makedev}, @code{major}, and
6169 @code{minor}. These functions may be defined by @file{sys/mkdev.h},
6170 @code{sys/sysmacros.h}, or @file{sys/types.h}.
6171
6172 @code{AC_HEADER_MAJOR} defines @code{MAJOR_IN_MKDEV} if they are in
6173 @file{sys/mkdev.h}, or @code{MAJOR_IN_SYSMACROS} if they are in
6174 @file{sys/sysmacros.h}. If neither macro is defined, they are either in
6175 @file{sys/types.h} or unavailable.
6176
6177 To properly use these functions, your code should contain something
6178 like:
6179
6180 @verbatim
6181 #include <sys/types.h>
6182 #ifdef MAJOR_IN_MKDEV
6183 # include <sys/mkdev.h>
6184 #elif defined MAJOR_IN_SYSMACROS
6185 # include <sys/sysmacros.h>
6186 #endif
6187 @end verbatim
6188
6189 Note: Configure scripts built with Autoconf 2.69 or earlier will not
6190 detect a problem if @file{sys/types.h} contains definitions of
6191 @code{major}, @code{minor}, and/or @code{makedev} that trigger compiler
6192 warnings upon use. This is known to occur with GNU libc 2.25, where
6193 those definitions are being deprecated to reduce namespace pollution.
6194 If it is not practical to use Autoconf 2.70 to regenerate the configure
6195 script of affected software, you can work around the problem by setting
6196 @samp{ac_cv_header_sys_types_h_makedev=no}, as an argument to
6197 @command{configure} or as part of a @file{config.site} site default file
6198 (@pxref{Site Defaults}).
6199 @end defmac
6200
6201 @defmac AC_HEADER_RESOLV
6202 @acindex{HEADER_RESOLV}
6203 @cvindex HAVE_RESOLV_H
6204 @hdrindex{resolv.h}
6205 Checks for header @file{resolv.h}, checking for prerequisites first.
6206 To properly use @file{resolv.h}, your code should contain something like
6207 the following:
6208
6209 @verbatim
6210 #ifdef HAVE_SYS_TYPES_H
6211 # include <sys/types.h>
6212 #endif
6213 #ifdef HAVE_NETINET_IN_H
6214 # include <netinet/in.h> /* inet_ functions / structs */
6215 #endif
6216 #ifdef HAVE_ARPA_NAMESER_H
6217 # include <arpa/nameser.h> /* DNS HEADER struct */
6218 #endif
6219 #ifdef HAVE_NETDB_H
6220 # include <netdb.h>
6221 #endif
6222 #include <resolv.h>
6223 @end verbatim
6224 @end defmac
6225
6226 @anchor{AC_HEADER_STAT}
6227 @defmac AC_HEADER_STAT
6228 @acindex{HEADER_STAT}
6229 @cvindex STAT_MACROS_BROKEN
6230 @hdrindex{sys/stat.h}
6231 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
6232 @file{sys/stat.h} do not work properly (returning false positives),
6233 define @code{STAT_MACROS_BROKEN}. This is the case on Tektronix UTekV,
6234 Amdahl UTS and Motorola System V/88.
6235
6236 This macro is obsolescent, as no current systems have the bug.
6237 New programs need not use this macro.
6238 @end defmac
6239
6240 @defmac AC_HEADER_STDBOOL
6241 @acindex{HEADER_STDBOOL}
6242 @cvindex HAVE_STDBOOL_H
6243 @cvindex HAVE__BOOL
6244 @hdrindex{stdbool.h}
6245 @caindex header_stdbool_h
6246 If @file{stdbool.h} exists and conforms to C99 or later, define
6247 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
6248 @code{HAVE__BOOL} to 1.
6249
6250 This macro is obsolescent, as all current C compilers have
6251 @file{stdbool.h}, a header that is itself obsolescent as of C23.
6252 Nowadays programs that need @code{bool}, @code{true} and @code{false}
6253 can include @file{stdbool.h} unconditionally, without using
6254 @code{AC_HEADER_STDBOOL}, and if such a program needs to be portable
6255 only to C23 or later it need not even include @file{stdbool.h}.
6256
6257 This macro caches its result in the @code{ac_cv_header_stdbool_h}
6258 variable.
6259
6260 This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
6261 defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
6262 does not.
6263 @end defmac
6264
6265 @anchor{AC_HEADER_STDC}
6266 @defmac AC_HEADER_STDC
6267 @acindex{HEADER_STDC}
6268 @cvindex STDC_HEADERS
6269 @caindex header_stdc
6270
6271 This macro is obsolescent. Its sole effect is to make sure that all the
6272 headers that are included by @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6273 Includes}), but not part of C89, have been checked for.
6274
6275 All hosted environments that are still of interest for portable code
6276 provide all of the headers specified in C89 (as amended in 1995).
6277 @end defmac
6278
6279 @defmac AC_HEADER_SYS_WAIT
6280 @acindex{HEADER_SYS_WAIT}
6281 @cvindex HAVE_SYS_WAIT_H
6282 @hdrindex{sys/wait.h}
6283 @caindex header_sys_wait_h
6284 If @file{sys/wait.h} exists and is compatible with POSIX, define
6285 @code{HAVE_SYS_WAIT_H}. Incompatibility can occur if @file{sys/wait.h}
6286 does not exist, or if it uses the old BSD @code{union wait} instead
6287 of @code{int} to store a status value. If @file{sys/wait.h} is not
6288 POSIX compatible, then instead of including it, define the
6289 POSIX macros with their usual interpretations. Here is an
6290 example:
6291
6292 @example
6293 @group
6294 #include <sys/types.h>
6295 #ifdef HAVE_SYS_WAIT_H
6296 # include <sys/wait.h>
6297 #endif
6298 #ifndef WEXITSTATUS
6299 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6300 #endif
6301 #ifndef WIFEXITED
6302 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6303 #endif
6304 @end group
6305 @end example
6306
6307 @noindent
6308 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6309 variable.
6310
6311 This macro is obsolescent, as current systems are compatible with POSIX@.
6312 New programs need not use this macro.
6313 @end defmac
6314
6315 @cvindex _POSIX_VERSION
6316 @hdrindex{unistd.h}
6317 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6318 POSIX systems. If there is no @file{unistd.h}, it is definitely
6319 not a POSIX system. However, some non-POSIX systems do
6320 have @file{unistd.h}.
6321
6322 The way to check whether the system says it supports POSIX is:
6323
6324 @example
6325 @group
6326 #ifdef HAVE_UNISTD_H
6327 # include <sys/types.h>
6328 # include <unistd.h>
6329 #endif
6330
6331 #ifdef _POSIX_VERSION
6332 /* Code for POSIX systems. */
6333 #endif
6334 @end group
6335 @end example
6336
6337 @defmac AC_HEADER_TIOCGWINSZ
6338 @acindex{HEADER_TIOCGWINSZ}
6339 @cvindex GWINSZ_IN_SYS_IOCTL
6340 @hdrindex{sys/ioctl.h}
6341 @hdrindex{termios.h}
6342 @c FIXME: I need clarifications from Jim.
6343 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6344 define @code{GWINSZ_IN_SYS_IOCTL}. Otherwise @code{TIOCGWINSZ} can be
6345 found in @file{<termios.h>}.
6346
6347 Use:
6348
6349 @example
6350 @group
6351 #ifdef HAVE_TERMIOS_H
6352 # include <termios.h>
6353 #endif
6354
6355 #ifdef GWINSZ_IN_SYS_IOCTL
6356 # include <sys/ioctl.h>
6357 #endif
6358 @end group
6359 @end example
6360 @end defmac
6361
6362 @node Generic Headers
6363 @subsection Generic Header Checks
6364
6365 These macros are used to find system header files not covered by the
6366 ``particular'' test macros. If you need to check the contents of a header
6367 as well as find out whether it is present, you have to write your own
6368 test for it (@pxref{Writing Tests}).
6369
6370 @anchor{AC_CHECK_HEADER}
6371 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6372 @ovar{action-if-not-found}, @ovar{includes})
6373 @acindex{CHECK_HEADER}
6374 @caindex header_@var{header-file}
6375 If the system header file @var{header-file} is compilable, execute shell
6376 commands @var{action-if-found}, otherwise execute
6377 @var{action-if-not-found}. If you just want to define a symbol if the
6378 header file is available, consider using @code{AC_CHECK_HEADERS}
6379 instead.
6380
6381 @var{includes} should be the appropriate @dfn{prerequisite} code, i.e.@:
6382 whatever might be required to appear above
6383 @samp{#include <@var{header-file}>} for it to compile without error.
6384 This can be anything, but will normally be additional @samp{#include}
6385 directives. If @var{includes} is omitted or empty, @file{configure} will
6386 use the contents of the macro @code{AC_INCLUDES_DEFAULT}.
6387 @xref{Default Includes}.
6388
6389 This macro used to check only for the @emph{presence} of a header, not
6390 whether its contents were acceptable to the compiler. Some older
6391 @command{configure} scripts rely on this behavior, so it is still
6392 available by specifying @samp{-} as @var{includes}. This mechanism is
6393 deprecated as of Autoconf 2.70; situations where a preprocessor-only
6394 check is required should use @code{AC_PREPROC_IFELSE}.
6395 @xref{Running the Preprocessor}.
6396
6397 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6398 variable, with characters not suitable for a variable name mapped to
6399 underscores.
6400 @end defmac
6401
6402 @anchor{AC_CHECK_HEADERS}
6403 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6404 @ovar{action-if-found}, @ovar{action-if-not-found}, @
6405 @ovar{includes})
6406 @acindex{CHECK_HEADERS}
6407 @cvindex HAVE_@var{header}
6408 @caindex header_@var{header-file}
6409 For each given system header file @var{header-file} in the
6410 blank-separated argument list that exists, define
6411 @code{HAVE_@var{header-file}} (in all capitals). If @var{action-if-found}
6412 is given, it is additional shell code to execute when one of the header
6413 files is found. You can give it a value of @samp{break} to break out of
6414 the loop on the first match. If @var{action-if-not-found} is given, it
6415 is executed when one of the header files is not found.
6416
6417 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6418 choose the set of preprocessor directives supplied before the header
6419 under test.
6420
6421 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6422 variable, with characters not suitable for a variable name mapped to
6423 underscores.
6424 @end defmac
6425
6426 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6427 @acindex{CHECK_HEADERS_ONCE}
6428 @cvindex HAVE_@var{header}
6429 For each given system header file @var{header-file} in the
6430 blank-separated argument list that exists, define
6431 @code{HAVE_@var{header-file}} (in all capitals).
6432
6433 If you do not need the full power of @code{AC_CHECK_HEADERS}, this
6434 variant generates smaller, faster @command{configure} files. All
6435 headers passed to @code{AC_CHECK_HEADERS_ONCE} are checked for in one
6436 pass, early during the @command{configure} run. The checks cannot be
6437 conditionalized, you cannot specify an @var{action-if-found} or
6438 @var{action-if-not-found}, and @code{AC_INCLUDES_DEFAULT} is always used
6439 for the prerequisites.
6440 @end defmac
6441
6442 In previous versions of Autoconf, these macros merely checked whether
6443 the header was accepted by the preprocessor. This was changed because
6444 the old test was inappropriate for typical uses. Headers are typically
6445 used to compile, not merely to preprocess, and the old behavior
6446 sometimes accepted headers that clashed at compile-time
6447 (@pxref{Present But Cannot Be Compiled}). If for some reason it is
6448 inappropriate to check whether a header is compilable, you should use
6449 @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}) instead of
6450 these macros.
6451
6452 Requiring each header to compile improves the robustness of the test,
6453 but it also requires you to make sure that the @var{includes} are
6454 correct. Most system headers nowadays make sure to @code{#include}
6455 whatever they require, or else have their dependencies satisfied by
6456 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), but
6457 @pxref{Header Portability}, for known exceptions. In general, if you
6458 are looking for @file{bar.h}, which requires that @file{foo.h} be
6459 included first if it exists, you should do something like this:
6460
6461 @example
6462 AC_CHECK_HEADERS([foo.h])
6463 AC_CHECK_HEADERS([bar.h], [], [],
6464 [#ifdef HAVE_FOO_H
6465 # include <foo.h>
6466 #endif
6467 ])
6468 @end example
6469
6470 @node Declarations
6471 @section Declarations
6472 @cindex Declaration, checking
6473
6474 The following macros check for the declaration of variables and
6475 functions. If there is no macro specifically defined to check for a
6476 symbol you need, then you can use the general macros (@pxref{Generic
6477 Declarations}) or, for more complex tests, you may use
6478 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6479
6480 @menu
6481 * Particular Declarations:: Macros to check for certain declarations
6482 * Generic Declarations:: How to find other declarations
6483 @end menu
6484
6485 @node Particular Declarations
6486 @subsection Particular Declaration Checks
6487
6488 There are no specific macros for declarations.
6489
6490 @node Generic Declarations
6491 @subsection Generic Declaration Checks
6492
6493 These macros are used to find declarations not covered by the ``particular''
6494 test macros.
6495
6496 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6497 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6498 @acindex{CHECK_DECL}
6499 @caindex have_decl_@var{symbol}
6500 If @var{symbol} (a function, variable, or constant) is not declared in
6501 @var{includes} and a declaration is needed, run the shell commands
6502 @var{action-if-not-found}, otherwise @var{action-if-found}.
6503 @var{includes} is a series of include directives, defaulting to
6504 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6505 prior to the declaration under test.
6506
6507 This macro actually tests whether @var{symbol} is defined as a macro or
6508 can be used as an r-value, not whether it is really declared, because it
6509 is much safer to avoid introducing extra declarations when they are not
6510 needed. In order to facilitate use of C++ and overloaded function
6511 declarations, it is possible to specify function argument types in
6512 parentheses for types which can be zero-initialized:
6513
6514 @example
6515 AC_CHECK_DECL([basename(char *)])
6516 @end example
6517
6518 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6519 variable, with characters not suitable for a variable name mapped to
6520 underscores.
6521 @end defmac
6522
6523 @anchor{AC_CHECK_DECLS}
6524 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6525 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6526 @acindex{CHECK_DECLS}
6527 @cvindex HAVE_DECL_@var{symbol}
6528 @caindex have_decl_@var{symbol}
6529 For each of the @var{symbols} (@emph{comma}-separated list with optional
6530 function argument types for C++ overloads), define
6531 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6532 @var{symbol} is declared, otherwise to @samp{0}. If
6533 @var{action-if-not-found} is given, it is additional shell code to
6534 execute when one of the function declarations is needed, otherwise
6535 @var{action-if-found} is executed.
6536
6537 @var{includes} is a series of include directives, defaulting to
6538 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6539 prior to the declarations under test.
6540
6541 This macro uses an M4 list as first argument:
6542 @example
6543 AC_CHECK_DECLS([strdup])
6544 AC_CHECK_DECLS([strlen])
6545 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6546 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6547 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6548 @end example
6549
6550 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6551 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6552 of leaving @code{HAVE_DECL_@var{symbol}} undeclared. When you are
6553 @emph{sure} that the check was performed, use
6554 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6555
6556 @example
6557 #if !HAVE_DECL_SYMBOL
6558 extern char *symbol;
6559 #endif
6560 @end example
6561
6562 @noindent
6563 If the test may have not been performed, however, because it is safer
6564 @emph{not} to declare a symbol than to use a declaration that conflicts
6565 with the system's one, you should use:
6566
6567 @example
6568 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6569 void *malloc (size_t *s);
6570 #endif
6571 @end example
6572
6573 @noindent
6574 You fall into the second category only in extreme situations: either
6575 your files may be used without being configured, or they are used during
6576 the configuration. In most cases the traditional approach is enough.
6577
6578 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6579 variables, with characters not suitable for a variable name mapped to
6580 underscores.
6581 @end defmac
6582
6583 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6584 @acindex{CHECK_DECLS_ONCE}
6585 @cvindex HAVE_DECL_@var{symbol}
6586 For each of the @var{symbols} (@emph{comma}-separated list), define
6587 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6588 @var{symbol} is declared in the default include files, otherwise to
6589 @samp{0}. This is a once-only variant of @code{AC_CHECK_DECLS}. It
6590 generates the checking code at most once, so that @command{configure} is
6591 smaller and faster; but the checks cannot be conditionalized and are
6592 always done once, early during the @command{configure} run.
6593 @end defmac
6594
6595
6596 @node Structures
6597 @section Structures
6598 @cindex Structure, checking
6599
6600 The following macros check for the presence of certain members in C
6601 structures. If there is no macro specifically defined to check for a
6602 member you need, then you can use the general structure-member macros
6603 (@pxref{Generic Structures}) or, for more complex tests, you may use
6604 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6605
6606 @menu
6607 * Particular Structures:: Macros to check for certain structure members
6608 * Generic Structures:: How to find other structure members
6609 @end menu
6610
6611 @node Particular Structures
6612 @subsection Particular Structure Checks
6613
6614 The following macros check for certain structures or structure members.
6615
6616 @defmac AC_STRUCT_DIRENT_D_INO
6617 @acindex{STRUCT_DIRENT_D_INO}
6618 @cvindex HAVE_STRUCT_DIRENT_D_INO
6619 @c @caindex header_dirent_dirent_h
6620 @c @caindex member_struct_dirent_d_ino
6621 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6622 Headers}). Then, if @code{struct dirent} contains a @code{d_ino}
6623 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6624
6625 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6626 @code{d_ino}, not whether its contents are always reliable.
6627 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6628 though current systems hide this detail from the user and never return
6629 zero @code{d_ino} values.
6630 Many current systems report an incorrect @code{d_ino} for a directory
6631 entry that is a mount point.
6632 @end defmac
6633
6634 @defmac AC_STRUCT_DIRENT_D_TYPE
6635 @acindex{STRUCT_DIRENT_D_TYPE}
6636 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6637 @c @caindex header_dirent_dirent_h
6638 @c @caindex member_struct_dirent_d_type
6639 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6640 Headers}). Then, if @code{struct dirent} contains a @code{d_type}
6641 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6642 @end defmac
6643
6644 @anchor{AC_STRUCT_ST_BLOCKS}
6645 @defmac AC_STRUCT_ST_BLOCKS
6646 @acindex{STRUCT_ST_BLOCKS}
6647 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6648 @cvindex HAVE_ST_BLOCKS
6649 @ovindex LIBOBJS
6650 @caindex member_struct_stat_st_blocks
6651 If @code{struct stat} contains an @code{st_blocks} member, define
6652 @code{HAVE_STRUCT_STAT_ST_BLOCKS}. Otherwise, require an
6653 @code{AC_LIBOBJ} replacement of @samp{fileblocks}. The former name,
6654 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6655 future.
6656
6657 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6658 variable.
6659 @end defmac
6660
6661 @defmac AC_STRUCT_TM
6662 @acindex{STRUCT_TM}
6663 @cvindex TM_IN_SYS_TIME
6664 @hdrindex{time.h}
6665 @hdrindex{sys/time.h}
6666 If @file{time.h} does not define @code{struct tm}, define
6667 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6668 had better define @code{struct tm}.
6669
6670 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6671 current systems. New programs need not use this macro.
6672 @end defmac
6673
6674 @anchor{AC_STRUCT_TIMEZONE}
6675 @defmac AC_STRUCT_TIMEZONE
6676 @acindex{STRUCT_TIMEZONE}
6677 @cvindex HAVE_DECL_TZNAME
6678 @cvindex HAVE_STRUCT_TM_TM_ZONE
6679 @cvindex HAVE_TM_ZONE
6680 @cvindex HAVE_TZNAME
6681 @c @caindex member_struct_tm_tm_zone
6682 @c @caindex struct_tm
6683 Figure out how to get the current timezone. If @code{struct tm} has a
6684 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6685 obsoleted @code{HAVE_TM_ZONE}). Otherwise, if the external array
6686 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6687 define @code{HAVE_DECL_TZNAME}.
6688 @end defmac
6689
6690 @node Generic Structures
6691 @subsection Generic Structure Checks
6692
6693 These macros are used to find structure members not covered by the
6694 ``particular'' test macros.
6695
6696 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6697 @ovar{action-if-found}, @ovar{action-if-not-found}, @
6698 @dvar{includes, AC_INCLUDES_DEFAULT})
6699 @acindex{CHECK_MEMBER}
6700 @caindex member_@var{aggregate}_@var{member}
6701 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6702 If no @var{includes} are specified, the default includes are used
6703 (@pxref{Default Includes}).
6704
6705 @example
6706 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6707 [AC_MSG_ERROR([we need 'passwd.pw_gecos'])],
6708 [[#include <pwd.h>]])
6709 @end example
6710
6711 You can use this macro for submembers:
6712
6713 @example
6714 AC_CHECK_MEMBER(struct top.middle.bot)
6715 @end example
6716
6717 This macro caches its result in the
6718 @code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6719 characters not suitable for a variable name mapped to underscores.
6720 @end defmac
6721
6722 @anchor{AC_CHECK_MEMBERS}
6723 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6724 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6725 @acindex{CHECK_MEMBERS}
6726 @cvindex HAVE_@var{aggregate}_@var{member}
6727 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6728 @var{members} using the previous macro. When @var{member} belongs to
6729 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6730 capitals, with spaces and dots replaced by underscores). If
6731 @var{action-if-found} is given, it is executed for each of the found
6732 members. If @var{action-if-not-found} is given, it is executed for each
6733 of the members that could not be found.
6734
6735 @var{includes} is a series of include directives, defaulting to
6736 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6737 prior to the members under test.
6738
6739 This macro uses M4 lists:
6740 @example
6741 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6742 @end example
6743 @end defmac
6744
6745
6746 @node Types
6747 @section Types
6748 @cindex Types
6749 @cindex C types
6750
6751 The following macros check for C types, either builtin or typedefs. If
6752 there is no macro specifically defined to check for a type you need, and
6753 you don't need to check for any special properties of it, then you can
6754 use a general type-check macro.
6755
6756 @menu
6757 * Particular Types:: Special handling to find certain types
6758 * Generic Types:: How to find other types
6759 @end menu
6760
6761 @node Particular Types
6762 @subsection Particular Type Checks
6763
6764 @hdrindex{sys/types.h}
6765 @hdrindex{stdlib.h}
6766 @hdrindex{stdint.h}
6767 @hdrindex{inttypes.h}
6768 These macros check for particular C types in @file{sys/types.h},
6769 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6770 exist.
6771
6772 The Gnulib @code{stdint} module is an alternate way to define many of
6773 these symbols; it is useful if you prefer your code to assume a
6774 C99-or-better environment. @xref{Gnulib}.
6775
6776 @anchor{AC_TYPE_GETGROUPS}
6777 @defmac AC_TYPE_GETGROUPS
6778 @acindex{TYPE_GETGROUPS}
6779 @cvindex GETGROUPS_T
6780 @caindex type_getgroups
6781 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6782 is the base type of the array argument to @code{getgroups}.
6783
6784 This macro caches the base type in the @code{ac_cv_type_getgroups}
6785 variable.
6786 @end defmac
6787
6788 @defmac AC_TYPE_INT8_T
6789 @acindex{TYPE_INT8_T}
6790 @cvindex HAVE_INT8_T
6791 @cvindex int8_t
6792 @caindex c_int8_t
6793 If @file{stdint.h} or @file{inttypes.h} does not define the type
6794 @code{int8_t}, define @code{int8_t} to a signed
6795 integer type that is exactly 8 bits wide and that uses two's complement
6796 representation, if such a type exists.
6797 If you are worried about porting to hosts that lack such a type, you can
6798 use the results of this macro as follows:
6799
6800 @example
6801 #if HAVE_STDINT_H
6802 # include <stdint.h>
6803 #endif
6804 #if defined INT8_MAX || defined int8_t
6805 @emph{code using int8_t}
6806 #else
6807 @emph{complicated alternative using >8-bit 'signed char'}
6808 #endif
6809 @end example
6810
6811 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6812 @end defmac
6813
6814 @defmac AC_TYPE_INT16_T
6815 @acindex{TYPE_INT16_T}
6816 @cvindex HAVE_INT16_T
6817 @cvindex int16_t
6818 @caindex c_int16_t
6819 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6820 @end defmac
6821
6822 @defmac AC_TYPE_INT32_T
6823 @acindex{TYPE_INT32_T}
6824 @cvindex HAVE_INT32_T
6825 @cvindex int32_t
6826 @caindex c_int32_t
6827 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6828 @end defmac
6829
6830 @defmac AC_TYPE_INT64_T
6831 @acindex{TYPE_INT64_T}
6832 @cvindex HAVE_INT64_T
6833 @cvindex int64_t
6834 @caindex c_int64_t
6835 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6836 @end defmac
6837
6838 @defmac AC_TYPE_INTMAX_T
6839 @acindex{TYPE_INTMAX_T}
6840 @cvindex HAVE_INTMAX_T
6841 @cvindex intmax_t
6842 @c @caindex type_intmax_t
6843 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6844 define @code{HAVE_INTMAX_T}. Otherwise, define @code{intmax_t} to the
6845 widest signed integer type.
6846 @end defmac
6847
6848 @defmac AC_TYPE_INTPTR_T
6849 @acindex{TYPE_INTPTR_T}
6850 @cvindex HAVE_INTPTR_T
6851 @cvindex intptr_t
6852 @c @caindex type_intptr_t
6853 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6854 define @code{HAVE_INTPTR_T}. Otherwise, define @code{intptr_t} to a
6855 signed integer type wide enough to hold a pointer, if such a type
6856 exists.
6857 @end defmac
6858
6859 @defmac AC_TYPE_LONG_DOUBLE
6860 @acindex{TYPE_LONG_DOUBLE}
6861 @cvindex HAVE_LONG_DOUBLE
6862 @caindex type_long_double
6863 If the C compiler supports a working @code{long double} type, define
6864 @code{HAVE_LONG_DOUBLE}. The @code{long double} type might have the
6865 same range and precision as @code{double}.
6866
6867 This macro caches its result in the @code{ac_cv_type_long_double}
6868 variable.
6869
6870 This macro is obsolescent, as current C compilers support @code{long
6871 double}. New programs need not use this macro.
6872 @end defmac
6873
6874 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6875 @acindex{TYPE_LONG_DOUBLE_WIDER}
6876 @cvindex HAVE_LONG_DOUBLE_WIDER
6877 @caindex type_long_double_wider
6878 If the C compiler supports a working @code{long double} type with more
6879 range or precision than the @code{double} type, define
6880 @code{HAVE_LONG_DOUBLE_WIDER}.
6881
6882 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6883 variable.
6884 @end defmac
6885
6886 @defmac AC_TYPE_LONG_LONG_INT
6887 @acindex{TYPE_LONG_LONG_INT}
6888 @cvindex HAVE_LONG_LONG_INT
6889 @caindex type_long_long_int
6890 If the C compiler supports a working @code{long long int} type, define
6891 @code{HAVE_LONG_LONG_INT}. However, this test does not test
6892 @code{long long int} values in preprocessor @code{#if} expressions,
6893 because too many compilers mishandle such expressions.
6894 @xref{Preprocessor Arithmetic}.
6895
6896 This macro caches its result in the @code{ac_cv_type_long_long_int}
6897 variable.
6898 @end defmac
6899
6900 @defmac AC_TYPE_MBSTATE_T
6901 @acindex{TYPE_MBSTATE_T}
6902 @cvindex mbstate_t
6903 @hdrindex{wchar.h}
6904 @caindex type_mbstate_t
6905 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6906 @code{mbstate_t} type. Also, define @code{mbstate_t} to be a type if
6907 @code{<wchar.h>} does not declare it.
6908
6909 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6910 variable.
6911 @end defmac
6912
6913 @anchor{AC_TYPE_MODE_T}
6914 @defmac AC_TYPE_MODE_T
6915 @acindex{TYPE_MODE_T}
6916 @cvindex mode_t
6917 @caindex type_mode_t
6918 Define @code{mode_t} to a suitable type, if standard headers do not
6919 define it.
6920
6921 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6922 @end defmac
6923
6924 @anchor{AC_TYPE_OFF_T}
6925 @defmac AC_TYPE_OFF_T
6926 @acindex{TYPE_OFF_T}
6927 @cvindex off_t
6928 @caindex type_off_t
6929 Define @code{off_t} to a suitable type, if standard headers do not
6930 define it.
6931
6932 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6933 @end defmac
6934
6935 @anchor{AC_TYPE_PID_T}
6936 @defmac AC_TYPE_PID_T
6937 @acindex{TYPE_PID_T}
6938 @cvindex pid_t
6939 @caindex type_pid_t
6940 Define @code{pid_t} to a suitable type, if standard headers do not
6941 define it.
6942
6943 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6944 @end defmac
6945
6946 @anchor{AC_TYPE_SIZE_T}
6947 @defmac AC_TYPE_SIZE_T
6948 @acindex{TYPE_SIZE_T}
6949 @cvindex size_t
6950 @caindex type_size_t
6951 Define @code{size_t} to a suitable type, if standard headers do not
6952 define it.
6953
6954 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6955 @end defmac
6956
6957 @defmac AC_TYPE_SSIZE_T
6958 @acindex{TYPE_SSIZE_T}
6959 @cvindex ssize_t
6960 @caindex type_ssize_t
6961 Define @code{ssize_t} to a suitable type, if standard headers do not
6962 define it.
6963
6964 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6965 @end defmac
6966
6967 @anchor{AC_TYPE_UID_T}
6968 @defmac AC_TYPE_UID_T
6969 @acindex{TYPE_UID_T}
6970 @cvindex uid_t
6971 @cvindex gid_t
6972 @caindex type_uid_t
6973 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6974 headers do not define them.
6975
6976 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6977 @end defmac
6978
6979 @defmac AC_TYPE_UINT8_T
6980 @acindex{TYPE_UINT8_T}
6981 @cvindex HAVE_UINT8_T
6982 @cvindex uint8_t
6983 @caindex c_uint8_t
6984 If @file{stdint.h} or @file{inttypes.h} does not define the type
6985 @code{uint8_t}, define @code{uint8_t} to an
6986 unsigned integer type that is exactly 8 bits wide, if such a type
6987 exists.
6988 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6989 @end defmac
6990
6991 @defmac AC_TYPE_UINT16_T
6992 @acindex{TYPE_UINT16_T}
6993 @cvindex HAVE_UINT16_T
6994 @cvindex uint16_t
6995 @caindex c_uint16_t
6996 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6997 @end defmac
6998
6999 @defmac AC_TYPE_UINT32_T
7000 @acindex{TYPE_UINT32_T}
7001 @cvindex HAVE_UINT32_T
7002 @cvindex uint32_t
7003 @caindex c_uint32_t
7004 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
7005 @end defmac
7006
7007 @defmac AC_TYPE_UINT64_T
7008 @acindex{TYPE_UINT64_T}
7009 @cvindex HAVE_UINT64_T
7010 @cvindex uint64_t
7011 @caindex c_uint64_t
7012 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
7013 @end defmac
7014
7015 @defmac AC_TYPE_UINTMAX_T
7016 @acindex{TYPE_UINTMAX_T}
7017 @cvindex HAVE_UINTMAX_T
7018 @cvindex uintmax_t
7019 @c @caindex type_uintmax_t
7020 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
7021 define @code{HAVE_UINTMAX_T}. Otherwise, define @code{uintmax_t} to the
7022 widest unsigned integer type.
7023 @end defmac
7024
7025 @defmac AC_TYPE_UINTPTR_T
7026 @acindex{TYPE_UINTPTR_T}
7027 @cvindex HAVE_UINTPTR_T
7028 @cvindex uintptr_t
7029 @c @caindex type_uintptr_t
7030 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
7031 define @code{HAVE_UINTPTR_T}. Otherwise, define @code{uintptr_t} to an
7032 unsigned integer type wide enough to hold a pointer, if such a type
7033 exists.
7034 @end defmac
7035
7036 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
7037 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
7038 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
7039 @caindex type_unsigned_long_long_int
7040 If the C compiler supports a working @code{unsigned long long int} type,
7041 define @code{HAVE_UNSIGNED_LONG_LONG_INT}. However, this test does not test
7042 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
7043 because too many compilers mishandle such expressions.
7044 @xref{Preprocessor Arithmetic}.
7045
7046 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
7047 variable.
7048 @end defmac
7049
7050 @node Generic Types
7051 @subsection Generic Type Checks
7052
7053 These macros are used to check for types not covered by the ``particular''
7054 test macros.
7055
7056 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
7057 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
7058 @acindex{CHECK_TYPE}
7059 @caindex type_@var{type}
7060 Check whether @var{type} is defined. It may be a compiler builtin type
7061 or defined by the @var{includes}. @var{includes} is a series of include
7062 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
7063 Includes}), which are used prior to the type under test.
7064
7065 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
7066 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not). The
7067 same test is applied when compiling for C++, which means that in C++
7068 @var{type} should be a type-id and should not be an anonymous
7069 @samp{struct} or @samp{union}.
7070
7071 This macro caches its result in the @code{ac_cv_type_@var{type}}
7072 variable, with @samp{*} mapped to @samp{p} and other characters not
7073 suitable for a variable name mapped to underscores.
7074 @end defmac
7075
7076
7077 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
7078 @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
7079 @acindex{CHECK_TYPES}
7080 @cvindex HAVE_@var{type}
7081 For each @var{type} of the @var{types} that is defined, define
7082 @code{HAVE_@var{type}} (in all capitals). Each @var{type} must follow
7083 the rules of @code{AC_CHECK_TYPE}. If no @var{includes} are
7084 specified, the default includes are used (@pxref{Default Includes}). If
7085 @var{action-if-found} is given, it is additional shell code to execute
7086 when one of the types is found. If @var{action-if-not-found} is given,
7087 it is executed when one of the types is not found.
7088
7089 This macro uses M4 lists:
7090 @example
7091 AC_CHECK_TYPES([ptrdiff_t])
7092 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
7093 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
7094 @end example
7095
7096 @end defmac
7097
7098 Autoconf, up to 2.13, used to provide to another version of
7099 @code{AC_CHECK_TYPE}, broken by design. In order to keep backward
7100 compatibility, a simple heuristic, quite safe but not totally, is
7101 implemented. In case of doubt, read the documentation of the former
7102 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
7103
7104
7105 @node Compilers and Preprocessors
7106 @section Compilers and Preprocessors
7107 @cindex Compilers
7108 @cindex Preprocessors
7109
7110 @ovindex EXEEXT
7111 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
7112 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
7113 the output of the compiler, typically to the empty string if
7114 POSIX and @samp{.exe} if a DOS variant.
7115
7116 @ovindex OBJEXT
7117 They also define the output variable @code{OBJEXT} based on the
7118 output of the compiler, after @file{.c} files have been excluded, typically
7119 to @samp{o} if POSIX, @samp{obj} if a DOS variant.
7120
7121 If the compiler being used does not produce executables, the tests fail. If
7122 the executables can't be run, and cross-compilation is not enabled, they
7123 fail too. @xref{Manual Configuration}, for more on support for cross
7124 compiling.
7125
7126 @menu
7127 * Specific Compiler Characteristics:: Some portability issues
7128 * Generic Compiler Characteristics:: Language independent tests and features
7129 * C Compiler:: Checking its characteristics
7130 * C++ Compiler:: Likewise
7131 * Objective C Compiler:: Likewise
7132 * Objective C++ Compiler:: Likewise
7133 * Erlang Compiler and Interpreter:: Likewise
7134 * Fortran Compiler:: Likewise
7135 * Go Compiler:: Likewise
7136 * Algol 68 Compiler:: Likewise
7137 @end menu
7138
7139 @node Specific Compiler Characteristics
7140 @subsection Specific Compiler Characteristics
7141
7142 Some compilers exhibit different behaviors.
7143
7144 @table @asis
7145 @item Static/Dynamic Expressions
7146 Autoconf relies on a trick to extract one bit of information from the C
7147 compiler: using negative array sizes. For instance the following
7148 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
7149 bytes wide:
7150
7151 @example
7152 static int test_array[sizeof (int) == 4 ? 1 : -1];
7153 @end example
7154
7155 @noindent
7156 To our knowledge, there is a single compiler that does not support this
7157 trick: the HP C compilers (the real ones, not only the
7158 ``bundled'') on HP-UX 11.00.
7159 They incorrectly reject the above program with the diagnostic
7160 ``Variable-length arrays cannot have static storage.''
7161 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
7162 not from the @code{? 1 : -1}, and
7163 Autoconf works around this problem by casting @code{sizeof (int)} to
7164 @code{long int} before comparing it.
7165 @end table
7166
7167 @node Generic Compiler Characteristics
7168 @subsection Generic Compiler Characteristics
7169
7170 @anchor{AC_CHECK_SIZEOF}
7171 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7172 @dvar{includes, AC_INCLUDES_DEFAULT})
7173 @acindex{CHECK_SIZEOF}
7174 @cvindex SIZEOF_@var{type-or-expr}
7175 @caindex sizeof_@var{type-or-expr}
7176 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7177 the size in bytes of @var{type-or-expr}, which may be either a type or
7178 an expression returning a value that has a size. If the expression
7179 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7180 @var{includes} is a series of include directives, defaulting to
7181 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7182 prior to the expression under test.
7183
7184 This macro now works even when cross-compiling. The @var{unused}
7185 argument was used when cross-compiling.
7186
7187 For example, the call
7188
7189 @example
7190 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7191 AC_CHECK_SIZEOF([int *])
7192 @end example
7193
7194 @noindent
7195 defines @code{SIZEOF_INT_P} to be 8 on x86-64 systems.
7196
7197 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7198 variable, with @samp{*} mapped to @samp{p} and other characters not
7199 suitable for a variable name mapped to underscores.
7200 @end defmac
7201
7202 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7203 @acindex{CHECK_ALIGNOF}
7204 @cvindex ALIGNOF_@var{type}
7205 @caindex alignof_@var{type-or-expr}
7206 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7207 alignment in bytes of @var{type}. @samp{@var{type} y;} must be valid as
7208 a structure member declaration. If @samp{type} is unknown, the result
7209 is 0. If no @var{includes} are specified, the default includes are used
7210 (@pxref{Default Includes}).
7211
7212 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7213 variable, with @samp{*} mapped to @samp{p} and other characters not
7214 suitable for a variable name mapped to underscores.
7215 @end defmac
7216
7217 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7218 @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7219 @acindex{COMPUTE_INT}
7220 Store into the shell variable @var{var} the value of the integer
7221 @var{expression}. The
7222 value should fit in an initializer in a C variable of type @code{signed
7223 long}. To support cross compilation, it should be possible to evaluate
7224 the expression at compile-time. If no @var{includes} are specified, the
7225 default includes are used (@pxref{Default Includes}).
7226
7227 Execute @var{action-if-fails} if the value cannot be determined correctly.
7228 @end defmac
7229
7230 @defmac AC_LANG_WERROR
7231 @acindex{LANG_WERROR}
7232 Normally Autoconf ignores warnings generated by the compiler, linker, and
7233 preprocessor. If this macro is used, warnings count as fatal
7234 errors for the current language. This macro is useful when the
7235 results of configuration are used where warnings are unacceptable; for
7236 instance, if parts of a program are built with the GCC
7237 @option{-Werror}
7238 option. If the whole program is built using @option{-Werror} it is
7239 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7240 etc.).
7241 @end defmac
7242
7243 @defmac AC_OPENMP
7244 @acindex{OPENMP}
7245 @cvindex _OPENMP
7246 @ovindex OPENMP_CFLAGS
7247 @ovindex OPENMP_CXXFLAGS
7248 @ovindex OPENMP_FFLAGS
7249 @ovindex OPENMP_FCFLAGS
7250 @caindex prog_c_openmp
7251 @caindex prog_cxx_openmp
7252 @caindex prog_f77_openmp
7253 @caindex prog_fc_openmp
7254 @uref{https://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7255 and Fortran that simplify optimization of shared memory parallelism,
7256 which is a common problem on multi-core CPUs.
7257
7258 If the current language is C, the macro @code{AC_OPENMP} sets the
7259 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7260 supporting OpenMP@. @code{OPENMP_CFLAGS} is set to empty if the
7261 compiler already supports OpenMP, if it has no way to activate OpenMP
7262 support, or if the user rejects OpenMP support by invoking
7263 @samp{configure} with the @samp{--disable-openmp} option.
7264
7265 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7266 preprocessing program source, and when linking programs. Therefore you
7267 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7268 that use OpenMP@. If you preprocess OpenMP-specific C code, you also
7269 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}. The presence of
7270 OpenMP support is revealed at compile time by the preprocessor macro
7271 @code{_OPENMP}.
7272
7273 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7274 shared library to the program's dependencies, so its use is recommended
7275 only on programs that actually require OpenMP.
7276
7277 If the current language is C++, @code{AC_OPENMP} sets the variable
7278 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler. The same remarks
7279 hold as for C.
7280
7281 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7282 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7283 respectively. Similar remarks as for C hold, except that
7284 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7285 signals OpenMP support.
7286
7287 For portability, it is best to avoid spaces between @samp{#} and
7288 @samp{pragma omp}. That is, write @samp{#pragma omp}, not
7289 @samp{# pragma omp}. The Sun WorkShop 6.2 C compiler chokes on the
7290 latter.
7291
7292 This macro caches its result in the @code{ac_cv_prog_c_openmp},
7293 @code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7294 @code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7295
7296 @strong{Caution:} Some of the compiler options that @code{AC_OPENMP}
7297 tests, mean ``enable OpenMP'' to one compiler, but ``write output to a
7298 file named @file{mp} or @file{penmp}'' to other compilers. We cannot
7299 guarantee that the implementation of @code{AC_OPENMP} will not overwrite
7300 an existing file with either of these names.
7301
7302 Therefore, as a defensive measure, a @command{configure} script that
7303 uses @code{AC_OPENMP} will issue an error and stop (before doing any of
7304 the operations that might overwrite these files) upon encountering
7305 either of these files in its working directory.
7306 @command{autoconf} will also issue an error if it finds either of
7307 these files in the same directory as a @file{configure.ac} that
7308 uses @code{AC_OPENMP}.
7309
7310 If you have files with either of these names at the top level of your
7311 source tree, and you need to use @code{AC_OPENMP}, we recommend you
7312 either change their names or move them into a subdirectory.
7313 @end defmac
7314
7315 @node C Compiler
7316 @subsection C Compiler Characteristics
7317
7318 The following macros provide ways to find and exercise a C Compiler.
7319 There are a few constructs that ought to be avoided, but do not deserve
7320 being checked for, since they can easily be worked around.
7321
7322 @table @asis
7323 @item Don't use lines containing solitary backslashes
7324 They tickle a bug in the HP-UX C compiler (checked on
7325 HP-UX 10.20,
7326 11.00, and 11i). When given the following source:
7327
7328 @example
7329 #ifdef __STDC__
7330 /\
7331 * A comment with backslash-newlines in it. %@{ %@} *\
7332 \
7333 /
7334 char str[] = "\\
7335 " A string with backslash-newlines in it %@{ %@} \\
7336 "";
7337 char apostrophe = '\\
7338 \
7339 '\
7340 ';
7341 #endif
7342 @end example
7343
7344 @noindent
7345 the compiler incorrectly fails with the diagnostics ``Non-terminating
7346 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7347 Removing the lines with solitary backslashes solves the problem.
7348
7349 @item Don't compile several files at once if output matters to you
7350 Some compilers, such as HP's, report names of files being
7351 compiled when given more than one file operand. For instance:
7352
7353 @example
7354 $ @kbd{cc a.c b.c}
7355 a.c:
7356 b.c:
7357 @end example
7358
7359 @noindent
7360 This can cause problems if you observe the output of the compiler to
7361 detect failures. Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7362 b.o} solves the issue.
7363
7364 @item Don't rely on correct @code{#line} support
7365 On Solaris, @command{c89} (at least through Oracle Developer Studio 12.6)
7366 diagnoses @code{#line} directives whose line
7367 numbers are greater than 32767. Nothing in POSIX
7368 makes this invalid. That is why Autoconf stopped issuing
7369 @code{#line} directives.
7370 @end table
7371
7372 @anchor{AC_PROG_CC}
7373 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7374 @acindex{PROG_CC}
7375 @evindex CC
7376 @evindex CFLAGS
7377 @ovindex CC
7378 @ovindex CFLAGS
7379 Determine a C compiler to use.
7380
7381 If the environment variable @code{CC} is set, its value will be taken as
7382 the name of the C compiler to use. Otherwise, search for a C compiler
7383 under a series of likely names, trying @code{gcc} and @code{cc} first.
7384 Regardless, the output variable @code{CC} is set to the chosen compiler.
7385
7386 If the optional first argument to the macro is used, it must be a
7387 whitespace-separated list of potential names for a C compiler,
7388 which overrides the built-in list.
7389
7390 If no C compiler can be found, @command{configure} will error out.
7391
7392 If the selected C compiler is found to be GNU C (regardless of
7393 its name), the shell variable @code{GCC} will be set to @samp{yes}.
7394 If the shell variable @code{CFLAGS} was not already set, it is set
7395 to @option{-g -O2} for the GNU C compiler (@option{-O2} on systems
7396 where GCC does not accept @option{-g}), or @option{-g} for other
7397 compilers. @code{CFLAGS} is then made an output variable.
7398 You can override the default for @code{CFLAGS} by inserting a shell
7399 default assignment between @code{AC_INIT} and @code{AC_PROG_CC}:
7400
7401 @example
7402 : $@{CFLAGS="@var{options}"@}
7403 @end example
7404
7405 where @var{options} are the appropriate set of options to use by
7406 default. (It is important to use this construct rather than a normal
7407 assignment, so that @code{CFLAGS} can still be overridden by the
7408 person building the package. @xref{Preset Output Variables}.)
7409
7410 If necessary, options are added to @code{CC} to enable support for
7411 ISO Standard C features with extensions, preferring the newest edition
7412 of the C standard for which detection is supported. Currently the
7413 newest edition Autoconf knows how to detect support for is C23. After calling
7414 this macro you can check whether the C compiler has been set to accept
7415 standard C by inspecting the shell variable @code{ac_prog_cc_stdc}.
7416 Its value is @samp{c23}, @samp{c11}, @samp{c99}, or @samp{c89}, respectively,
7417 if the C compiler has been set to use the 2023, 2011, 1999, or 1990 edition of
7418 the C standard, and @samp{no} if the compiler does not support compiling
7419 standard C at all.
7420 (There is no special value for the 2017 edition of the C standard,
7421 as it is a minor revision that does not introduce new language features.)
7422
7423 The tests for standard conformance are not comprehensive. They test the
7424 value of @code{__STDC_VERSION__}, and a
7425 representative sample of the language features added in each version of
7426 the C standard. They do not examine @code{__STDC__}
7427 because some compilers by default leave it undefined.
7428 They do not test for variable-length arrays,
7429 a C99 feature that was made optional in C11;
7430 if you need to use this feature when available, use @code{AC_C_VARARRAYS}.
7431 They do not test the C standard library, because the C
7432 compiler might be generating code for a ``freestanding environment''
7433 (in which most of the standard library is optional). If you need to know
7434 whether a particular C standard header exists, use @code{AC_CHECK_HEADER}.
7435
7436 None of the options that may be added to @code{CC} by this macro
7437 enable @emph{strict} conformance to the C standard. In particular,
7438 system-specific extensions are not disabled. (For example, for GNU C,
7439 the @option{-std=gnu@var{nn}} options may be used, but not the
7440 @option{-std=c@var{nn}} options.)
7441
7442 Many Autoconf macros use a compiler, and thus call
7443 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7444 determined before the body of the outermost @code{AC_DEFUN} macro.
7445 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7446 performs certain checks (such as the proper value of @env{EXEEXT}) only
7447 on the first invocation. Therefore, care must be used when invoking
7448 this macro from within another macro rather than at the top level
7449 (@pxref{Expanded Before Required}).
7450 @end defmac
7451
7452 @anchor{AC_PROG_CC_C_O}
7453 @defmac AC_PROG_CC_C_O
7454 @acindex{PROG_CC_C_O}
7455 @cvindex NO_MINUS_C_MINUS_O
7456 @caindex prog_cc_@var{compiler}_c_o
7457 If the C compiler does not accept the @option{-c} and @option{-o} options
7458 simultaneously, define @code{NO_MINUS_C_MINUS_O}. This macro actually
7459 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7460 the first @code{cc} in the path. The test fails if one fails. This
7461 macro was created for GNU Make to choose the default C compilation
7462 rule.
7463
7464 For the compiler @var{compiler}, this macro caches its result in the
7465 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7466 @end defmac
7467
7468
7469 @defmac AC_PROG_CPP
7470 @acindex{PROG_CPP}
7471 @evindex CPP
7472 @ovindex CPP
7473 Set output variable @code{CPP} to a command that runs the
7474 C preprocessor. If @samp{$CC -E} doesn't work, tries @code{cpp} and
7475 @file{/lib/cpp}, in that order.
7476
7477 It is only portable to run @code{CPP} on files with a @file{.c}
7478 extension.
7479
7480 Some preprocessors don't indicate missing include files by the error
7481 status. For such preprocessors an internal variable is set that causes
7482 other macros to check the standard error from the preprocessor and
7483 consider the test failed if any warnings have been reported.
7484 For most preprocessors, though, warnings do not cause include-file
7485 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7486 @end defmac
7487
7488 @defmac AC_PROG_CPP_WERROR
7489 @acindex{PROG_CPP_WERROR}
7490 @ovindex CPP
7491 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7492 preprocessor as errors even if the preprocessor exit status indicates
7493 success. This is useful for avoiding headers that generate mandatory
7494 warnings, such as deprecation notices.
7495 @end defmac
7496
7497
7498 The following macros check for C compiler or machine architecture
7499 features. To check for characteristics not listed here, use
7500 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7501 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7502
7503 @defmac AC_C_BACKSLASH_A
7504 @acindex{C_BACKSLASH_A}
7505 @cvindex HAVE_C_BACKSLASH_A
7506 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7507 @samp{\a}.
7508
7509 This macro is obsolescent, as current C compilers understand @samp{\a}.
7510 New programs need not use this macro.
7511 @end defmac
7512
7513 @anchor{AC_C_BIGENDIAN}
7514 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7515 @ovar{action-if-unknown}, @ovar{action-if-universal})
7516 @acindex{C_BIGENDIAN}
7517 @cvindex WORDS_BIGENDIAN
7518 @cindex Endianness
7519 If words are stored with the most significant byte first (like Motorola
7520 and SPARC CPUs), execute @var{action-if-true}. If words are stored with
7521 the least significant byte first (like Intel and VAX CPUs), execute
7522 @var{action-if-false}.
7523
7524 This macro runs a test-case if endianness cannot be determined from the
7525 system header files. When cross-compiling, the test-case is not run but
7526 grep'ed for some magic values. @var{action-if-unknown} is executed if
7527 the latter case fails to determine the byte sex of the host system.
7528
7529 In some cases a single run of a compiler can generate code for multiple
7530 architectures. This can happen, for example, when generating Mac OS X
7531 universal binary files, which work on both PowerPC and Intel
7532 architectures. In this case, the different variants might be for
7533 architectures with differing endianness. If
7534 @command{configure} detects this, it executes @var{action-if-universal}
7535 instead of @var{action-if-unknown}.
7536
7537 The default for @var{action-if-true} is to define
7538 @samp{WORDS_BIGENDIAN}. The default for @var{action-if-false} is to do
7539 nothing. The default for @var{action-if-unknown} is to
7540 abort configure and tell the installer how to bypass this test.
7541 And finally, the default for @var{action-if-universal} is to ensure that
7542 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7543 detected and the current code is big-endian; this default works only if
7544 @command{autoheader} is used (@pxref{autoheader Invocation}).
7545
7546 If you use this macro without specifying @var{action-if-universal}, you
7547 should also use @code{AC_CONFIG_HEADERS}; otherwise
7548 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7549 binary files.
7550 @end defmac
7551
7552 @anchor{AC_C_CONST}
7553 @defmac AC_C_CONST
7554 @acindex{C_CONST}
7555 @cvindex const
7556 @caindex c_const
7557 If the C compiler does not fully support the @code{const} keyword,
7558 define @code{const} to be empty. Some C compilers that do
7559 not define @code{__STDC__} do support @code{const}; some compilers that
7560 define @code{__STDC__} do not completely support @code{const}. Programs
7561 can simply use @code{const} as if every C compiler supported it; for
7562 those that don't, the makefile or configuration header file
7563 defines it as empty.
7564
7565 Occasionally installers use a C++ compiler to compile C code, typically
7566 because they lack a C compiler. This causes problems with @code{const},
7567 because C and C++ treat @code{const} differently. For example:
7568
7569 @example
7570 const int foo;
7571 @end example
7572
7573 @noindent
7574 is valid in C but not in C++. These differences unfortunately cannot be
7575 papered over by defining @code{const} to be empty.
7576
7577 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7578 as this generally yields better results in practice. However, using a
7579 C++ compiler to compile C code is not recommended or supported, and
7580 installers who run into trouble in this area should get a C compiler
7581 like GCC to compile their C code.
7582
7583 This macro caches its result in the @code{ac_cv_c_const} variable.
7584
7585 This macro is obsolescent, as current C compilers support @code{const}.
7586 New programs need not use this macro.
7587 @end defmac
7588
7589 @defmac AC_C__GENERIC
7590 @acindex{C__GENERIC}
7591 @cvindex _Generic
7592 If the C compiler supports C11-style generic selection using the
7593 @code{_Generic} keyword, define @code{HAVE_C__GENERIC}.
7594 @end defmac
7595
7596 @defmac AC_C_RESTRICT
7597 @acindex{C_RESTRICT}
7598 @cvindex restrict
7599 @caindex c_restrict
7600 If the C compiler recognizes a variant spelling for the @code{restrict}
7601 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7602 then define @code{restrict} to that; this is more likely to do the right
7603 thing with compilers that support language variants where plain
7604 @code{restrict} is not a keyword. Otherwise, if the C compiler
7605 recognizes the @code{restrict} keyword, don't do anything.
7606 Otherwise, define @code{restrict} to be empty.
7607 Thus, programs may simply use @code{restrict} as if every C compiler
7608 supported it; for those that do not, the makefile
7609 or configuration header defines it away.
7610
7611 Although support in C++ for the @code{restrict} keyword is not
7612 required, several C++ compilers do accept the keyword.
7613 This macro works for them, too.
7614
7615 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7616 if @code{restrict} is not supported, and a supported spelling otherwise.
7617 @end defmac
7618
7619 @defmac AC_C_VOLATILE
7620 @acindex{C_VOLATILE}
7621 @cvindex volatile
7622 If the C compiler does not understand the keyword @code{volatile},
7623 define @code{volatile} to be empty. Programs can simply use
7624 @code{volatile} as if every C compiler supported it; for those that do
7625 not, the makefile or configuration header defines it as
7626 empty.
7627
7628 If the correctness of your program depends on the semantics of
7629 @code{volatile}, simply defining it to be empty does, in a sense, break
7630 your code. However, given that the compiler does not support
7631 @code{volatile}, you are at its mercy anyway. At least your
7632 program compiles, when it wouldn't before.
7633 @xref{Volatile Objects}, for more about @code{volatile}.
7634
7635 This macro is obsolescent, as current C compilers support @code{volatile}.
7636 New programs need not use this macro.
7637 @end defmac
7638
7639 @anchor{AC_C_INLINE}
7640 @defmac AC_C_INLINE
7641 @acindex{C_INLINE}
7642 @cvindex inline
7643 If the C compiler supports the keyword @code{inline}, do nothing.
7644 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7645 if it accepts one of those, otherwise define @code{inline} to be empty.
7646 @end defmac
7647
7648 @anchor{AC_C_CHAR_UNSIGNED}
7649 @defmac AC_C_CHAR_UNSIGNED
7650 @acindex{C_CHAR_UNSIGNED}
7651 @cvindex __CHAR_UNSIGNED__
7652 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7653 unless the C compiler predefines it.
7654
7655 These days, using this macro is not necessary. The same information can
7656 be determined by this portable alternative, thus avoiding the use of
7657 preprocessor macros in the namespace reserved for the implementation.
7658
7659 @example
7660 #include <limits.h>
7661 #if CHAR_MIN == 0
7662 # define CHAR_UNSIGNED 1
7663 #endif
7664 @end example
7665 @end defmac
7666
7667 @defmac AC_C_STRINGIZE
7668 @acindex{C_STRINGIZE}
7669 @cvindex HAVE_STRINGIZE
7670 If the C preprocessor supports the stringizing operator, define
7671 @code{HAVE_STRINGIZE}. The stringizing operator is @samp{#} and is
7672 found in macros such as this:
7673
7674 @example
7675 #define x(y) #y
7676 @end example
7677
7678 This macro is obsolescent, as current C compilers support the
7679 stringizing operator. New programs need not use this macro.
7680 @end defmac
7681
7682 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7683 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7684 @cvindex FLEXIBLE_ARRAY_MEMBER
7685 If the C compiler supports flexible array members, define
7686 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7687 That way, a declaration like this:
7688
7689 @example
7690 struct s
7691 @{
7692 size_t n_vals;
7693 double val[FLEXIBLE_ARRAY_MEMBER];
7694 @};
7695 @end example
7696
7697 @noindent
7698 will let applications use the ``struct hack'' even with compilers that
7699 do not support flexible array members. To allocate and use such an
7700 object, you can use code like this:
7701
7702 @example
7703 size_t i;
7704 size_t n = compute_value_count ();
7705 struct s *p =
7706 malloc (offsetof (struct s, val)
7707 + n * sizeof (double));
7708 p->n_vals = n;
7709 for (i = 0; i < n; i++)
7710 p->val[i] = compute_value (i);
7711 @end example
7712 @end defmac
7713
7714 @defmac AC_C_VARARRAYS
7715 @acindex{C_VARARRAYS}
7716 @cvindex __STDC_NO_VLA__
7717 @cvindex HAVE_C_VARARRAYS
7718 If the C compiler does not support variable-length arrays, define the
7719 macro @code{__STDC_NO_VLA__} to be 1 if it is not already defined. A
7720 variable-length array is an array of automatic storage duration whose
7721 length is determined at run time, when the array is declared. For
7722 backward compatibility this macro also defines @code{HAVE_C_VARARRAYS}
7723 if the C compiler supports variable-length arrays, but this usage is
7724 obsolescent and new programs should use @code{__STDC_NO_VLA__}.
7725 @end defmac
7726
7727 @defmac AC_C_TYPEOF
7728 @acindex{C_TYPEOF}
7729 @cvindex HAVE_TYPEOF
7730 @cvindex typeof
7731 If the C compiler supports GNU C's @code{typeof} syntax either
7732 directly or
7733 through a different spelling of the keyword (e.g., @code{__typeof__}),
7734 define @code{HAVE_TYPEOF}. If the support is available only through a
7735 different spelling, define @code{typeof} to that spelling.
7736 @end defmac
7737
7738 @defmac AC_C_PROTOTYPES
7739 @acindex{C_PROTOTYPES}
7740 @cvindex PROTOTYPES
7741 @cvindex __PROTOTYPES
7742 @cvindex PARAMS
7743 If function prototypes are understood by the compiler (as determined by
7744 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7745 Defining @code{__PROTOTYPES} is for the benefit of
7746 header files that cannot use macros that infringe on user name space.
7747
7748 This macro is obsolescent, as current C compilers support prototypes.
7749 New programs need not use this macro.
7750 @end defmac
7751
7752 @node C++ Compiler
7753 @subsection C++ Compiler Characteristics
7754
7755
7756 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7757 @acindex{PROG_CXX}
7758 @evindex CXX
7759 @evindex CXXFLAGS
7760 @ovindex CXX
7761 @ovindex CXXFLAGS
7762 Determine a C++ compiler to use.
7763
7764 If either the environment variable @code{CXX} or the environment
7765 variable @code{CCC} is set, its value will be taken as the name of a
7766 C++ compiler. If both are set, @code{CXX} is preferred. If neither
7767 are set, search for a C++ compiler under a series of likely names,
7768 trying @code{g++} and @code{c++} first. Regardless, the output
7769 variable @code{CXX} is set to the chosen compiler.
7770
7771 If the optional first argument to the macro is used, it must be a
7772 whitespace-separated list of potential names for a C++ compiler,
7773 which overrides the built-in list.
7774
7775 If no C++ compiler can be found, as a last resort @code{CXX} is set to
7776 @code{g++} (and subsequent tests will probably fail).
7777
7778 If the selected C++ compiler is found to be GNU C++ (regardless of
7779 its name), the shell variable @code{GXX} will be set to @samp{yes}.
7780 If the shell variable @code{CXXFLAGS} was not already set, it is set
7781 to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on systems
7782 where G++ does not accept @option{-g}), or @option{-g} for other
7783 compilers. @code{CXXFLAGS} is then made an output variable.
7784 You can override the default for @code{CXXFLAGS} by inserting a shell
7785 default assignment between @code{AC_INIT} and @code{AC_PROG_CXX}:
7786
7787 @example
7788 : $@{CXXFLAGS="@var{options}"@}
7789 @end example
7790
7791 where @var{options} are the appropriate set of options to use by
7792 default. (It is important to use this construct rather than a normal
7793 assignment, so that @code{CXXFLAGS} can still be overridden by the
7794 person building the package. @xref{Preset Output Variables}.)
7795 @end defmac
7796
7797 @defmac AC_PROG_CXXCPP
7798 @acindex{PROG_CXXCPP}
7799 @evindex CXXCPP
7800 @ovindex CXXCPP
7801 Set output variable @code{CXXCPP} to a command that runs the C++
7802 preprocessor. If @samp{$CXX -E} doesn't work, tries @code{cpp} and
7803 @file{/lib/cpp}, in that order. Because of this fallback, @code{CXXCPP}
7804 may or may not set C++-specific predefined macros (such as @code{__cplusplus}).
7805
7806 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7807 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7808
7809 Some preprocessors don't indicate missing include files by the error
7810 status. For such preprocessors an internal variable is set that causes
7811 other macros to check the standard error from the preprocessor and
7812 consider the test failed if any warnings have been reported. However,
7813 it is not known whether such broken preprocessors exist for C++.
7814 @end defmac
7815
7816 @defmac AC_PROG_CXX_C_O
7817 @acindex{PROG_CXX_C_O}
7818 @cvindex CXX_NO_MINUS_C_MINUS_O
7819 Test whether the C++ compiler accepts the options @option{-c} and
7820 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7821 if it does not.
7822 @end defmac
7823
7824
7825 @node Objective C Compiler
7826 @subsection Objective C Compiler Characteristics
7827
7828
7829 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7830 @acindex{PROG_OBJC}
7831 @evindex OBJC
7832 @evindex OBJCFLAGS
7833 @ovindex OBJC
7834 @ovindex OBJCFLAGS
7835 Determine an Objective C compiler to use. If @code{OBJC} is not already
7836 set in the environment, check for Objective C compilers. Set output
7837 variable @code{OBJC} to the name of the compiler found.
7838
7839 This macro may, however, be invoked with an optional first argument
7840 which, if specified, must be a blank-separated list of Objective C compilers to
7841 search for. This just gives the user an opportunity to specify an
7842 alternative search list for the Objective C compiler. For example, if you
7843 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7844 like this:
7845
7846 @example
7847 AC_PROG_OBJC([gcc objcc objc])
7848 @end example
7849
7850 If using a compiler that supports GNU Objective C, set shell variable
7851 @code{GOBJC} to @samp{yes}. If output variable @code{OBJCFLAGS} was not
7852 already set, set it to @option{-g -O2} for a GNU Objective C
7853 compiler (@option{-O2} on systems where the compiler does not accept
7854 @option{-g}), or @option{-g} for other compilers.
7855 @end defmac
7856
7857 @defmac AC_PROG_OBJCPP
7858 @acindex{PROG_OBJCPP}
7859 @evindex OBJCPP
7860 @ovindex OBJCPP
7861 Set output variable @code{OBJCPP} to a command that runs the Objective C
7862 preprocessor. If @samp{$OBJC -E} doesn't work, tries @code{cpp} and
7863 @file{/lib/cpp}, in that order. Because of this fallback, @code{CXXCPP}
7864 may or may not set Objective-C-specific predefined macros (such as
7865 @code{__OBJC__}).
7866 @end defmac
7867
7868
7869 @node Objective C++ Compiler
7870 @subsection Objective C++ Compiler Characteristics
7871
7872
7873 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7874 @acindex{PROG_OBJCXX}
7875 @evindex OBJCXX
7876 @evindex OBJCXXFLAGS
7877 @ovindex OBJCXX
7878 @ovindex OBJCXXFLAGS
7879 Determine an Objective C++ compiler to use. If @code{OBJCXX} is not already
7880 set in the environment, check for Objective C++ compilers. Set output
7881 variable @code{OBJCXX} to the name of the compiler found.
7882
7883 This macro may, however, be invoked with an optional first argument
7884 which, if specified, must be a blank-separated list of Objective C++ compilers
7885 to search for. This just gives the user an opportunity to specify an
7886 alternative search list for the Objective C++ compiler. For example, if you
7887 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7888 like this:
7889
7890 @example
7891 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7892 @end example
7893
7894 If using a compiler that supports GNU Objective C++, set shell variable
7895 @code{GOBJCXX} to @samp{yes}. If output variable @code{OBJCXXFLAGS} was not
7896 already set, set it to @option{-g -O2} for a GNU Objective C++
7897 compiler (@option{-O2} on systems where the compiler does not accept
7898 @option{-g}), or @option{-g} for other compilers.
7899 @end defmac
7900
7901 @defmac AC_PROG_OBJCXXCPP
7902 @acindex{PROG_OBJCXXCPP}
7903 @evindex OBJCXXCPP
7904 @ovindex OBJCXXCPP
7905 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7906 preprocessor. If @samp{$OBJCXX -E} doesn't work, tries @code{cpp} and
7907 @file{/lib/cpp}, in that order. Because of this fallback, @code{CXXCPP}
7908 may or may not set Objective-C++-specific predefined macros (such as
7909 @code{__cplusplus} and @code{__OBJC__}).
7910 @end defmac
7911
7912
7913 @node Erlang Compiler and Interpreter
7914 @subsection Erlang Compiler and Interpreter Characteristics
7915 @cindex Erlang
7916
7917 Autoconf defines the following macros for determining paths to the essential
7918 Erlang/OTP programs:
7919
7920 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7921 @acindex{ERLANG_PATH_ERLC}
7922 @evindex ERLC
7923 @evindex ERLCFLAGS
7924 @ovindex ERLC
7925 @ovindex ERLCFLAGS
7926 Determine an Erlang compiler to use. If @code{ERLC} is not already set in the
7927 environment, check for @command{erlc}. Set output variable @code{ERLC} to the
7928 complete path of the compiler command found. In addition, if @code{ERLCFLAGS}
7929 is not set in the environment, set it to an empty value.
7930
7931 The two optional arguments have the same meaning as the two last arguments of
7932 macro @code{AC_PATH_PROG} for looking for the @command{erlc} program. For
7933 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7934 directory:
7935
7936 @example
7937 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7938 @end example
7939 @end defmac
7940
7941 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7942 @acindex{ERLANG_NEED_ERLC}
7943 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7944 error message and exits the @command{configure} script if the @command{erlc}
7945 program is not found.
7946 @end defmac
7947
7948 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7949 @acindex{ERLANG_PATH_ERL}
7950 @evindex ERL
7951 @ovindex ERL
7952 Determine an Erlang interpreter to use. If @code{ERL} is not already
7953 set in the
7954 environment, check for @command{erl}. Set output variable @code{ERL} to the
7955 complete path of the interpreter command found.
7956
7957 The two optional arguments have the same meaning as the two last arguments of
7958 macro @code{AC_PATH_PROG} for looking for the @command{erl} program. For
7959 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7960 directory:
7961
7962 @example
7963 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7964 @end example
7965 @end defmac
7966
7967 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7968 @acindex{ERLANG_NEED_ERL}
7969 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7970 error message and exits the @command{configure} script if the @command{erl}
7971 program is not found.
7972 @end defmac
7973
7974
7975 @node Fortran Compiler
7976 @subsection Fortran Compiler Characteristics
7977 @cindex Fortran
7978 @cindex F77
7979
7980 The Autoconf Fortran support is divided into two categories: legacy
7981 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7982 The former are intended for traditional Fortran 77 code, and have output
7983 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}. The latter
7984 are for newer programs that can (or must) compile under the newer
7985 Fortran standards, and have output variables like @code{FC},
7986 @code{FCFLAGS}, and @code{FCLIBS}.
7987
7988 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7989 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7990 @code{FC} and @code{F77} macros behave almost identically, and so they
7991 are documented together in this section.
7992
7993
7994 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7995 @acindex{PROG_F77}
7996 @evindex F77
7997 @evindex FFLAGS
7998 @ovindex F77
7999 @ovindex FFLAGS
8000 @caindex f77_compiler_gnu
8001 @caindex prog_f77_g
8002 Determine a Fortran 77 compiler to use. If @code{F77} is not already
8003 set in the environment, then check for @code{g77} and @code{f77}, and
8004 then some other names. Set the output variable @code{F77} to the name
8005 of the compiler found.
8006
8007 This macro may, however, be invoked with an optional first argument
8008 which, if specified, must be a blank-separated list of Fortran 77
8009 compilers to search for. This just gives the user an opportunity to
8010 specify an alternative search list for the Fortran 77 compiler. For
8011 example, if you didn't like the default order, then you could invoke
8012 @code{AC_PROG_F77} like this:
8013
8014 @example
8015 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
8016 @end example
8017
8018 If using a compiler that supports GNU Fortran 77,
8019 set the shell variable @code{G77} to @samp{yes}.
8020 If the output variable @code{FFLAGS} was not already set in the
8021 environment, set it to @option{-g -02} for @code{g77} (or @option{-O2}
8022 where the GNU Fortran 77 compiler does not accept @option{-g}), or
8023 @option{-g} for other compilers.
8024
8025 The result of the GNU test is cached in the
8026 @code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
8027 @code{ac_cv_prog_f77_g} variable.
8028 @end defmac
8029
8030 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
8031 @acindex{PROG_FC}
8032 @evindex FC
8033 @evindex FCFLAGS
8034 @ovindex FC
8035 @ovindex FCFLAGS
8036 @caindex fc_compiler_gnu
8037 @caindex prog_fc_g
8038 Determine a Fortran compiler to use. If @code{FC} is not already set in
8039 the environment, then @code{dialect} is a hint to indicate what Fortran
8040 dialect to search for; the default is to search for the newest available
8041 dialect. Set the output variable @code{FC} to the name of the compiler
8042 found.
8043
8044 By default, newer dialects are preferred over older dialects, but if
8045 @code{dialect} is specified then older dialects are preferred starting
8046 with the specified dialect. @code{dialect} can currently be one of
8047 Fortran 77, Fortran 90, or Fortran 95. However, this is only a hint of
8048 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
8049 and no attempt is made to guarantee that a particular language standard
8050 is actually supported. Thus, it is preferable that you avoid the
8051 @code{dialect} option, and use AC_PROG_FC only for code compatible with
8052 the latest Fortran standard.
8053
8054 This macro may, alternatively, be invoked with an optional first argument
8055 which, if specified, must be a blank-separated list of Fortran
8056 compilers to search for, just as in @code{AC_PROG_F77}.
8057
8058 If using a compiler that supports GNU Fortran,
8059 set the shell variable @code{GFC} to @samp{yes}.
8060 If the output variable @code{FCFLAGS} was not already set in the
8061 environment, then set it to @option{-g -02} for a GNU Fortran compiler (or
8062 @option{-O2} where the compiler does not accept @option{-g}), or
8063 @option{-g} for other compilers.
8064
8065 The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
8066 variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
8067 variable.
8068 @end defmac
8069
8070 @defmac AC_PROG_F77_C_O
8071 @defmacx AC_PROG_FC_C_O
8072 @acindex{PROG_F77_C_O}
8073 @acindex{PROG_FC_C_O}
8074 @cvindex F77_NO_MINUS_C_MINUS_O
8075 @cvindex FC_NO_MINUS_C_MINUS_O
8076 @caindex prog_f77_c_o
8077 @caindex prog_fc_c_o
8078 Test whether the Fortran compiler accepts the options @option{-c} and
8079 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
8080 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
8081
8082 The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
8083 @code{ac_cv_prog_fc_c_o} variable, respectively.
8084 @end defmac
8085
8086 The following macros check for Fortran compiler characteristics.
8087 To check for characteristics not listed here, use
8088 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
8089 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
8090 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
8091 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
8092
8093
8094 @defmac AC_F77_LIBRARY_LDFLAGS
8095 @defmacx AC_FC_LIBRARY_LDFLAGS
8096 @acindex{F77_LIBRARY_LDFLAGS}
8097 @ovindex FLIBS
8098 @acindex{FC_LIBRARY_LDFLAGS}
8099 @ovindex FCLIBS
8100 @caindex prog_f77_v
8101 @caindex prog_fc_v
8102 @caindex f77_libs
8103 @caindex fc_libs
8104 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
8105 @dfn{Fortran intrinsic and runtime libraries} that are required to
8106 successfully link a Fortran program or shared library. The output
8107 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
8108 should be included after @code{LIBS} when linking).
8109
8110 This macro is intended to be used in those situations when it is
8111 necessary to mix, e.g., C++ and Fortran source code in a single
8112 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
8113 automake, GNU Automake}).
8114
8115 For example, if object files from a C++ and Fortran compiler must be
8116 linked together, then the C++ compiler/linker must be used for linking
8117 (since special C++-ish things need to happen at link time like calling
8118 global constructors, instantiating templates, enabling exception
8119 support, etc.).
8120
8121 However, the Fortran intrinsic and runtime libraries must be linked in
8122 as well, but the C++ compiler/linker doesn't know by default how to add
8123 these Fortran 77 libraries. Hence, this macro was created to determine
8124 these Fortran libraries.
8125
8126 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8127 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
8128 link C/C++ with Fortran; see below. Further, it is highly recommended
8129 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
8130 because the complex defines that the function wrapper macros create
8131 may not work with C/C++ compiler drivers.
8132
8133 These macros internally compute the flag needed to verbose linking
8134 output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
8135 variables, respectively. The computed linker flags are cached in
8136 @code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
8137 @end defmac
8138
8139 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @
8140 @dvar{action-if-not-found, AC_MSG_FAILURE})
8141 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @
8142 @dvar{action-if-not-found, AC_MSG_FAILURE})
8143 @acindex{F77_DUMMY_MAIN}
8144 @cvindex F77_DUMMY_MAIN
8145 @acindex{FC_DUMMY_MAIN}
8146 @cvindex FC_DUMMY_MAIN
8147 @caindex f77_dummy_main
8148 @caindex fc_dummy_main
8149 With many compilers, the Fortran libraries detected by
8150 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
8151 their own @code{main} entry function that initializes things like
8152 Fortran I/O, and which then calls a user-provided entry function named
8153 (say) @code{MAIN__} to run the user's program. The
8154 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8155 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
8156 this interaction.
8157
8158 When using Fortran for purely numerical functions (no I/O, etc.)@: often
8159 one prefers to provide one's own @code{main} and skip the Fortran
8160 library initializations. In this case, however, one may still need to
8161 provide a dummy @code{MAIN__} routine in order to prevent linking errors
8162 on some systems. @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8163 detects whether any such routine is @emph{required} for linking, and
8164 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8165 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8166 was found, and @code{none} when no such dummy main is needed.
8167
8168 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8169 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8170 @emph{if} it is required. @var{action-if-not-found} defaults to
8171 exiting with an error.
8172
8173 In order to link with Fortran routines, the user's C/C++ program should
8174 then include the following code to define the dummy main if it is
8175 needed:
8176
8177 @example
8178 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8179 #ifdef F77_DUMMY_MAIN
8180 # ifdef __cplusplus
8181 extern "C"
8182 # endif
8183 int F77_DUMMY_MAIN (void) @{ return 1; @}
8184 #endif
8185 @end example
8186
8187 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8188
8189 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8190 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8191 explicitly unless one wants to change the default actions.
8192
8193 The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8194 @code{ac_cv_fc_dummy_main} variable, respectively.
8195 @end defmac
8196
8197 @defmac AC_F77_MAIN
8198 @defmacx AC_FC_MAIN
8199 @acindex{F77_MAIN}
8200 @cvindex F77_MAIN
8201 @acindex{FC_MAIN}
8202 @cvindex FC_MAIN
8203 @caindex f77_main
8204 @caindex fc_main
8205 As discussed above, many Fortran libraries allow you to provide an entry
8206 point called (say) @code{MAIN__} instead of the usual @code{main}, which
8207 is then called by a @code{main} function in the Fortran libraries that
8208 initializes things like Fortran I/O@. The
8209 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8210 @emph{possible} to utilize such an alternate main function, and defines
8211 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function. (If no
8212 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8213 simply defined to @code{main}.)
8214
8215 Thus, when calling Fortran routines from C that perform things like I/O,
8216 one should use this macro and declare the "main" function like so:
8217
8218 @example
8219 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8220 #ifdef __cplusplus
8221 extern "C"
8222 #endif
8223 int F77_MAIN (int argc, char *argv[]);
8224 @end example
8225
8226 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8227
8228 The result of this macro is cached in the @code{ac_cv_f77_main} or
8229 @code{ac_cv_fc_main} variable, respectively.
8230 @end defmac
8231
8232 @defmac AC_F77_WRAPPERS
8233 @defmacx AC_FC_WRAPPERS
8234 @acindex{F77_WRAPPERS}
8235 @cvindex F77_FUNC
8236 @cvindex F77_FUNC_
8237 @acindex{FC_WRAPPERS}
8238 @cvindex FC_FUNC
8239 @cvindex FC_FUNC_
8240 @caindex f77_mangling
8241 @caindex fc_mangling
8242 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8243 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8244 mangle the names of C/C++ identifiers, and identifiers with underscores,
8245 respectively, so that they match the name-mangling scheme used by the
8246 Fortran compiler.
8247
8248 Fortran is case-insensitive, and in order to achieve this the Fortran
8249 compiler converts all identifiers into a canonical case and format. To
8250 call a Fortran subroutine from C or to write a C function that is
8251 callable from Fortran, the C program must explicitly use identifiers in
8252 the format expected by the Fortran compiler. In order to do this, one
8253 simply wraps all C identifiers in one of the macros provided by
8254 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}. For example, suppose
8255 you have the following Fortran 77 subroutine:
8256
8257 @example
8258 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8259 subroutine foobar (x, y)
8260 double precision x, y
8261 y = 3.14159 * x
8262 return
8263 end
8264 @end example
8265
8266 You would then declare its prototype in C or C++ as:
8267
8268 @example
8269 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8270 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8271 #ifdef __cplusplus
8272 extern "C" /* prevent C++ name mangling */
8273 #endif
8274 void FOOBAR_F77 (double *x, double *y);
8275 @end example
8276
8277 Note that we pass both the lowercase and uppercase versions of the
8278 function name to @code{F77_FUNC} so that it can select the right one.
8279 Note also that all parameters to Fortran 77 routines are passed as
8280 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8281 Automake}).
8282
8283 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8284
8285 Although Autoconf tries to be intelligent about detecting the
8286 name-mangling scheme of the Fortran compiler, there may be Fortran
8287 compilers that it doesn't support yet. In this case, the above code
8288 generates a compile-time error, but some other behavior
8289 (e.g., disabling Fortran-related features) can be induced by checking
8290 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8291
8292 Now, to call that routine from a C program, we would do something like:
8293
8294 @example
8295 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8296 @{
8297 double x = 2.7183, y;
8298 FOOBAR_F77 (&x, &y);
8299 @}
8300 @end example
8301
8302 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8303 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8304 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments). This is
8305 because some Fortran compilers mangle names differently if they contain
8306 an underscore.
8307
8308 The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8309 @code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8310 the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8311 @end defmac
8312
8313 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8314 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8315 @acindex{F77_FUNC}
8316 @acindex{FC_FUNC}
8317 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8318 hold the mangled version @var{name} according to the rules of the
8319 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8320 @code{AC_FC_WRAPPERS}). @var{shellvar} is optional; if it is not
8321 supplied, the shell variable is simply @var{name}. The purpose of
8322 this macro is to give the caller a way to access the name-mangling
8323 information other than through the C preprocessor as above, for example,
8324 to call Fortran routines from some language other than C/C++.
8325 @end defmac
8326
8327 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8328 @dvar{action-if-failure, AC_MSG_FAILURE})
8329 @defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8330 @dvar{action-if-failure, AC_MSG_FAILURE})
8331 @acindex{FC_SRCEXT}
8332 @acindex{FC_PP_SRCEXT}
8333 @caindex fc_srcext_@var{ext}
8334 @caindex fc_pp_srcext_@var{ext}
8335 By default, the @code{FC} macros perform their tests using a @file{.f}
8336 extension for source-code files. Some compilers, however, only enable
8337 newer language features for appropriately named files, e.g., Fortran 90
8338 features only for @file{.f90} files, or preprocessing only with
8339 @file{.F} files or maybe other upper-case extensions. On the other
8340 hand, some other compilers expect all source files to end in @file{.f}
8341 and require special flags to support other file name extensions. The
8342 @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8343 issues.
8344
8345 The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8346 accept files ending with the extension @file{.@var{ext}} (i.e.,
8347 @var{ext} does @emph{not} contain the dot). If any special compiler
8348 flags are needed for this, it stores them in the output variable
8349 @code{FCFLAGS_@var{ext}}. This extension and these flags are then used
8350 for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8351 @code{AC_FC_PP_SRCEXT} is called another time).
8352
8353 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8354 @file{.f90} extension in future tests, and it would set the
8355 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8356 to compile such files.
8357
8358 Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8359 compiler to preprocess and compile files with the extension
8360 @file{.@var{ext}}. When both @command{fpp} and @command{cpp} style
8361 preprocessing are provided, the former is preferred, as the latter may
8362 treat continuation lines, @code{//} tokens, and white space differently
8363 from what some Fortran dialects expect. Conversely, if you do not want
8364 files to be preprocessed, use only lower-case characters in the file
8365 name extension. Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8366 are stored in the @code{FCFLAGS_@var{ext}} variable.
8367
8368 The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8369 into @code{FCFLAGS}, for two reasons based on the limitations of some
8370 compilers. First, only one @code{FCFLAGS_@var{ext}} can be used at a
8371 time, so files with different extensions must be compiled separately.
8372 Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8373 the source-code file name when compiling. So, continuing the example
8374 above, you might compile a @file{foo.f90} file in your makefile with the
8375 command:
8376
8377 @example
8378 foo.o: foo.f90
8379 $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8380 @end example
8381
8382 If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8383 files with the @var{ext} extension, it calls @var{action-if-success}
8384 (defaults to nothing). If it fails, and cannot find a way to make the
8385 @code{FC} compiler accept such files, it calls @var{action-if-failure}
8386 (defaults to exiting with an error message).
8387
8388 The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8389 results in @code{ac_cv_fc_srcext_@var{ext}} and
8390 @code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8391 @end defmac
8392
8393 @defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @
8394 @dvar{action-if-failure, AC_MSG_FAILURE})
8395 @acindex{FC_PP_DEFINE}
8396 @caindex fc_pp_define
8397
8398 Find a flag to specify defines for preprocessed Fortran. Not all
8399 Fortran compilers use @option{-D}. Substitute @code{FC_DEFINE} with
8400 the result and call @var{action-if-success} (defaults to nothing) if
8401 successful, and @var{action-if-failure} (defaults to failing with an
8402 error message) if not.
8403
8404 This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8405 preprocess a @file{conftest.F} file, but restores a previously used
8406 Fortran source file extension afterwards again.
8407
8408 The result of this test is cached in the @code{ac_cv_fc_pp_define}
8409 variable.
8410 @end defmac
8411
8412 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @
8413 @dvar{action-if-failure, AC_MSG_FAILURE})
8414 @acindex{FC_FREEFORM}
8415 @caindex fc_freeform
8416
8417 Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8418 source code (as opposed to the older fixed-format style from Fortran
8419 77). If necessary, it may add some additional flags to @code{FCFLAGS}.
8420
8421 This macro is most important if you are using the default @file{.f}
8422 extension, since many compilers interpret this extension as indicating
8423 fixed-format source unless an additional flag is supplied. If you
8424 specify a different extension with @code{AC_FC_SRCEXT}, such as
8425 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8426 modifying @code{FCFLAGS}. For extensions which the compiler does not
8427 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8428 the compiler assume Fortran 77 by default, however.
8429
8430 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8431 calls @var{action-if-success} (defaults to nothing). If it fails, it
8432 calls @var{action-if-failure} (defaults to exiting with an error
8433 message).
8434
8435 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8436 the @code{ac_cv_fc_freeform} variable.
8437 @end defmac
8438
8439 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @
8440 @dvar{action-if-failure, AC_MSG_FAILURE})
8441 @acindex{FC_FIXEDFORM}
8442 @caindex fc_fixedform
8443
8444 Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8445 fixed-format source code (as opposed to free-format style). If
8446 necessary, it may add some additional flags to @code{FCFLAGS}.
8447
8448 This macro is needed for some compilers alias names like @command{xlf95}
8449 which assume free-form source code by default, and in case you want to
8450 use fixed-form source with an extension like @file{.f90} which many
8451 compilers interpret as free-form by default. If you specify a different
8452 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8453 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8454 @code{FCFLAGS}.
8455
8456 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8457 calls @var{action-if-success} (defaults to nothing). If it fails, it
8458 calls @var{action-if-failure} (defaults to exiting with an error
8459 message).
8460
8461 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8462 the @code{ac_cv_fc_fixedform} variable.
8463 @end defmac
8464
8465 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8466 @dvar{action-if-failure, AC_MSG_FAILURE})
8467 @acindex{FC_LINE_LENGTH}
8468 @caindex fc_line_length
8469
8470 Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8471 code lines. The @var{length} argument may be given as 80, 132, or
8472 unlimited, and defaults to 132. Note that line lengths above 250
8473 columns are not portable, and some compilers do not accept more than 132
8474 columns at least for fixed format source. If necessary, it may add some
8475 additional flags to @code{FCFLAGS}.
8476
8477 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8478 calls @var{action-if-success} (defaults to nothing). If it fails, it
8479 calls @var{action-if-failure} (defaults to exiting with an error
8480 message).
8481
8482 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8483 the @code{ac_cv_fc_line_length} variable.
8484 @end defmac
8485
8486 @defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8487 @dvar{action-if-failure, AC_MSG_FAILURE})
8488 @acindex{FC_CHECK_BOUNDS}
8489 @caindex fc_check_bounds
8490
8491 The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8492 in the Fortran compiler. If successful, the @var{action-if-success}
8493 is called and any needed flags are added to @code{FCFLAGS}. Otherwise,
8494 @var{action-if-failure} is called, which defaults to failing with an error
8495 message. The macro currently requires Fortran 90 or a newer dialect.
8496
8497 The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8498 variable.
8499 @end defmac
8500
8501 @defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8502 @dvar{action-if-failure, AC_MSG_FAILURE})
8503 @defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8504 @dvar{action-if-failure, AC_MSG_FAILURE})
8505 @acindex{F77_IMPLICIT_NONE}
8506 @acindex{FC_IMPLICIT_NONE}
8507 @caindex f77_implicit_none
8508 @caindex fc_implicit_none
8509
8510 Try to disallow implicit declarations in the Fortran compiler. If
8511 successful, @var{action-if-success} is called and any needed flags
8512 are added to @code{FFLAGS} or @code{FCFLAGS}, respectively. Otherwise,
8513 @var{action-if-failure} is called, which defaults to failing with an error
8514 message.
8515
8516 The result of these macros are cached in the
8517 @code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8518 variables, respectively.
8519 @end defmac
8520
8521 @defmac AC_FC_MODULE_EXTENSION
8522 @acindex{FC_MODULE_EXTENSION}
8523 @caindex fc_module_ext
8524 @ovindex FC_MODEXT
8525
8526 Find the Fortran 90 module file name extension. Most Fortran 90
8527 compilers store module information in files separate from the object
8528 files. The module files are usually named after the name of the module
8529 rather than the source file name, with characters possibly turned to
8530 upper case, plus an extension, often @file{.mod}.
8531
8532 Not all compilers use module files at all, or by default. The Cray
8533 Fortran compiler requires @option{-e m} in order to store and search
8534 module information in @file{.mod} files rather than in object files.
8535 Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8536 indicate how module information is stored.
8537
8538 The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8539 without the leading dot, and stores that in the @code{FC_MODEXT}
8540 variable. If the compiler does not produce module files, or the
8541 extension cannot be determined, @code{FC_MODEXT} is empty. Typically,
8542 the result of this macro may be used in cleanup @command{make} rules as
8543 follows:
8544
8545 @example
8546 clean-modules:
8547 -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8548 @end example
8549
8550 The extension, or @samp{unknown}, is cached in the
8551 @code{ac_cv_fc_module_ext} variable.
8552 @end defmac
8553
8554 @defmac AC_FC_MODULE_FLAG (@ovar{action-if-success}, @
8555 @dvar{action-if-failure, AC_MSG_FAILURE})
8556 @acindex{FC_MODULE_FLAG}
8557 @caindex fc_module_flag
8558 @ovindex FC_MODINC
8559 @ovindex ac_empty
8560
8561 Find the compiler flag to include Fortran 90 module information from
8562 another directory, and store that in the @code{FC_MODINC} variable.
8563 Call @var{action-if-success} (defaults to nothing) if successful, and
8564 set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8565 to exiting with an error message) if not.
8566
8567 Most Fortran 90 compilers provide a way to specify module directories.
8568 Some have separate flags for the directory to write module files to,
8569 and directories to search them in, whereas others only allow writing to
8570 the current directory or to the first directory specified in the include
8571 path. Further, with some compilers, the module search path and the
8572 preprocessor search path can only be modified with the same flag. Thus,
8573 for portability, write module files to the current directory only and
8574 list that as first directory in the search path.
8575
8576 There may be no whitespace between @code{FC_MODINC} and the following
8577 directory name, but @code{FC_MODINC} may contain trailing white space.
8578 For example, if you use Automake and would like to search @file{../lib}
8579 for module files, you can use the following:
8580
8581 @example
8582 AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8583 @end example
8584
8585 Inside @command{configure} tests, you can use:
8586
8587 @example
8588 if test -n "$FC_MODINC"; then
8589 FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8590 fi
8591 @end example
8592
8593 The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8594 The substituted value of @code{FC_MODINC} may refer to the
8595 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8596 the significant trailing whitespace in a @file{Makefile}.
8597 @end defmac
8598
8599 @defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-success}, @
8600 @dvar{action-if-failure, AC_MSG_FAILURE})
8601 @acindex{FC_MODULE_OUTPUT_FLAG}
8602 @caindex fc_module_output_flag
8603 @ovindex FC_MODOUT
8604
8605 Find the compiler flag to write Fortran 90 module information to
8606 another directory, and store that in the @code{FC_MODOUT} variable.
8607 Call @var{action-if-success} (defaults to nothing) if successful, and
8608 set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8609 to exiting with an error message) if not.
8610
8611 Not all Fortran 90 compilers write module files, and of those that do,
8612 not all allow writing to a directory other than the current one, nor
8613 do all have separate flags for writing and reading; see the description
8614 of @code{AC_FC_MODULE_FLAG} above. If you need to be able to write to
8615 another directory, for maximum portability use @code{FC_MODOUT} before
8616 any @code{FC_MODINC} and include both the current directory and the one
8617 you write to in the search path:
8618
8619 @example
8620 AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8621 @end example
8622
8623 The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8624 The substituted value of @code{FC_MODOUT} may refer to the
8625 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8626 the significant trailing whitespace in a @file{Makefile}.
8627 @end defmac
8628
8629 @defmac AC_F77_CRAY_POINTERS (@ovar{action-if-success}, @
8630 @dvar{action-if-failure, AC_MSG_FAILURE})
8631 @defmacx AC_FC_CRAY_POINTERS (@ovar{action-if-success}, @
8632 @dvar{action-if-failure, AC_MSG_FAILURE})
8633 @acindex{F77_CRAY_POINTERS}
8634 @acindex{FC_CRAY_POINTERS}
8635 @caindex fc_cray_pointer
8636
8637 Try to ensure that the Fortran compiler (@code{$F77} or @code{$FC})
8638 accepts Cray pointers. If successful, the @var{action-if-success} is
8639 called and any needed flags are added to @code{FFLAGS} or
8640 @code{FCFLAGS}. Otherwise, @var{action-if-failure} is called, which
8641 defaults to failing with an error message.
8642
8643 Cray pointers are a non-standard extension supported by many Fortran
8644 compilers which allow an integer to be declared as C-like pointer to
8645 a target variable.
8646
8647 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8648 the @code{ac_cv_f77_cray_ptr} or @code{ac_cv_fc_cray_ptr} variable.
8649 @end defmac
8650
8651
8652 @node Go Compiler
8653 @subsection Go Compiler Characteristics
8654 @cindex Go
8655
8656 Autoconf provides basic support for the Go programming language when
8657 using the @code{gccgo} compiler (there is currently no support for the
8658 @code{6g} and @code{8g} compilers).
8659
8660 @defmac AC_PROG_GO (@ovar{compiler-search-list})
8661 Find the Go compiler to use. Check whether the environment variable
8662 @code{GOC} is set; if so, then set output variable @code{GOC} to its
8663 value.
8664
8665 Otherwise, if the macro is invoked without an argument, then search for
8666 a Go compiler named @code{gccgo}. If it is not found, then as a last
8667 resort set @code{GOC} to @code{gccgo}.
8668
8669 This macro may be invoked with an optional first argument which, if
8670 specified, must be a blank-separated list of Go compilers to search for.
8671
8672 If output variable @code{GOFLAGS} was not already set, set it to
8673 @option{-g -O2}. If your package does not like this default,
8674 @code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8675 @end defmac
8676
8677
8678 @node Algol 68 Compiler
8679 @subsection Algol 68 Compiler
8680 @cindex Algol 68
8681
8682 Autoconf provides basic support for the Algol 68 programming language
8683 when using the @code{ga68} compiler.
8684
8685 Note that the GCC Algol 68 front-end is not yet integrated in the main
8686 compiler, so it is developed and distributed off-tree. See
8687 @url{https://gcc.gnu.org/wiki/Algol68FrontEnd}. Additional information
8688 about the Algol 68 programming language, and how it is being evolved by
8689 the GNU Algol 68 Working Group can be found at
8690 @url{https://algol68-lang.org}.
8691
8692 @defmac AC_PROG_A68 (@ovar{compiler-search-list})
8693 Find the Algol 68 compiler to use. Check whether the environment
8694 variable @code{A68} is set; if so, then set output variable @code{A68}
8695 to its value.
8696
8697 Otherwise, if the macro is invoked without an argument, then search for
8698 an Algol 68 compiler named @code{ga68}. If it is not found, then as a
8699 last resort set @code{A68} to @code{ga68}.
8700
8701 This macro may be invoked with an optional first argument which, if
8702 specified, must be a blank-separated list of Algol 68 compilers to
8703 search for.
8704
8705 If output variable @code{A68FLAGS} was not already set, set it to
8706 @option{-g -O2}. If your package does not like this default,
8707 @code{A68FLAGS} may be set before @code{AC_PROG_A68}.
8708 @end defmac
8709
8710 @node System Services
8711 @section System Services
8712
8713 The following macros check for operating system services or capabilities.
8714
8715 @anchor{AC_PATH_X}
8716 @defmac AC_PATH_X
8717 @acindex{PATH_X}
8718 @evindex XMKMF
8719 @cindex X Window System
8720 Try to locate the X Window System include files and libraries. If the
8721 user gave the command line options @option{--x-includes=@var{dir}} and
8722 @option{--x-libraries=@var{dir}}, use those directories.
8723
8724 If either or both were not given, get the missing values by running
8725 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8726 environment variable) on a trivial @file{Imakefile} and examining the
8727 makefile that it produces. Setting @code{XMKMF} to @samp{false}
8728 disables this method.
8729
8730 If this method fails to find the X Window System, @command{configure}
8731 looks for the files in several directories where they often reside.
8732 If either method is successful, set the shell variables
8733 @code{x_includes} and @code{x_libraries} to their locations, unless they
8734 are in directories the compiler searches by default.
8735
8736 If both methods fail, or the user gave the command line option
8737 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8738 otherwise set it to the empty string.
8739 @end defmac
8740
8741 @anchor{AC_PATH_XTRA}
8742 @defmac AC_PATH_XTRA
8743 @acindex{PATH_XTRA}
8744 @ovindex X_CFLAGS
8745 @ovindex X_LIBS
8746 @ovindex X_EXTRA_LIBS
8747 @ovindex X_PRE_LIBS
8748 @cvindex X_DISPLAY_MISSING
8749 An enhanced version of @code{AC_PATH_X}. It adds the C compiler flags
8750 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8751 to @code{X_LIBS}. Define @code{X_DISPLAY_MISSING} if X is not
8752 available.
8753
8754 This macro also checks for special libraries that some systems need in
8755 order to compile X programs. It adds any that the system needs to
8756 output variable @code{X_EXTRA_LIBS}. And it checks for special X11R6
8757 libraries that need to be linked with before @option{-lX11}, and adds
8758 any found to the output variable @code{X_PRE_LIBS}.
8759
8760 @c This is an incomplete kludge. Make a real way to do it.
8761 @c If you need to check for other X functions or libraries yourself, then
8762 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8763 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8764 @end defmac
8765
8766 @anchor{AC_SYS_INTERPRETER}
8767 @defmac AC_SYS_INTERPRETER
8768 @acindex{SYS_INTERPRETER}
8769 Check whether the system supports starting scripts with a line of the
8770 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8771 After running this macro, shell code in @file{configure.ac} can check
8772 the shell variable @code{interpval}; it is set to @samp{yes}
8773 if the system supports @samp{#!}, @samp{no} if not.
8774 @end defmac
8775
8776 @anchor{AC_SYS_LARGEFILE}
8777 @defmac AC_SYS_LARGEFILE
8778 @acindex{SYS_LARGEFILE}
8779 @cvindex _FILE_OFFSET_BITS
8780 @cvindex _TIME_BITS
8781 @ovindex CC
8782 @cindex Large file support
8783 @cindex LFS
8784 If the default @code{off_t} type is a 32-bit integer,
8785 and therefore cannot be used with files 2 GiB or larger,
8786 make a wider @code{off_t} available if the system supports it.
8787 Similarly, widen other types related to sizes of files and file systems
8788 if possible. These types may include @code{blkcnt_t}, @code{dev_t},
8789 @code{ino_t}, @code{fsblkcnt_t}, @code{fsfilcnt_t}, and @code{rlim_t}.
8790
8791 Also, arrange for a @command{configure} option @code{--enable-year2038}
8792 to request widening the type @code{time_t} as needed to represent file
8793 wand other timestamps after mid-January 2038. This widening is possible
8794 only on 32-bit GNU/Linux x86 and ARM systems with glibc 2.34 or later.
8795 If year-2038 support is requested but @command{configure} fails to find a way
8796 to widen @code{time_t} and inspection of the system suggests that
8797 this feature is available somehow, @command{configure} will error out.
8798 If you want the default to be @code{--enable-year2038}, you can use
8799 @code{AC_SYS_YEAR2038} or @code{AC_SYS_YEAR2038_RECOMMENDED}
8800 instead of @code{AC_SYS_LARGEFILE}.
8801 In other words, older packages that have long used @code{AC_SYS_LARGEFILE}
8802 can have year-2038 support on 32-bit GNU/Linux x86 and ARM systems either by
8803 regenerating @file{configure} with current Autoconf and configuring with
8804 @option{--enable-year2038}, or by using @code{AC_SYS_YEAR2038} or
8805 @code{AC_SYS_YEAR2038_RECOMMENDED} and configuring without
8806 @option{--disable-year2038}.
8807 A future version of Autoconf might change the @code{AC_SYS_LARGEFILE}
8808 default to @code{--enable-year2038}; if and when that happens,
8809 @code{AC_SYS_LARGEFILE} and @code{AC_SYS_YEAR2038} will become equivalent.
8810 @xref{AC_SYS_YEAR2038}.
8811
8812 Set the shell variable @code{ac_have_largefile} to @samp{yes} or
8813 @code{no} depending on whether a wide @code{off_t} is available,
8814 regardless of whether arrangements were necessary.
8815 Similarly, set the shell variable @code{ac_have_year2038} to @code{yes}
8816 or @code{no} depending on whether a wide-enough @code{time_t} is available.
8817
8818 Define preprocessor macros if necessary to make types wider;
8819 for example, on GNU/Linux systems the macros @code{_FILE_OFFSET_BITS}
8820 and @code{_TIME_BITS} can be defined. Some of these macros work only if
8821 defined before the first system header is included;
8822 therefore, when using this macro in concert with
8823 @code{AC_CONFIG_HEADERS}, make sure that @file{config.h} is included
8824 before any system headers.
8825
8826 Large-file support can be disabled by configuring with the
8827 @option{--disable-largefile} option, and year-2038 support can
8828 be enabled and disabled via the @option{--enable-year2038} and
8829 @option{--disable-year2038} options. These options have no effect on
8830 systems where types are wide enough by default.
8831 Large-file support is required for year-2038 support: if you configure
8832 with @option{--disable-largefile} on a platform with 32-bit
8833 @code{time_t}, then year-2038 support is not available.
8834
8835 Disabling large-file or year-2038 support can have surprising effects,
8836 such as causing functions like @code{readdir} and @code{stat} to fail
8837 even on a small file because its inode number or timestamp is out of range.
8838
8839 Regardless of whether you use this macro, portable programs should not
8840 assume that any of the types listed above fit into a @code{long int}.
8841 For example, it is not portable to print an arbitrary @code{off_t} or
8842 @code{time_t} value @code{X} with @code{printf ("%ld", (long int) X)}.
8843
8844 The standard C library functions @code{fseek} and @code{ftell}
8845 do not use @code{off_t}. If you need to use either of these functions,
8846 you should use @code{AC_FUNC_FSEEKO} as well as @code{AC_SYS_LARGEFILE},
8847 and then use their POSIX replacements @code{fseeko} and @code{ftello}.
8848 @xref{AC_FUNC_FSEEKO}.
8849
8850 When using @code{AC_SYS_LARGEFILE} in different packages that are linked
8851 together and that have interfaces that depend on the width of @code{off_t},
8852 @code{time_t} or related types, the simplest thing is to configure all
8853 components the same way. For example, if an application uses
8854 @code{AC_SYS_LARGEFILE} and is configured with
8855 @option{--enable-year2038}, libraries it links to with an @code{off_t}-
8856 or @code{time_t}-dependent interface should be configured equivalently.
8857 Alternatively, you can modify libraries to support both 32- and 64-bit
8858 interfaces though this is more work and few libraries other than the C
8859 library itself are modified in this way.
8860
8861 Applications and libraries should be configured compatibly.
8862 If @code{off_t}, @code{time_t} or related types appear in a library's
8863 public interface, enabling or disabling the library's large-file or
8864 year-2038 support may break binary compatibility with applications or
8865 with other libraries. Similarly, if an application links to a such a
8866 library, enabling or disabling the application's large-file support may
8867 break binary compatibility with that library.
8868 @end defmac
8869
8870 @anchor{AC_SYS_LONG_FILE_NAMES}
8871 @defmac AC_SYS_LONG_FILE_NAMES
8872 @acindex{SYS_LONG_FILE_NAMES}
8873 @cvindex HAVE_LONG_FILE_NAMES
8874 If the system supports file names longer than 14 characters, define
8875 @code{HAVE_LONG_FILE_NAMES}.
8876 @end defmac
8877
8878 @defmac AC_SYS_POSIX_TERMIOS
8879 @acindex{SYS_POSIX_TERMIOS}
8880 @cindex POSIX termios headers
8881 @cindex termios POSIX headers
8882 @caindex sys_posix_termios
8883 Check to see if the POSIX termios headers and functions are available on the
8884 system. If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8885 @samp{yes}. If not, set the variable to @samp{no}.
8886 @end defmac
8887
8888 @anchor{AC_SYS_YEAR2038}
8889 @defmac AC_SYS_YEAR2038
8890 @acindex{SYS_YEAR2038}
8891 @cindex Year 2038
8892 This is like @code{AC_SYS_LARGEFILE} except it defaults to enabling
8893 instead of disabling year-2038 support. Year-2038 support for
8894 applications and libraries should be configured compatibly.
8895 @xref{AC_SYS_LARGEFILE}.
8896 @end defmac
8897
8898 @defmac AC_SYS_YEAR2038_RECOMMENDED
8899 @acindex{SYS_YEAR2038_RECOMMENDED}
8900 This macro has the same effect as @code{AC_SYS_YEAR2038},
8901 but also declares that the program being configured
8902 should support timestamps after mid-January 2038.
8903 If a large @code{time_t} is unavailable, @command{configure} will error
8904 out unless the @option{--disable-year2038} option is specified.
8905
8906 Year-2038 support for applications and libraries should be configured
8907 compatibly. @xref{AC_SYS_YEAR2038}.
8908 @end defmac
8909
8910 @node C and POSIX Variants
8911 @section C and POSIX Variants
8912
8913 The following macro makes it possible to use C language and library
8914 extensions defined by the C standards committee, features of POSIX that
8915 are extensions to C, and platform extensions not defined by POSIX.
8916
8917 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8918 @defmac AC_USE_SYSTEM_EXTENSIONS
8919 @acindex{USE_SYSTEM_EXTENSIONS}
8920 If possible, enable extensions to C or POSIX on hosts that normally
8921 disable the extensions, typically due to standards-conformance namespace
8922 issues. This should be called before any macros that run the C
8923 compiler. Also, when using this macro in concert with
8924 @code{AC_CONFIG_HEADERS}, be sure that @file{config.h} is included
8925 before any system header.
8926
8927 Define the following preprocessor macros unconditionally:
8928
8929 @table @code
8930 @item _ALL_SOURCE
8931 @cvindex _ALL_SOURCE
8932 Enable extensions on AIX and z/OS.
8933 @item _COSMO_SOURCE
8934 @cvindex _COSMO_SOURCE
8935 Enable extensions on Cosmopolitan Libc.
8936 @item _DARWIN_C_SOURCE
8937 @cvindex _DARWIN_C_SOURCE
8938 Enable extensions on macOS.
8939 @item _GNU_SOURCE
8940 @cvindex _GNU_SOURCE
8941 Enable extensions on GNU systems.
8942 @item _NETBSD_SOURCE
8943 @cvindex _NETBSD_SOURCE
8944 Enable general extensions on NetBSD.
8945 Enable NetBSD compatibility extensions on Minix.
8946 @item _OPENBSD_SOURCE
8947 @cvindex _OPENBSD_SOURCE
8948 Enable OpenBSD compatibility extensions on NetBSD.
8949 Oddly enough, this does nothing on OpenBSD.
8950 @item _POSIX_PTHREAD_SEMANTICS
8951 @cvindex _POSIX_PTHREAD_SEMANTICS
8952 Enable POSIX-compatible threading on Solaris.
8953 @item __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8954 @cvindex __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8955 Enable extensions specified by ISO/IEC TS 18661-5:2014.
8956 @item __STDC_WANT_IEC_60559_BFP_EXT__
8957 @cvindex __STDC_WANT_IEC_60559_BFP_EXT__
8958 Enable extensions specified by ISO/IEC TS 18661-1:2014.
8959 @item __STDC_WANT_IEC_60559_DFP_EXT__
8960 @cvindex __STDC_WANT_IEC_60559_DFP_EXT__
8961 Enable extensions specified by ISO/IEC TS 18661-2:2015.
8962 @item __STDC_WANT_IEC_60559_EXT__
8963 @cvindex __STDC_WANT_IEC_60559_EXT__
8964 Enable extensions specified by C23 Annex F.
8965 @item __STDC_WANT_IEC_60559_FUNCS_EXT__
8966 @cvindex __STDC_WANT_IEC_60559_FUNCS_EXT__
8967 Enable extensions specified by ISO/IEC TS 18661-4:2015.
8968 @item __STDC_WANT_IEC_60559_TYPES_EXT__
8969 @cvindex __STDC_WANT_IEC_60559_TYPES_EXT__
8970 Enable extensions specified by C23 Annex H and by ISO/IEC TS 18661-3:2015.
8971 @item __STDC_WANT_LIB_EXT2__
8972 @cvindex __STDC_WANT_LIB_EXT2__
8973 Enable extensions specified by ISO/IEC TR 24731-2:2010.
8974 @item __STDC_WANT_MATH_SPEC_FUNCS__
8975 @cvindex __STDC_WANT_MATH_SPEC_FUNCS__
8976 Enable extensions specified by ISO/IEC 24747:2009.
8977 @item _TANDEM_SOURCE
8978 @cvindex _TANDEM_SOURCE
8979 Enable extensions on HP NonStop systems.
8980 @end table
8981
8982 The following preprocessor macros are defined only when necessary;
8983 they enable access to extensions on some operating systems but
8984 @emph{disable} extensions on other operating systems.
8985
8986 @table @code
8987 @item __EXTENSIONS__
8988 @cvindex __EXTENSIONS__
8989 Enable general extensions on Solaris. This macro is defined only if
8990 the headers included by @code{AC_INCLUDES_DEFAULT}
8991 (@pxref{Default Includes}) work correctly with it defined.
8992
8993 @item _MINIX
8994 @itemx _POSIX_SOURCE
8995 @itemx _POSIX_1_SOURCE
8996 @cvindex _MINIX
8997 @cvindex _POSIX_SOURCE
8998 @cvindex _POSIX_1_SOURCE
8999 Defined only on MINIX. @code{_POSIX_SOURCE} and @code{_POSIX_1_SOURCE}
9000 are needed to enable a number of POSIX features on this OS.
9001 @code{_MINIX} does not affect the system headers' behavior;
9002 future versions of Autoconf may stop defining it.
9003 Programs that need to recognize Minix should use @code{AC_CANONICAL_HOST}.
9004
9005 @item _XOPEN_SOURCE
9006 @cvindex _XOPEN_SOURCE
9007 Defined (with value 500) only if needed to make @file{wchar.h} declare
9008 @code{mbstate_t}. This is known to be necessary on some versions of HP-UX.
9009 @end table
9010
9011 @cvindex __STDC_WANT_DEC_FP__
9012 The C preprocessor macro @code{__STDC_WANT_DEC_FP__} is not defined.
9013 ISO/IEC TR 24732:2009 was superseded by ISO/IEC TS 18661-2:2015.
9014
9015 @cvindex __STDC_WANT_LIB_EXT1__
9016 The C preprocessor macro @code{__STDC_WANT_LIB_EXT1__} is not defined,
9017 as the C standard's Annex K is problematic. See: O'Donell C, Sebor M.
9018 @uref{https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm, Field
9019 Experience With Annex K---Bounds Checking Interfaces}.
9020
9021 The Autoconf macro @code{AC_USE_SYSTEM_EXTENSIONS} was introduced in
9022 Autoconf 2.60.
9023 @end defmac
9024
9025
9026 @node Erlang Libraries
9027 @section Erlang Libraries
9028 @cindex Erlang, Library, checking
9029
9030 The following macros check for an installation of Erlang/OTP, and for the
9031 presence of certain Erlang libraries. All those macros require the
9032 configuration of an Erlang interpreter and an Erlang compiler
9033 (@pxref{Erlang Compiler and Interpreter}).
9034
9035 @defmac AC_ERLANG_SUBST_ERTS_VER
9036 @acindex{ERLANG_SUBST_ERTS_VER}
9037 @ovindex ERLANG_ERTS_VER
9038 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
9039 Erlang runtime system (as returned by Erlang's
9040 @code{erlang:system_info(version)} function). The result of this test
9041 is cached if caching is enabled when running @command{configure}. The
9042 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
9043 for features of specific ERTS versions, but to be used for substituting
9044 the ERTS version in Erlang/OTP release resource files (@code{.rel}
9045 files), as shown below.
9046 @end defmac
9047
9048 @defmac AC_ERLANG_SUBST_ROOT_DIR
9049 @acindex{ERLANG_SUBST_ROOT_DIR}
9050 @ovindex ERLANG_ROOT_DIR
9051 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
9052 directory in which Erlang/OTP is installed (as returned by Erlang's
9053 @code{code:root_dir/0} function). The result of this test is cached if
9054 caching is enabled when running @command{configure}.
9055 @end defmac
9056
9057 @defmac AC_ERLANG_SUBST_LIB_DIR
9058 @acindex{ERLANG_SUBST_LIB_DIR}
9059 @ovindex ERLANG_LIB_DIR
9060 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
9061 directory of Erlang/OTP (as returned by Erlang's
9062 @code{code:lib_dir/0} function), which subdirectories each contain an installed
9063 Erlang/OTP library. The result of this test is cached if caching is enabled
9064 when running @command{configure}.
9065 @end defmac
9066
9067 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
9068 @ovar{action-if-not-found})
9069 @acindex{ERLANG_CHECK_LIB}
9070 @ovindex ERLANG_LIB_DIR_@var{library}
9071 @ovindex ERLANG_LIB_VER_@var{library}
9072 Test whether the Erlang/OTP library @var{library} is installed by
9073 calling Erlang's @code{code:lib_dir/1} function. The result of this
9074 test is cached if caching is enabled when running @command{configure}.
9075 @var{action-if-found} is a list of shell commands to run if the library
9076 is installed; @var{action-if-not-found} is a list of shell commands to
9077 run if it is not. Additionally, if the library is installed, the output
9078 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
9079 library installation directory, and the output variable
9080 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
9081 part of the subdirectory name, if it is in the standard form
9082 (@code{@var{library}-@var{version}}). If the directory name does not
9083 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
9084 empty string. If the library is not installed,
9085 @samp{ERLANG_LIB_DIR_@var{library}} and
9086 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}. For
9087 example, to check if library @code{stdlib} is installed:
9088
9089 @example
9090 AC_ERLANG_CHECK_LIB([stdlib],
9091 [AS_ECHO(["stdlib version \"$ERLANG_LIB_VER_stdlib\""])
9092 AS_ECHO(["is installed in \"$ERLANG_LIB_DIR_stdlib\""])],
9093 [AC_MSG_ERROR([stdlib was not found!])])
9094 @end example
9095
9096 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
9097 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
9098 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
9099 testing for features of specific versions of libraries or of the Erlang
9100 runtime system. Those variables are intended to be substituted in
9101 Erlang release resource files (@code{.rel} files). For instance, to
9102 generate a @file{example.rel} file for an application depending on the
9103 @code{stdlib} library, @file{configure.ac} could contain:
9104
9105 @example
9106 AC_ERLANG_SUBST_ERTS_VER
9107 AC_ERLANG_CHECK_LIB([stdlib],
9108 [],
9109 [AC_MSG_ERROR([stdlib was not found!])])
9110 AC_CONFIG_FILES([example.rel])
9111 @end example
9112
9113 @noindent
9114 The @file{example.rel.in} file used to generate @file{example.rel}
9115 should contain:
9116
9117 @example
9118 @{release,
9119 @{"@@PACKAGE@@", "@@VERSION@@"@},
9120 @{erts, "@@ERLANG_ERTS_VER@@"@},
9121 [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
9122 @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
9123 @end example
9124 @end defmac
9125
9126 In addition to the above macros, which test installed Erlang libraries, the
9127 following macros determine the paths to the directories into which newly built
9128 Erlang libraries are to be installed:
9129
9130 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
9131 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
9132 @ovindex ERLANG_INSTALL_LIB_DIR
9133
9134 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
9135 which every built Erlang library should be installed in a separate
9136 subdirectory.
9137 If this variable is not set in the environment when @command{configure} runs,
9138 its default value is @code{$@{libdir@}/erlang/lib}.
9139 @end defmac
9140
9141 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
9142 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
9143 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
9144
9145 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
9146 directory into which the built Erlang library @var{library} version
9147 @var{version} should be installed. If this variable is not set in the
9148 environment when @command{configure} runs, its default value is
9149 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
9150 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
9151 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
9152 @end defmac
9153
9154
9155
9156
9157
9158 @c ========================================================= Writing Tests
9159
9160 @node Writing Tests
9161 @chapter Writing Tests
9162
9163 If the existing feature tests don't do something you need, you have to
9164 write new ones. These macros are the building blocks. They provide
9165 ways for other macros to check whether various kinds of features are
9166 available and report the results.
9167
9168 This chapter contains some suggestions and some of the reasons why the
9169 existing tests are written the way they are. You can also learn a lot
9170 about how to write Autoconf tests by looking at the existing ones. If
9171 something goes wrong in one or more of the Autoconf tests, this
9172 information can help you understand the assumptions behind them, which
9173 might help you figure out how to best solve the problem.
9174
9175 These macros check the output of the compiler system of the current
9176 language (@pxref{Language Choice}). They do not cache the results of
9177 their tests for future use (@pxref{Caching Results}), because they don't
9178 know enough about the information they are checking for to generate a
9179 cache variable name. They also do not print any messages, for the same
9180 reason. The checks for particular kinds of features call these macros
9181 and do cache their results and print messages about what they're
9182 checking for.
9183
9184 When you write a feature test that could be applicable to more than one
9185 software package, the best thing to do is encapsulate it in a new macro.
9186 @xref{Writing Autoconf Macros}, for how to do that.
9187
9188 @menu
9189 * Language Choice:: Selecting which language to use for testing
9190 * Writing Test Programs:: Forging source files for compilers
9191 * Running the Preprocessor:: Detecting preprocessor symbols
9192 * Running the Compiler:: Detecting language or header features
9193 * Running the Linker:: Detecting library features
9194 * Runtime:: Testing for runtime features
9195 * Multiple Cases:: Tests for several possible values
9196 @end menu
9197
9198 @node Language Choice
9199 @section Language Choice
9200 @cindex Language
9201
9202 Autoconf-generated @command{configure} scripts check for the C compiler and
9203 its features by default. Packages that use other programming languages
9204 (maybe more than one, e.g., C and C++) need to test features of the
9205 compilers for the respective languages. The following macros determine
9206 which programming language is used in the subsequent tests in
9207 @file{configure.ac}.
9208
9209 @anchor{AC_LANG}
9210 @defmac AC_LANG (@var{language})
9211 @acindex{LANG}
9212 Do compilation tests using the compiler, preprocessor, and file
9213 extensions for the specified @var{language}.
9214
9215 Supported languages are:
9216
9217 @table @samp
9218 @item C
9219 Do compilation tests using @code{CC} and @code{CPP} and use extension
9220 @file{.c} for test programs. Use compilation flags: @code{CPPFLAGS} with
9221 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
9222
9223 @item C++
9224 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
9225 extension @file{.C} for test programs. Use compilation flags:
9226 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
9227 @code{CXXFLAGS} with @code{CXX}.
9228
9229 @item Fortran 77
9230 Do compilation tests using @code{F77} and use extension @file{.f} for
9231 test programs. Use compilation flags: @code{FFLAGS}.
9232
9233 @item Fortran
9234 Do compilation tests using @code{FC} and use extension @file{.f} (or
9235 whatever has been set by @code{AC_FC_SRCEXT}) for test programs. Use
9236 compilation flags: @code{FCFLAGS}.
9237
9238 @item Erlang
9239 @ovindex ERLC
9240 @ovindex ERL
9241 @ovindex ERLCFLAGS
9242 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
9243 @file{.erl} for test Erlang modules. Use compilation flags: @code{ERLCFLAGS}.
9244
9245 @item Objective C
9246 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
9247 extension @file{.m} for test programs. Use compilation flags:
9248 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
9249 @code{OBJCFLAGS} with @code{OBJC}.
9250
9251 @item Objective C++
9252 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
9253 extension @file{.mm} for test programs. Use compilation flags:
9254 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
9255 @code{OBJCXXFLAGS} with @code{OBJCXX}.
9256
9257 @item Go
9258 Do compilation tests using @code{GOC} and use extension @file{.go} for
9259 test programs. Use compilation flags @code{GOFLAGS}.
9260
9261 @item Algol 68
9262 Do compilation tests using @code{A68} and use extension @file{.a68} for
9263 test programs. Use compilation flags @code{A68FLAGS}.
9264 @end table
9265 @end defmac
9266
9267 @anchor{AC_LANG_PUSH}
9268 @defmac AC_LANG_PUSH (@var{language})
9269 @acindex{LANG_PUSH}
9270 Remember the current language (as set by @code{AC_LANG}) on a stack, and
9271 then select the @var{language}. Use this macro and @code{AC_LANG_POP}
9272 in macros that need to temporarily switch to a particular language.
9273 @end defmac
9274
9275 @defmac AC_LANG_POP (@ovar{language})
9276 @acindex{LANG_POP}
9277 Select the language that is saved on the top of the stack, as set by
9278 @code{AC_LANG_PUSH}, and remove it from the stack.
9279
9280 If given, @var{language} specifies the language we just @emph{quit}. It
9281 is a good idea to specify it when it's known (which should be the
9282 case@dots{}), since Autoconf detects inconsistencies.
9283
9284 @example
9285 AC_LANG_PUSH([Fortran 77])
9286 # Perform some tests on Fortran 77.
9287 # @dots{}
9288 AC_LANG_POP([Fortran 77])
9289 @end example
9290 @end defmac
9291
9292 @defmac AC_LANG_ASSERT (@var{language})
9293 @acindex{LANG_ASSERT}
9294 Check statically that the current language is @var{language}.
9295 You should use this in your language specific macros
9296 to avoid that they be called with an inappropriate language.
9297
9298 This macro runs only at @command{autoconf} time, and incurs no cost at
9299 @command{configure} time. Sadly enough and because Autoconf is a two
9300 layer language @footnote{Because M4 is not aware of Sh code,
9301 especially conditionals, some optimizations that look nice statically
9302 may produce incorrect results at runtime.}, the macros
9303 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
9304 therefore as much as possible you ought to avoid using them to wrap
9305 your code, rather, require from the user to run the macro with a
9306 correct current language, and check it with @code{AC_LANG_ASSERT}.
9307 And anyway, that may help the user understand she is running a Fortran
9308 macro while expecting a result about her Fortran 77 compiler@enddots{}
9309 @end defmac
9310
9311
9312 @defmac AC_REQUIRE_CPP
9313 @acindex{REQUIRE_CPP}
9314 Ensure that whichever preprocessor would currently be used for tests has
9315 been found. Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
9316 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
9317 depending on which language is current.
9318 @end defmac
9319
9320
9321 @node Writing Test Programs
9322 @section Writing Test Programs
9323
9324 Autoconf tests follow a common scheme: feed some program with some
9325 input, and most of the time, feed a compiler with some source file.
9326 This section is dedicated to these source samples.
9327
9328 @menu
9329 * Guidelines:: General rules for writing test programs
9330 * Test Functions:: Avoiding pitfalls in test programs
9331 * Generating Sources:: Source program boilerplate
9332 @end menu
9333
9334 @node Guidelines
9335 @subsection Guidelines for Test Programs
9336
9337 The most important rule to follow when writing testing samples is:
9338
9339 @center @emph{Look for realism.}
9340
9341 This motto means that testing samples must be written with the same
9342 strictness as real programs are written. In particular, you should
9343 avoid ``shortcuts'' and simplifications.
9344
9345 Don't just play with the preprocessor if you want to prepare a
9346 compilation. For instance, using @command{cpp} to check whether a header is
9347 functional might let your @command{configure} accept a header which
9348 causes some @emph{compiler} error. Do not hesitate to check a header with
9349 other headers included before, especially required headers.
9350
9351 Make sure the symbols you use are properly defined, i.e., refrain from
9352 simply declaring a function yourself instead of including the proper
9353 header.
9354
9355 Test programs should not write to standard output. They
9356 should exit with status 0 if the test succeeds, and with status 1
9357 otherwise, so that success
9358 can be distinguished easily from a core dump or other failure;
9359 segmentation violations and other failures produce a nonzero exit
9360 status. Unless you arrange for @code{exit} to be declared, test
9361 programs should @code{return}, not @code{exit}, from @code{main},
9362 because on many systems @code{exit} is not declared by default.
9363
9364 Test programs can use @code{#if} or @code{#ifdef} to check the values of
9365 preprocessor macros defined by tests that have already run. For
9366 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9367 @file{configure.ac} you can have a test program that includes
9368 @file{stdbool.h} conditionally:
9369
9370 @example
9371 @group
9372 #ifdef HAVE_STDBOOL_H
9373 # include <stdbool.h>
9374 #endif
9375 @end group
9376 @end example
9377
9378 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9379 work with any standard C compiler. Some developers prefer @code{#if}
9380 because it is easier to read, while others prefer @code{#ifdef} because
9381 it avoids diagnostics with picky compilers like GCC with the
9382 @option{-Wundef} option.
9383
9384 If a test program needs to use or create a data file, give it a name
9385 that starts with @file{conftest}, such as @file{conftest.data}. The
9386 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
9387 after running test programs and if the script is interrupted.
9388
9389 @node Test Functions
9390 @subsection Test Functions
9391
9392 Functions in test code should use function prototypes, introduced in C89
9393 and required in C23.
9394
9395 Functions that test programs declare should also be conditionalized for
9396 C++, which requires @samp{extern "C"} prototypes. Make sure to not
9397 include any header files containing clashing prototypes.
9398
9399 @example
9400 #ifdef __cplusplus
9401 extern "C"
9402 #endif
9403 void *valloc (size_t);
9404 @end example
9405
9406 If a test program calls a function with invalid parameters (just to see
9407 whether it exists), organize the program to ensure that it never invokes
9408 that function. You can do this by calling it in another function that is
9409 never invoked. You can't do it by putting it after a call to
9410 @code{exit}, because GCC version 2 knows that @code{exit}
9411 never returns
9412 and optimizes out any code that follows it in the same block.
9413
9414 If you include any header files, be sure to call the functions
9415 relevant to them with the correct number of arguments, even if they are
9416 just 0, to avoid compilation errors due to prototypes. GCC
9417 version 2
9418 has internal prototypes for several functions that it automatically
9419 inlines; for example, @code{memcpy}. To avoid errors when checking for
9420 them, either pass them the correct number of arguments or redeclare them
9421 with a different return type (such as @code{char}).
9422
9423
9424 @node Generating Sources
9425 @subsection Generating Sources
9426
9427 Autoconf provides a set of macros that can be used to generate test
9428 source files. They are written to be language generic, i.e., they
9429 actually depend on the current language (@pxref{Language Choice}) to
9430 ``format'' the output properly.
9431
9432
9433 @defmac AC_LANG_CONFTEST (@var{source})
9434 @acindex{LANG_CONFTEST}
9435 Save the @var{source} text in the current test source file:
9436 @file{conftest.@var{extension}} where the @var{extension} depends on the
9437 current language. As of Autoconf 2.63b, the source file also contains
9438 the results of all of the @code{AC_DEFINE} performed so far.
9439
9440 Note that the @var{source} is evaluated exactly once, like regular
9441 Autoconf macro arguments, and therefore (i) you may pass a macro
9442 invocation, (ii) if not, be sure to double quote if needed.
9443
9444 The @var{source} text is expanded as an unquoted here-document, so
9445 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9446 @xref{Here-Documents}.
9447
9448 This macro issues a warning during @command{autoconf} processing if
9449 @var{source} does not include an expansion of the macro
9450 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9451 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9452
9453 This macro is seldom called directly, but is used under the hood by more
9454 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9455 @end defmac
9456
9457 @defmac AC_LANG_DEFINES_PROVIDED
9458 @acindex{LANG_DEFINES_PROVIDED}
9459 This macro is called as a witness that the file
9460 @file{conftest.@var{extension}} appropriate for the current language is
9461 complete, including all previously determined results from
9462 @code{AC_DEFINE}. This macro is seldom called directly, but exists if
9463 you have a compelling reason to write a conftest file without using
9464 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9465 @code{AC_LANG_CONFTEST}.
9466 @end defmac
9467
9468 @defmac AC_LANG_SOURCE (@var{source})
9469 @acindex{LANG_SOURCE}
9470 Expands into the @var{source}, with the definition of
9471 all the @code{AC_DEFINE} performed so far. This macro includes an
9472 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9473
9474 In many cases, you may find it more convenient to use the wrapper
9475 @code{AC_LANG_PROGRAM}.
9476 @end defmac
9477
9478 For instance, executing (observe the double quotation!):
9479
9480 @example
9481 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9482 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9483 [https://www.example.org/])
9484 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9485 [Greetings string.])
9486 AC_LANG([C])
9487 AC_LANG_CONFTEST(
9488 [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9489 gcc -E -dD conftest.c
9490 @end example
9491
9492 @noindent
9493 on a system with @command{gcc} installed, results in:
9494
9495 @example
9496 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9497 @dots{}
9498 @asis{#} 1 "conftest.c"
9499
9500 #define PACKAGE_NAME "Hello"
9501 #define PACKAGE_TARNAME "hello"
9502 #define PACKAGE_VERSION "1.0"
9503 #define PACKAGE_STRING "Hello 1.0"
9504 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9505 #define PACKAGE_URL "https://www.example.org/"
9506 #define HELLO_WORLD "Hello, World\n"
9507
9508 const char hw[] = "Hello, World\n";
9509 @end example
9510
9511 When the test language is Fortran, Erlang, Go, or Algol 68,
9512 the @code{AC_DEFINE}
9513 definitions are not automatically translated into constants in the
9514 source code by this macro.
9515
9516 @defmac AC_LANG_PROGRAM (@ovar{prologue}, @ovar{body})
9517 @acindex{LANG_PROGRAM}
9518 Expands into a source file which consists of the @var{prologue}, and
9519 then @var{body} as body of the main function (e.g., @code{main} in
9520 C). Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9521 available.
9522 @end defmac
9523
9524 For instance:
9525
9526 @example
9527 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9528 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9529 [https://www.example.org/])
9530 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9531 [Greetings string.])
9532 AC_LANG_CONFTEST(
9533 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9534 [[fputs (hw, stdout);]])])
9535 gcc -E -dD conftest.c
9536 @end example
9537
9538 @noindent
9539 on a system with @command{gcc} installed, results in:
9540
9541 @example
9542 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9543 @dots{}
9544 @asis{#} 1 "conftest.c"
9545
9546 #define PACKAGE_NAME "Hello"
9547 #define PACKAGE_TARNAME "hello"
9548 #define PACKAGE_VERSION "1.0"
9549 #define PACKAGE_STRING "Hello 1.0"
9550 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9551 #define PACKAGE_URL "https://www.example.org/"
9552 #define HELLO_WORLD "Hello, World\n"
9553
9554 const char hw[] = "Hello, World\n";
9555 int
9556 main (void)
9557 @{
9558 fputs (hw, stdout);
9559 ;
9560 return 0;
9561 @}
9562 @end example
9563
9564 In Erlang tests, the created source file is that of an Erlang module called
9565 @code{conftest} (@file{conftest.erl}). This module defines and exports
9566 at least
9567 one @code{start/0} function, which is called to perform the test. The
9568 @var{prologue} is optional code that is inserted between the module header and
9569 the @code{start/0} function definition. @var{body} is the body of the
9570 @code{start/0} function without the final period (@pxref{Runtime}, about
9571 constraints on this function's behavior).
9572
9573 For instance:
9574
9575 @example
9576 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9577 AC_LANG(Erlang)
9578 AC_LANG_CONFTEST(
9579 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9580 [[io:format("~s~n", [?HELLO_WORLD])]])])
9581 cat conftest.erl
9582 @end example
9583
9584 @noindent
9585 results in:
9586
9587 @example
9588 -module(conftest).
9589 -export([start/0]).
9590 -define(HELLO_WORLD, "Hello, world!").
9591 start() ->
9592 io:format("~s~n", [?HELLO_WORLD])
9593 .
9594 @end example
9595
9596 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
9597 @acindex{LANG_CALL}
9598 Expands into a source file which consists of the @var{prologue}, and
9599 then a call to the @var{function} as body of the main function (e.g.,
9600 @code{main} in C). Since it uses @code{AC_LANG_PROGRAM}, the feature
9601 of the latter are available.
9602
9603 This function will probably be replaced in the future by a version
9604 which would enable specifying the arguments. The use of this macro is
9605 not encouraged, as it violates strongly the typing system.
9606
9607 This macro cannot be used for Erlang tests.
9608 @end defmac
9609
9610 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9611 @acindex{LANG_FUNC_LINK_TRY}
9612 Expands into a source file which uses the @var{function} in the body of
9613 the main function (e.g., @code{main} in C). Since it uses
9614 @code{AC_LANG_PROGRAM}, the features of the latter are available.
9615
9616 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9617 It is considered to be severely broken, and in the future will be
9618 removed in favor of actual function calls (with properly typed
9619 arguments).
9620
9621 This macro cannot be used for Erlang tests.
9622 @end defmac
9623
9624 @node Running the Preprocessor
9625 @section Running the Preprocessor
9626
9627 Sometimes one might need to run the preprocessor on some source file.
9628 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9629 your project, not merely run the preprocessor on it; therefore you
9630 certainly want to run the compiler, not the preprocessor. Resist the
9631 temptation of following the easiest path.
9632
9633 Nevertheless, if you need to run the preprocessor, then use
9634 @code{AC_PREPROC_IFELSE}.
9635
9636 The macros described in this section cannot be used for tests in Erlang,
9637 Fortran, Go, or Algol 68 since those languages require no preprocessor.
9638
9639 @anchor{AC_PREPROC_IFELSE}
9640 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9641 @ovar{action-if-false})
9642 @acindex{PREPROC_IFELSE}
9643 Run the preprocessor of the current language (@pxref{Language Choice})
9644 on the @var{input}, run the shell commands @var{action-if-true} on
9645 success, @var{action-if-false} otherwise.
9646
9647 If @var{input} is nonempty use the equivalent of
9648 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9649 file; otherwise reuse the already-existing test source file.
9650 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9651 The @var{input} text is expanded as an unquoted here-document, so
9652 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9653 @xref{Here-Documents}.
9654
9655 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9656 @option{-g}, @option{-O}, etc.@: are not valid options to many C
9657 preprocessors.
9658
9659 It is customary to report unexpected failures with
9660 @code{AC_MSG_FAILURE}. If needed, @var{action-if-true} can further access
9661 the preprocessed output in the file @file{conftest.i}.
9662 @end defmac
9663
9664 For instance:
9665
9666 @example
9667 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9668 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9669 [Greetings string.])
9670 AC_PREPROC_IFELSE(
9671 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9672 [[fputs (hw, stdout);]])],
9673 [AC_MSG_RESULT([OK])],
9674 [AC_MSG_FAILURE([unexpected preprocessor failure])])
9675 @end example
9676
9677 @noindent
9678 might result in:
9679
9680 @example
9681 checking for gcc... gcc
9682 checking whether the C compiler works... yes
9683 checking for C compiler default output file name... a.out
9684 checking for suffix of executables...
9685 checking whether we are cross compiling... no
9686 checking for suffix of object files... o
9687 checking whether the compiler supports GNU C... yes
9688 checking whether gcc accepts -g... yes
9689 checking for gcc option to enable C23 features... -std=gnu23
9690 checking how to run the C preprocessor... gcc -std=gnu23 -E
9691 OK
9692 @end example
9693
9694 @sp 1
9695
9696 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9697 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9698 it impossible to use it to elaborate sources. You are encouraged to
9699 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9700 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9701 to run the @emph{preprocessor} and not the compiler?
9702
9703 @anchor{AC_EGREP_HEADER}
9704 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9705 @var{action-if-found}, @ovar{action-if-not-found})
9706 @acindex{EGREP_HEADER}
9707 @var{pattern}, after being expanded as if in a double-quoted shell string,
9708 is an extended regular expression.
9709 If the output of running the preprocessor on the system header file
9710 @var{header-file} contains a line matching
9711 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9712 execute @var{action-if-not-found}.
9713
9714 See below for some problems involving this macro.
9715 @end defmac
9716
9717 @anchor{AC_EGREP_CPP}
9718 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9719 @ovar{action-if-found}, @ovar{action-if-not-found})
9720 @acindex{EGREP_CPP}
9721 @var{pattern}, after being expanded as if in a double-quoted shell string,
9722 is an extended regular expression.
9723 @var{program} is the text of a C or C++ program, which is expanded as an
9724 unquoted here-document (@pxref{Here-Documents}). If the
9725 output of running the preprocessor on @var{program} contains a line
9726 matching @var{pattern}, execute shell commands
9727 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9728
9729 See below for some problems involving this macro.
9730 @end defmac
9731
9732 @code{AC_EGREP_CPP} and @code{AC_EGREP_HEADER} should be used with care,
9733 as preprocessors can insert line breaks between output tokens. For
9734 example, the preprocessor might transform this:
9735
9736 @example
9737 #define MAJOR 2
9738 #define MINOR 23
9739 Version MAJOR . MINOR
9740 @end example
9741
9742 @noindent
9743 into this:
9744
9745 @example
9746 Version
9747 2
9748 .
9749 23
9750 @end example
9751
9752 @noindent
9753 Because preprocessors are allowed to insert white space, change escapes
9754 in string constants, insert backlash-newline pairs, or do any of a number
9755 of things that do not change the meaning of the preprocessed program, it
9756 is better to rely on @code{AC_PREPROC_IFELSE} than to resort to
9757 @code{AC_EGREP_CPP} or @code{AC_EGREP_HEADER}.
9758
9759 For more information about what can appear in portable extended regular
9760 expressions, @pxref{Problematic Expressions,,,grep, GNU Grep}.
9761
9762 @node Running the Compiler
9763 @section Running the Compiler
9764
9765 To check for a syntax feature of the current language's (@pxref{Language
9766 Choice}) compiler, such as whether it recognizes a certain keyword, or
9767 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9768 to compile a small program that uses that feature.
9769
9770 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9771 @ovar{action-if-false})
9772 @acindex{COMPILE_IFELSE}
9773 Run the compiler and compilation flags of the current language
9774 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9775 @var{action-if-true} on success, @var{action-if-false} otherwise.
9776
9777 If @var{input} is nonempty use the equivalent of
9778 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9779 file; otherwise reuse the already-existing test source file.
9780 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9781 The @var{input} text is expanded as an unquoted here-document, so
9782 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9783 @xref{Here-Documents}.
9784
9785 It is customary to report unexpected failures with
9786 @code{AC_MSG_FAILURE}. This macro does not try to link; use
9787 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9788 Linker}). If needed, @var{action-if-true} can further access the
9789 just-compiled object file @file{conftest.$OBJEXT}.
9790
9791 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9792 current language, which means that if the compiler has not yet been
9793 determined, the compiler determination will be made prior to the body of
9794 the outermost @code{AC_DEFUN} macro that triggered this macro to
9795 expand (@pxref{Expanded Before Required}).
9796 @end defmac
9797
9798 @ovindex ERL
9799 For tests in Erlang, the @var{input} must be the source code of a module named
9800 @code{conftest}. @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9801 file that can be interpreted by the Erlang virtual machine (@code{ERL}). It is
9802 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9803 to ensure that the Erlang module has the right name.
9804
9805 @node Running the Linker
9806 @section Running the Linker
9807
9808 To check for a library, a function, or a global variable, Autoconf
9809 @command{configure} scripts try to compile and link a small program that
9810 uses it. This is unlike Metaconfig, which by default uses @code{nm} or
9811 @code{ar} on the C library to try to figure out which functions are
9812 available. Trying to link with the function is usually a more reliable
9813 approach because it avoids dealing with the variations in the options
9814 and output formats of @code{nm} and @code{ar} and in the location of the
9815 standard libraries. It also allows configuring for cross-compilation or
9816 checking a function's runtime behavior if needed. On the other hand,
9817 it can be slower than scanning the libraries once, but accuracy is more
9818 important than speed.
9819
9820 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9821 functions and global variables. It is also used by @code{AC_CHECK_LIB}
9822 to check for libraries (@pxref{Libraries}), by adding the library being
9823 checked for to @code{LIBS} temporarily and trying to link a small
9824 program.
9825
9826 @anchor{AC_LINK_IFELSE}
9827 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9828 @ovar{action-if-false})
9829 @acindex{LINK_IFELSE}
9830 Run the compiler (and compilation flags) and the linker of the current
9831 language (@pxref{Language Choice}) on the @var{input}, run the shell
9832 commands @var{action-if-true} on success, @var{action-if-false}
9833 otherwise. If needed, @var{action-if-true} can further access the
9834 just-linked program file @file{conftest$EXEEXT}.
9835
9836 If @var{input} is nonempty use the equivalent of
9837 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9838 file; otherwise reuse the already-existing test source file.
9839 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9840 The @var{input} text is expanded as an unquoted here-document, so
9841 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9842 @xref{Here-Documents}.
9843
9844 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9845 current compilation flags.
9846
9847 It is customary to report unexpected failures with
9848 @code{AC_MSG_FAILURE}. This macro does not try to execute the program;
9849 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9850 @end defmac
9851
9852 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9853 programs are interpreted and do not require linking.
9854
9855
9856
9857 @node Runtime
9858 @section Checking Runtime Behavior
9859
9860 Sometimes you need to find out how a system performs at runtime, such
9861 as whether a given function has a certain capability or bug. If you
9862 can, make such checks when your program runs instead of when it is
9863 configured. You can check for things like the machine's endianness when
9864 your program initializes itself.
9865
9866 If you really need to test for a runtime behavior while configuring,
9867 you can write a test program to determine the result, and compile and
9868 run it using @code{AC_RUN_IFELSE}. Avoid running test programs if
9869 possible, because this prevents people from configuring your package for
9870 cross-compiling.
9871
9872 @anchor{AC_RUN_IFELSE}
9873 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9874 @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9875 @acindex{RUN_IFELSE}
9876 Run the compiler (and compilation flags) and the linker of the current
9877 language (@pxref{Language Choice}) on the @var{input}, then execute the
9878 resulting program. If the program returns an exit
9879 status of 0 when executed, run shell commands @var{action-if-true}.
9880 Otherwise, run shell commands @var{action-if-false}.
9881
9882 If @var{input} is nonempty use the equivalent of
9883 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9884 file; otherwise reuse the already-existing test source file.
9885 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9886 The @var{input} text is expanded as an unquoted here-document, so
9887 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9888 @xref{Here-Documents}.
9889
9890 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9891 compilation flags of the current language (@pxref{Language Choice}).
9892 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9893 for further testing.
9894
9895 In the @var{action-if-false} section, the failing exit status is
9896 available in the shell variable @samp{$?}. This exit status might be
9897 that of a failed compilation, or it might be that of a failed program
9898 execution.
9899
9900 If cross-compilation mode is enabled (this is the case if either the
9901 compiler being used does not produce executables that run on the system
9902 where @command{configure} is being run, or if the options @code{--build}
9903 and @code{--host} were both specified and their values are different),
9904 then the test program is
9905 not run. If the optional shell commands @var{action-if-cross-compiling}
9906 are given, those commands are run instead; typically these commands
9907 provide pessimistic defaults that allow cross-compilation to work even
9908 if the guess was wrong. If the fourth argument is empty or omitted, but
9909 cross-compilation is detected, then @command{configure} prints an error
9910 message and exits. If you want your package to be useful in a
9911 cross-compilation scenario, you @emph{should} provide a non-empty
9912 @var{action-if-cross-compiling} clause, as well as wrap the
9913 @code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9914 (@pxref{Caching Results}) which allows the user to override the
9915 pessimistic default if needed.
9916
9917 It is customary to report unexpected failures with
9918 @code{AC_MSG_FAILURE}.
9919 @end defmac
9920
9921 @command{autoconf} prints a warning message when creating
9922 @command{configure} each time it encounters a call to
9923 @code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9924 given. If you are not concerned about users configuring your package
9925 for cross-compilation, you may ignore the warning. A few of the macros
9926 distributed with Autoconf produce this warning message; but if this is a
9927 problem for you, please report it as a bug, along with an appropriate
9928 pessimistic guess to use instead.
9929
9930 To configure for cross-compiling you can also choose a value for those
9931 parameters based on the canonical system name (@pxref{Manual
9932 Configuration}). Alternatively, set up a test results cache file with
9933 the correct values for the host system (@pxref{Caching Results}).
9934
9935 @ovindex cross_compiling
9936 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9937 in other macros, including a few of the ones that come with Autoconf,
9938 you can test whether the shell variable @code{cross_compiling} is set to
9939 @samp{yes}, and then use an alternate method to get the results instead
9940 of calling the macros.
9941
9942 It is also permissible to temporarily assign to @code{cross_compiling}
9943 in order to force tests to behave as though they are in a
9944 cross-compilation environment, particularly since this provides a way to
9945 test your @var{action-if-cross-compiling} even when you are not using a
9946 cross-compiler.
9947
9948 @example
9949 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9950 # to use the slow link-only method
9951 save_cross_compiling=$cross_compiling
9952 cross_compiling=yes
9953 AC_COMPUTE_INT([@dots{}])
9954 cross_compiling=$save_cross_compiling
9955 @end example
9956
9957 A C or C++ runtime test should be portable.
9958 @xref{Portable C and C++}.
9959
9960 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9961 function: the given status code is used to determine the success of the test
9962 (status is @code{0}) or its failure (status is different than @code{0}), as
9963 explained above. It must be noted that data output through the standard output
9964 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9965 Therefore, if a test must output configuration information, it is recommended
9966 to create and to output data into the temporary file named @file{conftest.out},
9967 using the functions of module @code{file}. The @code{conftest.out} file is
9968 automatically deleted by the @code{AC_RUN_IFELSE} macro. For instance, a
9969 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9970 macro is:
9971
9972 @example
9973 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9974 AC_ERLANG_NEED_ERL
9975 AC_LANG(Erlang)
9976 AC_RUN_IFELSE(
9977 [AC_LANG_PROGRAM([], [dnl
9978 file:write_file("conftest.out", code:lib_dir()),
9979 halt(0)])],
9980 [AS_ECHO(["code:lib_dir() returned: `cat conftest.out`"])],
9981 [AC_MSG_FAILURE([test Erlang program execution failed])])
9982 @end example
9983
9984
9985 @node Multiple Cases
9986 @section Multiple Cases
9987
9988 Some operations are accomplished in several possible ways, depending on
9989 the OS variant. Checking for them essentially requires a ``case
9990 statement''. Autoconf does not directly provide one; however, it is
9991 easy to simulate by using a shell variable to keep track of whether a
9992 way to perform the operation has been found yet.
9993
9994 Here is an example that uses the shell variable @code{fstype} to keep
9995 track of whether the remaining cases need to be checked. Note that
9996 since the value of @code{fstype} is under our control, we don't have to
9997 use the longer @samp{test "x$fstype" = xno}.
9998
9999 @example
10000 @group
10001 AC_MSG_CHECKING([how to get file system type])
10002 fstype=no
10003 # The order of these tests is important.
10004 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
10005 #include <sys/fstyp.h>
10006 ]])],
10007 [AC_DEFINE([FSTYPE_STATVFS], [1],
10008 [Define if statvfs exists.])
10009 fstype=SVR4])
10010 AS_IF([test $fstype = no],
10011 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
10012 #include <sys/fstyp.h>
10013 ]])],
10014 [AC_DEFINE([FSTYPE_USG_STATFS], [1],
10015 [Define if USG statfs.])
10016 fstype=SVR3])])
10017 AS_IF([test $fstype = no],
10018 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
10019 #include <sys/vmount.h>
10020 ]])],
10021 [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
10022 [Define if AIX statfs.])
10023 fstype=AIX])])
10024 # (more cases omitted here)
10025 AC_MSG_RESULT([$fstype])
10026 @end group
10027 @end example
10028
10029 @c ====================================================== Results of Tests.
10030
10031 @node Results
10032 @chapter Results of Tests
10033
10034 Once @command{configure} has determined whether a feature exists, what can
10035 it do to record that information? There are four sorts of things it can
10036 do: define a C preprocessor symbol, set a variable in the output files,
10037 save the result in a cache file for future @command{configure} runs, and
10038 print a message letting the user know the result of the test.
10039
10040 @menu
10041 * Defining Symbols:: Defining C preprocessor symbols
10042 * Setting Output Variables:: Replacing variables in output files
10043 * Special Chars in Variables:: Characters to beware of in variables
10044 * Caching Results:: Speeding up subsequent @command{configure} runs
10045 * Printing Messages:: Notifying @command{configure} users
10046 @end menu
10047
10048 @node Defining Symbols
10049 @section Defining C Preprocessor Symbols
10050
10051 A common action to take in response to a feature test is to define a C
10052 preprocessor symbol indicating the results of the test. That is done by
10053 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
10054
10055 By default, @code{AC_OUTPUT} places the symbols defined by these macros
10056 into the output variable @code{DEFS}, which contains an option
10057 @option{-D@var{symbol}=@var{value}} for each symbol defined. Unlike in
10058 Autoconf version 1, there is no variable @code{DEFS} defined while
10059 @command{configure} is running. To check whether Autoconf macros have
10060 already defined a certain C preprocessor symbol, test the value of the
10061 appropriate cache variable, as in this example:
10062
10063 @example
10064 AC_CHECK_FUNC([vprintf],
10065 [AC_DEFINE([HAVE_VPRINTF], [1],
10066 [Define if vprintf exists.])])
10067 AS_IF([test "x$ac_cv_func_vprintf" != xyes],
10068 [AC_CHECK_FUNC([_doprnt],
10069 [AC_DEFINE([HAVE_DOPRNT], [1],
10070 [Define if _doprnt exists.])])])
10071 @end example
10072
10073 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
10074 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
10075 correct values into @code{#define} statements in a template file.
10076 @xref{Configuration Headers}, for more information about this kind of
10077 output.
10078
10079 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
10080 @defmacx AC_DEFINE (@var{variable})
10081 @cvindex @var{variable}
10082 @acindex{DEFINE}
10083 Define @var{variable} to @var{value} (verbatim), by defining a C
10084 preprocessor macro for @var{variable}. @var{variable} should be a C
10085 identifier, optionally suffixed by a parenthesized argument list to
10086 define a C preprocessor macro with arguments. The macro argument list,
10087 if present, should be a comma-separated list of C identifiers, possibly
10088 terminated by an ellipsis @samp{...} if C99-or-later syntax is employed.
10089 @var{variable} should not contain comments, white space, trigraphs,
10090 backslash-newlines, universal character names, or non-ASCII
10091 characters.
10092
10093 @var{value} may contain backslash-escaped newlines, which will be
10094 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
10095 via @code{@@DEFS@@} (with no effect on the compilation, since the
10096 preprocessor sees only one line in the first place). @var{value} should
10097 not contain raw newlines. If you are not using
10098 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
10099 characters, as @command{make} tends to eat them. To use a shell
10100 variable, use @code{AC_DEFINE_UNQUOTED} instead.
10101
10102 @var{description} is only useful if you are using
10103 @code{AC_CONFIG_HEADERS}. In this case, @var{description} is put into
10104 the generated @file{config.h.in} as the comment before the macro define.
10105 The following example defines the C preprocessor variable
10106 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
10107
10108 @example
10109 AC_DEFINE([EQUATION], ["$a > $b"],
10110 [Equation string.])
10111 @end example
10112
10113 If neither @var{value} nor @var{description} are given, then
10114 @var{value} defaults to 1 instead of to the empty string. This is for
10115 backwards compatibility with older versions of Autoconf, but this usage
10116 is obsolescent and may be withdrawn in future versions of Autoconf.
10117
10118 If the @var{variable} is a literal string, it is passed to
10119 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
10120
10121 If multiple @code{AC_DEFINE} statements are executed for the same
10122 @var{variable} name (not counting any parenthesized argument list),
10123 the last one wins.
10124 @end defmac
10125
10126 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
10127 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
10128 @acindex{DEFINE_UNQUOTED}
10129 @cvindex @var{variable}
10130 Like @code{AC_DEFINE}, but three shell expansions are
10131 performed---once---on @var{variable} and @var{value}: variable expansion
10132 (@samp{$}), command substitution (@samp{`}), and backslash escaping
10133 (@samp{\}), as if in an unquoted here-document. Single and double quote
10134 characters in the value have no
10135 special meaning. Use this macro instead of @code{AC_DEFINE} when
10136 @var{variable} or @var{value} is a shell variable. Examples:
10137
10138 @example
10139 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
10140 [Configuration machine file.])
10141 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
10142 [getgroups return type.])
10143 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
10144 [Translated header name.])
10145 @end example
10146 @end defmac
10147
10148 Due to a syntactical oddity of the Bourne shell, do not use
10149 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
10150 calls from other macro calls or shell code; that can cause syntax errors
10151 in the resulting @command{configure} script. Use either blanks or
10152 newlines. That is, do this:
10153
10154 @example
10155 AC_CHECK_HEADER([elf.h],
10156 [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
10157 @end example
10158
10159 @noindent
10160 or this:
10161
10162 @example
10163 AC_CHECK_HEADER([elf.h],
10164 [AC_DEFINE([SVR4], [1], [System V Release 4])
10165 LIBS="-lelf $LIBS"])
10166 @end example
10167
10168 @noindent
10169 instead of this:
10170
10171 @example
10172 AC_CHECK_HEADER([elf.h],
10173 [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
10174 @end example
10175
10176 @node Setting Output Variables
10177 @section Setting Output Variables
10178 @cindex Output variables
10179
10180 Another way to record the results of tests is to set @dfn{output
10181 variables}, which are shell variables whose values are substituted into
10182 files that @command{configure} outputs. The two macros below create new
10183 output variables. @xref{Preset Output Variables}, for a list of output
10184 variables that are always available.
10185
10186 @defmac AC_SUBST (@var{variable}, @ovar{value})
10187 @acindex{SUBST}
10188 Create an output variable from a shell variable. Make @code{AC_OUTPUT}
10189 substitute the variable @var{variable} into output files (typically one
10190 or more makefiles). This means that @code{AC_OUTPUT}
10191 replaces instances of @samp{@@@var{variable}@@} in input files with the
10192 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
10193 is called. The value can contain any non-@code{NUL} character, including
10194 newline. If you are using Automake 1.11 or newer, for newlines in values
10195 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
10196 @command{automake} from adding a line @code{@var{variable} =
10197 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
10198 Automake, automake, Other things Automake recognizes}).
10199
10200 Variable occurrences should not overlap: e.g., an input file should
10201 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
10202 are variable names.
10203 The substituted value is not rescanned for more output variables;
10204 occurrences of @samp{@@@var{variable}@@} in the value are inserted
10205 literally into the output file. (The algorithm uses the special marker
10206 @code{|#_!!_#|} internally, so neither the substituted value nor the
10207 output file may contain @code{|#_!!_#|}.)
10208
10209 If @var{value} is given, in addition assign it to @var{variable}.
10210
10211 The string @var{variable} is passed to @code{m4_pattern_allow}
10212 (@pxref{Forbidden Patterns}). @var{variable} is not further expanded,
10213 even if there is another macro by the same name.
10214 @end defmac
10215
10216 @defmac AC_SUBST_FILE (@var{variable})
10217 @acindex{SUBST_FILE}
10218 Another way to create an output variable from a shell variable. Make
10219 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
10220 named by shell variable @var{variable} into output files. This means
10221 that @code{AC_OUTPUT} replaces instances of
10222 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
10223 with the contents of the file that the shell variable @var{variable}
10224 names when @code{AC_OUTPUT} is called. Set the variable to
10225 @file{/dev/null} for cases that do not have a file to insert.
10226 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
10227 line by itself, optionally surrounded by spaces and tabs. The
10228 substitution replaces the whole line, including the spaces, tabs, and
10229 the terminating newline.
10230
10231 This macro is useful for inserting makefile fragments containing
10232 special dependencies or other @command{make} directives for particular host
10233 or target types into makefiles. For example, @file{configure.ac}
10234 could contain:
10235
10236 @example
10237 AC_SUBST_FILE([host_frag])
10238 host_frag=$srcdir/conf/sun4.mh
10239 @end example
10240
10241 @noindent
10242 and then a @file{Makefile.in} could contain:
10243
10244 @example
10245 @@host_frag@@
10246 @end example
10247
10248 The string @var{variable} is passed to @code{m4_pattern_allow}
10249 (@pxref{Forbidden Patterns}).
10250 @end defmac
10251
10252 @cindex Precious Variable
10253 @cindex Variable, Precious
10254 Running @command{configure} in varying environments can be extremely
10255 dangerous. If for instance the user runs @samp{CC=bizarre-cc
10256 ./configure}, then the cache, @file{config.h}, and many other output
10257 files depend upon @command{bizarre-cc} being the C compiler. If
10258 for some reason the user runs @command{./configure} again, or if it is
10259 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
10260 and @pxref{config.status Invocation}), then the configuration can be
10261 inconsistent, composed of results depending upon two different
10262 compilers.
10263
10264 Environment variables that affect this situation, such as @samp{CC}
10265 above, are called @dfn{precious variables}, and can be declared as such
10266 by @code{AC_ARG_VAR}.
10267
10268 @defmac AC_ARG_VAR (@var{variable}, @var{description})
10269 @acindex{ARG_VAR}
10270 Declare @var{variable} is a precious variable, and include its
10271 @var{description} in the variable section of @samp{./configure --help}.
10272
10273 Being precious means that
10274 @itemize @minus
10275 @item
10276 @var{variable} is substituted via @code{AC_SUBST}.
10277
10278 @item
10279 The value of @var{variable} when @command{configure} was launched is
10280 saved in the cache, including if it was not specified on the command
10281 line but via the environment. Indeed, while @command{configure} can
10282 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
10283 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
10284 which, unfortunately, is what most users do.
10285
10286 We emphasize that it is the @emph{initial} value of @var{variable} which
10287 is saved, not that found during the execution of @command{configure}.
10288 Indeed, specifying @samp{./configure FOO=foo} and letting
10289 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
10290 different things.
10291
10292 @item
10293 @var{variable} is checked for consistency between two
10294 @command{configure} runs. For instance:
10295
10296 @example
10297 $ @kbd{./configure --silent --config-cache}
10298 $ @kbd{CC=cc ./configure --silent --config-cache}
10299 configure: error: 'CC' was not set in the previous run
10300 configure: error: changes in the environment can compromise \
10301 the build
10302 configure: error: run 'make distclean' and/or \
10303 'rm config.cache' and start over
10304 @end example
10305
10306 @noindent
10307 and similarly if the variable is unset, or if its content is changed.
10308 If the content has white space changes only, then the error is degraded
10309 to a warning only, but the old value is reused.
10310
10311 @item
10312 @var{variable} is kept during automatic reconfiguration
10313 (@pxref{config.status Invocation}) as if it had been passed as a command
10314 line argument, including when no cache is used:
10315
10316 @example
10317 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
10318 $ @kbd{./config.status --recheck}
10319 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
10320 CC=/usr/bin/cc --no-create --no-recursion
10321 @end example
10322 @end itemize
10323 @end defmac
10324
10325 @node Special Chars in Variables
10326 @section Special Characters in Output Variables
10327 @cindex Output variables, special characters in
10328
10329 Many output variables are intended to be evaluated both by
10330 @command{make} and by the shell. Some characters are expanded
10331 differently in these two contexts, so to avoid confusion these
10332 variables' values should not contain any of the following characters:
10333
10334 @example
10335 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
10336 @end example
10337
10338 Also, these variables' values should neither contain newlines, nor start
10339 with @samp{~}, nor contain white space or @samp{:} immediately followed
10340 by @samp{~}. The values can contain nonempty sequences of white space
10341 characters like tabs and spaces, but each such sequence might
10342 arbitrarily be replaced by a single space during substitution.
10343
10344 These restrictions apply both to the values that @command{configure}
10345 computes, and to the values set directly by the user. For example, the
10346 following invocations of @command{configure} are problematic, since they
10347 attempt to use special characters within @code{CPPFLAGS} and white space
10348 within @code{$(srcdir)}:
10349
10350 @example
10351 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
10352
10353 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
10354 @end example
10355
10356 @node Caching Results
10357 @section Caching Results
10358 @cindex Cache
10359
10360 To avoid checking for the same features repeatedly in various
10361 @command{configure} scripts (or in repeated runs of one script),
10362 @command{configure} can optionally save the results of many checks in a
10363 @dfn{cache file} (@pxref{Cache Files}). If a @command{configure} script
10364 runs with caching enabled and finds a cache file, it reads the results
10365 of previous runs from the cache and avoids rerunning those checks. As a
10366 result, @command{configure} can then run much faster than if it had to
10367 perform all of the checks every time.
10368
10369 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10370 @acindex{CACHE_VAL}
10371 Ensure that the results of the check identified by @var{cache-id} are
10372 available. If the results of the check were in the cache file that was
10373 read, and @command{configure} was not given the @option{--quiet} or
10374 @option{--silent} option, print a message saying that the result was
10375 cached; otherwise, run the shell commands @var{commands-to-set-it}. If
10376 the shell commands are run to determine the value, the value is
10377 saved in the cache file just before @command{configure} creates its output
10378 files. @xref{Cache Variable Names}, for how to choose the name of the
10379 @var{cache-id} variable.
10380
10381 The @var{commands-to-set-it} @emph{must have no side effects} except for
10382 setting the variable @var{cache-id}, see below.
10383 @end defmac
10384
10385 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10386 @var{commands-to-set-it})
10387 @acindex{CACHE_CHECK}
10388 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10389 messages. This macro provides a convenient shorthand for the most
10390 common way to use these macros. It calls @code{AC_MSG_CHECKING} for
10391 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10392 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10393
10394 The @var{commands-to-set-it} @emph{must have no side effects} except for
10395 setting the variable @var{cache-id}, see below.
10396 @end defmac
10397
10398 It is common to find buggy macros using @code{AC_CACHE_VAL} or
10399 @code{AC_CACHE_CHECK}, because people are tempted to call
10400 @code{AC_DEFINE} in the @var{commands-to-set-it}. Instead, the code that
10401 @emph{follows} the call to @code{AC_CACHE_VAL} should call
10402 @code{AC_DEFINE}, by examining the value of the cache variable. For
10403 instance, the following macro is broken:
10404
10405 @example
10406 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10407 @group
10408 AC_DEFUN([AC_SHELL_TRUE],
10409 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10410 [my_cv_shell_true_works=no
10411 (true) 2>/dev/null && my_cv_shell_true_works=yes
10412 if test "x$my_cv_shell_true_works" = xyes; then
10413 AC_DEFINE([TRUE_WORKS], [1],
10414 [Define if 'true(1)' works properly.])
10415 fi])
10416 ])
10417 @end group
10418 @end example
10419
10420 @noindent
10421 This fails if the cache is enabled: the second time this macro is run,
10422 @code{TRUE_WORKS} @emph{will not be defined}. The proper implementation
10423 is:
10424
10425 @example
10426 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10427 @group
10428 AC_DEFUN([AC_SHELL_TRUE],
10429 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10430 [my_cv_shell_true_works=no
10431 (true) 2>/dev/null && my_cv_shell_true_works=yes])
10432 if test "x$my_cv_shell_true_works" = xyes; then
10433 AC_DEFINE([TRUE_WORKS], [1],
10434 [Define if 'true(1)' works properly.])
10435 fi
10436 ])
10437 @end group
10438 @end example
10439
10440 Also, @var{commands-to-set-it} should not print any messages, for
10441 example with @code{AC_MSG_CHECKING}; do that before calling
10442 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10443 the results of the check are retrieved from the cache or determined by
10444 running the shell commands.
10445
10446 @menu
10447 * Cache Variable Names:: Shell variables used in caches
10448 * Cache Files:: Files @command{configure} uses for caching
10449 * Cache Checkpointing:: Loading and saving the cache file
10450 @end menu
10451
10452 @node Cache Variable Names
10453 @subsection Cache Variable Names
10454 @cindex Cache variable
10455
10456 The names of cache variables should have the following format:
10457
10458 @example
10459 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10460 @end example
10461
10462 @noindent
10463 for example, @samp{ac_cv_header_stat_broken} or
10464 @samp{ac_cv_prog_gcc_traditional}. The parts of the variable name are:
10465
10466 @table @asis
10467 @item @var{package-prefix}
10468 An abbreviation for your package or organization; the same prefix you
10469 begin local Autoconf macros with, except lowercase by convention.
10470 For cache values used by the distributed Autoconf macros, this value is
10471 @samp{ac}.
10472
10473 @item @code{_cv_}
10474 Indicates that this shell variable is a cache value. This string
10475 @emph{must} be present in the variable name, including the leading
10476 underscore.
10477
10478 @item @var{value-type}
10479 A convention for classifying cache values, to produce a rational naming
10480 system. The values used in Autoconf are listed in @ref{Macro Names}.
10481
10482 @item @var{specific-value}
10483 Which member of the class of cache values this test applies to.
10484 For example, which function (@samp{alloca}), program (@samp{gcc}), or
10485 output variable (@samp{INSTALL}).
10486
10487 @item @var{additional-options}
10488 Any particular behavior of the specific member that this test applies to.
10489 For example, @samp{broken} or @samp{set}. This part of the name may
10490 be omitted if it does not apply.
10491 @end table
10492
10493 The values assigned to cache variables may not contain newlines.
10494 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10495 names of files or functions; so this is not an important restriction.
10496 @ref{Cache Variable Index} for an index of cache variables with
10497 documented semantics.
10498
10499
10500 @node Cache Files
10501 @subsection Cache Files
10502
10503 A cache file is a shell script that caches the results of configure
10504 tests run on one system so they can be shared between configure scripts
10505 and configure runs. It is not useful on other systems. If its contents
10506 are invalid for some reason, the user may delete or edit it, or override
10507 documented cache variables on the @command{configure} command line.
10508
10509 By default, @command{configure} uses no cache file,
10510 to avoid problems caused by accidental
10511 use of stale cache files.
10512
10513 To enable caching, @command{configure} accepts @option{--config-cache} (or
10514 @option{-C}) to cache results in the file @file{config.cache}.
10515 Alternatively, @option{--cache-file=@var{file}} specifies that
10516 @var{file} be the cache file. The cache file is created if it does not
10517 exist already. When @command{configure} calls @command{configure} scripts in
10518 subdirectories, it uses the @option{--cache-file} argument so that they
10519 share the same cache. @xref{Subdirectories}, for information on
10520 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10521
10522 @file{config.status} only pays attention to the cache file if it is
10523 given the @option{--recheck} option, which makes it rerun
10524 @command{configure}.
10525
10526 It is wrong to try to distribute cache files for particular system types.
10527 There is too much room for error in doing that, and too much
10528 administrative overhead in maintaining them. For any features that
10529 can't be guessed automatically, use the standard method of the canonical
10530 system type and linking files (@pxref{Manual Configuration}).
10531
10532 The site initialization script can specify a site-wide cache file to
10533 use, instead of the usual per-program cache. In this case, the cache
10534 file gradually accumulates information whenever someone runs a new
10535 @command{configure} script. (Running @command{configure} merges the new cache
10536 results with the existing cache file.) This may cause problems,
10537 however, if the system configuration (e.g., the installed libraries or
10538 compilers) changes and the stale cache file is not deleted.
10539
10540 If @command{configure} is interrupted at the right time when it updates
10541 a cache file outside of the build directory where the @command{configure}
10542 script is run, it may leave behind a temporary file named after the
10543 cache file with digits following it. You may safely delete such a file.
10544
10545
10546 @node Cache Checkpointing
10547 @subsection Cache Checkpointing
10548
10549 If your configure script, or a macro called from @file{configure.ac}, happens
10550 to abort the configure process, it may be useful to checkpoint the cache
10551 a few times at key points using @code{AC_CACHE_SAVE}. Doing so
10552 reduces the amount of time it takes to rerun the configure script with
10553 (hopefully) the error that caused the previous abort corrected.
10554
10555 @c FIXME: Do we really want to document this guy?
10556 @defmac AC_CACHE_LOAD
10557 @acindex{CACHE_LOAD}
10558 Loads values from existing cache file, or creates a new cache file if a
10559 cache file is not found. Called automatically from @code{AC_INIT}.
10560 @end defmac
10561
10562 @defmac AC_CACHE_SAVE
10563 @acindex{CACHE_SAVE}
10564 Flushes all cached values to the cache file. Called automatically from
10565 @code{AC_OUTPUT}, but it can be quite useful to call
10566 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10567 @end defmac
10568
10569 For instance:
10570
10571 @example
10572 @r{ @dots{} AC_INIT, etc. @dots{}}
10573 @group
10574 # Checks for programs.
10575 AC_PROG_CC
10576 AC_PROG_AWK
10577 @r{ @dots{} more program checks @dots{}}
10578 AC_CACHE_SAVE
10579 @end group
10580
10581 @group
10582 # Checks for libraries.
10583 AC_CHECK_LIB([nsl], [gethostbyname])
10584 AC_CHECK_LIB([socket], [connect])
10585 @r{ @dots{} more lib checks @dots{}}
10586 AC_CACHE_SAVE
10587 @end group
10588
10589 @group
10590 # Might abort@dots{}
10591 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10592 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10593 @end group
10594 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
10595 @end example
10596
10597 @node Printing Messages
10598 @section Printing Messages
10599 @cindex Messages, from @command{configure}
10600
10601 @command{configure} scripts need to give users running them several kinds
10602 of information. The following macros print messages in ways appropriate
10603 for each kind. The arguments to all of them get enclosed in shell
10604 double quotes, so the shell performs variable and back-quote
10605 substitution on them.
10606
10607 These macros are all wrappers around the @command{printf} shell command.
10608 They direct output to the appropriate file descriptor (@pxref{File
10609 Descriptor Macros}).
10610 @command{configure} scripts should rarely need to run @command{printf} directly
10611 to print messages for the user. Using these macros makes it easy to
10612 change how and when each kind of message is printed; such changes need
10613 only be made to the macro definitions and all the callers change
10614 automatically.
10615
10616 To diagnose static issues, i.e., when @command{autoconf} is run, see
10617 @ref{Diagnostic Macros}.
10618
10619 @defmac AC_MSG_CHECKING (@var{feature-description})
10620 @acindex{MSG_CHECKING}
10621 Notify the user that @command{configure} is checking for a particular
10622 feature. This macro prints a message that starts with @samp{checking }
10623 and ends with @samp{...} and no newline. It must be followed by a call
10624 to @code{AC_MSG_RESULT} to print the result of the check and the
10625 newline. The @var{feature-description} should be something like
10626 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10627 _Alignof}.
10628
10629 This macro prints nothing if @command{configure} is run with the
10630 @option{--quiet} or @option{--silent} option.
10631 @end defmac
10632
10633 @anchor{AC_MSG_RESULT}
10634 @defmac AC_MSG_RESULT (@var{result-description})
10635 @acindex{MSG_RESULT}
10636 Notify the user of the results of a check. @var{result-description} is
10637 almost always the value of the cache variable for the check, typically
10638 @samp{yes}, @samp{no}, or a file name. This macro should follow a call
10639 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10640 the completion of the message printed by the call to
10641 @code{AC_MSG_CHECKING}.
10642
10643 This macro prints nothing if @command{configure} is run with the
10644 @option{--quiet} or @option{--silent} option.
10645 @end defmac
10646
10647 @anchor{AC_MSG_NOTICE}
10648 @defmac AC_MSG_NOTICE (@var{message})
10649 @acindex{MSG_NOTICE}
10650 Deliver the @var{message} to the user. It is useful mainly to print a
10651 general description of the overall purpose of a group of feature checks,
10652 e.g.,
10653
10654 @example
10655 AC_MSG_NOTICE([checking if stack overflow is detectable])
10656 @end example
10657
10658 This macro prints nothing if @command{configure} is run with the
10659 @option{--quiet} or @option{--silent} option.
10660 @end defmac
10661
10662 @anchor{AC_MSG_ERROR}
10663 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10664 @acindex{MSG_ERROR}
10665 Notify the user of an error that prevents @command{configure} from
10666 completing. This macro prints an error message to the standard error
10667 output and exits @command{configure} with @var{exit-status} (@samp{$?}
10668 by default, except that @samp{0} is converted to @samp{1}).
10669 @var{error-description} should be something like @samp{invalid value
10670 $HOME for \$HOME}.
10671
10672 The @var{error-description} should start with a lower-case letter, and
10673 ``cannot'' is preferred to ``can't''.
10674 @end defmac
10675
10676 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10677 @acindex{MSG_FAILURE}
10678 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10679 prevents @command{configure} from completing @emph{and} that additional
10680 details are provided in @file{config.log}. This is typically used when
10681 abnormal results are found during a compilation.
10682 @end defmac
10683
10684 @anchor{AC_MSG_WARN}
10685 @defmac AC_MSG_WARN (@var{problem-description})
10686 @acindex{MSG_WARN}
10687 Notify the @command{configure} user of a possible problem. This macro
10688 prints the message to the standard error output; @command{configure}
10689 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10690 provide a default (back-up) behavior for the situations they warn about.
10691 @var{problem-description} should be something like @samp{ln -s seems to
10692 make hard links}.
10693 @end defmac
10694
10695
10696
10697 @c ====================================================== Programming in M4.
10698
10699 @node Programming in M4
10700 @chapter Programming in M4
10701 @cindex M4
10702
10703 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10704 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10705 provides macros dedicated to shell script generation.
10706
10707 As of this version of Autoconf, these two layers still contain
10708 experimental macros, whose interface might change in the future. As a
10709 matter of fact, @emph{anything that is not documented must not be used}.
10710
10711 @menu
10712 * M4 Quotation:: Protecting macros from unwanted expansion
10713 * Using autom4te:: The Autoconf executables backbone
10714 * Programming in M4sugar:: Convenient pure M4 macros
10715 * Debugging via autom4te:: Figuring out what M4 was doing
10716 @end menu
10717
10718 @node M4 Quotation
10719 @section M4 Quotation
10720 @cindex M4 quotation
10721 @cindex quotation
10722
10723 The most common problem with existing macros is an improper quotation.
10724 This section, which users of Autoconf can skip, but which macro writers
10725 @emph{must} read, first justifies the quotation scheme that was chosen
10726 for Autoconf and then ends with a rule of thumb. Understanding the
10727 former helps one to follow the latter.
10728
10729 @menu
10730 * Active Characters:: Characters that change the behavior of M4
10731 * One Macro Call:: Quotation and one macro call
10732 * Quoting and Parameters:: M4 vs. shell parameters
10733 * Quotation and Nested Macros:: Macros calling macros
10734 * Changequote is Evil:: Worse than INTERCAL: M4 + changequote
10735 * Quadrigraphs:: Another way to escape special characters
10736 * Balancing Parentheses:: Dealing with unbalanced parentheses
10737 * Quotation Rule Of Thumb:: One parenthesis, one quote
10738 @end menu
10739
10740 @node Active Characters
10741 @subsection Active Characters
10742
10743 To fully understand where proper quotation is important, you first need
10744 to know what the special characters are in Autoconf: @samp{#} introduces
10745 a comment inside which no macro expansion is performed, @samp{,}
10746 separates arguments, @samp{[} and @samp{]} are the quotes
10747 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10748 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10749 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10750 @samp{$} inside a macro definition.
10751
10752 In order to understand the delicate case of macro calls, we first have
10753 to present some obvious failures. Below they are ``obvious-ified'',
10754 but when you find them in real life, they are usually in disguise.
10755
10756 Comments, introduced by a hash and running up to the newline, are opaque
10757 tokens to the top level: active characters are turned off, and there is
10758 no macro expansion:
10759
10760 @example
10761 # define([def], ine)
10762 @result{}# define([def], ine)
10763 @end example
10764
10765 Each time there can be a macro expansion, there is a quotation
10766 expansion, i.e., one level of quotes is stripped:
10767
10768 @example
10769 int tab[10];
10770 @result{}int tab10;
10771 [int tab[10];]
10772 @result{}int tab[10];
10773 @end example
10774
10775 Without this in mind, the reader might try hopelessly to use her macro
10776 @code{array}:
10777
10778 @example
10779 define([array], [int tab[10];])
10780 array
10781 @result{}int tab10;
10782 [array]
10783 @result{}array
10784 @end example
10785
10786 @noindent
10787 How can you correctly output the intended results@footnote{Using
10788 @code{defn}.}?
10789
10790
10791 @node One Macro Call
10792 @subsection One Macro Call
10793
10794 Let's proceed on the interaction between active characters and macros
10795 with this small macro, which just returns its first argument:
10796
10797 @example
10798 define([car], [$1])
10799 @end example
10800
10801 @noindent
10802 The two pairs of quotes above are not part of the arguments of
10803 @code{define}; rather, they are understood by the top level when it
10804 tries to find the arguments of @code{define}. Therefore, assuming
10805 @code{car} is not already defined, it is equivalent to write:
10806
10807 @example
10808 define(car, $1)
10809 @end example
10810
10811 @noindent
10812 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10813 quotes, it is bad practice for Autoconf macros which must both be more
10814 robust and also advocate perfect style.
10815
10816 At the top level, there are only two possibilities: either you
10817 quote or you don't:
10818
10819 @example
10820 car(foo, bar, baz)
10821 @result{}foo
10822 [car(foo, bar, baz)]
10823 @result{}car(foo, bar, baz)
10824 @end example
10825
10826 Let's pay attention to the special characters:
10827
10828 @example
10829 car(#)
10830 @error{}EOF in argument list
10831 @end example
10832
10833 The closing parenthesis is hidden in the comment; with a hypothetical
10834 quoting, the top level understood it this way:
10835
10836 @example
10837 car([#)]
10838 @end example
10839
10840 @noindent
10841 Proper quotation, of course, fixes the problem:
10842
10843 @example
10844 car([#])
10845 @result{}#
10846 @end example
10847
10848 Here are more examples:
10849
10850 @example
10851 car(foo, bar)
10852 @result{}foo
10853 car([foo, bar])
10854 @result{}foo, bar
10855 car((foo, bar))
10856 @result{}(foo, bar)
10857 car([(foo], [bar)])
10858 @result{}(foo
10859 define([a], [b])
10860 @result{}
10861 car(a)
10862 @result{}b
10863 car([a])
10864 @result{}b
10865 car([[a]])
10866 @result{}a
10867 car([[[a]]])
10868 @result{}[a]
10869 @end example
10870
10871 @node Quoting and Parameters
10872 @subsection Quoting and Parameters
10873
10874 When M4 encounters @samp{$} within a macro definition, followed
10875 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10876 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10877 expansion. This happens regardless of how many layers of quotes the
10878 parameter expansion is nested within, or even if it occurs in text that
10879 will be rescanned as a comment.
10880
10881 @example
10882 define([none], [$1])
10883 @result{}
10884 define([one], [[$1]])
10885 @result{}
10886 define([two], [[[$1]]])
10887 @result{}
10888 define([comment], [# $1])
10889 @result{}
10890 define([active], [ACTIVE])
10891 @result{}
10892 none([active])
10893 @result{}ACTIVE
10894 one([active])
10895 @result{}active
10896 two([active])
10897 @result{}[active]
10898 comment([active])
10899 @result{}# active
10900 @end example
10901
10902 On the other hand, since autoconf generates shell code, you often want
10903 to output shell variable expansion, rather than performing M4 parameter
10904 expansion. To do this, you must use M4 quoting to separate the @samp{$}
10905 from the next character in the definition of your macro. If the macro
10906 definition occurs in single-quoted text, then insert another level of
10907 quoting; if the usage is already inside a double-quoted string, then
10908 split it into concatenated strings.
10909
10910 @example
10911 define([foo], [a single-quoted $[]1 definition])
10912 @result{}
10913 define([bar], [[a double-quoted $][1 definition]])
10914 @result{}
10915 foo
10916 @result{}a single-quoted $1 definition
10917 bar
10918 @result{}a double-quoted $1 definition
10919 @end example
10920
10921 POSIX states that M4 implementations are free to provide implementation
10922 extensions when @samp{$@{} is encountered in a macro definition.
10923 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10924 extensions that will be available in the future GNU M4 2.0,
10925 but guarantees that all other instances of @samp{$@{} will be output
10926 literally. Therefore, this idiom can also be used to output shell code
10927 parameter references:
10928
10929 @example
10930 define([first], [$@{1@}])first
10931 @result{}$@{1@}
10932 @end example
10933
10934 POSIX also states that @samp{$11} should expand to the first parameter
10935 concatenated with a literal @samp{1}, although some versions of
10936 GNU M4 expand the eleventh parameter instead. For
10937 portability, you should only use single-digit M4 parameter expansion.
10938
10939 With this in mind, we can explore the cases where macros invoke
10940 macros@enddots{}
10941
10942 @node Quotation and Nested Macros
10943 @subsection Quotation and Nested Macros
10944
10945 The examples below use the following macros:
10946
10947 @example
10948 define([car], [$1])
10949 define([active], [ACT, IVE])
10950 define([array], [int tab[10]])
10951 @end example
10952
10953 Each additional embedded macro call introduces other possible
10954 interesting quotations:
10955
10956 @example
10957 car(active)
10958 @result{}ACT
10959 car([active])
10960 @result{}ACT, IVE
10961 car([[active]])
10962 @result{}active
10963 @end example
10964
10965 In the first case, the top level looks for the arguments of @code{car},
10966 and finds @samp{active}. Because M4 evaluates its arguments
10967 before applying the macro, @samp{active} is expanded, which results in:
10968
10969 @example
10970 car(ACT, IVE)
10971 @result{}ACT
10972 @end example
10973
10974 @noindent
10975 In the second case, the top level gives @samp{active} as first and only
10976 argument of @code{car}, which results in:
10977
10978 @example
10979 active
10980 @result{}ACT, IVE
10981 @end example
10982
10983 @noindent
10984 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10985 In the third case, @code{car} receives @samp{[active]}, which results in:
10986
10987 @example
10988 [active]
10989 @result{}active
10990 @end example
10991
10992 @noindent
10993 exactly as we already saw above.
10994
10995 The example above, applied to a more realistic example, gives:
10996
10997 @example
10998 car(int tab[10];)
10999 @result{}int tab10;
11000 car([int tab[10];])
11001 @result{}int tab10;
11002 car([[int tab[10];]])
11003 @result{}int tab[10];
11004 @end example
11005
11006 @noindent
11007 Huh? The first case is easily understood, but why is the second wrong,
11008 and the third right? To understand that, you must know that after
11009 M4 expands a macro, the resulting text is immediately subjected
11010 to macro expansion and quote removal. This means that the quote removal
11011 occurs twice---first before the argument is passed to the @code{car}
11012 macro, and second after the @code{car} macro expands to the first
11013 argument.
11014
11015 As the author of the Autoconf macro @code{car}, you then consider it to
11016 be incorrect that your users have to double-quote the arguments of
11017 @code{car}, so you ``fix'' your macro. Let's call it @code{qar} for
11018 quoted car:
11019
11020 @example
11021 define([qar], [[$1]])
11022 @end example
11023
11024 @noindent
11025 and check that @code{qar} is properly fixed:
11026
11027 @example
11028 qar([int tab[10];])
11029 @result{}int tab[10];
11030 @end example
11031
11032 @noindent
11033 Ahhh! That's much better.
11034
11035 But note what you've done: now that the result of @code{qar} is always
11036 a literal string, the only time a user can use nested macros is if she
11037 relies on an @emph{unquoted} macro call:
11038
11039 @example
11040 qar(active)
11041 @result{}ACT
11042 qar([active])
11043 @result{}active
11044 @end example
11045
11046 @noindent
11047 leaving no way for her to reproduce what she used to do with @code{car}:
11048
11049 @example
11050 car([active])
11051 @result{}ACT, IVE
11052 @end example
11053
11054 @noindent
11055 Worse yet: she wants to use a macro that produces a set of @code{cpp}
11056 macros:
11057
11058 @example
11059 define([my_includes], [#include <stdio.h>])
11060 car([my_includes])
11061 @result{}#include <stdio.h>
11062 qar(my_includes)
11063 @error{}EOF in argument list
11064 @end example
11065
11066 This macro, @code{qar}, because it double quotes its arguments, forces
11067 its users to leave their macro calls unquoted, which is dangerous.
11068 Commas and other active symbols are interpreted by M4 before
11069 they are given to the macro, often not in the way the users expect.
11070 Also, because @code{qar} behaves differently from the other macros,
11071 it's an exception that should be avoided in Autoconf.
11072
11073 @node Changequote is Evil
11074 @subsection @code{changequote} is Evil
11075 @cindex @code{changequote}
11076
11077 The temptation is often high to bypass proper quotation, in particular
11078 when it's late at night. Then, many experienced Autoconf hackers
11079 finally surrender to the dark side of the force and use the ultimate
11080 weapon: @code{changequote}.
11081
11082 The M4 builtin @code{changequote} belongs to a set of primitives that
11083 allow one to adjust the syntax of the language to adjust it to one's
11084 needs. For instance, by default M4 uses @samp{`} and @samp{'} as
11085 quotes, but in the context of shell programming (and actually of most
11086 programming languages), that's about the worst choice one can make:
11087 because of strings and back-quoted expressions in shell code (such as
11088 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
11089 programming languages (as in @samp{'0'}), there are many unbalanced
11090 @samp{`} and @samp{'}. Proper M4 quotation then becomes a nightmare, if
11091 not impossible. In order to make M4 useful in such a context, its
11092 designers have equipped it with @code{changequote}, which makes it
11093 possible to choose another pair of quotes. M4sugar, M4sh, Autoconf, and
11094 Autotest all have chosen to use @samp{[} and @samp{]}. Not especially
11095 because they are unlikely characters, but @emph{because they are
11096 characters unlikely to be unbalanced}.
11097
11098 There are other magic primitives, such as @code{changecom} to specify
11099 what syntactic forms are comments (it is common to see
11100 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
11101 @code{changeword} and @code{changesyntax} to change other syntactic
11102 details (such as the character to denote the @var{n}th argument, @samp{$} by
11103 default, the parentheses around arguments, etc.).
11104
11105 These primitives are really meant to make M4 more useful for specific
11106 domains: they should be considered like command line options:
11107 @option{--quotes}, @option{--comments}, @option{--words}, and
11108 @option{--syntax}. Nevertheless, they are implemented as M4 builtins, as
11109 it makes M4 libraries self contained (no need for additional options).
11110
11111 There lies the problem@enddots{}
11112
11113 @sp 1
11114
11115 The problem is that it is then tempting to use them in the middle of an
11116 M4 script, as opposed to its initialization. This, if not carefully
11117 thought out, can lead to disastrous effects: @emph{you are changing the
11118 language in the middle of the execution}. Changing and restoring the
11119 syntax is often not enough: if you happened to invoke macros in between,
11120 these macros are lost, as the current syntax is probably not
11121 the one they were implemented with.
11122
11123 @c FIXME: I've been looking for a short, real case example, but I
11124 @c lost them all :(
11125
11126
11127 @node Quadrigraphs
11128 @subsection Quadrigraphs
11129 @cindex quadrigraphs
11130 @cindex @samp{@@S|@@}
11131 @cindex @samp{@@&t@@}
11132 @c Info cannot handle ':' in index entries.
11133 @ifnotinfo
11134 @cindex @samp{@@<:@@}
11135 @cindex @samp{@@:>@@}
11136 @cindex @samp{@@%:@@}
11137 @cindex @samp{@@@{:@@}
11138 @cindex @samp{@@:@}@@}
11139 @end ifnotinfo
11140
11141 When writing an Autoconf macro you may occasionally need to generate
11142 special characters that are difficult to express with the standard
11143 Autoconf quoting rules. For example, you may need to output the regular
11144 expression @samp{[^[]}, which matches any character other than @samp{[}.
11145 This expression contains unbalanced brackets so it cannot be put easily
11146 into an M4 macro.
11147
11148 Additionally, there are a few m4sugar macros (such as @code{m4_split}
11149 and @code{m4_expand}) which internally use special markers in addition
11150 to the regular quoting characters. If the arguments to these macros
11151 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
11152 might behave incorrectly.
11153
11154 You can work around these problems by using one of the following
11155 @dfn{quadrigraphs}:
11156
11157 @table @samp
11158 @item @@<:@@
11159 @samp{[}
11160 @item @@:>@@
11161 @samp{]}
11162 @item @@S|@@
11163 @samp{$}
11164 @item @@%:@@
11165 @samp{#}
11166 @item @@@{:@@
11167 @samp{(}
11168 @item @@:@}@@
11169 @samp{)}
11170 @item @@&t@@
11171 Expands to nothing.
11172 @end table
11173
11174 Quadrigraphs are replaced at a late stage of the translation process,
11175 after @command{m4} is run, so they do not get in the way of M4 quoting.
11176 For example, the string @samp{^@@<:@@}, independently of its quotation,
11177 appears as @samp{^[} in the output.
11178
11179 The empty quadrigraph can be used:
11180
11181 @itemize @minus
11182 @item to mark trailing spaces explicitly
11183
11184 Trailing spaces are smashed by @command{autom4te}. This is a feature.
11185
11186 @item to produce quadrigraphs and other strings reserved by m4sugar
11187
11188 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}. For a more
11189 contrived example:
11190
11191 @example
11192 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
11193 m4_split([a )@}>=- b -=<@{( c])
11194 @result{}[a], [], [B], [], [c]
11195 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
11196 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
11197 @end example
11198
11199 @item to escape @emph{occurrences} of forbidden patterns
11200
11201 For instance you might want to mention @code{AC_FOO} in a comment, while
11202 still being sure that @command{autom4te} still catches unexpanded
11203 @samp{AC_*}. Then write @samp{AC@@&t@@_FOO}.
11204 @end itemize
11205
11206 The name @samp{@@&t@@} was suggested by Paul Eggert:
11207
11208 @quotation
11209 I should give some credit to the @samp{@@&t@@} pun. The @samp{&} is my
11210 own invention, but the @samp{t} came from the source code of the
11211 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
11212 and which used @samp{mt} to denote the empty string. In C, it would
11213 have looked like something like:
11214
11215 @example
11216 char const mt[] = "";
11217 @end example
11218
11219 @noindent
11220 but of course the source code was written in Algol 68.
11221
11222 I don't know where he got @samp{mt} from: it could have been his own
11223 invention, and I suppose it could have been a common pun around the
11224 Cambridge University computer lab at the time.
11225 @end quotation
11226
11227
11228 @node Balancing Parentheses
11229 @subsection Dealing with unbalanced parentheses
11230 @cindex balancing parentheses
11231 @cindex parentheses, balancing
11232 @cindex unbalanced parentheses, managing
11233
11234 One of the pitfalls of portable shell programming is that
11235 if you intend your script to run with obsolescent shells,
11236 @command{case} statements require unbalanced parentheses.
11237 @xref{case, , Limitations of Shell Builtins}.
11238 With syntax highlighting
11239 editors, the presence of unbalanced @samp{)} can interfere with editors
11240 that perform syntax highlighting of macro contents based on finding the
11241 matching @samp{(}. Another concern is how much editing must be done
11242 when transferring code snippets between shell scripts and macro
11243 definitions. But most importantly, the presence of unbalanced
11244 parentheses can introduce expansion bugs.
11245
11246 For an example, here is an underquoted attempt to use the macro
11247 @code{my_case}, which happens to expand to a portable @command{case}
11248 statement:
11249
11250 @example
11251 AC_DEFUN([my_case],
11252 [case $file_name in
11253 *.c) file_type='C source code';;
11254 esac])
11255 AS_IF(:, my_case)
11256 @end example
11257
11258 @noindent
11259 In the above example, the @code{AS_IF} call under-quotes its arguments.
11260 As a result, the unbalanced @samp{)} generated by the premature
11261 expansion of @code{my_case} results in expanding @code{AS_IF} with a
11262 truncated parameter, and the expansion is syntactically invalid:
11263
11264 @example
11265 if :
11266 then :
11267 case $file_name in
11268 *.c
11269 fi file_type='C source code';;
11270 esac)
11271 @end example
11272
11273 If nothing else, this should emphasize the importance of the quoting
11274 arguments to macro calls. On the other hand, there are several
11275 variations for defining @code{my_case} to be more robust, even when used
11276 without proper quoting, each with some benefits and some drawbacks.
11277
11278 @itemize @w{}
11279 @item Use left parenthesis before pattern
11280 @example
11281 AC_DEFUN([my_case],
11282 [case $file_name in
11283 (*.c) file_type='C source code';;
11284 esac])
11285 @end example
11286 @noindent
11287 This is simple and provides balanced parentheses. Although this is not
11288 portable to obsolescent shells (notably Solaris 10 @command{/bin/sh}),
11289 platforms with these shells invariably have a more-modern shell
11290 available somewhere so this approach typically suffices nowadays.
11291
11292 @item Creative literal shell comment
11293 @example
11294 AC_DEFUN([my_case],
11295 [case $file_name in #(
11296 *.c) file_type='C source code';;
11297 esac])
11298 @end example
11299 @noindent
11300 This version provides balanced parentheses to several editors, and can
11301 be copied and pasted into a terminal as is. Unfortunately, it is still
11302 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
11303 that masks the normal properties of @samp{(}.
11304
11305 @item Quadrigraph shell comment
11306 @example
11307 AC_DEFUN([my_case],
11308 [case $file_name in @@%:@@(
11309 *.c) file_type='C source code';;
11310 esac])
11311 @end example
11312 @noindent
11313 This version provides balanced parentheses to even more editors, and can
11314 be used as a balanced Autoconf argument. Unfortunately, it requires
11315 some editing before it can be copied and pasted into a terminal, and the
11316 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
11317
11318 @item Quoting just the parenthesis
11319 @example
11320 AC_DEFUN([my_case],
11321 [case $file_name in
11322 *.c[)] file_type='C source code';;
11323 esac])
11324 @end example
11325 @noindent
11326 This version quotes the @samp{)}, so that it can be used as a balanced
11327 Autoconf argument. As written, this is not balanced to an editor, but
11328 it can be coupled with @samp{[#(]} to meet that need, too. However, it
11329 still requires some edits before it can be copied and pasted into a
11330 terminal.
11331
11332 @item Double-quoting the entire statement
11333 @example
11334 AC_DEFUN([my_case],
11335 [[case $file_name in #(
11336 *.c) file_type='C source code';;
11337 esac]])
11338 @end example
11339 @noindent
11340 Since the entire macro is double-quoted, there is no problem with using
11341 this as an Autoconf argument; and since the double-quoting is over the
11342 entire statement, this code can be easily copied and pasted into a
11343 terminal. However, the double quoting prevents the expansion of any
11344 macros inside the case statement, which may cause its own set of
11345 problems.
11346
11347 @item Using @code{AS_CASE}
11348 @example
11349 AC_DEFUN([my_case],
11350 [AS_CASE([$file_name],
11351 [*.c], [file_type='C source code'])])
11352 @end example
11353 @noindent
11354 This version avoids the balancing issue altogether, by relying on
11355 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
11356 expansion of @code{AC_REQUIRE} to occur prior to the entire case
11357 statement, rather than within a branch of the case statement that might
11358 not be taken. However, the abstraction comes with a penalty that it is
11359 no longer a quick copy, paste, and edit to get back to shell code.
11360 @end itemize
11361
11362
11363 @node Quotation Rule Of Thumb
11364 @subsection Quotation Rule Of Thumb
11365
11366 To conclude, the quotation rule of thumb is:
11367
11368 @center @emph{One pair of quotes per pair of parentheses.}
11369
11370 Never over-quote, never under-quote, in particular in the definition of
11371 macros. In the few places where the macros need to use brackets
11372 (usually in C program text or regular expressions), properly quote
11373 @emph{the arguments}!
11374
11375 It is common to read Autoconf programs with snippets like:
11376
11377 @example
11378 AC_TRY_LINK(
11379 changequote(<<, >>)dnl
11380 <<#include <time.h>
11381 #ifndef tzname /* For SGI. */
11382 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
11383 #endif>>,
11384 changequote([, ])dnl
11385 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11386 @end example
11387
11388 @noindent
11389 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11390 double quoting, so you just need:
11391
11392 @example
11393 AC_TRY_LINK(
11394 [#include <time.h>
11395 #ifndef tzname /* For SGI. */
11396 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
11397 #endif],
11398 [atoi (*tzname);],
11399 [ac_cv_var_tzname=yes],
11400 [ac_cv_var_tzname=no])
11401 @end example
11402
11403 @noindent
11404 The M4-fluent reader might note that these two examples are rigorously
11405 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11406 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11407 quotes are not part of the arguments!
11408
11409 Simplified, the example above is just doing this:
11410
11411 @example
11412 changequote(<<, >>)dnl
11413 <<[]>>
11414 changequote([, ])dnl
11415 @end example
11416
11417 @noindent
11418 instead of simply:
11419
11420 @example
11421 [[]]
11422 @end example
11423
11424 With macros that do not double quote their arguments (which is the
11425 rule), double-quote the (risky) literals:
11426
11427 @example
11428 AC_LINK_IFELSE([AC_LANG_PROGRAM(
11429 [[#include <time.h>
11430 #ifndef tzname /* For SGI. */
11431 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
11432 #endif]],
11433 [atoi (*tzname);])],
11434 [ac_cv_var_tzname=yes],
11435 [ac_cv_var_tzname=no])
11436 @end example
11437
11438 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11439 should be using @code{AC_LINK_IFELSE} instead.
11440
11441 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
11442 where quoting does not suffice.
11443
11444 When you create a @command{configure} script using newly written macros,
11445 examine it carefully to check whether you need to add more quotes in
11446 your macros. If one or more words have disappeared in the M4
11447 output, you need more quotes. When in doubt, quote.
11448
11449 However, it's also possible to put on too many layers of quotes. If
11450 this happens, the resulting @command{configure} script may contain
11451 unexpanded macros. The @command{autoconf} program checks for this problem
11452 by looking for the string @samp{AC_} in @file{configure}. However, this
11453 heuristic does not work in general: for example, it does not catch
11454 overquoting in @code{AC_DEFINE} descriptions.
11455
11456
11457 @c ---------------------------------------- Using autom4te
11458
11459 @node Using autom4te
11460 @section Using @command{autom4te}
11461
11462 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11463 to Autoconf per se, heavily rely on M4. All these different uses
11464 revealed common needs factored into a layer over M4:
11465 @command{autom4te}@footnote{
11466 @c
11467 Yet another great name from Lars J. Aas.
11468 @c
11469 }.
11470
11471 @command{autom4te} is a preprocessor that is like @command{m4}.
11472 It supports M4 extensions designed for use in tools like Autoconf.
11473
11474 @menu
11475 * autom4te Invocation:: A GNU M4 wrapper
11476 * Customizing autom4te:: Customizing the Autoconf package
11477 @end menu
11478
11479 @node autom4te Invocation
11480 @subsection Invoking @command{autom4te}
11481
11482 The command line arguments are modeled after M4's:
11483
11484 @example
11485 autom4te @var{options} @var{files}
11486 @end example
11487
11488 @noindent
11489 @evindex M4
11490 where the @var{files} are directly passed to @command{m4}. By default,
11491 GNU M4 is found during configuration, but the environment
11492 variable
11493 @env{M4} can be set to tell @command{autom4te} where to look. In addition
11494 to the regular expansion, it handles the replacement of the quadrigraphs
11495 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11496 output. It supports an extended syntax for the @var{files}:
11497
11498 @table @file
11499 @item @var{file}.m4f
11500 This file is an M4 frozen file. Note that @emph{all the previous files
11501 are ignored}. See the @option{--melt} option for the rationale.
11502
11503 @item @var{file}?
11504 If found in the library path, the @var{file} is included for expansion,
11505 otherwise it is ignored instead of triggering a failure.
11506 @end table
11507
11508 @sp 1
11509
11510 Of course, it supports the Autoconf common subset of options:
11511
11512 @table @option
11513 @item --help
11514 @itemx -h
11515 Print a summary of the command line options and exit.
11516
11517 @item --version
11518 @itemx -V
11519 Print the version number of Autoconf and exit.
11520
11521 @item --verbose
11522 @itemx -v
11523 Report processing steps.
11524
11525 @item --debug
11526 @itemx -d
11527 Don't remove the temporary files and be even more verbose.
11528
11529 @item --include=@var{dir}
11530 @itemx -I @var{dir}
11531 Also look for input files in @var{dir}. Multiple invocations
11532 accumulate.
11533
11534 @item --output=@var{file}
11535 @itemx -o @var{file}
11536 Save output (script or trace) to @var{file}. The file @option{-} stands
11537 for the standard output.
11538 @end table
11539
11540 @sp 1
11541
11542 As an extension of @command{m4}, it includes the following options:
11543
11544 @table @option
11545
11546 @item --warnings=@var{category}[,@var{category}...]
11547 @itemx -W@var{category}[,@var{category}...]
11548 @evindex WARNINGS
11549 Enable or disable warnings related to each @var{category}.
11550 @xref{m4_warn}, for a comprehensive list of categories.
11551 Special values include:
11552
11553 @table @samp
11554 @item all
11555 Enable all categories of warnings.
11556
11557 @item none
11558 Disable all categories of warnings.
11559
11560 @item error
11561 Treat all warnings as errors.
11562
11563 @item no-@var{category}
11564 Disable warnings falling into @var{category}.
11565 @end table
11566
11567 The environment variable @env{WARNINGS} may also be set to a
11568 comma-separated list of warning categories to enable or disable.
11569 It is interpreted exactly the same way as the argument of
11570 @option{--warnings}, but unknown categories are silently ignored.
11571 The command line takes precedence; for instance, if @env{WARNINGS}
11572 is set to @code{obsolete}, but @option{-Wnone} is given on the
11573 command line, no warnings will be issued.
11574
11575 Some categories of warnings are on by default.
11576 Again, for details see @ref{m4_warn}.
11577
11578 @item --melt
11579 @itemx -M
11580 Do not use frozen files. Any argument @code{@var{file}.m4f} is
11581 replaced by @code{@var{file}.m4}. This helps tracing the macros which
11582 are executed only when the files are frozen, typically
11583 @code{m4_define}. For instance, running:
11584
11585 @example
11586 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11587 @end example
11588
11589 @noindent
11590 is roughly equivalent to running:
11591
11592 @example
11593 m4 1.m4 2.m4 3.m4 4.m4 input.m4
11594 @end example
11595
11596 @noindent
11597 while
11598
11599 @example
11600 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11601 @end example
11602
11603 @noindent
11604 is equivalent to:
11605
11606 @example
11607 m4 --reload-state=4.m4f input.m4
11608 @end example
11609
11610 @item --freeze
11611 @itemx -F
11612 Produce a frozen state file. @command{autom4te} freezing is stricter
11613 than M4's: it must produce no warnings, and no output other than empty
11614 lines (a line with white space is @emph{not} empty) and comments
11615 (starting with @samp{#}). Unlike @command{m4}'s similarly-named option,
11616 this option takes no argument:
11617
11618 @example
11619 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11620 @end example
11621
11622 @noindent
11623 corresponds to
11624
11625 @example
11626 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11627 @end example
11628
11629 @item --mode=@var{octal-mode}
11630 @itemx -m @var{octal-mode}
11631 Set the mode of the non-traces output to @var{octal-mode}; by default
11632 @samp{0666}.
11633 @end table
11634
11635 @sp 1
11636
11637 @cindex @file{autom4te.cache}
11638 As another additional feature over @command{m4}, @command{autom4te}
11639 caches its results. GNU M4 is able to produce a regular
11640 output and traces at the same time. Traces are heavily used in the
11641 GNU Build System: @command{autoheader} uses them to build
11642 @file{config.h.in}, @command{autoreconf} to determine what
11643 GNU Build System components are used, @command{automake} to
11644 ``parse'' @file{configure.ac} etc. To avoid recomputation,
11645 traces are cached while performing regular expansion,
11646 and conversely. This cache is (actually, the caches are) stored in
11647 the directory @file{autom4te.cache}. @emph{It can safely be removed}
11648 at any moment (especially if for some reason @command{autom4te}
11649 considers it trashed).
11650
11651 @table @option
11652 @item --cache=@var{directory}
11653 @itemx -C @var{directory}
11654 Specify the name of the directory where the result should be cached.
11655 Passing an empty value disables caching. Be sure to pass a relative
11656 file name, as for the time being, global caches are not supported.
11657
11658 @item --no-cache
11659 Don't cache the results.
11660
11661 @item --force
11662 @itemx -f
11663 If a cache is used, consider it obsolete (but update it anyway).
11664 @end table
11665
11666 @sp 1
11667
11668 Because traces are so important to the GNU Build System,
11669 @command{autom4te} provides high level tracing features as compared to
11670 M4, and helps exploiting the cache:
11671
11672 @table @option
11673 @item --trace=@var{macro}[:@var{format}]
11674 @itemx -t @var{macro}[:@var{format}]
11675 Trace the invocations of @var{macro} according to the @var{format}.
11676 Multiple @option{--trace} arguments can be used to list several macros.
11677 Multiple @option{--trace} arguments for a single macro are not
11678 cumulative; instead, you should just make @var{format} as long as
11679 needed.
11680
11681 The @var{format} is a regular string, with newlines if desired, and
11682 several special escape codes. It defaults to @samp{$f:$l:$n:$%}. It can
11683 use the following special escapes:
11684
11685 @table @samp
11686 @item $$
11687 @c $$ restore font-lock
11688 The character @samp{$}.
11689
11690 @item $f
11691 The file name from which @var{macro} is called.
11692
11693 @item $l
11694 The line number from which @var{macro} is called.
11695
11696 @item $d
11697 The depth of the @var{macro} call. This is an M4 technical detail that
11698 you probably don't want to know about.
11699
11700 @item $n
11701 The name of the @var{macro}.
11702
11703 @item $@var{num}
11704 The @var{num}th argument of the call to @var{macro}.
11705
11706 @item $@@
11707 @itemx $@var{sep}@@
11708 @itemx $@{@var{separator}@}@@
11709 All the arguments passed to @var{macro}, separated by the character
11710 @var{sep} or the string @var{separator} (@samp{,} by default). Each
11711 argument is quoted, i.e., enclosed in a pair of square brackets.
11712
11713 @item $*
11714 @itemx $@var{sep}*
11715 @itemx $@{@var{separator}@}*
11716 As above, but the arguments are not quoted.
11717
11718 @item $%
11719 @itemx $@var{sep}%
11720 @itemx $@{@var{separator}@}%
11721 As above, but the arguments are not quoted, all new line characters in
11722 the arguments are smashed, and the default separator is @samp{:}.
11723
11724 The escape @samp{$%} produces single-line trace outputs (unless you put
11725 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11726 not.
11727 @end table
11728
11729 @xref{autoconf Invocation}, for examples of trace uses.
11730
11731 @item --preselect=@var{macro}
11732 @itemx -p @var{macro}
11733 Cache the traces of @var{macro}, but do not enable traces. This is
11734 especially important to save CPU cycles in the future. For instance,
11735 when invoked, @command{autoconf} pre-selects all the macros that
11736 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11737 trace, so that running @command{m4} is not needed to trace them: the
11738 cache suffices. This results in a huge speed-up.
11739 @end table
11740
11741 @sp 1
11742
11743 @cindex Autom4te Library
11744 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11745 libraries}. They consists in a powerful yet extremely simple feature:
11746 sets of combined command line arguments:
11747
11748 @table @option
11749 @item --language=@var{language}
11750 @itemx -l @var{language}
11751 Use the @var{language} Autom4te library. Current languages include:
11752
11753 @table @code
11754 @item M4sugar
11755 create M4sugar output.
11756
11757 @item M4sh
11758 create M4sh executable shell scripts.
11759
11760 @item Autotest
11761 create Autotest executable test suites.
11762
11763 @item Autoconf-without-aclocal-m4
11764 create Autoconf executable configure scripts without
11765 reading @file{aclocal.m4}.
11766
11767 @item Autoconf
11768 create Autoconf executable configure scripts. This language inherits
11769 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11770 additionally reads @file{aclocal.m4}.
11771 @end table
11772
11773 @item --prepend-include=@var{dir}
11774 @itemx -B @var{dir}
11775 Prepend directory @var{dir} to the search path. This is used to include
11776 the language-specific files before any third-party macros.
11777
11778 @end table
11779
11780 @cindex @file{autom4te.cfg}
11781 As an example, if Autoconf is installed in its default location,
11782 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11783 strictly equivalent to the command:
11784
11785 @example
11786 autom4te --prepend-include /usr/local/share/autoconf \
11787 m4sugar/m4sugar.m4f foo.m4
11788 @end example
11789
11790 @noindent
11791 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11792 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11793 foo.m4}, i.e.:
11794
11795 @example
11796 autom4te --prepend-include /usr/local/share/autoconf \
11797 m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11798 @end example
11799
11800 @noindent
11801 The definition of the languages is stored in @file{autom4te.cfg}.
11802
11803 @node Customizing autom4te
11804 @subsection Customizing @command{autom4te}
11805
11806 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11807 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11808 as found in the directory from which @command{autom4te} is run). The
11809 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11810 then @file{./.autom4te.cfg}, and finally the command line arguments.
11811
11812 In these text files, comments are introduced with @code{#}, and empty
11813 lines are ignored. Customization is performed on a per-language basis,
11814 wrapped in between a @samp{begin-language: "@var{language}"},
11815 @samp{end-language: "@var{language}"} pair.
11816
11817 Customizing a language stands for appending options (@pxref{autom4te
11818 Invocation}) to the current definition of the language. Options, and
11819 more generally arguments, are introduced by @samp{args:
11820 @var{arguments}}. You may use the traditional shell syntax to quote the
11821 @var{arguments}.
11822
11823 As an example, to disable Autoconf caches (@file{autom4te.cache})
11824 globally, include the following lines in @file{~/.autom4te.cfg}:
11825
11826 @verbatim
11827 ## ------------------ ##
11828 ## User Preferences. ##
11829 ## ------------------ ##
11830
11831 begin-language: "Autoconf-without-aclocal-m4"
11832 args: --no-cache
11833 end-language: "Autoconf-without-aclocal-m4"
11834 @end verbatim
11835
11836
11837 @node Programming in M4sugar
11838 @section Programming in M4sugar
11839
11840 @cindex M4sugar
11841 M4 by itself provides only a small, but sufficient, set of all-purpose
11842 macros. M4sugar introduces additional generic macros. Its name was
11843 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11844 M4sugar''.
11845
11846 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11847 the macro namespace @samp{^m4_} for M4sugar macros. You should not
11848 define your own macros into these namespaces.
11849
11850 @menu
11851 * Redefined M4 Macros:: M4 builtins changed in M4sugar
11852 * Diagnostic Macros:: Diagnostic messages from M4sugar
11853 * Diversion support:: Diversions in M4sugar
11854 * Conditional constructs:: Conditions in M4
11855 * Looping constructs:: Iteration in M4
11856 * Evaluation Macros:: More quotation and evaluation control
11857 * Text processing Macros:: String manipulation in M4
11858 * Number processing Macros:: Arithmetic computation in M4
11859 * Set manipulation Macros:: Set manipulation in M4
11860 * Forbidden Patterns:: Catching unexpanded macros
11861 @end menu
11862
11863 @node Redefined M4 Macros
11864 @subsection Redefined M4 Macros
11865
11866 @msindex{builtin}
11867 @msindex{changecom}
11868 @msindex{changequote}
11869 @msindex{debugfile}
11870 @msindex{debugmode}
11871 @msindex{decr}
11872 @msindex{define}
11873 @msindex{divnum}
11874 @msindex{errprint}
11875 @msindex{esyscmd}
11876 @msindex{eval}
11877 @msindex{format}
11878 @msindex{ifdef}
11879 @msindex{incr}
11880 @msindex{index}
11881 @msindex{indir}
11882 @msindex{len}
11883 @msindex{pushdef}
11884 @msindex{shift}
11885 @msindex{substr}
11886 @msindex{syscmd}
11887 @msindex{sysval}
11888 @msindex{traceoff}
11889 @msindex{traceon}
11890 @msindex{translit}
11891 With a few exceptions, all the M4 native macros are moved in the
11892 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11893 @code{m4_define} etc.
11894
11895 The list of macros unchanged from M4, except for their name, is:
11896 @itemize @minus
11897 @item m4_builtin
11898 @item m4_changecom
11899 @item m4_changequote
11900 @item m4_debugfile
11901 @item m4_debugmode
11902 @item m4_decr
11903 @item m4_define
11904 @item m4_divnum
11905 @item m4_errprint
11906 @item m4_esyscmd
11907 @item m4_eval
11908 @item m4_format
11909 @item m4_ifdef
11910 @item m4_incr
11911 @item m4_index
11912 @item m4_indir
11913 @item m4_len
11914 @item m4_pushdef
11915 @item m4_shift
11916 @item m4_substr
11917 @item m4_syscmd
11918 @item m4_sysval
11919 @item m4_traceoff
11920 @item m4_traceon
11921 @item m4_translit
11922 @end itemize
11923
11924 Some M4 macros are redefined, and are slightly incompatible with their
11925 native equivalent.
11926
11927 @defmac __file__
11928 @defmacx __line__
11929 @MSindex __file__
11930 @MSindex __line__
11931 All M4 macros starting with @samp{__} retain their original name: for
11932 example, no @code{m4__file__} is defined.
11933 @end defmac
11934
11935 @defmac __oline__
11936 @MSindex __oline__
11937 This is not technically a macro, but a feature of Autom4te. The
11938 sequence @code{__oline__} can be used similarly to the other m4sugar
11939 location macros, but rather than expanding to the location of the input
11940 file, it is translated to the line number where it appears in the output
11941 file after all other M4 expansions.
11942 @end defmac
11943
11944 @defmac dnl
11945 @MSindex dnl
11946 This macro kept its original name: no @code{m4_dnl} is defined.
11947 @end defmac
11948
11949 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11950 @msindex{bpatsubst}
11951 @anchor{m4_bpatsubst}
11952 This is the M4sugar name for the M4 native macro @code{patsubst}.
11953
11954 It uses the same regular expression syntax as @code{m4_bregexp}; see
11955 @ref{m4_bregexp}. Also see @ref{Patsubst,,Substituting text by regular
11956 expression,m4,GNU m4 macro processor}, for details of how the
11957 @var{replacement} is processed.
11958
11959 The name @code{m4_patsubst} is reserved for use by a future version of
11960 M4sugar, when there is a version of GNU M4 that supports POSIX extended
11961 regular expression syntax.
11962 @end defmac
11963
11964 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11965 @msindex{bregexp}
11966 @anchor{m4_bregexp}
11967 This is the M4sugar name for the M4 native macro @code{regexp}.
11968
11969 The only regular expression syntax understood by GNU M4 is similar to,
11970 but not the same as, POSIX basic regular expression syntax.
11971 @xref{Regexp,,Searching for regular expressions,m4,GNU m4 macro
11972 processor}, for the precise syntax.
11973
11974 The name @code{m4_regexp} is reserved for use by a future version of
11975 M4sugar, when there is a version of GNU M4 that supports POSIX extended
11976 regular expression syntax.
11977 @end defmac
11978
11979 @defmac m4_copy (@var{source}, @var{dest})
11980 @defmacx m4_copy_force (@var{source}, @var{dest})
11981 @defmacx m4_rename (@var{source}, @var{dest})
11982 @defmacx m4_rename_force (@var{source}, @var{dest})
11983 @msindex{copy}
11984 @msindex{copy_force}
11985 @msindex{rename}
11986 @msindex{rename_force}
11987 These macros aren't directly builtins, but are closely related to
11988 @code{m4_pushdef} and @code{m4_defn}. @code{m4_copy} and
11989 @code{m4_rename} ensure that @var{dest} is undefined, while
11990 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11991 definition. All four macros then proceed to copy the entire pushdef
11992 stack of definitions of @var{source} over to @var{dest}. @code{m4_copy}
11993 and @code{m4_copy_force} preserve the source (including in the special
11994 case where @var{source} is undefined), while @code{m4_rename} and
11995 @code{m4_rename_force} undefine the original macro name (making it an
11996 error to rename an undefined @var{source}).
11997
11998 Note that attempting to invoke a renamed macro might not work, since the
11999 macro may have a dependence on helper macros accessed via composition of
12000 @samp{$0} but that were not also renamed; likewise, other macros may
12001 have a hard-coded dependence on @var{source} and could break if
12002 @var{source} has been deleted. On the other hand, it is always safe to
12003 rename a macro to temporarily move it out of the way, then rename it
12004 back later to restore original semantics.
12005 @end defmac
12006
12007 @defmac m4_defn (@var{macro}@dots{})
12008 @msindex{defn}
12009 This macro fails if @var{macro} is not defined, even when using older
12010 versions of M4 that did not warn. See @code{m4_undefine}.
12011 Unfortunately, in order to support these older versions of M4, there are
12012 some situations involving unbalanced quotes where concatenating multiple
12013 macros together will work in newer M4 but not in m4sugar; use
12014 quadrigraphs to work around this.
12015 @end defmac
12016
12017 @defmac m4_divert (@var{diversion})
12018 @msindex{divert}
12019 M4sugar relies heavily on diversions, so rather than behaving as a
12020 primitive, @code{m4_divert} behaves like:
12021 @example
12022 m4_divert_pop()m4_divert_push([@var{diversion}])
12023 @end example
12024 @noindent
12025 @xref{Diversion support}, for more details about the use of the
12026 diversion stack. In particular, this implies that @var{diversion}
12027 should be a named diversion rather than a raw number. But be aware that
12028 it is seldom necessary to explicitly change the diversion stack, and
12029 that when done incorrectly, it can lead to syntactically invalid
12030 scripts.
12031 @end defmac
12032
12033 @defmac m4_dumpdef (@var{name}@dots{})
12034 @defmacx m4_dumpdefs (@var{name}@dots{})
12035 @msindex{dumpdef}
12036 @msindex{dumpdefs}
12037 @code{m4_dumpdef} is like the M4 builtin, except that this version
12038 requires at least one argument, output always goes to standard error
12039 rather than the current debug file, no sorting is done on multiple
12040 arguments, and an error is issued if any
12041 @var{name} is undefined. @code{m4_dumpdefs} is a convenience macro that
12042 calls @code{m4_dumpdef} for all of the
12043 @code{m4_pushdef} stack of definitions, starting with the current, and
12044 silently does nothing if @var{name} is undefined.
12045
12046 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
12047 builtin is output as the empty string. This behavior is rectified by
12048 using M4 1.6 or newer. However, this behavior difference means that
12049 @code{m4_dumpdef} should only be used while developing m4sugar macros,
12050 and never in the final published form of a macro.
12051 @end defmac
12052
12053 @defmac m4_esyscmd_s (@var{command})
12054 @msindex{esyscmd_s}
12055 Like @code{m4_esyscmd}, this macro expands to the result of running
12056 @var{command} in a shell. The difference is that any trailing newlines
12057 are removed, so that the output behaves more like shell command
12058 substitution.
12059 @end defmac
12060
12061 @defmac m4_exit (@var{exit-status})
12062 @msindex{exit}
12063 This macro corresponds to @code{m4exit}.
12064 @end defmac
12065
12066 @defmac m4_if (@var{comment})
12067 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
12068 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
12069 @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
12070 @msindex{if}
12071 This macro corresponds to @code{ifelse}. @var{string-1} and
12072 @var{string-2} are compared literally, so usually one of the two
12073 arguments is passed unquoted. @xref{Conditional constructs}, for more
12074 conditional idioms.
12075 @end defmac
12076
12077 @defmac m4_include (@var{file})
12078 @defmacx m4_sinclude (@var{file})
12079 @msindex{include}
12080 @msindex{sinclude}
12081 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
12082 @end defmac
12083
12084 @defmac m4_mkstemp (@var{template})
12085 @defmacx m4_maketemp (@var{template})
12086 @msindex{maketemp}
12087 @msindex{mkstemp}
12088 Older versions of POSIX specified a macro @code{maketemp},
12089 which replaced the trailing @samp{X}
12090 characters in @var{template} with the process id, without regards to the
12091 existence of a file by that name.
12092 This was a security hole, so current POSIX instead specifies a macro
12093 @code{mkstemp} that always creates a uniquely named file. In M4sugar,
12094 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
12095 and both have the secure semantics regardless of which macro the
12096 underlying M4 provides.
12097 @end defmac
12098
12099 @defmac m4_popdef (@var{macro}@dots{})
12100 @msindex{popdef}
12101 This macro fails if @var{macro} is not defined, even when using older
12102 versions of M4 that did not warn. See @code{m4_undefine}.
12103 @end defmac
12104
12105 @defmac m4_undefine (@var{macro}@dots{})
12106 @msindex{undefine}
12107 This macro fails if @var{macro} is not defined, even when using older
12108 versions of M4 that did not warn. Use
12109
12110 @example
12111 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
12112 @end example
12113
12114 @noindent
12115 if you are not sure whether @var{macro} is defined.
12116 @end defmac
12117
12118 @defmac m4_undivert (@var{diversion}@dots{})
12119 @msindex{undivert}
12120 Unlike the M4 builtin, at least one @var{diversion} must be specified.
12121 Also, since the M4sugar diversion stack prefers named
12122 diversions, the use of @code{m4_undivert} to include files is risky.
12123 @xref{Diversion support}, for more details about the use of the
12124 diversion stack. But be aware that it is seldom necessary to explicitly
12125 change the diversion stack, and that when done incorrectly, it can lead
12126 to syntactically invalid scripts.
12127 @end defmac
12128
12129 @defmac m4_wrap (@var{text})
12130 @defmacx m4_wrap_lifo (@var{text})
12131 @msindex{wrap}
12132 @msindex{wrap_lifo}
12133 These macros correspond to @code{m4wrap}. POSIX requires arguments of
12134 multiple wrap calls to be reprocessed at EOF in the same order
12135 as the original calls (first-in, first-out). GNU M4 versions
12136 through 1.4.10, however, reprocess them in reverse order (last-in,
12137 first-out). Both orders are useful, therefore, you can rely on
12138 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
12139 LIFO semantics, regardless of the underlying GNU M4 version.
12140
12141 Unlike the GNU M4 builtin, these macros only recognize one
12142 argument, and avoid token pasting between consecutive invocations. On
12143 the other hand, nested calls to @code{m4_wrap} from within wrapped text
12144 work just as in the builtin.
12145 @end defmac
12146
12147
12148 @node Diagnostic Macros
12149 @subsection Diagnostic messages from M4sugar
12150 @cindex Messages, from @command{M4sugar}
12151
12152 When macros statically diagnose abnormal situations, benign or fatal,
12153 they should report them using these macros. For issuing dynamic issues,
12154 i.e., when @command{configure} is run, see @ref{Printing Messages}.
12155
12156 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
12157 @msindex{assert}
12158 Assert that the arithmetic @var{expression} evaluates to non-zero.
12159 Otherwise, issue a fatal error, and exit @command{autom4te} with
12160 @var{exit-status}.
12161 @end defmac
12162
12163 @defmac m4_errprintn (@var{message})
12164 @msindex{errprintn}
12165 Similar to the builtin @code{m4_errprint}, except that a newline is
12166 guaranteed after @var{message}.
12167 @end defmac
12168
12169 @anchor{m4_fatal}
12170 @defmac m4_fatal (@var{message})
12171 @msindex{fatal}
12172 Report a severe error @var{message} prefixed with the current location,
12173 and have @command{autom4te} die.
12174 @end defmac
12175
12176 @defmac m4_location
12177 @msindex{location}
12178 Useful as a prefix in a message line. Short for:
12179 @example
12180 __file__:__line__
12181 @end example
12182 @end defmac
12183
12184 @anchor{m4_warn}
12185 @defmac m4_warn (@var{category}, @var{message})
12186 @msindex{warn}
12187 Report @var{message} as a warning (or as an error if requested by the
12188 user) if warnings of the @var{category} are turned on. If the message
12189 is emitted, it is prefixed with the current location, and followed by a
12190 call trace of all macros defined via @code{AC_DEFUN} used to get to the
12191 current expansion.
12192
12193 The @var{category} must be one of:
12194
12195 @table @samp
12196 @item cross
12197 Warnings about constructs that may interfere with cross-compilation,
12198 such as using @code{AC_RUN_IFELSE} without a default.
12199
12200 @item gnu
12201 Warnings related to the GNU Coding Standards
12202 (@pxref{Top,,, standards, The GNU Coding Standards}).
12203 On by default.
12204
12205 @item obsolete
12206 Warnings about obsolete features. On by default.
12207
12208 @item override
12209 Warnings about redefinitions of Autoconf internals.
12210
12211 @item portability
12212 Warnings about non-portable constructs.
12213
12214 @item portability-recursive
12215 Warnings about recursive Make variable expansions (@code{$(foo$(x))}).
12216
12217 @item extra-portability
12218 Extra warnings about non-portable constructs, covering rarely-used
12219 tools.
12220
12221 @item syntax
12222 Warnings about questionable syntactic constructs, incorrectly ordered
12223 macro calls, typos, etc. On by default.
12224
12225 @item unsupported
12226 Warnings about unsupported features. On by default.
12227 @end table
12228
12229 @strong{Hacking Note:} The set of categories is defined by code in
12230 @command{autom4te}, not by M4sugar itself. Additions should be
12231 coordinated with Automake, so that both sets of tools accept the same
12232 options.
12233 @end defmac
12234
12235 @node Diversion support
12236 @subsection Diversion support
12237
12238 M4sugar makes heavy use of diversions under the hood, because it is
12239 often the case that
12240 text that must appear early in the output is not discovered until late
12241 in the input. Additionally, some of the topological sorting algorithms
12242 used in resolving macro dependencies use diversions. However, most
12243 macros should not need to change diversions directly, but rather rely on
12244 higher-level M4sugar macros to manage diversions transparently. If you
12245 change diversions improperly, you risk generating a syntactically
12246 invalid script, because an incorrect diversion will violate assumptions
12247 made by many macros about whether prerequisite text has been previously
12248 output. In short, if you manually change the diversion, you should not
12249 expect any macros provided by the Autoconf package to work until you
12250 have restored the diversion stack back to its original state.
12251
12252 In the rare case that it is necessary to write a macro that explicitly
12253 outputs text to a different diversion, it is important to be aware of an
12254 M4 limitation regarding diversions: text only goes to a diversion if it
12255 is not part of argument collection. Therefore, any macro that changes
12256 the current diversion cannot be used as an unquoted argument to another
12257 macro, but must be expanded at the top level. The macro
12258 @code{m4_expand} will diagnose any attempt to change diversions, since
12259 it is generally useful only as an argument to another macro. The
12260 following example shows what happens when diversion manipulation is
12261 attempted within macro arguments:
12262
12263 @example
12264 m4_do([normal text]
12265 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
12266 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
12267 @result{}normal text
12268 @result{}unwanted
12269 @end example
12270
12271 @noindent
12272 Notice that the unquoted text @code{unwanted} is output, even though it
12273 was processed while the current diversion was @code{KILL}, because it
12274 was collected as part of the argument to @code{m4_do}. However, the
12275 text @code{discarded} disappeared as desired, because the diversion
12276 changes were single-quoted, and were not expanded until the top-level
12277 rescan of the output of @code{m4_do}.
12278
12279 To make diversion management easier, M4sugar uses the concept of named
12280 diversions. Rather than using diversion numbers directly, it is nicer
12281 to associate a name with each diversion. The diversion number associated
12282 with a particular diversion name is an implementation detail, and a
12283 syntax warning is issued if a diversion number is used instead of a
12284 name. In general, you should not output text
12285 to a named diversion until after calling the appropriate initialization
12286 routine for your language (@code{m4_init}, @code{AS_INIT},
12287 @code{AT_INIT}, @dots{}), although there are some exceptions documented
12288 below.
12289
12290 M4sugar defines two named diversions.
12291 @table @code
12292 @item KILL
12293 Text written to this diversion is discarded. This is the default
12294 diversion once M4sugar is initialized.
12295 @item GROW
12296 This diversion is used behind the scenes by topological sorting macros,
12297 such as @code{AC_REQUIRE}.
12298 @end table
12299
12300 M4sh adds several more named diversions.
12301 @table @code
12302 @item BINSH
12303 This diversion is reserved for the @samp{#!} interpreter line.
12304 @item HEADER-REVISION
12305 This diversion holds text from @code{AC_REVISION}.
12306 @item HEADER-COMMENT
12307 This diversion holds comments about the purpose of a file.
12308 @item HEADER-COPYRIGHT
12309 This diversion is managed by @code{AC_COPYRIGHT}.
12310 @item M4SH-SANITIZE
12311 This diversion contains M4sh sanitization code, used to ensure M4sh is
12312 executing in a reasonable shell environment.
12313 @item M4SH-INIT
12314 This diversion contains M4sh initialization code, initializing variables
12315 that are required by other M4sh macros.
12316 @item BODY
12317 This diversion contains the body of the shell code, and is the default
12318 diversion once M4sh is initialized.
12319 @end table
12320
12321 Autotest inherits diversions from M4sh, and changes the default
12322 diversion from @code{BODY} back to @code{KILL}. It also adds several
12323 more named diversions, with the following subset designed for developer
12324 use.
12325 @table @code
12326 @item PREPARE_TESTS
12327 This diversion contains initialization sequences which are executed
12328 after @file{atconfig} and @file{atlocal}, and after all command line
12329 arguments have been parsed, but prior to running any tests. It can be
12330 used to set up state that is required across all tests. This diversion
12331 will work even before @code{AT_INIT}.
12332 @end table
12333
12334 Autoconf inherits diversions from M4sh, and adds the following named
12335 diversions which developers can utilize.
12336 @table @code
12337 @item DEFAULTS
12338 This diversion contains shell variable assignments to set defaults that
12339 must be in place before arguments are parsed. This diversion is placed
12340 early enough in @file{configure} that it is unsafe to expand any
12341 autoconf macros into this diversion.
12342 @item HELP_ENABLE
12343 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
12344 diversion will be included as part of a quoted here-doc providing all of
12345 the @option{--help} output of @file{configure} related to options
12346 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
12347 @item INIT_PREPARE
12348 This diversion occurs after all command line options have been parsed,
12349 but prior to the main body of the @file{configure} script. This
12350 diversion is the last chance to insert shell code such as variable
12351 assignments or shell function declarations that will used by the
12352 expansion of other macros.
12353 @end table
12354
12355 For now, the remaining named diversions of Autoconf, Autoheader, and
12356 Autotest are not documented. In other words,
12357 intentionally outputting text into an undocumented diversion is subject
12358 to breakage in a future release of Autoconf.
12359
12360 @defmac m4_cleardivert (@var{diversion}@dots{})
12361 @msindex{cleardivert}
12362 Permanently discard any text that has been diverted into
12363 @var{diversion}.
12364 @end defmac
12365
12366 @defmac m4_divert_once (@var{diversion}, @ovar{content})
12367 @msindex{divert_once}
12368 Similar to @code{m4_divert_text}, except that @var{content} is only
12369 output to @var{diversion} if this is the first time that
12370 @code{m4_divert_once} has been called with its particular arguments.
12371 @end defmac
12372
12373 @defmac m4_divert_pop (@ovar{diversion})
12374 @msindex{divert_pop}
12375 If provided, check that the current diversion is indeed @var{diversion}.
12376 Then change to the diversion located earlier on the stack, giving an
12377 error if an attempt is made to pop beyond the initial m4sugar diversion
12378 of @code{KILL}.
12379 @end defmac
12380
12381 @defmac m4_divert_push (@var{diversion})
12382 @msindex{divert_push}
12383 Remember the former diversion on the diversion stack, and output
12384 subsequent text into @var{diversion}. M4sugar maintains a diversion
12385 stack, and issues an error if there is not a matching pop for every
12386 push.
12387 @end defmac
12388
12389 @anchor{m4_divert_text}
12390 @defmac m4_divert_text (@var{diversion}, @ovar{content})
12391 @msindex{divert_text}
12392 Output @var{content} and a newline into @var{diversion}, without
12393 affecting the current diversion. Shorthand for:
12394 @example
12395 m4_divert_push([@var{diversion}])@var{content}
12396 m4_divert_pop([@var{diversion}])dnl
12397 @end example
12398
12399 One use of @code{m4_divert_text} is to develop two related macros, where
12400 macro @samp{MY_A} does the work, but adjusts what work is performed
12401 based on whether the optional macro @samp{MY_B} has also been expanded.
12402 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
12403 require that @samp{MY_B} occurs first, if it occurs at all. But this
12404 imposes an ordering restriction on the user; it would be nicer if macros
12405 @samp{MY_A} and @samp{MY_B} can be invoked in either order. The trick
12406 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
12407 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
12408 expanded.
12409
12410 @example
12411 AC_DEFUN([MY_A],
12412 [# various actions
12413 if test -n "$b_was_used"; then
12414 # extra action
12415 fi])
12416 AC_DEFUN([MY_B],
12417 [AC_REQUIRE([MY_A])dnl
12418 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12419 @end example
12420
12421 @end defmac
12422
12423 @defmac m4_init
12424 @msindex{init}
12425 Initialize the M4sugar environment, setting up the default named
12426 diversion to be @code{KILL}.
12427 @end defmac
12428
12429 @node Conditional constructs
12430 @subsection Conditional constructs
12431
12432 The following macros provide additional conditional constructs as
12433 convenience wrappers around @code{m4_if}.
12434
12435 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12436 @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12437 @msindex{bmatch}
12438 The string @var{string} is repeatedly compared against a series of
12439 @var{regex} arguments; if a match is found, the expansion is the
12440 corresponding @var{value}, otherwise, the macro moves on to the next
12441 @var{regex}. If no @var{regex} match, then the result is the optional
12442 @var{default}, or nothing.
12443
12444 The regular expression syntax understood by @code{m4_bmatch} is the same as
12445 that understood by @code{m4_bregexp}; see @ref{m4_bregexp}. The name
12446 @code{m4_match} is reserved for use by a future version of M4sugar, when
12447 there is a version of GNU M4 that supports POSIX extended
12448 regular expression syntax.
12449 @end defmac
12450
12451 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12452 @ovar{regex-2}, @ovar{subst-2}, @dots{})
12453 @msindex{bpatsubsts}
12454 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12455 as if by:
12456 @example
12457 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12458 @end example
12459
12460 @noindent
12461 The result of the substitution is then passed through the next set of
12462 @var{regex} and @var{subst}, and so forth. An empty @var{subst} implies
12463 deletion of any matched portions in the current string. Note that this
12464 macro over-quotes @var{string}; this behavior is intentional, so that
12465 the result of each step of the recursion remains as a quoted string.
12466 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12467 will line up with the extra quotations, and not the characters of the
12468 original string. The overquoting is removed after the final
12469 substitution.
12470
12471 The regular expression and replacement syntax understood by
12472 @code{m4_bpatsubsts} is the same as that understood by @code{m4_bpatsubst};
12473 see @ref{m4_bpatsubst}. The name @code{m4_patsubsts} is reserved for use by
12474 future version of M4sugar, when there is a version of GNU M4 that
12475 supports POSIX extended regular expression syntax.
12476 @end defmac
12477
12478 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12479 @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12480 @msindex{case}
12481 Test @var{string} against multiple @var{value} possibilities, resulting
12482 in the first @var{if-value} for a match, or in the optional
12483 @var{default}. This is shorthand for:
12484 @example
12485 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12486 [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12487 [@var{default}])
12488 @end example
12489 @end defmac
12490
12491 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12492 @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12493 @msindex{cond}
12494 This macro was introduced in Autoconf 2.62. Similar to @code{m4_if},
12495 except that each @var{test} is expanded only when it is encountered.
12496 This is useful for short-circuiting expensive tests; while @code{m4_if}
12497 requires all its strings to be expanded up front before doing
12498 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12499 tests have failed.
12500
12501 For an example, these two sequences give the same result, but in the
12502 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12503 version only expands @code{m4_index} once, instead of five times, for
12504 faster computation if this is a common case for @samp{$1}. Notice that
12505 every third argument is unquoted for @code{m4_if}, and quoted for
12506 @code{m4_cond}:
12507
12508 @example
12509 m4_if(m4_index([$1], [\]), [-1], [$2],
12510 m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12511 m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12512 m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12513 m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12514 [$2])
12515 m4_cond([m4_index([$1], [\])], [-1], [$2],
12516 [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12517 [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12518 [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12519 [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12520 [$2])
12521 @end example
12522 @end defmac
12523
12524 @defmac m4_default (@var{expr-1}, @var{expr-2})
12525 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12526 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12527 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12528 @msindex{default}
12529 @msindex{default_quoted}
12530 @msindex{default_nblank}
12531 @msindex{default_nblank_quoted}
12532 If @var{expr-1} contains text, use it. Otherwise, select @var{expr-2}.
12533 @code{m4_default} expands the result, while @code{m4_default_quoted}
12534 does not. Useful for providing a fixed default if the expression that
12535 results in @var{expr-1} would otherwise be empty. The difference
12536 between @code{m4_default} and @code{m4_default_nblank} is whether an
12537 argument consisting of just blanks (space, tab, newline) is
12538 significant. When using the expanding versions, note that an argument
12539 may contain text but still expand to an empty string.
12540
12541 @example
12542 m4_define([active], [ACTIVE])dnl
12543 m4_define([empty], [])dnl
12544 m4_define([demo1], [m4_default([$1], [$2])])dnl
12545 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12546 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12547 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12548 demo1([active], [default])
12549 @result{}ACTIVE
12550 demo1([], [active])
12551 @result{}ACTIVE
12552 demo1([empty], [text])
12553 @result{}
12554 -demo1([ ], [active])-
12555 @result{}- -
12556 demo2([active], [default])
12557 @result{}active
12558 demo2([], [active])
12559 @result{}active
12560 demo2([empty], [text])
12561 @result{}empty
12562 -demo2([ ], [active])-
12563 @result{}- -
12564 demo3([active], [default])
12565 @result{}ACTIVE
12566 demo3([], [active])
12567 @result{}ACTIVE
12568 demo3([empty], [text])
12569 @result{}
12570 -demo3([ ], [active])-
12571 @result{}-ACTIVE-
12572 demo4([active], [default])
12573 @result{}active
12574 demo4([], [active])
12575 @result{}active
12576 demo4([empty], [text])
12577 @result{}empty
12578 -demo4([ ], [active])-
12579 @result{}-active-
12580 @end example
12581 @end defmac
12582
12583 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
12584 @msindex{define_default}
12585 If @var{macro} does not already have a definition, then define it to
12586 @var{default-definition}.
12587 @end defmac
12588
12589 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12590 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12591 @msindex{ifblank}
12592 @msindex{ifnblank}
12593 If @var{cond} is empty or consists only of blanks (space, tab, newline),
12594 then expand @var{if-blank}; otherwise, expand @var{if-text}. Two
12595 variants exist, in order to make it easier to select the correct logical
12596 sense when using only two parameters. Note that this is more efficient
12597 than the equivalent behavior of:
12598 @example
12599 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12600 @end example
12601 @end defmac
12602
12603 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12604 @msindex{ifndef}
12605 This is shorthand for:
12606 @example
12607 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12608 @end example
12609 @end defmac
12610
12611 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12612 @msindex{ifset}
12613 If @var{macro} is undefined, or is defined as the empty string, expand
12614 to @var{if-false}. Otherwise, expands to @var{if-true}. Similar to:
12615 @example
12616 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12617 @end example
12618 @noindent
12619 except that it is not an error if @var{macro} is undefined.
12620 @end defmac
12621
12622 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12623 @msindex{ifval}
12624 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12625 @var{if-false}. This is shorthand for:
12626 @example
12627 m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12628 @end example
12629 @end defmac
12630
12631 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12632 @msindex{ifvaln}
12633 Similar to @code{m4_ifval}, except guarantee that a newline is present
12634 after any non-empty expansion. Often followed by @code{dnl}.
12635 @end defmac
12636
12637 @defmac m4_n (@var{text})
12638 @msindex{n}
12639 Expand to @var{text}, and add a newline if @var{text} is not empty.
12640 Often followed by @code{dnl}.
12641 @end defmac
12642
12643
12644 @node Looping constructs
12645 @subsection Looping constructs
12646
12647 The following macros are useful in implementing recursive algorithms in
12648 M4, including loop operations. An M4 list is formed by quoting a list
12649 of quoted elements; generally the lists are comma-separated, although
12650 @code{m4_foreach_w} is whitespace-separated. For example, the list
12651 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12652 It is common to see lists with unquoted elements when those elements are
12653 not likely to be macro names, as in @samp{[fputc_unlocked,
12654 fgetc_unlocked]}.
12655
12656 Although not generally recommended, it is possible for quoted lists to
12657 have side effects; all side effects are expanded only once, and prior to
12658 visiting any list element. On the other hand, the fact that unquoted
12659 macros are expanded exactly once means that macros without side effects
12660 can be used to generate lists. For example,
12661
12662 @example
12663 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12664 @error{}hi
12665 @result{}123
12666 m4_define([list], [[1], [2], [3]])
12667 @result{}
12668 m4_foreach([i], [list], [i])
12669 @result{}123
12670 @end example
12671
12672 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12673 @msindex{argn}
12674 Extracts argument @var{n} (larger than 0) from the remaining arguments.
12675 If there are too few arguments, the empty string is used. For any
12676 @var{n} besides 1, this is more efficient than the similar
12677 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12678 @end defmac
12679
12680 @defmac m4_car (@var{arg}@dots{})
12681 @msindex{car}
12682 Expands to the quoted first @var{arg}. Can be used with @code{m4_cdr}
12683 to recursively iterate
12684 through a list. Generally, when using quoted lists of quoted elements,
12685 @code{m4_car} should be called without any extra quotes.
12686 @end defmac
12687
12688 @defmac m4_cdr (@var{arg}@dots{})
12689 @msindex{cdr}
12690 Expands to a quoted list of all but the first @var{arg}, or the empty
12691 string if there was only one argument. Generally, when using quoted
12692 lists of quoted elements, @code{m4_cdr} should be called without any
12693 extra quotes.
12694
12695 For example, this is a simple implementation of @code{m4_map}; note how
12696 each iteration checks for the end of recursion, then merely applies the
12697 first argument to the first element of the list, then repeats with the
12698 rest of the list. (The actual implementation in M4sugar is a bit more
12699 involved, to gain some speed and share code with @code{m4_map_sep}, and
12700 also to avoid expanding side effects in @samp{$2} twice).
12701 @example
12702 m4_define([m4_map], [m4_ifval([$2],
12703 [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12704 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12705 @result{} 1 2 a
12706 @end example
12707 @end defmac
12708
12709 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12710 @var{expression})
12711 @msindex{for}
12712 Loop over the numeric values between @var{first} and @var{last}
12713 including bounds by increments of @var{step}. For each iteration,
12714 expand @var{expression} with the numeric value assigned to @var{var}.
12715 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12716 on the order of the limits. If given, @var{step} has to match this
12717 order. The number of iterations is determined independently from
12718 definition of @var{var}; iteration cannot be short-circuited or
12719 lengthened by modifying @var{var} from within @var{expression}.
12720 @end defmac
12721
12722 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12723 @msindex{foreach}
12724 Loop over the comma-separated M4 list @var{list}, assigning each value
12725 to @var{var}, and expand @var{expression}. The following example
12726 outputs two lines:
12727
12728 @example
12729 m4_foreach([myvar], [[foo], [bar, baz]],
12730 [echo myvar
12731 ])dnl
12732 @result{}echo foo
12733 @result{}echo bar, baz
12734 @end example
12735
12736 Note that for some forms of @var{expression}, it may be faster to use
12737 @code{m4_map_args}.
12738 @end defmac
12739
12740 @anchor{m4_foreach_w}
12741 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12742 @msindex{foreach_w}
12743 Loop over the white-space-separated list @var{list}, assigning each value
12744 to @var{var}, and expand @var{expression}. If @var{var} is only
12745 referenced once in @var{expression}, it is more efficient to use
12746 @code{m4_map_args_w}.
12747
12748 The deprecated macro @code{AC_FOREACH} is an alias of
12749 @code{m4_foreach_w}.
12750 @end defmac
12751
12752 @defmac m4_map (@var{macro}, @var{list})
12753 @defmacx m4_mapall (@var{macro}, @var{list})
12754 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12755 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12756 @msindex{map}
12757 @msindex{mapall}
12758 @msindex{map_sep}
12759 @msindex{mapall_sep}
12760 Loop over the comma separated quoted list of argument descriptions in
12761 @var{list}, and invoke @var{macro} with the arguments. An argument
12762 description is in turn a comma-separated quoted list of quoted elements,
12763 suitable for @code{m4_apply}. The macros @code{m4_map} and
12764 @code{m4_map_sep} ignore empty argument descriptions, while
12765 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12766 arguments. The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12767 additionally expand @var{separator} between invocations of @var{macro}.
12768
12769 Note that @var{separator} is expanded, unlike in @code{m4_join}. When
12770 separating output with commas, this means that the map result can be
12771 used as a series of arguments, by using a single-quoted comma as
12772 @var{separator}, or as a single string, by using a double-quoted comma.
12773
12774 @example
12775 m4_map([m4_count], [])
12776 @result{}
12777 m4_map([ m4_count], [[],
12778 [[1]],
12779 [[1], [2]]])
12780 @result{} 1 2
12781 m4_mapall([ m4_count], [[],
12782 [[1]],
12783 [[1], [2]]])
12784 @result{} 0 1 2
12785 m4_map_sep([m4_eval], [,], [[[1+2]],
12786 [[10], [16]]])
12787 @result{}3,a
12788 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12789 @result{}a,b
12790 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12791 @result{}2
12792 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12793 @result{}a,b
12794 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12795 @result{}1
12796 @end example
12797 @end defmac
12798
12799 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12800 @msindex{map_args}
12801 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12802 argument. In the following example, three solutions are presented with
12803 the same expansion; the solution using @code{m4_map_args} is the most
12804 efficient.
12805 @example
12806 m4_define([active], [ACTIVE])dnl
12807 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12808 @result{} plain active
12809 m4_map([ m4_echo], [[[plain]], [[active]]])
12810 @result{} plain active
12811 m4_map_args([ m4_echo], [plain], [active])
12812 @result{} plain active
12813 @end example
12814
12815 In cases where it is useful to operate on additional parameters besides
12816 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12817 to supply the argument currying necessary to generate the desired
12818 argument list. In the following example, @code{list_add_n} is more
12819 efficient than @code{list_add_x}. On the other hand, using
12820 @code{m4_map_args_sep} can be even more efficient.
12821
12822 @example
12823 m4_define([list], [[1], [2], [3]])dnl
12824 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12825 dnl list_add_n(N, ARG...)
12826 dnl Output a list consisting of each ARG added to N
12827 m4_define([list_add_n],
12828 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12829 list_add_n([1], list)
12830 @result{}2,3,4
12831 list_add_n([2], list)
12832 @result{}3,4,5
12833 m4_define([list_add_x],
12834 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12835 [,add([$1],m4_defn([var]))]))])dnl
12836 list_add_x([1], list)
12837 @result{}2,3,4
12838 @end example
12839 @end defmac
12840
12841 @defmac m4_map_args_pair (@var{macro}, @dvarv{macro-end, macro}, @
12842 @var{arg}@dots{})
12843 @msindex{map_args_pair}
12844 For every pair of arguments @var{arg}, invoke @var{macro} with two
12845 arguments. If there is an odd number of arguments, invoke
12846 @var{macro-end}, which defaults to @var{macro}, with the remaining
12847 argument.
12848
12849 @example
12850 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12851 @result{}, 2, 1, 3
12852 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12853 @result{}, 2, 1, [3]
12854 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12855 @result{}, 2, 1, 4, 3
12856 @end example
12857 @end defmac
12858
12859 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12860 @msindex{map_args_sep}
12861 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12862 argument, additionally expanding @var{sep} between arguments. One
12863 common use of this macro is constructing a macro call, where the opening
12864 and closing parentheses are split between @var{pre} and @var{post}; in
12865 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12866 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}. This
12867 macro provides the most efficient means for iterating over an arbitrary
12868 list of arguments, particularly when repeatedly constructing a macro
12869 call with more arguments than @var{arg}.
12870 @end defmac
12871
12872 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12873 @msindex{map_args_w}
12874 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12875 the whitespace-separated @var{string}, additionally expanding @var{sep}
12876 between words. This macro provides the most efficient means for
12877 iterating over a whitespace-separated string. In particular,
12878 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12879 efficient than @code{m4_foreach_w([var], [@var{string}],
12880 [@var{action}(m4_defn([var]))])}.
12881 @end defmac
12882
12883 @defmac m4_shiftn (@var{count}, @dots{})
12884 @defmacx m4_shift2 (@dots{})
12885 @defmacx m4_shift3 (@dots{})
12886 @msindex{shift2}
12887 @msindex{shift3}
12888 @msindex{shiftn}
12889 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12890 along with validation that enough arguments were passed in to match the
12891 shift count, and that the count is positive. @code{m4_shift2} and
12892 @code{m4_shift3} are specializations
12893 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12894 for two and three shifts, respectively.
12895 @end defmac
12896
12897 @defmac m4_stack_foreach (@var{macro}, @var{action})
12898 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12899 @msindex{stack_foreach}
12900 @msindex{stack_foreach_lifo}
12901 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12902 @var{action} with the single argument of a definition of @var{macro}.
12903 @code{m4_stack_foreach} starts with the oldest definition, while
12904 @code{m4_stack_foreach_lifo} starts with the current definition.
12905 @var{action} should not push or pop definitions of @var{macro}, nor is
12906 there any guarantee that the current definition of @var{macro} matches
12907 the argument that was passed to @var{action}. The macro @code{m4_curry}
12908 can be used if @var{action} needs more than one argument, although in
12909 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12910
12911 Due to technical limitations, there are a few low-level m4sugar
12912 functions, such as @code{m4_pushdef}, that cannot be used as the
12913 @var{macro} argument.
12914
12915 @example
12916 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12917 m4_stack_foreach([a], [ m4_incr])
12918 @result{} 2 3
12919 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12920 @result{} cd bcd
12921 @end example
12922 @end defmac
12923
12924 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12925 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12926 @ovar{sep})
12927 @msindex{stack_foreach_sep}
12928 @msindex{stack_foreach_sep_lifo}
12929 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12930 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12931 @var{sep} between definitions. @code{m4_stack_foreach_sep} visits the
12932 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12933 the current definition first. This macro provides the most efficient
12934 means for iterating over a pushdef stack. In particular,
12935 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12936 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12937 @end defmac
12938
12939 @node Evaluation Macros
12940 @subsection Evaluation Macros
12941
12942 The following macros give some control over the order of the evaluation
12943 by adding or removing levels of quotes.
12944
12945 @defmac m4_apply (@var{macro}, @var{list})
12946 @msindex{apply}
12947 Apply the elements of the quoted, comma-separated @var{list} as the
12948 arguments to @var{macro}. If @var{list} is empty, invoke @var{macro}
12949 without arguments. Note the difference between @code{m4_indir}, which
12950 expects its first argument to be a macro name but can use names that are
12951 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12952 other text, but must end in a valid macro name.
12953 @example
12954 m4_apply([m4_count], [])
12955 @result{}0
12956 m4_apply([m4_count], [[]])
12957 @result{}1
12958 m4_apply([m4_count], [[1], [2]])
12959 @result{}2
12960 m4_apply([m4_join], [[|], [1], [2]])
12961 @result{}1|2
12962 @end example
12963 @end defmac
12964
12965 @defmac m4_count (@var{arg}, @dots{})
12966 @msindex{count}
12967 This macro returns the number of arguments it was passed.
12968 @end defmac
12969
12970 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12971 @msindex{curry}
12972 This macro performs argument currying. The expansion of this macro is
12973 another macro name that expects exactly one argument; that argument is
12974 then appended to the @var{arg} list, and then @var{macro} is expanded
12975 with the resulting argument list.
12976
12977 @example
12978 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12979 @result{}3, 2, 1
12980 @end example
12981
12982 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12983 pass the definition of a builtin macro as the argument to the output of
12984 @code{m4_curry}; the empty string is used instead of the builtin token.
12985 This behavior is rectified by using M4 1.6 or newer.
12986 @end defmac
12987
12988 @defmac m4_do (@var{arg}, @dots{})
12989 @msindex{do}
12990 This macro loops over its arguments and expands each @var{arg} in
12991 sequence. Its main use is for readability; it allows the use of
12992 indentation and fewer @code{dnl} to result in the same expansion. This
12993 macro guarantees that no expansion will be concatenated with subsequent
12994 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12995 @var{arg@dots{}}))}.
12996
12997 @example
12998 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12999 m4_do([a],[b])c
13000 @result{}abc
13001 m4_unquote(m4_join([],[a],[b]))c
13002 @result{}3
13003 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
13004 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
13005 m4_do([a],[b])c
13006 @result{}ABC
13007 m4_unquote(m4_join([],[a],[b]))c
13008 @result{}3
13009 @end example
13010 @end defmac
13011
13012 @defmac m4_dquote (@var{arg}, @dots{})
13013 @msindex{dquote}
13014 Return the arguments as a quoted list of quoted arguments.
13015 Conveniently, if there is just one @var{arg}, this effectively adds a
13016 level of quoting.
13017 @end defmac
13018
13019 @defmac m4_dquote_elt (@var{arg}, @dots{})
13020 @msindex{dquote_elt}
13021 Return the arguments as a series of double-quoted arguments. Whereas
13022 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
13023 as many arguments as it was passed.
13024 @end defmac
13025
13026 @defmac m4_echo (@var{arg}, @dots{})
13027 @msindex{echo}
13028 Return the arguments, with the same level of quoting. Other than
13029 discarding whitespace after unquoted commas, this macro is a no-op.
13030 @end defmac
13031
13032 @defmac m4_expand (@var{arg})
13033 @msindex{expand}
13034 Return the expansion of @var{arg} as a quoted string. Whereas
13035 @code{m4_quote} is designed to collect expanded text into a single
13036 argument, @code{m4_expand} is designed to perform one level of expansion
13037 on quoted text. One distinction is in the treatment of whitespace
13038 following a comma in the original @var{arg}. Any time multiple
13039 arguments are collected into one with @code{m4_quote}, the M4 argument
13040 collection rules discard the whitespace. However, with @code{m4_expand},
13041 whitespace is preserved, even after the expansion of macros contained in
13042 @var{arg}. Additionally, @code{m4_expand} is able to expand text that
13043 would involve an unterminated comment, whereas expanding that same text
13044 as the argument to @code{m4_quote} runs into difficulty in finding the
13045 end of the argument. Since manipulating diversions during argument
13046 collection is inherently unsafe, @code{m4_expand} issues an error if
13047 @var{arg} attempts to change the current diversion (@pxref{Diversion
13048 support}).
13049
13050 @example
13051 m4_define([active], [ACT, IVE])dnl
13052 m4_define([active2], [[ACT, IVE]])dnl
13053 m4_quote(active, active)
13054 @result{}ACT,IVE,ACT,IVE
13055 m4_expand([active, active])
13056 @result{}ACT, IVE, ACT, IVE
13057 m4_quote(active2, active2)
13058 @result{}ACT, IVE,ACT, IVE
13059 m4_expand([active2, active2])
13060 @result{}ACT, IVE, ACT, IVE
13061 m4_expand([# m4_echo])
13062 @result{}# m4_echo
13063 m4_quote(# m4_echo)
13064 )
13065 @result{}# m4_echo)
13066 @result{}
13067 @end example
13068
13069 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
13070 literal unbalanced quotes, but that quadrigraphs can be used when
13071 unbalanced output is necessary. Likewise, unbalanced parentheses should
13072 be supplied with double quoting or a quadrigraph.
13073
13074 @example
13075 m4_define([pattern], [[!@@<:@@]])dnl
13076 m4_define([bar], [BAR])dnl
13077 m4_expand([case $foo in
13078 m4_defn([pattern])@@:@}@@ bar ;;
13079 *[)] blah ;;
13080 esac])
13081 @result{}case $foo in
13082 @result{} [![]) BAR ;;
13083 @result{} *) blah ;;
13084 @result{}esac
13085 @end example
13086 @end defmac
13087
13088 @defmac m4_ignore (@dots{})
13089 @msindex{ignore}
13090 This macro was introduced in Autoconf 2.62. Expands to nothing,
13091 ignoring all of its arguments. By itself, this isn't very useful.
13092 However, it can be used to conditionally ignore an arbitrary number of
13093 arguments, by deciding which macro name to apply to a list of arguments.
13094 @example
13095 dnl foo outputs a message only if [debug] is defined.
13096 m4_define([foo],
13097 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
13098 @end example
13099
13100 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
13101 serve the same purpose, although it is less readable.
13102 @end defmac
13103
13104 @defmac m4_make_list (@var{arg}, @dots{})
13105 @msindex{make_list}
13106 This macro exists to aid debugging of M4sugar algorithms. Its net
13107 effect is similar to @code{m4_dquote}---it produces a quoted list of
13108 quoted arguments, for each @var{arg}. The difference is that this
13109 version uses a comma-newline separator instead of just comma, to improve
13110 readability of the list; with the result that it is less efficient than
13111 @code{m4_dquote}.
13112 @example
13113 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
13114 m4_dquote(zero, [one], [[two]])
13115 @result{}[0],[one],[[two]]
13116 m4_make_list(zero, [one], [[two]])
13117 @result{}[0],
13118 @result{}[one],
13119 @result{}[[two]]
13120 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
13121 @result{} 0 1 two
13122 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
13123 @result{} 0 1 two
13124 @end example
13125 @end defmac
13126
13127 @c m4_noquote is too dangerous to document - it invokes macros that
13128 @c probably rely on @samp{[]} nested quoting for proper operation. The
13129 @c user should generally prefer m4_unquote instead.
13130
13131 @defmac m4_quote (@var{arg}, @dots{})
13132 @msindex{quote}
13133 Return the arguments as a single entity, i.e., wrap them into a pair of
13134 quotes. This effectively collapses multiple arguments into one,
13135 although it loses whitespace after unquoted commas in the process.
13136 @end defmac
13137
13138 @defmac m4_reverse (@var{arg}, @dots{})
13139 @msindex{reverse}
13140 Outputs each argument with the same level of quoting, but in reverse
13141 order, and with space following each comma for readability.
13142
13143 @example
13144 m4_define([active], [ACT,IVE])
13145 @result{}
13146 m4_reverse(active, [active])
13147 @result{}active, IVE, ACT
13148 @end example
13149 @end defmac
13150
13151 @defmac m4_unquote (@var{arg}, @dots{})
13152 @msindex{unquote}
13153 This macro was introduced in Autoconf 2.62. Expand each argument,
13154 separated by commas. For a single @var{arg}, this effectively removes a
13155 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
13156 than the equivalent @code{m4_do([@var{arg}])}. For multiple arguments,
13157 this results in an unquoted list of expansions. This is commonly used
13158 with @code{m4_split}, in order to convert a single quoted list into a
13159 series of quoted elements.
13160 @end defmac
13161
13162 The following example aims at emphasizing the difference between several
13163 scenarios: not using these macros, using @code{m4_defn}, using
13164 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
13165
13166 @example
13167 $ @kbd{cat example.m4}
13168 dnl Overquote, so that quotes are visible.
13169 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
13170 m4_define([a], [A])
13171 m4_define([mkargs], [1, 2[,] 3])
13172 m4_define([arg1], [[$1]])
13173 m4_divert([0])dnl
13174 show(a, b)
13175 show([a, b])
13176 show(m4_quote(a, b))
13177 show(m4_dquote(a, b))
13178 show(m4_expand([a, b]))
13179
13180 arg1(mkargs)
13181 arg1([mkargs])
13182 arg1(m4_defn([mkargs]))
13183 arg1(m4_quote(mkargs))
13184 arg1(m4_dquote(mkargs))
13185 arg1(m4_expand([mkargs]))
13186 $ @kbd{autom4te -l m4sugar example.m4}
13187 $1 = A, $@@ = [A],[b]
13188 $1 = a, b, $@@ = [a, b]
13189 $1 = A,b, $@@ = [A,b]
13190 $1 = [A],[b], $@@ = [[A],[b]]
13191 $1 = A, b, $@@ = [A, b]
13192
13193 1
13194 mkargs
13195 1, 2[,] 3
13196 1,2, 3
13197 [1],[2, 3]
13198 1, 2, 3
13199 @end example
13200
13201
13202 @node Text processing Macros
13203 @subsection String manipulation in M4
13204
13205 The following macros may be used to manipulate strings in M4. Many of
13206 the macros in this section intentionally result in quoted strings as
13207 output, rather than subjecting the arguments to further expansions. As
13208 a result, if you are manipulating text that contains active M4
13209 characters, the arguments are passed with single quoting rather than
13210 double.
13211
13212 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
13213 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
13214 @ovar{if-uniq}, @ovar{if-duplicate})
13215 @msindex{append}
13216 @msindex{append_uniq}
13217 Redefine @var{macro-name} to its former contents with @var{separator}
13218 and @var{string} added at the end. If @var{macro-name} was undefined
13219 before (but not if it was defined but empty), then no @var{separator} is
13220 added. As of Autoconf 2.62, neither @var{string} nor @var{separator}
13221 are expanded during this macro; instead, they are expanded when
13222 @var{macro-name} is invoked.
13223
13224 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
13225 to grow strings without duplicating substrings. Additionally,
13226 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
13227 @var{if-uniq} is expanded if @var{string} was appended, and
13228 @var{if-duplicate} is expanded if @var{string} was already present.
13229 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
13230 occurs within @var{string}, since that can lead to duplicates.
13231
13232 Note that @code{m4_append} can scale linearly in the length of the final
13233 string, depending on the quality of the underlying M4 implementation,
13234 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
13235 If an algorithm can tolerate duplicates in the final string, use the
13236 former for speed. If duplicates must be avoided, consider using
13237 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
13238
13239 @example
13240 m4_define([active], [ACTIVE])dnl
13241 m4_append([sentence], [This is an])dnl
13242 m4_append([sentence], [ active ])dnl
13243 m4_append([sentence], [symbol.])dnl
13244 sentence
13245 @result{}This is an ACTIVE symbol.
13246 m4_undefine([active])dnl
13247 @result{}This is an active symbol.
13248 m4_append_uniq([list], [one], [, ], [new], [existing])
13249 @result{}new
13250 m4_append_uniq([list], [one], [, ], [new], [existing])
13251 @result{}existing
13252 m4_append_uniq([list], [two], [, ], [new], [existing])
13253 @result{}new
13254 m4_append_uniq([list], [three], [, ], [new], [existing])
13255 @result{}new
13256 m4_append_uniq([list], [two], [, ], [new], [existing])
13257 @result{}existing
13258 list
13259 @result{}one, two, three
13260 m4_dquote(list)
13261 @result{}[one],[two],[three]
13262 m4_append([list2], [one], [[, ]])dnl
13263 m4_append_uniq([list2], [two], [[, ]])dnl
13264 m4_append([list2], [three], [[, ]])dnl
13265 list2
13266 @result{}one, two, three
13267 m4_dquote(list2)
13268 @result{}[one, two, three]
13269 @end example
13270 @end defmac
13271
13272 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
13273 @msindex{append_uniq_w}
13274 This macro was introduced in Autoconf 2.62. It is similar to
13275 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
13276 separated list of words to append, and only appends unique words.
13277 @var{macro-name} is updated with a single space between new words.
13278 @example
13279 m4_append_uniq_w([numbers], [1 1 2])dnl
13280 m4_append_uniq_w([numbers], [ 2 3 ])dnl
13281 numbers
13282 @result{}1 2 3
13283 @end example
13284 @end defmac
13285
13286 @defmac m4_chomp (@var{string})
13287 @defmacx m4_chomp_all (@var{string})
13288 @msindex{chomp}
13289 @msindex{chomp_all}
13290 Output @var{string} in quotes, but without a trailing newline. The
13291 macro @code{m4_chomp} is slightly faster, and removes at most one
13292 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
13293 newlines. Unlike @code{m4_flatten}, embedded newlines are left intact,
13294 and backslash does not influence the result.
13295 @end defmac
13296
13297 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
13298 @var{suffix-1}, @ovar{suffix-2}, @dots{})
13299 @msindex{combine}
13300 This macro produces a quoted string containing the pairwise combination
13301 of every element of the quoted, comma-separated @var{prefix-list}, and
13302 every element from the @var{suffix} arguments. Each pairwise
13303 combination is joined with @var{infix} in the middle, and successive
13304 pairs are joined by @var{separator}. No expansion occurs on any of the
13305 arguments. No output occurs if either the @var{prefix} or @var{suffix}
13306 list is empty, but the lists can contain empty elements.
13307 @example
13308 m4_define([a], [oops])dnl
13309 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
13310 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
13311 m4_combine([, ], [[a], [b]], [-])
13312 @result{}
13313 m4_combine([, ], [[a], [b]], [-], [])
13314 @result{}a-, b-
13315 m4_combine([, ], [], [-], [1], [2])
13316 @result{}
13317 m4_combine([, ], [[]], [-], [1], [2])
13318 @result{}-1, -2
13319 @end example
13320 @end defmac
13321
13322 @defmac m4_escape (@var{string})
13323 @msindex{escape}
13324 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
13325 within @var{string} into their respective quadrigraphs. The result is
13326 still a quoted string.
13327 @end defmac
13328
13329 @defmac m4_flatten (@var{string})
13330 @msindex{flatten}
13331 Flatten @var{string} into a single line. Delete all backslash-newline
13332 pairs, and replace all remaining newlines with a space. The result is
13333 still a quoted string.
13334 @end defmac
13335
13336 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
13337 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
13338 @msindex{join}
13339 @msindex{joinall}
13340 Concatenate each @var{arg}, separated by @var{separator}.
13341 @code{joinall} uses every argument, while @code{join} omits empty
13342 arguments so that there are no back-to-back separators in the output.
13343 The result is a quoted string.
13344 @example
13345 m4_define([active], [ACTIVE])dnl
13346 m4_join([|], [one], [], [active], [two])
13347 @result{}one|active|two
13348 m4_joinall([|], [one], [], [active], [two])
13349 @result{}one||active|two
13350 @end example
13351
13352 Note that if all you intend to do is join @var{args} with commas between
13353 them, to form a quoted list suitable for @code{m4_foreach}, it is more
13354 efficient to use @code{m4_dquote}.
13355 @end defmac
13356
13357 @defmac m4_newline (@ovar{text})
13358 @msindex{newline}
13359 This macro was introduced in Autoconf 2.62, and expands to a newline,
13360 followed by any @var{text}.
13361 It is primarily useful for maintaining macro formatting, and ensuring
13362 that M4 does not discard leading whitespace during argument collection.
13363 @end defmac
13364
13365 @defmac m4_normalize (@var{string})
13366 @msindex{normalize}
13367 Remove leading and trailing spaces and tabs, sequences of
13368 backslash-then-newline, and replace multiple spaces, tabs, and newlines
13369 with a single space. This is a combination of @code{m4_flatten} and
13370 @code{m4_strip}. To determine if @var{string} consists only of bytes
13371 that would be removed by @code{m4_normalize}, you can use
13372 @code{m4_ifblank}.
13373 @end defmac
13374
13375 @defmac m4_re_escape (@var{string})
13376 @msindex{re_escape}
13377 Backslash-escape all characters in @var{string} that are active in
13378 regexps.
13379 @end defmac
13380
13381 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13382 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
13383 @msindex{split}
13384 Split @var{string} into an M4 list of elements quoted by @samp{[} and
13385 @samp{]}, while keeping white space at the beginning and at the end.
13386 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
13387 If @var{string} is empty, the result is an empty list.
13388 @end defmac
13389
13390 @defmac m4_strip (@var{string})
13391 @msindex{strip}
13392 Strip whitespace from @var{string}. Sequences of spaces and tabs are
13393 reduced to a single space, then leading and trailing spaces are removed.
13394 The result is still a quoted string. Note that this does not interfere
13395 with newlines; if you want newlines stripped as well, consider
13396 @code{m4_flatten}, or do it all at once with @code{m4_normalize}. To
13397 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
13398 @end defmac
13399
13400 @defmac m4_text_box (@var{message}, @dvar{frame, -})
13401 @msindex{text_box}
13402 Add a text box around @var{message}, using @var{frame} as the border
13403 character above and below the message. The @var{frame} argument must be
13404 a single byte, and does not support quadrigraphs.
13405 The frame correctly accounts for
13406 the subsequent expansion of @var{message}. For example:
13407 @example
13408 m4_define([macro], [abc])dnl
13409 m4_text_box([macro])
13410 @result{}## --- ##
13411 @result{}## abc ##
13412 @result{}## --- ##
13413 @end example
13414
13415 The @var{message} must contain balanced quotes and parentheses, although
13416 quadrigraphs can be used to work around this.
13417 @end defmac
13418
13419 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
13420 @dvarv{prefix1, prefix}, @dvar{width, 79})
13421 @msindex{text_wrap}
13422 Break @var{string} into a series of whitespace-separated words, then
13423 output those words separated by spaces, and wrapping lines any time the
13424 output would exceed @var{width} columns. If given, @var{prefix1} begins
13425 the first line, and @var{prefix} begins all wrapped lines. If
13426 @var{prefix1} is longer than @var{prefix}, then the first line consists
13427 of just @var{prefix1}. If @var{prefix} is longer than @var{prefix1},
13428 padding is inserted so that the first word of @var{string} begins at the
13429 same indentation as all wrapped lines. Note that using literal tab
13430 characters in any of the arguments will interfere with the calculation
13431 of width. No expansions occur on @var{prefix}, @var{prefix1}, or the
13432 words of @var{string}, although quadrigraphs are recognized.
13433
13434 For some examples:
13435 @example
13436 m4_text_wrap([Short string */], [ ], [/* ], [20])
13437 @result{}/* Short string */
13438 m4_text_wrap([Much longer string */], [ ], [/* ], [20])
13439 @result{}/* Much longer
13440 @result{} string */
13441 m4_text_wrap([Short doc.], [ ], [ --short ], [30])
13442 @result{} --short Short doc.
13443 m4_text_wrap([Short doc.], [ ], [ --too-wide ], [30])
13444 @result{} --too-wide
13445 @result{} Short doc.
13446 m4_text_wrap([Super long documentation.], [ ],
13447 [ --too-wide ], 30)
13448 @result{} --too-wide
13449 @result{} Super long
13450 @result{} documentation.
13451 @end example
13452 @end defmac
13453
13454 @defmac m4_tolower (@var{string})
13455 @defmacx m4_toupper (@var{string})
13456 @msindex{tolower}
13457 @msindex{toupper}
13458 Return @var{string} with letters converted to upper or lower case,
13459 respectively.
13460 @end defmac
13461
13462 @node Number processing Macros
13463 @subsection Arithmetic computation in M4
13464
13465 The following macros facilitate integer arithmetic operations.
13466
13467 Where a parameter is documented as taking an arithmetic expression, you
13468 can use anything that can be parsed by @code{m4_eval}.
13469 Any other numeric parameter should consist of an optional sign followed
13470 by one or more decimal digits; it is treated as a decimal integer.
13471
13472 Macros that expand to a number do so as either @samp{0}, or an optional
13473 @samp{-} followed by a nonzero decimal digit followed by zero or more
13474 decimal digits.
13475
13476 Due to @command{m4} limitations, arithmetic expressions and numeric
13477 parameters should use only numbers that fit into a 32-bit signed
13478 integer.
13479
13480 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
13481 @msindex{cmp}
13482 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13483 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13484 equal, and @samp{1} if @var{expr-1} is larger.
13485 @end defmac
13486
13487 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
13488 @msindex{list_cmp}
13489 Compare the two M4 lists consisting of comma-separated arithmetic
13490 expressions, left to right. Expand to @samp{-1} for the first element
13491 pairing where the value from @var{list-1} is smaller, @samp{1} where the
13492 value from @var{list-2} is smaller, or @samp{0} if both lists have the
13493 same values. If one list is shorter than the other, the remaining
13494 elements of the longer list are compared against zero.
13495 @example
13496 m4_list_cmp([1, 0], [1])
13497 @result{}0
13498 m4_list_cmp([1, [1 * 0]], [1, 0])
13499 @result{}0
13500 m4_list_cmp([1, 2], [1, 0])
13501 @result{}1
13502 m4_list_cmp([1, [1+1], 3],[1, 2])
13503 @result{}1
13504 m4_list_cmp([1, 2, -3], [1, 2])
13505 @result{}-1
13506 m4_list_cmp([1, 0], [1, 2])
13507 @result{}-1
13508 m4_list_cmp([1], [1, 2])
13509 @result{}-1
13510 @end example
13511 @end defmac
13512
13513 @defmac m4_max (@var{arg}, @dots{})
13514 @msindex{max}
13515 This macro was introduced in Autoconf 2.62. Expand to the value
13516 of the maximum arithmetic expression among all the arguments.
13517 @end defmac
13518
13519 @defmac m4_min (@var{arg}, @dots{})
13520 @msindex{min}
13521 This macro was introduced in Autoconf 2.62. Expand to the value
13522 of the minimum arithmetic expression among all the arguments.
13523 @end defmac
13524
13525 @defmac m4_sign (@var{expr})
13526 @msindex{sign}
13527 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13528 @samp{1} if it is positive, and @samp{0} if it is zero.
13529 @end defmac
13530
13531 @anchor{m4_version_compare}
13532 @defmac m4_version_compare (@var{version-1}, @var{version-2})
13533 @msindex{version_compare}
13534 This macro was introduced in Autoconf 2.53, but had a number of
13535 usability limitations that were not lifted until Autoconf 2.62. Compare
13536 the version strings @var{version-1} and @var{version-2}, and expand to
13537 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13538 or @samp{1} @var{version-2} is smaller. Version strings must be a list
13539 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13540 element is a number along with optional case-insensitive letters
13541 designating beta releases. The comparison stops at the leftmost element
13542 that contains a difference, although a 0 element compares equal to a
13543 missing element.
13544
13545 It is permissible to include commit identifiers in @var{version}, such
13546 as an abbreviated SHA1 of the commit, provided there is still a
13547 monotonically increasing prefix to allow for accurate version-based
13548 comparisons. For example, this paragraph was written when the
13549 development snapshot of autoconf claimed to be at version
13550 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13551 abbreviated commit identification of @samp{dc51}.
13552
13553 @example
13554 m4_version_compare([1.1], [2.0])
13555 @result{}-1
13556 m4_version_compare([2.0b], [2.0a])
13557 @result{}1
13558 m4_version_compare([1.1.1], [1.1.1a])
13559 @result{}-1
13560 m4_version_compare([1.2], [1.1.1a])
13561 @result{}1
13562 m4_version_compare([1.0], [1])
13563 @result{}0
13564 m4_version_compare([1.1pre], [1.1PRE])
13565 @result{}0
13566 m4_version_compare([1.1a], [1,10])
13567 @result{}-1
13568 m4_version_compare([2.61a], [2.61a-248-dc51])
13569 @result{}-1
13570 m4_version_compare([2.61b], [2.61a-248-dc51])
13571 @result{}1
13572 @end example
13573 @end defmac
13574
13575 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13576 @dvar{if-old, m4_fatal})
13577 @msindex{version_prereq}
13578 Compares @var{version} against the version of Autoconf currently
13579 running. If the running version is at @var{version} or newer, expand
13580 @var{if-new-enough}, but if @var{version} is larger than the version
13581 currently executing, expand @var{if-old}, which defaults to printing an
13582 error message and exiting m4sugar with status 63. When given only one
13583 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13584 Remember that the autoconf philosophy favors feature checks over version
13585 checks.
13586 @end defmac
13587
13588 @node Set manipulation Macros
13589 @subsection Set manipulation in M4
13590 @cindex Set manipulation
13591 @cindex Data structure, set
13592 @cindex Unordered set manipulation
13593
13594 Sometimes, it is necessary to track a set of data, where the order does
13595 not matter and where there are no duplicates in the set. The following
13596 macros facilitate set manipulations. Each set is an opaque object,
13597 which can only be accessed via these basic operations. The underlying
13598 implementation guarantees linear scaling for set creation, which is more
13599 efficient than using the quadratic @code{m4_append_uniq}. Both set
13600 names and values can be arbitrary strings, except for unbalanced quotes.
13601 This implementation ties up memory for removed elements until the next
13602 operation that must traverse all the elements of a set; and although
13603 that may slow down some operations until the memory for removed elements
13604 is pruned, it still guarantees linear performance.
13605
13606 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13607 @msindex{set_add}
13608 Adds the string @var{value} as a member of set @var{set}. Expand
13609 @var{if-uniq} if the element was added, or @var{if-dup} if it was
13610 previously in the set. Operates in amortized constant time, so that set
13611 creation scales linearly.
13612 @end defmac
13613
13614 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13615 @msindex{set_add_all}
13616 Adds each @var{value} to the set @var{set}. This is slightly more
13617 efficient than repeatedly invoking @code{m4_set_add}.
13618 @end defmac
13619
13620 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13621 @ovar{if-absent})
13622 @msindex{set_contains}
13623 Expands @var{if-present} if the string @var{value} is a member of
13624 @var{set}, otherwise @var{if-absent}.
13625
13626 @example
13627 m4_set_contains([a], [1], [yes], [no])
13628 @result{}no
13629 m4_set_add([a], [1], [added], [dup])
13630 @result{}added
13631 m4_set_add([a], [1], [added], [dup])
13632 @result{}dup
13633 m4_set_contains([a], [1], [yes], [no])
13634 @result{}yes
13635 m4_set_remove([a], [1], [removed], [missing])
13636 @result{}removed
13637 m4_set_contains([a], [1], [yes], [no])
13638 @result{}no
13639 m4_set_remove([a], [1], [removed], [missing])
13640 @result{}missing
13641 @end example
13642 @end defmac
13643
13644 @defmac m4_set_contents (@var{set}, @ovar{sep})
13645 @defmacx m4_set_dump (@var{set}, @ovar{sep})
13646 @msindex{set_contents}
13647 @msindex{set_dump}
13648 Expands to a single string consisting of all the members of the set
13649 @var{set}, each separated by @var{sep}, which is not expanded.
13650 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13651 memory occupied by removed elements, while @code{m4_set_dump} is a
13652 faster one-shot action that also deletes the set. No provision is made
13653 for disambiguating members that contain a non-empty @var{sep} as a
13654 substring; use @code{m4_set_empty} to distinguish between an empty set
13655 and the set containing only the empty string. The order of the output
13656 is unspecified; in the current implementation, part of the speed of
13657 @code{m4_set_dump} results from using a different output order than
13658 @code{m4_set_contents}. These macros scale linearly in the size of the
13659 set before memory pruning, and @code{m4_set_contents([@var{set}],
13660 [@var{sep}])} is faster than
13661 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13662
13663 @example
13664 m4_set_add_all([a], [1], [2], [3])
13665 @result{}
13666 m4_set_contents([a], [-])
13667 @result{}1-2-3
13668 m4_joinall([-]m4_set_listc([a]))
13669 @result{}1-2-3
13670 m4_set_dump([a], [-])
13671 @result{}3-2-1
13672 m4_set_contents([a])
13673 @result{}
13674 m4_set_add([a], [])
13675 @result{}
13676 m4_set_contents([a], [-])
13677 @result{}
13678 @end example
13679 @end defmac
13680
13681 @defmac m4_set_delete (@var{set})
13682 @msindex{set_delete}
13683 Delete all elements and memory associated with @var{set}. This is
13684 linear in the set size, and faster than removing one element at a time.
13685 @end defmac
13686
13687 @defmac m4_set_difference (@var{seta}, @var{setb})
13688 @defmacx m4_set_intersection (@var{seta}, @var{setb})
13689 @defmacx m4_set_union (@var{seta}, @var{setb})
13690 @msindex{set_difference}
13691 @msindex{set_intersection}
13692 @msindex{set_union}
13693 Compute the relation between @var{seta} and @var{setb}, and output the
13694 result as a list of quoted arguments without duplicates and with a
13695 leading comma. Set difference selects the elements in @var{seta} but
13696 not @var{setb}, intersection selects only elements in both sets, and
13697 union selects elements in either set. These actions are linear in the
13698 sum of the set sizes. The leading comma is necessary to distinguish
13699 between no elements and the empty string as the only element.
13700
13701 @example
13702 m4_set_add_all([a], [1], [2], [3])
13703 @result{}
13704 m4_set_add_all([b], [3], [], [4])
13705 @result{}
13706 m4_set_difference([a], [b])
13707 @result{},1,2
13708 m4_set_difference([b], [a])
13709 @result{},,4
13710 m4_set_intersection([a], [b])
13711 @result{},3
13712 m4_set_union([a], [b])
13713 @result{},1,2,3,,4
13714 @end example
13715 @end defmac
13716
13717 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13718 @msindex{set_empty}
13719 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13720 expand @var{if-elements}. This macro operates in constant time. Using
13721 this macro can help disambiguate output from @code{m4_set_contents} or
13722 @code{m4_set_list}.
13723 @end defmac
13724
13725 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13726 @msindex{set_foreach}
13727 For each element in the set @var{set}, expand @var{action} with the
13728 macro @var{variable} defined as the set element. Behavior is
13729 unspecified if @var{action} recursively lists the contents of @var{set}
13730 (although listing other sets is acceptable), or if it modifies the set
13731 in any way other than removing the element currently contained in
13732 @var{variable}. This macro is faster than the corresponding
13733 @code{m4_foreach([@var{variable}],
13734 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13735 although @code{m4_set_map} might be faster still.
13736
13737 @example
13738 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13739 @result{}
13740 m4_set_contents([a])
13741 @result{}12345
13742 m4_set_foreach([a], [i],
13743 [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13744 @result{}24
13745 m4_set_contents([a])
13746 @result{}135
13747 @end example
13748 @end defmac
13749
13750 @defmac m4_set_list (@var{set})
13751 @defmacx m4_set_listc (@var{set})
13752 @msindex{set_list}
13753 @msindex{set_listc}
13754 Produce a list of arguments, where each argument is a quoted element
13755 from the set @var{set}. The variant @code{m4_set_listc} is unambiguous,
13756 by adding a leading comma if there are any set elements, whereas the
13757 variant @code{m4_set_list} cannot distinguish between an empty set and a
13758 set containing only the empty string. These can be directly used in
13759 macros that take multiple arguments, such as @code{m4_join} or
13760 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13761 take a quoted list, such as @code{m4_map} or @code{m4_foreach}. Any
13762 memory occupied by removed elements is reclaimed during these macros.
13763
13764 @example
13765 m4_set_add_all([a], [1], [2], [3])
13766 @result{}
13767 m4_set_list([a])
13768 @result{}1,2,3
13769 m4_set_list([b])
13770 @result{}
13771 m4_set_listc([b])
13772 @result{}
13773 m4_count(m4_set_list([b]))
13774 @result{}1
13775 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13776 @result{}0
13777 m4_set_add([b], [])
13778 @result{}
13779 m4_set_list([b])
13780 @result{}
13781 m4_set_listc([b])
13782 @result{},
13783 m4_count(m4_set_list([b]))
13784 @result{}1
13785 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13786 @result{}1
13787 @end example
13788 @end defmac
13789
13790 @defmac m4_set_map (@var{set}, @var{action})
13791 @msindex{set_map}
13792 For each element in the set @var{set}, expand @var{action} with a single
13793 argument of the set element. Behavior is unspecified if @var{action}
13794 recursively lists the contents of @var{set} (although listing other sets
13795 is acceptable), or if it modifies the set in any way other than removing
13796 the element passed as an argument. This macro is faster than either
13797 corresponding counterpart of
13798 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13799 @code{m4_set_foreach([@var{set}], [var],
13800 [@var{action}(m4_defn([var]))])}. It is possible to use @code{m4_curry}
13801 if more than one argument is needed for @var{action}, although it is
13802 more efficient to use @code{m4_set_map_sep} in that case.
13803 @end defmac
13804
13805 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13806 @msindex{set_map_sep}
13807 For each element in the set @var{set}, expand
13808 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13809 between elements. Behavior is unspecified if the expansion recursively
13810 lists the contents of @var{set} (although listing other sets
13811 is acceptable), or if it modifies the set in any way other than removing
13812 the element visited by the expansion. This macro provides the most
13813 efficient means for non-destructively visiting the elements of a set; in
13814 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13815 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13816 @end defmac
13817
13818 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13819 @ovar{if-absent})
13820 @msindex{set_remove}
13821 If @var{value} is an element in the set @var{set}, then remove it and
13822 expand @var{if-present}. Otherwise expand @var{if-absent}. This macro
13823 operates in constant time so that multiple removals will scale linearly
13824 rather than quadratically; but when used outside of
13825 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13826 until the set is later
13827 compacted by @code{m4_set_contents} or @code{m4_set_list}. Several
13828 other set operations are then less efficient between the time of element
13829 removal and subsequent memory compaction, but still maintain their
13830 guaranteed scaling performance.
13831 @end defmac
13832
13833 @defmac m4_set_size (@var{set})
13834 @msindex{set_size}
13835 Expand to the size of the set @var{set}. This implementation operates
13836 in constant time, and is thus more efficient than
13837 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13838 @end defmac
13839
13840
13841 @node Forbidden Patterns
13842 @subsection Forbidden Patterns
13843 @cindex Forbidden patterns
13844 @cindex Patterns, forbidden
13845
13846 M4sugar provides a means to define suspicious patterns, patterns
13847 describing tokens which should not be found in the output. For
13848 instance, if an Autoconf @file{configure} script includes tokens such as
13849 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13850 wrong (typically a macro was not evaluated because of overquotation).
13851
13852 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13853 Additional layers, such as M4sh and Autoconf, add additional forbidden
13854 patterns to the list.
13855
13856 @defmac m4_pattern_forbid (@var{pattern})
13857 @msindex{pattern_forbid}
13858 Declare that no token matching @var{pattern} must be found in the
13859 output. The output file is (temporarily) split into one word per line
13860 as part of the @command{autom4te} post-processing, with each line (and
13861 therefore word) then being checked against the Perl regular expression
13862 @var{pattern}. If the regular expression matches, and
13863 @code{m4_pattern_allow} does not also match, then an error is raised.
13864
13865 Comments are not checked; this can be a problem if, for instance, you
13866 have some macro left unexpanded after an @samp{#include}. No consensus
13867 is currently found in the Autoconf community, as some people consider it
13868 should be valid to name macros in comments (which doesn't make sense to
13869 the authors of this documentation: input, such as macros, should be
13870 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13871 document the output).
13872
13873 As an example, if you define your own macros that begin with @samp{M_}
13874 and are composed from capital letters and underscores, the specification
13875 of @code{m4_pattern_forbid([^M_[A-Z_]+])} will ensure all your macros
13876 are expanded when not used in comments.
13877
13878 As an example of a common use of this macro, consider what happens in
13879 packages that want to use the @command{pkg-config} script via the
13880 third-party @code{PKG_CHECK_MODULES} macro. By default, if a developer
13881 checks out the development tree but has not yet installed the pkg-config
13882 macros locally, they can manage to successfully run @command{autoconf}
13883 on the package, but the resulting @file{configure} file will likely
13884 result in a confusing shell message about a syntax error on the line
13885 mentioning the unexpanded @code{PKG_CHECK_MODULES} macro. On the other hand,
13886 if @file{configure.ac} includes @code{m4_pattern_forbid([^PKG_])}, the
13887 missing pkg-config macros will be detected immediately without allowing
13888 @command{autoconf} to succeed.
13889 @end defmac
13890
13891 Of course, you might encounter exceptions to these generic rules, for
13892 instance you might have to refer to @samp{$m4_flags}.
13893
13894 @defmac m4_pattern_allow (@var{pattern})
13895 @msindex{pattern_allow}
13896 Any token matching @var{pattern} is allowed, including if it matches an
13897 @code{m4_pattern_forbid} pattern.
13898
13899 For example, Gnulib uses @code{m4_pattern_forbid([^gl_])} to reserve the
13900 @code{gl_} namespace for itself, but also uses
13901 @code{m4_pattern_allow([^gl_ES$])} to avoid a false negative on the
13902 valid locale name.
13903 @end defmac
13904
13905 @node Debugging via autom4te
13906 @section Debugging via autom4te
13907 @cindex debugging tips
13908 @cindex autom4te debugging tips
13909 @cindex m4sugar debugging tips
13910 At times, it is desirable to see what was happening inside m4, to see
13911 why output was not matching expectations. However, post-processing done
13912 by @command{autom4te} means that directly using the m4 builtin
13913 @code{m4_traceon} is likely to interfere with operation. Also, frequent
13914 diversion changes and the concept of forbidden tokens make it difficult
13915 to use @code{m4_defn} to generate inline comments in the final output.
13916
13917 There are a couple of tools to help with this. One is the use of the
13918 @option{--trace} option provided by @command{autom4te} (as well as each
13919 of the programs that wrap @command{autom4te}, such as
13920 @command{autoconf}), in order to inspect when a macro is called and with
13921 which arguments. For example, when this paragraph was written, the
13922 autoconf version could be found by:
13923
13924 @example
13925 $ @kbd{autoconf --trace=AC_INIT}
13926 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13927 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13928 version is 2.63b.95-3963
13929 @end example
13930
13931 Another trick is to print out the expansion of various m4 expressions to
13932 standard error or to an independent file, with no further m4 expansion,
13933 and without interfering with diversion changes or the post-processing
13934 done to standard output. @code{m4_errprintn} shows a given expression
13935 on standard error. For example, if you want to see the expansion of an
13936 autoconf primitive or of one of your autoconf macros, you can do it like
13937 this:
13938
13939 @example
13940 $ @kbd{cat <<\EOF > configure.ac}
13941 AC_INIT
13942 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13943 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13944 AC_OUTPUT
13945 EOF
13946 $ @kbd{autoconf}
13947 @error{}The definition of AC_DEFINE_UNQUOTED:
13948 @error{}_AC_DEFINE_Q([], $@@)
13949 @end example
13950
13951 @node Programming in M4sh
13952 @chapter Programming in M4sh
13953
13954 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13955 scripts. This name was coined by Lars J. Aas, who notes that,
13956 according to the Webster's Revised Unabridged Dictionary (1913):
13957
13958 @quotation
13959 Mash \Mash\, n. [Akin to G. meisch, maisch, meische, maische, mash,
13960 wash, and prob.@: to AS. miscian to mix. See ``Mix''.]
13961
13962 @enumerate 1
13963 @item
13964 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13965 pressure@enddots{}
13966
13967 @item
13968 A mixture of meal or bran and water fed to animals.
13969
13970 @item
13971 A mess; trouble. [Obs.] --Beau.@: & Fl.
13972 @end enumerate
13973 @end quotation
13974
13975 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13976 the namespace @samp{^AS_} for M4sh macros. It also reserves the shell
13977 and environment variable namespace @samp{^as_}, and the here-document
13978 delimiter namespace @samp{^_AS[A-Z]} in the output file. You should not
13979 define your own macros or output shell code that conflicts with these
13980 namespaces.
13981
13982 @menu
13983 * Common Shell Constructs:: Portability layer for common shell constructs
13984 * Polymorphic Variables:: Support for indirect variable names
13985 * Initialization Macros:: Macros to establish a sane shell environment
13986 * File Descriptor Macros:: File descriptor macros for input and output
13987 @end menu
13988
13989 @node Common Shell Constructs
13990 @section Common Shell Constructs
13991
13992 M4sh provides portable alternatives for some common shell constructs
13993 that unfortunately are not portable in practice.
13994
13995 @c Deprecated, to be replaced by a better API
13996 @ignore
13997 @defmac AS_BASENAME (@var{file-name})
13998 @asindex{BASENAME}
13999 Output the non-directory portion of @var{file-name}. For example,
14000 if @code{$file} is @samp{/one/two/three}, the command
14001 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
14002 @end defmac
14003 @end ignore
14004
14005 @defmac AS_BOX (@var{text}, @dvar{char, -})
14006 @asindex{BOX}
14007 Expand into shell code that will output @var{text} surrounded by a box
14008 with @var{char} in the top and bottom border. @var{text} should not
14009 contain a newline, but may contain shell expansions valid for unquoted
14010 here-documents. @var{char} defaults to @samp{-}, but can be any
14011 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
14012 @samp{&}, or @samp{`}. This is useful for outputting a comment box into
14013 log files to separate distinct phases of script operation.
14014 @end defmac
14015
14016 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
14017 @dots{}, @ovar{default})
14018 @asindex{CASE}
14019 Expand into a shell @samp{case} statement, where @var{word} is matched
14020 against one or more patterns. @var{if-matched} is run if the
14021 corresponding pattern matched @var{word}, else @var{default} is run.
14022 @xref{Prerequisite Macros} for why
14023 this macro should be used instead of plain @samp{case} in code
14024 outside of an @code{AC_DEFUN} macro, when the contents of the
14025 @samp{case} use @code{AC_REQUIRE} directly or indirectly.
14026 @xref{case, , Limitations of Shell Builtins},
14027 for how this macro avoids some portability issues.
14028 @xref{Balancing Parentheses}
14029 for how this macro lets you write code with balanced parentheses
14030 even if your code must run on obsolescent shells.
14031 @end defmac
14032
14033 @c Deprecated, to be replaced by a better API
14034 @defmac AS_DIRNAME (@var{file-name})
14035 @asindex{DIRNAME}
14036 Output the directory portion of @var{file-name}. For example,
14037 if @code{$file} is @samp{/one/two/three}, the command
14038 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
14039
14040 @code{AS_DIRNAME} was designed long ago when
14041 the @command{dirname} command was not universally supported.
14042 Nowadays one can safely use @code{dir=`dirname -- "$file"`} instead.
14043 This interface may be improved in the future to avoid forks and losing
14044 trailing newlines.
14045 @end defmac
14046
14047 @defmac AS_ECHO (@var{word})
14048 @asindex{ECHO}
14049 Emit @var{word} to the standard output, followed by a newline.
14050 The @var{word} must be a single shell word (typically a quoted string).
14051 Output the shell expansion of @var{word} as-is,
14052 even if it starts with @samp{-} or contains @samp{\}.
14053 Redirections can be placed outside the macro invocation.
14054
14055 If the shell variable @var{foo} could contain @samp{\} or leading @samp{-}.
14056 @code{AS_ECHO(["$foo"])} is more portable than @command{echo "$foo"}.
14057 @xref{echo, , Limitations of Shell Builtins}.
14058
14059 Also, @code{AS_ECHO(["$foo"])} is often easier to read than the
14060 @samp{printf '%s\n' "$foo"} that it stands for.
14061 However, because it employs @samp{'} characters,
14062 in contexts where @samp{'} is not allowed
14063 it is better to use @command{printf} directly.
14064 For example, @samp{`eval 'foo=$@{'AS_ESCAPE([[$1]], [`\])'@};printf
14065 "%s\\n" "$foo")'`} would not work if @command{printf} were replaced
14066 with @code{AS_ECHO}.
14067
14068 @end defmac
14069
14070 @defmac AS_ECHO_N (@var{word})
14071 @asindex{ECHO_N}
14072 Act like @code{AS_ECHO(@var{word})}, except do not output a following newline.
14073 @end defmac
14074
14075 @c We cannot use @dvar because the macro expansion mistreats backslashes.
14076 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
14077 @asindex{ESCAPE}
14078 Expands to @var{string}, with any characters in @var{chars} escaped with
14079 a backslash (@samp{\}). @var{chars} should be at most four bytes long,
14080 and only contain characters from the set @samp{`\"$}; however,
14081 characters may be safely listed more than once in @var{chars} for the
14082 sake of syntax highlighting editors. The current implementation expands
14083 @var{string} after adding escapes; if @var{string} contains macro calls
14084 that in turn expand to text needing shell quoting, you can use
14085 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
14086
14087 The default for @var{chars} (@samp{\"$`}) is the set of characters
14088 needing escapes when @var{string} will be used literally within double
14089 quotes. One common variant is the set of characters to protect when
14090 @var{string} will be used literally within back-ticks or an unquoted
14091 here-document (@samp{\$`}). Another common variant is @samp{""}, which can
14092 be used to form a double-quoted string containing the same expansions
14093 that would have occurred if @var{string} were expanded in an unquoted
14094 here-document; however, when using this variant, care must be taken that
14095 @var{string} does not use double quotes within complex variable
14096 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
14097 with improper escapes.
14098
14099 This macro is often used with @code{AS_ECHO}. For an example, observe
14100 the output generated by the shell code generated from this snippet:
14101
14102 @example
14103 foo=bar
14104 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
14105 @result{}"$foo" = "bar"
14106 m4_define([macro], [a, [\b]])
14107 AS_ECHO(["AS_ESCAPE([[macro]])"])
14108 @result{}macro
14109 AS_ECHO(["AS_ESCAPE([macro])"])
14110 @result{}a, b
14111 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
14112 @result{}a, \b
14113 @end example
14114
14115 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
14116 @comment the case of @var{string} that does not contain '.
14117 To escape a string that will be placed within single quotes, use:
14118
14119 @example
14120 m4_bpatsubst([[@var{string}]], ['], ['\\''])
14121 @end example
14122 @end defmac
14123
14124 @defmac AS_EXECUTABLE_P (@var{file})
14125 @asindex{EXECUTABLE_P}
14126 Emit code to probe whether @var{file} is a regular file with executable
14127 permissions (and not a directory with search permissions). The caller
14128 is responsible for quoting @var{file}.
14129 @end defmac
14130
14131 @defmac AS_EXIT (@dvar{status, $?})
14132 @asindex{EXIT}
14133 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
14134 This macro
14135 works around shells that see the exit status of the command prior to
14136 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
14137 of Shell Builtins}).
14138 @end defmac
14139
14140 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
14141 @asindex{IF}
14142 Run shell code @var{test1}. If @var{test1} exits with a zero status then
14143 run shell code @var{run-if-true1}, else examine further tests. If no test
14144 exits with a zero status, run shell code @var{run-if-false}, with
14145 simplifications if either @var{run-if-true1} or @var{run-if-false}
14146 is empty. For example,
14147
14148 @example
14149 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
14150 [test "x$foo" != xno], [HANDLE_FOO([maybe])],
14151 [echo foo not specified])
14152 @end example
14153
14154 @noindent
14155 ensures any required macros of @code{HANDLE_FOO}
14156 are expanded before the first test.
14157
14158 This macro should be used instead of plain @samp{if} in code
14159 outside of an @code{AC_DEFUN} macro, when the contents of the @samp{if}
14160 use @code{AC_REQUIRE} directly or indirectly (@pxref{Prerequisite Macros}).
14161 @end defmac
14162
14163 @defmac AS_MKDIR_P (@var{file-name})
14164 @asindex{MKDIR_P}
14165 Make the directory @var{file-name}, including intervening directories
14166 as necessary. This is equivalent to @samp{mkdir -p -- @var{file-name}}.
14167 If creation of @var{file-name} fails, exit the script.
14168
14169 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
14170 @end defmac
14171
14172 @defmac AS_SET_STATUS (@var{status})
14173 @asindex{SET_STATUS}
14174 Emit shell code to set the value of @samp{$?} to @var{status}, as
14175 efficiently as possible. However, this is not guaranteed to abort a
14176 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
14177 Builtins}). This should also be used at the end of a complex shell
14178 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
14179 a DJGPP shell bug.
14180 @end defmac
14181
14182 @defmac AS_TR_CPP (@var{expression})
14183 @asindex{TR_CPP}
14184 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
14185 For example:
14186
14187 @example
14188 # This outputs "#define HAVE_CHAR_P 1".
14189 # Notice the m4 quoting around #, to prevent an m4 comment
14190 type="char *"
14191 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
14192 @end example
14193 @end defmac
14194
14195 @defmac AS_TR_SH (@var{expression})
14196 @asindex{TR_SH}
14197 Transform @var{expression} into shell code that generates a valid shell
14198 variable name. The result is literal when possible at m4 time, but must
14199 be used with @code{eval} if @var{expression} causes shell indirections.
14200 For example:
14201
14202 @example
14203 # This outputs "Have it!".
14204 header="sys/some file.h"
14205 eval AS_TR_SH([HAVE_$header])=yes
14206 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
14207 @end example
14208 @end defmac
14209
14210 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
14211 @asindex{SET_CATFILE}
14212 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
14213 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
14214 @var{file} is absolute, etc.).
14215 @end defmac
14216
14217 @defmac AS_UNSET (@var{var})
14218 @asindex{UNSET}
14219 Unsets the shell variable @var{var}, working around bugs in older
14220 shells (@pxref{unset, , Limitations of Shell
14221 Builtins}). @var{var} can be a literal or indirect variable name.
14222 @end defmac
14223
14224 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
14225 @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
14226 @asindex{VERSION_COMPARE}
14227 Compare two strings @var{version-1} and @var{version-2}, possibly
14228 containing shell variables, as version strings, and expand
14229 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
14230 depending upon the result.
14231 The algorithm to compare is similar to the one used by strverscmp in
14232 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
14233 The GNU C Library}).
14234 @end defmac
14235
14236 @node Polymorphic Variables
14237 @section Support for indirect variable names
14238 @cindex variable name indirection
14239 @cindex polymorphic variable name
14240 @cindex indirection, variable name
14241
14242 Often, it is convenient to write a macro that will emit shell code
14243 operating on a shell variable. The simplest case is when the variable
14244 name is known. But a more powerful idiom is writing shell code that can
14245 work through an indirection, where another variable or command
14246 substitution produces the name of the variable to actually manipulate.
14247 M4sh supports the notion of polymorphic shell variables, making it easy
14248 to write a macro that can deal with either literal or indirect variable
14249 names and output shell code appropriate for both use cases. Behavior is
14250 undefined if expansion of an indirect variable does not result in a
14251 literal variable name.
14252
14253 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
14254 @dvarv{if-simple-ref, if-not})
14255 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
14256 @ovar{if-not}, @dvarv{if-simple-ref, if-not})
14257 @asindex{LITERAL_IF}
14258 @asindex{LITERAL_WORD_IF}
14259 If the expansion of @var{expression} is definitely a shell literal,
14260 expand @var{if-literal}. If the expansion of @var{expression} looks
14261 like it might contain shell indirections (such as @code{$var} or
14262 @code{`expr`}), then @var{if-not} is expanded. Sometimes, it is
14263 possible to output optimized code if @var{expression} consists only of
14264 shell variable expansions (such as @code{$@{var@}}), in which case
14265 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
14266 should always be safe. @code{AS_LITERAL_WORD_IF} only expands
14267 @var{if-literal} if @var{expression} looks like a single shell word,
14268 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
14269 in @var{expression}.
14270
14271 In order to reduce the time spent recognizing whether an
14272 @var{expression} qualifies as a literal or a simple indirection, the
14273 implementation is somewhat conservative: @var{expression} must be a
14274 single shell word (possibly after stripping whitespace), consisting only
14275 of bytes that would have the same meaning whether unquoted or enclosed
14276 in double quotes (for example, @samp{a.b} results in @var{if-literal},
14277 even though it is not a valid shell variable name; while both @samp{'a'}
14278 and @samp{[$]} result in @var{if-not}, because they behave differently
14279 than @samp{"'a'"} and @samp{"[$]"}). This macro can be used in contexts
14280 for recognizing portable file names (such as in the implementation of
14281 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
14282 valid variable names (such as in the implementation of @code{AS_TR_SH},
14283 which uses an additional @code{m4_translit} to convert @samp{.} to
14284 @samp{_}).
14285
14286 This example shows how to read the contents of the shell variable
14287 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}. It
14288 results in a script that will output the line @samp{hello} three times.
14289
14290 @example
14291 AC_DEFUN([MY_ACTION],
14292 [AS_LITERAL_IF([$1],
14293 [AS_ECHO(["$$1"])],
14294 @c $$
14295 [AS_VAR_COPY([var], [$1])
14296 AS_ECHO(["$var"])],
14297 [AS_ECHO(["$'"$1"\"])])])
14298 foo=bar bar=hello
14299 MY_ACTION([bar])
14300 MY_ACTION([`echo bar`])
14301 MY_ACTION([$foo])
14302 @end example
14303 @end defmac
14304
14305 @defmac AS_VAR_APPEND (@var{var}, @var{text})
14306 @asindex{VAR_APPEND}
14307 Emit shell code to append the shell expansion of @var{text} to the end
14308 of the current contents of the polymorphic shell variable @var{var},
14309 taking advantage of shells that provide the @samp{+=} extension for more
14310 efficient scaling.
14311
14312 For situations where the final contents of @var{var} are relatively
14313 short (less than 256 bytes), it is more efficient to use the simpler
14314 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
14315 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
14316 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}). But in the case
14317 when the script will be repeatedly appending text into @code{var},
14318 issues of scaling start to become apparent. A naive implementation
14319 requires execution time linear to the length of the current contents of
14320 @var{var} as well as the length of @var{text} for a single append, for
14321 an overall quadratic scaling with multiple appends. This macro takes
14322 advantage of shells which provide the extension
14323 @code{@var{var}+=@var{text}}, which can provide amortized constant time
14324 for a single append, for an overall linear scaling with multiple
14325 appends. Note that unlike @code{AS_VAR_SET}, this macro requires that
14326 @var{text} be quoted properly to avoid field splitting and file name
14327 expansion.
14328 @end defmac
14329
14330 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
14331 @asindex{VAR_ARITH}
14332 Emit shell code to compute the arithmetic expansion of @var{expression},
14333 assigning the result as the contents of the polymorphic shell variable
14334 @var{var}. The code takes advantage of shells that provide @samp{$(())}
14335 for fewer forks, but uses @command{expr} as a fallback. Therefore, the
14336 syntax for a valid @var{expression} is rather limited: all operators
14337 must occur as separate shell arguments and with proper quoting;
14338 the only operators supported are @samp{*}, @samp{/}, @samp{%}, binary
14339 @samp{+}, binary @samp{-}, @samp{>}, @samp{>=}, @samp{<}, @samp{<=},
14340 @samp{!=}, @samp{&}, and @samp{|};
14341 all variables containing numbers must be expanded prior to the computation;
14342 the first shell argument must not start with @samp{-};
14343 and each number must be an optional @samp{-} followed by one or more
14344 decimal digits, where the first digit is nonzero if there is more than
14345 one digit. In the following example, this snippet
14346 will print @samp{(2+3)*4 == 20}.
14347
14348 @example
14349 bar=3
14350 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
14351 echo "(2+$bar)*4 == $foo"
14352 @end example
14353 @end defmac
14354
14355 @defmac AS_VAR_COPY (@var{dest}, @var{source})
14356 @asindex{VAR_COPY}
14357 Emit shell code to assign the contents of the polymorphic shell variable
14358 @var{source} to the polymorphic shell variable @var{dest}. For example,
14359 executing this M4sh snippet will output @samp{bar hi}:
14360
14361 @example
14362 foo=bar bar=hi
14363 AS_VAR_COPY([a], [foo])
14364 AS_VAR_COPY([b], [$foo])
14365 echo "$a $b"
14366 @end example
14367
14368 When it is necessary to access the contents of an indirect variable
14369 inside a shell double-quoted context, the recommended idiom is to first
14370 copy the contents into a temporary literal shell variable.
14371
14372 @smallexample
14373 for header in stdint_h inttypes_h ; do
14374 AS_VAR_COPY([var], [ac_cv_header_$header])
14375 AS_ECHO(["$header detected: $var"])
14376 done
14377 @end smallexample
14378 @end defmac
14379
14380 @comment AS_VAR_GET is intentionally undocumented; it can't handle
14381 @comment trailing newlines uniformly, and forks too much.
14382
14383 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
14384 @ovar{if-not-equal})
14385 @asindex{VAR_IF}
14386 Output a shell conditional statement. If the contents of the
14387 polymorphic shell variable @var{var} match the string @var{word},
14388 execute @var{if-equal}; otherwise execute @var{if-not-equal}. @var{word}
14389 must be a single shell word (typically a quoted string). Avoids
14390 shell bugs if an interrupt signal arrives while a command substitution
14391 in @var{var} is being expanded.
14392 @end defmac
14393
14394 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
14395 @defmacx AS_VAR_POPDEF (@var{m4-name})
14396 @asindex{VAR_PUSHDEF}
14397 @asindex{VAR_POPDEF}
14398 @cindex composing variable names
14399 @cindex variable names, composing
14400 A common M4sh idiom involves composing shell variable names from an m4
14401 argument (for example, writing a macro that uses a cache variable).
14402 @var{value} can be an arbitrary string, which will be transliterated
14403 into a valid shell name by @code{AS_TR_SH}. In order to access the
14404 composed variable name based on @var{value}, it is easier to declare a
14405 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
14406 that macro as the argument to subsequent @code{AS_VAR} macros as a
14407 polymorphic variable name, and finally free the temporary macro with
14408 @code{AS_VAR_POPDEF}. These macros are often followed with @code{dnl},
14409 to avoid excess newlines in the output.
14410
14411 Here is an involved example, that shows the power of writing macros that
14412 can handle composed shell variable names:
14413
14414 @example
14415 m4_define([MY_CHECK_HEADER],
14416 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
14417 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
14418 AS_VAR_POPDEF([my_Header])dnl
14419 ])
14420 MY_CHECK_HEADER([stdint.h])
14421 for header in inttypes.h stdlib.h ; do
14422 MY_CHECK_HEADER([$header])
14423 done
14424 @end example
14425
14426 @noindent
14427 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
14428 variable names. In the first invocation, the m4 argument is
14429 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
14430 As a result, the temporary macro @code{my_Header} expands to the literal
14431 shell name @samp{ac_cv_header_stdint_h}. In the second invocation, the
14432 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
14433 temporary macro @code{my_Header} expands to the indirect shell name
14434 @samp{$as_my_Header}. During the shell execution of the for loop, when
14435 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
14436 contains @samp{ac_cv_header_inttypes_h}. If this script is then run on a
14437 platform where all three headers have been previously detected, the
14438 output of the script will include:
14439
14440 @smallexample
14441 header stdint.h detected
14442 header inttypes.h detected
14443 header stdlib.h detected
14444 @end smallexample
14445 @end defmac
14446
14447 @defmac AS_VAR_SET (@var{var}, @ovar{value})
14448 @asindex{VAR_SET}
14449 Emit shell code to assign the contents of the polymorphic shell variable
14450 @var{var} to the shell expansion of @var{value}. @var{value} is not
14451 subject to field splitting or file name expansion, so if command
14452 substitution is used, it may be done with @samp{`""`} rather than using
14453 an intermediate variable (@pxref{Shell Substitutions}). However,
14454 @var{value} does undergo rescanning for additional macro names; behavior
14455 is unspecified if late expansion results in any shell meta-characters.
14456 @end defmac
14457
14458 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
14459 @asindex{VAR_SET_IF}
14460 Emit a shell conditional statement, which executes @var{if-set} if the
14461 polymorphic shell variable @code{var} is set to any value, and
14462 @var{if-undef} otherwise.
14463 @end defmac
14464
14465 @defmac AS_VAR_TEST_SET (@var{var})
14466 @asindex{VAR_TEST_SET}
14467 Emit a shell statement that results in a successful exit status only if
14468 the polymorphic shell variable @code{var} is set.
14469 @end defmac
14470
14471 @node Initialization Macros
14472 @section Initialization Macros
14473
14474 @defmac AS_BOURNE_COMPATIBLE
14475 @asindex{BOURNE_COMPATIBLE}
14476 Set up the shell to be more compatible with the Bourne shell as
14477 standardized by POSIX, if possible. This may involve setting
14478 environment variables, or setting options, or similar
14479 implementation-specific actions. This macro is deprecated, since
14480 @code{AS_INIT} already invokes it.
14481 @end defmac
14482
14483 @defmac AS_INIT
14484 @asindex{INIT}
14485 @evindex LC_ALL
14486 @evindex SHELL
14487 Initialize the M4sh environment. This macro calls @code{m4_init}, then
14488 outputs the @code{#! /bin/sh} line, a notice about where the output was
14489 generated from, and code to sanitize the environment for the rest of the
14490 script. Among other initializations, this sets @env{SHELL} to the shell
14491 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14492 ensure the C locale. Finally, it changes the current diversion to
14493 @code{BODY}. @code{AS_INIT} is called automatically by @code{AC_INIT}
14494 and @code{AT_INIT}, so shell code in @file{configure},
14495 @file{config.status}, and @file{testsuite} all benefit from a sanitized
14496 shell environment.
14497 @end defmac
14498
14499 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14500 @asindex{INIT_GENERATED}
14501 Emit shell code to start the creation of a subsidiary shell script in
14502 @var{file}, including changing @var{file} to be executable. This macro
14503 populates the child script with information learned from the parent
14504 (thus, the emitted code is equivalent in effect, but more efficient,
14505 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14506 @code{AS_SHELL_SANITIZE}). If present, @var{comment} is output near the
14507 beginning of the child, prior to the shell initialization code, and is
14508 subject to parameter expansion, command substitution, and backslash
14509 quote removal. The
14510 parent script should check the exit status after this macro, in case
14511 @var{file} could not be properly created (for example, if the disk was
14512 full). If successfully created, the parent script can then proceed to
14513 append additional M4sh constructs into the child script.
14514
14515 Note that the child script starts life without a log file open, so if
14516 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14517 must temporarily disable any attempts to use the log file until after
14518 emitting code to open a log within the child. On the other hand, if the
14519 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14520 @samp{1}, then the child script already has code that copies stdout to
14521 that descriptor. Currently, the suggested
14522 idiom for writing a M4sh shell script from within another script is:
14523
14524 @example
14525 AS_INIT_GENERATED([@var{file}], [[# My child script.
14526 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14527 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14528 cat >> "@var{file}" <<\__EOF__
14529 # Code to initialize AS_MESSAGE_LOG_FD
14530 m4_popdef([AS_MESSAGE_LOG_FD])dnl
14531 # Additional code
14532 __EOF__
14533 @end example
14534
14535 This, however, may change in the future as the M4sh interface is
14536 stabilized further.
14537
14538 Also, be aware that use of @env{LINENO} within the child script may
14539 report line numbers relative to their location in the parent script,
14540 even when using @code{AS_LINENO_PREPARE}, if the parent script was
14541 unable to locate a shell with working @env{LINENO} support.
14542 @end defmac
14543
14544 @defmac AS_LINENO_PREPARE
14545 @asindex{LINENO_PREPARE}
14546 @evindex LINENO
14547 Find a shell that supports the special variable @env{LINENO}, which
14548 contains the number of the currently executing line. This macro is
14549 automatically invoked by @code{AC_INIT} in configure scripts.
14550 @end defmac
14551
14552 @defmac AS_ME_PREPARE
14553 @asindex{ME_PREPARE}
14554 Set up variable @env{as_me} to be the basename of the currently executing
14555 script. This macro is automatically invoked by @code{AC_INIT} in
14556 configure scripts.
14557 @end defmac
14558
14559 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14560 @asindex{TMPDIR}
14561 @evindex TMPDIR
14562 @ovindex tmp
14563 Create, as safely as possible, a temporary sub-directory within
14564 @var{dir} with a name starting with @var{prefix}. @var{prefix} should
14565 be 2--4 characters, to make it slightly easier to identify the owner of
14566 the directory. If @var{dir} is omitted, then the value of @env{TMPDIR}
14567 will be used (defaulting to @samp{/tmp}). On success, the name of the
14568 newly created directory is stored in the shell variable @code{tmp}. On
14569 error, the script is aborted.
14570
14571 Typically, this macro is coupled with some exit traps to delete the created
14572 directory and its contents on exit or interrupt. However, there is a
14573 slight window between when the directory is created and when the name is
14574 actually known to the shell, so an interrupt at the right moment might
14575 leave the temporary directory behind. Hence it is important to use a
14576 @var{prefix} that makes it easier to determine if a leftover temporary
14577 directory from an interrupted script is safe to delete.
14578
14579 If you set @code{TMPDIR=$tmp} after invoking this macro, you should
14580 reset @code{TMPDIR} before deleting the created directory, to avoid
14581 breaking commands that rely on @code{$TMPDIR}.
14582
14583 The use of the output variable @samp{$tmp} rather than something in the
14584 @samp{as_} namespace is historical; it has the unfortunate consequence
14585 that reusing this otherwise common name for any other purpose inside
14586 your script has the potential to break any cleanup traps designed to
14587 remove the temporary directory.
14588 @end defmac
14589
14590 @defmac AS_SHELL_SANITIZE
14591 @asindex{SHELL_SANITIZE}
14592 Initialize the shell suitably for @command{configure} scripts. This has
14593 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14594 environment variables for predictable results from configuration tests.
14595 For example, it sets @env{LC_ALL} to change to the default C locale.
14596 @xref{Special Shell Variables}. This macro is deprecated, since
14597 @code{AS_INIT} already invokes it.
14598 @end defmac
14599
14600
14601 @node File Descriptor Macros
14602 @section File Descriptor Macros
14603 @cindex input
14604 @cindex standard input
14605 @cindex file descriptors
14606 @cindex descriptors
14607 @cindex low-level output
14608 @cindex output, low-level
14609
14610 The following macros define file descriptors used to output messages
14611 (or input values) from @file{configure} scripts.
14612 For example:
14613
14614 @example
14615 AS_ECHO(["$wombats found"]) >&AS_MESSAGE_LOG_FD
14616 AS_ECHO_N(['Enter desired kangaroo count: ']) >&AS_MESSAGE_FD
14617 read kangaroos <&AS_ORIGINAL_STDIN_FD
14618 @end example
14619
14620 @noindent
14621 However doing so is seldom needed, because Autoconf provides higher
14622 level macros as described below.
14623
14624 @defmac AS_MESSAGE_FD
14625 @asindex{MESSAGE_FD}
14626 The file descriptor for @samp{checking for...} messages and results.
14627 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14628 clients. However, @code{AC_INIT} shuffles things around to another file
14629 descriptor, in order to allow the @option{-q} option of
14630 @command{configure} to choose whether messages should go to the script's
14631 standard output or be discarded.
14632
14633 If you want to display some messages, consider using one of the printing
14634 macros (@pxref{Printing Messages}) instead. Copies of messages output
14635 via these macros are also recorded in @file{config.log}.
14636 @end defmac
14637
14638 @anchor{AS_MESSAGE_LOG_FD}
14639 @defmac AS_MESSAGE_LOG_FD
14640 @asindex{MESSAGE_LOG_FD}
14641 This must either be empty, or expand to a file descriptor for log
14642 messages. By default, @code{AS_INIT} sets this macro to the empty
14643 string for standalone M4sh clients, thus disabling logging. However,
14644 @code{AC_INIT} shuffles things around so that both @command{configure}
14645 and @command{config.status} use @file{config.log} for log messages.
14646 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14647 Compiler}), redirect all output to this descriptor. You may want to do
14648 so if you develop such a low-level macro.
14649 @end defmac
14650
14651 @defmac AS_ORIGINAL_STDIN_FD
14652 @asindex{ORIGINAL_STDIN_FD}
14653 This must expand to a file descriptor for the original standard input.
14654 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14655 M4sh clients. However, @code{AC_INIT} shuffles things around for
14656 safety.
14657
14658 When @command{configure} runs, it may accidentally execute an
14659 interactive command that has the same name as the non-interactive meant
14660 to be used or checked. If the standard input was the terminal, such
14661 interactive programs would cause @command{configure} to stop, pending
14662 some user input. Therefore @command{configure} redirects its standard
14663 input from @file{/dev/null} during its initialization. This is not
14664 normally a problem, since @command{configure} normally does not need
14665 user input.
14666
14667 In the extreme case where your @file{configure} script really needs to
14668 obtain some values from the original standard input, you can read them
14669 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14670 @end defmac
14671
14672
14673 @c =================================================== Writing Autoconf Macros.
14674
14675 @node Writing Autoconf Macros
14676 @chapter Writing Autoconf Macros
14677
14678 When you write a feature test that could be applicable to more than one
14679 software package, the best thing to do is encapsulate it in a new macro.
14680 Here are some instructions and guidelines for writing Autoconf macros.
14681 You should also familiarize yourself with M4sugar (@pxref{Programming in M4})
14682 and M4sh (@pxref{Programming in M4sh}).
14683
14684 @menu
14685 * Macro Definitions:: Basic format of an Autoconf macro
14686 * Macro Names:: What to call your new macros
14687 * Dependencies Between Macros:: What to do when macros depend on other macros
14688 * Obsoleting Macros:: Warning about old ways of doing things
14689 * Coding Style:: Writing Autoconf macros à la Autoconf
14690 @end menu
14691
14692 @node Macro Definitions
14693 @section Macro Definitions
14694
14695 @defmac AC_DEFUN (@var{name}, @ovar{body})
14696 @acindex{DEFUN}
14697 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14698 similar to the M4 builtin @code{m4_define} macro; this creates a macro
14699 named @var{name} and with @var{body} as its expansion. In addition to
14700 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14701 constrain the order in which macros are called, while avoiding redundant
14702 output (@pxref{Prerequisite Macros}).
14703 @end defmac
14704
14705 An Autoconf macro definition looks like this:
14706
14707 @example
14708 AC_DEFUN(@var{macro-name}, @var{macro-body})
14709 @end example
14710
14711 You can refer to any arguments passed to the macro as @samp{$1},
14712 @samp{$2}, etc. @xref{Definitions, , How to define new macros, m4,
14713 GNU M4}, for more complete information on writing M4 macros.
14714
14715 Most macros fall in one of two general categories. The first category
14716 includes macros which take arguments, in order to generate output
14717 parameterized by those arguments. Macros in this category are designed
14718 to be directly expanded, often multiple times, and should not be used as
14719 the argument to @code{AC_REQUIRE}. The other category includes macros
14720 which are shorthand for a fixed block of text, and therefore do not take
14721 arguments. For this category of macros, directly expanding the macro
14722 multiple times results in redundant output, so it is more common to use
14723 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14724 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14725
14726 Be sure to properly quote both the @var{macro-body} @emph{and} the
14727 @var{macro-name} to avoid any problems if the macro happens to have
14728 been previously defined.
14729
14730 Each macro should have a header comment that gives its prototype, and a
14731 brief description. When arguments have default values, display them in
14732 the prototype. For example:
14733
14734 @example
14735 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14736 # --------------------------------------
14737 m4_define([AC_MSG_ERROR],
14738 [@{ AS_MESSAGE([error: $1], [2])
14739 exit m4_default([$2], [1]); @}])
14740 @end example
14741
14742 Comments about the macro should be left in the header comment. Most
14743 other comments make their way into @file{configure}, so just keep
14744 using @samp{#} to introduce comments.
14745
14746 @cindex @code{dnl}
14747 If you have some special comments about pure M4 code, comments
14748 that make no sense in @file{configure} and in the header comment, then
14749 use the builtin @code{dnl}: it causes M4 to discard the text
14750 through the next newline.
14751
14752 Keep in mind that @code{dnl} is rarely needed to introduce comments;
14753 @code{dnl} is more useful to get rid of the newlines following macros
14754 that produce no output, such as @code{AC_REQUIRE}.
14755
14756 Public third-party macros need to use @code{AC_DEFUN}, and not
14757 @code{m4_define}, in order to be found by @command{aclocal}
14758 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14759 Additionally, if it is ever determined that a macro should be made
14760 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14761 in order to have @command{autoupdate} assist the user in choosing a
14762 better alternative, but there is no corresponding way to make
14763 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14764
14765 There is another subtle, but important, difference between using
14766 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14767 @code{AC_REQUIRE}. When writing a file, it is always safe to replace a
14768 block of text with a @code{m4_define} macro that will expand to the same
14769 text. But replacing a block of text with an @code{AC_DEFUN} macro with
14770 the same content does not necessarily give the same results, because it
14771 changes the location where any embedded but unsatisfied
14772 @code{AC_REQUIRE} invocations within the block will be expanded. For an
14773 example of this, see @ref{Expanded Before Required}.
14774
14775 @node Macro Names
14776 @section Macro Names
14777
14778 All of the public Autoconf macros have all-uppercase names in the
14779 namespace @samp{^AC_} to prevent them from accidentally conflicting with
14780 other text; Autoconf also reserves the namespace @samp{^_AC_} for
14781 internal macros. All shell variables that they use for internal
14782 purposes have mostly-lowercase names starting with @samp{ac_}. Autoconf
14783 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}. During
14784 @command{configure}, files produced by Autoconf make heavy use of the
14785 file system namespace @samp{^conf}.
14786
14787 Since Autoconf is built on top of M4sugar (@pxref{Programming in
14788 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14789 of those namespaces (@samp{^_?\(m4\|AS\)_}). And since
14790 @file{configure.ac} is also designed to be scanned by Autoheader,
14791 Autoscan, Autoupdate, and Automake, you should be aware of the
14792 @samp{^_?A[HNUM]_} namespaces. In general, you @emph{should not use}
14793 the namespace of a package that does not own the macro or shell code you
14794 are writing.
14795
14796 To ensure that your macros don't conflict with present or future
14797 Autoconf macros, you should prefix your own macro names and any shell
14798 variables they use with some other sequence. Possibilities include your
14799 initials, or an abbreviation for the name of your organization or
14800 software package. Historically, people have not always followed the
14801 rule of using a namespace appropriate for their package, and this has
14802 made it difficult for determining the origin of a macro (and where to
14803 report bugs about that macro), as well as difficult for the true
14804 namespace owner to add new macros without interference from pre-existing
14805 uses of third-party macros. Perhaps the best example of this confusion
14806 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14807 to Gettext.
14808
14809 Most of the Autoconf macros' names follow a structured naming convention
14810 that indicates the kind of feature check by the name. The macro names
14811 consist of several words, separated by underscores, going from most
14812 general to most specific. The names of their cache variables use the
14813 same convention (@pxref{Cache Variable Names}, for more information on
14814 them).
14815
14816 The first word of the name after the namespace initials (such as
14817 @samp{AC_}) usually tells the category
14818 of the feature being tested. Here are the categories used in Autoconf for
14819 specific test macros, the kind of macro that you are more likely to
14820 write. They are also used for cache variables, in all-lowercase. Use
14821 them where applicable; where they're not, invent your own categories.
14822
14823 @table @code
14824 @item C
14825 C language builtin features.
14826 @item DECL
14827 Declarations of C variables in header files.
14828 @item FUNC
14829 Functions in libraries.
14830 @item GROUP
14831 POSIX group owners of files.
14832 @item HEADER
14833 Header files.
14834 @item LIB
14835 C libraries.
14836 @item PROG
14837 The base names of programs.
14838 @item MEMBER
14839 Members of aggregates.
14840 @item SYS
14841 Operating system features.
14842 @item TYPE
14843 C builtin or declared types.
14844 @item VAR
14845 C variables in libraries.
14846 @end table
14847
14848 After the category comes the name of the particular feature being
14849 tested. Any further words in the macro name indicate particular aspects
14850 of the feature. For example, @code{AC_PROG_MAKE_SET} checks whether
14851 @command{make} sets a variable to its own name.
14852
14853 An internal macro should have a name that starts with an underscore;
14854 Autoconf internals should therefore start with @samp{_AC_}.
14855 Additionally, a macro that is an internal subroutine of another macro
14856 should have a name that starts with an underscore and the name of that
14857 other macro, followed by one or more words saying what the internal
14858 macro does. For example, @code{AC_PATH_X} has internal macros
14859 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14860
14861 @node Dependencies Between Macros
14862 @section Dependencies Between Macros
14863 @cindex Dependencies between macros
14864
14865 Some Autoconf macros depend on other macros having been called first in
14866 order to work correctly. Autoconf provides a way to ensure that certain
14867 macros are called if needed and a way to warn the user if macros are
14868 called in an order that might cause incorrect operation.
14869
14870 @menu
14871 * Prerequisite Macros:: Ensuring required information
14872 * Suggested Ordering:: Warning about possible ordering problems
14873 * One-Shot Macros:: Ensuring a macro is called only once
14874 @end menu
14875
14876 @node Prerequisite Macros
14877 @subsection Prerequisite Macros
14878 @cindex Prerequisite macros
14879 @cindex Macros, prerequisites
14880
14881 A macro that you write might need to use values that have previously
14882 been computed by other macros. For example, @code{AC_DECL_YYTEXT}
14883 examines the output of @code{flex} or @code{lex}, so it depends on
14884 @code{AC_PROG_LEX} having been called first to set the shell variable
14885 @code{LEX}.
14886
14887 Rather than forcing the user of the macros to keep track of the
14888 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14889 it automatically. @code{AC_REQUIRE} can ensure that a macro is only
14890 called if it is needed, and only called once.
14891
14892 @defmac AC_REQUIRE (@var{macro-name})
14893 @acindex{REQUIRE}
14894 If the M4 macro @var{macro-name} has not already been called, call it
14895 (without any arguments). Make sure to quote @var{macro-name} with
14896 square brackets. @var{macro-name} must have been defined using
14897 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14898 that it has been called.
14899
14900 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14901 must not be called from the top level. Also, it does not make sense to
14902 require a macro that takes parameters.
14903 @end defmac
14904
14905 @code{AC_REQUIRE} is often misunderstood. It really implements
14906 dependencies between macros in the sense that if one macro depends upon
14907 another, the latter is expanded @emph{before} the body of the
14908 former. To be more precise, the required macro is expanded before
14909 the outermost defined macro in the current expansion stack.
14910 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14911 @code{FOO}. For instance, this definition of macros:
14912
14913 @example
14914 @group
14915 AC_DEFUN([TRAVOLTA],
14916 [test "$body_temperature_in_Celsius" -gt 38 &&
14917 dance_floor=occupied])
14918 AC_DEFUN([NEWTON_JOHN],
14919 [test "x$hair_style" = xcurly &&
14920 dance_floor=occupied])
14921 @end group
14922
14923 @group
14924 AC_DEFUN([RESERVE_DANCE_FLOOR],
14925 [if test "x`date +%A`" = xSaturday; then
14926 AC_REQUIRE([TRAVOLTA])
14927 AC_REQUIRE([NEWTON_JOHN])
14928 fi])
14929 @end group
14930 @end example
14931
14932 @noindent
14933 with this @file{configure.ac}
14934
14935 @example
14936 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14937 RESERVE_DANCE_FLOOR
14938 if test "x$dance_floor" = xoccupied; then
14939 AC_MSG_ERROR([cannot pick up here, let's move])
14940 fi
14941 @end example
14942
14943 @noindent
14944 does not leave you with a better chance to meet a kindred soul on
14945 days other than Saturday, since the call to @code{RESERVE_DANCE_FLOOR}
14946 expands to:
14947
14948 @example
14949 @group
14950 test "$body_temperature_in_Celsius" -gt 38 &&
14951 dance_floor=occupied
14952 test "x$hair_style" = xcurly &&
14953 dance_floor=occupied
14954 if test "x`date +%A`" = xSaturday; then
14955
14956
14957 fi
14958 @end group
14959 @end example
14960
14961 This behavior was chosen on purpose: (i) it prevents messages in
14962 required macros from interrupting the messages in the requiring macros;
14963 (ii) it avoids bad surprises when shell conditionals are used, as in:
14964
14965 @example
14966 @group
14967 if @dots{}; then
14968 AC_REQUIRE([SOME_CHECK])
14969 fi
14970 @dots{}
14971 SOME_CHECK
14972 @end group
14973 @end example
14974
14975 However, this implementation can lead to another class of problems.
14976 Consider the case where an outer macro first expands, then indirectly
14977 requires, an inner macro:
14978
14979 @example
14980 AC_DEFUN([TESTA], [[echo in A
14981 if test -n "$SEEN_A" ; then echo duplicate ; fi
14982 SEEN_A=:]])
14983 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14984 if test -z "$SEEN_A" ; then echo bug ; fi]])
14985 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14986 AC_DEFUN([OUTER], [[echo in OUTER]
14987 TESTA
14988 TESTC])
14989 OUTER
14990 @end example
14991
14992 @noindent
14993 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14994 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14995 of @code{OUTER}, but because @code{TESTA} had already been directly
14996 expanded, it failed to hoist @code{TESTA}. Therefore, the expansion of
14997 @code{TESTB} occurs prior to its prerequisites, leading to the following
14998 output:
14999
15000 @example
15001 in B
15002 bug
15003 in OUTER
15004 in A
15005 in C
15006 @end example
15007
15008 @noindent
15009 Newer Autoconf is smart enough to recognize this situation, and hoists
15010 @code{TESTA} even though it has already been expanded, but issues a
15011 syntax warning in the process. This is because the hoisted expansion of
15012 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
15013 redundant code, and causes its own set of problems if the hoisted macro
15014 is not idempotent:
15015
15016 @example
15017 in A
15018 in B
15019 in OUTER
15020 in A
15021 duplicate
15022 in C
15023 @end example
15024
15025 The bug is not in Autoconf, but in the macro definitions. If you ever
15026 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
15027 that the macro only needs to be expanded once. But to enforce this,
15028 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
15029 this only helps in Autoconf 2.64 or newer), or all
15030 uses of that macro should be through @code{AC_REQUIRE}; directly
15031 expanding the macro defeats the point of using @code{AC_REQUIRE} to
15032 eliminate redundant expansion. In the example, this rule of thumb was
15033 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
15034 directly expands it. One way of fixing the bug is to factor
15035 @code{TESTA} into two macros, the portion designed for direct and
15036 repeated use (here, named @code{TESTA}), and the portion designed for
15037 one-shot output and used only inside @code{AC_REQUIRE} (here, named
15038 @code{TESTA_PREREQ}). Then, by fixing all clients to use the correct
15039 calling convention according to their needs:
15040
15041 @example
15042 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
15043 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
15044 if test -n "$SEEN_A" ; then echo duplicate ; fi
15045 SEEN_A=:]])
15046 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
15047 if test -z "$SEEN_A" ; then echo bug ; fi]])
15048 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
15049 AC_DEFUN([OUTER], [[echo in OUTER]
15050 TESTA
15051 TESTC])
15052 OUTER
15053 @end example
15054
15055 @noindent
15056 the resulting output will then obey all dependency rules and avoid any
15057 syntax warnings, whether the script is built with old or new Autoconf
15058 versions:
15059
15060 @example
15061 in A_PREREQ
15062 in B
15063 in OUTER
15064 in A
15065 in C
15066 @end example
15067
15068 You can use the helper macros @code{AS_IF} and @code{AS_CASE} in
15069 top-level code to enforce expansion of required macros outside of shell
15070 conditional constructs; these helpers are not needed in the bodies of
15071 macros defined by @code{AC_DEFUN}.
15072 You are furthermore encouraged, although not required, to
15073 put all @code{AC_REQUIRE} calls
15074 at the beginning of a macro. You can use @code{dnl} to avoid the empty
15075 lines they leave.
15076
15077 Autoconf will normally warn if an @code{AC_REQUIRE} call refers to a
15078 macro that has not been defined. However, the @command{aclocal} tool
15079 relies on parsing an incomplete set of input files to trace which macros
15080 have been required, in order to then pull in additional files that
15081 provide those macros; for this particular use case, pre-defining the
15082 macro @code{m4_require_silent_probe} will avoid the warnings.
15083
15084 @node Suggested Ordering
15085 @subsection Suggested Ordering
15086 @cindex Macros, ordering
15087 @cindex Ordering macros
15088
15089 Some macros should be run before another macro if both are called, but
15090 neither @emph{requires} that the other be called. For example, a macro
15091 that changes the behavior of the C compiler should be called before any
15092 macros that run the C compiler. Many of these dependencies are noted in
15093 the documentation.
15094
15095 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
15096 with this kind of dependency appear out of order in a
15097 @file{configure.ac} file. The warning occurs when creating
15098 @command{configure} from @file{configure.ac}, not when running
15099 @command{configure}.
15100
15101 For example, @code{AC_PROG_CPP} checks whether the C compiler
15102 can run the C preprocessor when given the @option{-E} option. It should
15103 therefore be called after any macros that change which C compiler is
15104 being used, such as @code{AC_PROG_CC}. So @code{AC_PROG_CC} contains:
15105
15106 @example
15107 AC_BEFORE([$0], [AC_PROG_CPP])dnl
15108 @end example
15109
15110 @noindent
15111 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
15112 when @code{AC_PROG_CC} is called.
15113
15114 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
15115 @acindex{BEFORE}
15116 Make M4 print a warning message to the standard error output if
15117 @var{called-macro-name} has already been called. @var{this-macro-name}
15118 should be the name of the macro that is calling @code{AC_BEFORE}. The
15119 macro @var{called-macro-name} must have been defined using
15120 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
15121 that it has been called.
15122 @end defmac
15123
15124 @node One-Shot Macros
15125 @subsection One-Shot Macros
15126 @cindex One-shot macros
15127 @cindex Macros, called once
15128
15129 Some macros should be called only once, either because calling them
15130 multiple time is unsafe, or because it is bad style. For instance
15131 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
15132 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
15133 sense to run these expensive checks more than once. Such one-shot
15134 macros can be defined using @code{AC_DEFUN_ONCE}.
15135
15136 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
15137 @acindex{DEFUN_ONCE}
15138 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
15139 Definitions}), but add additional logic that guarantees that only the
15140 first use of the macro (whether by direct expansion or
15141 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
15142 expansion will occur before the start of any enclosing macro defined by
15143 @code{AC_DEFUN}. Subsequent expansions are silently ignored.
15144 Generally, it does not make sense for @var{macro-body} to use parameters
15145 such as @code{$1}.
15146 @end defmac
15147
15148 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
15149 emit a warning if it was directly expanded a second time, so for
15150 portability, it is better to use @code{AC_REQUIRE} than direct
15151 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
15152 (@pxref{Prerequisite Macros}).
15153
15154 @node Obsoleting Macros
15155 @section Obsoleting Macros
15156 @cindex Obsoleting macros
15157 @cindex Macros, obsoleting
15158
15159 Configuration and portability technology has evolved over the years.
15160 Often better ways of solving a particular problem are developed, or
15161 ad-hoc approaches are systematized. This process has occurred in many
15162 parts of Autoconf. One result is that some of the macros are now
15163 considered @dfn{obsolete}; they still work, but are no longer considered
15164 the best thing to do, hence they should be replaced with more modern
15165 macros. Ideally, @command{autoupdate} should replace the old macro calls
15166 with their modern implementation.
15167
15168 Autoconf provides a simple means to obsolete a macro.
15169
15170 @anchor{AU_DEFUN}
15171 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message}, @ovar{silent})
15172 @auindex{DEFUN}
15173 Define @var{old-macro} as @var{implementation}, just like
15174 @code{AC_DEFUN}, but also declare @var{old-macro} to be obsolete.
15175 When @command{autoupdate} is run, occurrences of @var{old-macro} will
15176 be replaced by the text of @var{implementation} in the updated
15177 @file{configure.ac} file.
15178
15179 If a simple textual replacement is not enough to finish the job of
15180 updating a @file{configure.ac} to modern style, provide instructions for
15181 whatever additional manual work is required as @var{message}. These
15182 instructions will be printed by @command{autoupdate}, and embedded in the
15183 updated @file{configure.ac} file, next to the text of @var{implementation}.
15184
15185 Normally, @command{autoconf} will also issue a warning (in the
15186 ``obsolete'' category) when it expands @var{old-macro}. This warning
15187 does not include @var{message}; it only advises the maintainer to run
15188 @command{autoupdate}. If it is inappropriate to issue this warning, set
15189 the @var{silent} argument to the word @code{silent}. One might want to
15190 use a silent @code{AU_DEFUN} when @var{old-macro} is used in a
15191 widely-distributed third-party macro. If that macro's maintainers are
15192 aware of the need to update their code, it's unnecessary to nag all
15193 of the transitive users of @var{old-macro} as well. This capability
15194 was added to @code{AU_DEFUN} in Autoconf 2.70; older versions of
15195 autoconf will ignore the @var{silent} argument and issue the warning
15196 anyway.
15197
15198 @strong{Caution:} If @var{implementation} contains M4 or M4sugar macros,
15199 they will be evaluated when @command{autoupdate} is run, not emitted
15200 verbatim like the rest of @var{implementation}. This cannot be avoided
15201 with extra quotation, because then @var{old-macro} will not work when
15202 it is called normally. See the definition of @code{AC_FOREACH} in
15203 @file{general.m4} for a workaround.
15204 @end defmac
15205
15206 @defmac AU_ALIAS (@var{old-name}, @var{new-name}, @ovar{silent})
15207 @auindex{ALIAS}
15208 A shorthand version of @code{AU_DEFUN}, to be used when a macro has
15209 simply been renamed. @command{autoupdate} will replace calls to
15210 @var{old-name} with calls to @var{new-name}, keeping any arguments
15211 intact. No instructions for additional manual work will be printed.
15212
15213 The @var{silent} argument works the same as the @var{silent} argument
15214 to @code{AU_DEFUN}. It was added to @code{AU_ALIAS} in Autoconf 2.70.
15215
15216 @strong{Caution:} @code{AU_ALIAS} cannot be used when @var{new-name} is
15217 an M4 or M4sugar macro. See above.
15218 @end defmac
15219
15220 @node Coding Style
15221 @section Coding Style
15222 @cindex Coding style
15223
15224 The Autoconf macros follow a strict coding style. You are encouraged to
15225 follow this style, especially if you intend to distribute your macro,
15226 either by contributing it to Autoconf itself or the
15227 @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
15228 Archive}, or by other means.
15229
15230 The first requirement is to pay great attention to the quotation. For
15231 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
15232
15233 Do not try to invent new interfaces. It is likely that there is a macro
15234 in Autoconf that resembles the macro you are defining: try to stick to
15235 this existing interface (order of arguments, default values, etc.). We
15236 @emph{are} conscious that some of these interfaces are not perfect;
15237 nevertheless, when harmless, homogeneity should be preferred over
15238 creativity.
15239
15240 Be careful about clashes both between M4 symbols and between shell
15241 variables.
15242
15243 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
15244 you are unlikely to generate conflicts. Nevertheless, when you need to
15245 set a special value, @emph{avoid using a regular macro name}; rather,
15246 use an ``impossible'' name. For instance, up to version 2.13, the macro
15247 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
15248 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
15249 But since there is a macro named @code{AC_SUBST_FILE}, it was just
15250 impossible to @samp{AC_SUBST(FILE)}! In this case,
15251 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
15252 have been used (yes, with the parentheses).
15253 @c or better yet, high-level macros such as @code{m4_expand_once}
15254
15255 No Autoconf macro should ever enter the user-variable name space; i.e.,
15256 except for the variables that are the actual result of running the
15257 macro, all shell variables should start with @code{ac_}. In
15258 addition, small macros or any macro that is likely to be embedded in
15259 other macros should be careful not to use obvious names.
15260
15261 @cindex @code{dnl}
15262 Do not use @code{dnl} to introduce comments: most of the comments you
15263 are likely to write are either header comments which are not output
15264 anyway, or comments that should make their way into @file{configure}.
15265 There are exceptional cases where you do want to comment special M4
15266 constructs, in which case @code{dnl} is right, but keep in mind that it
15267 is unlikely.
15268
15269 M4 ignores the leading blanks and newlines before each argument.
15270 Use this feature to
15271 indent in such a way that arguments are (more or less) aligned with the
15272 opening parenthesis of the macro being called. For instance, instead of
15273
15274 @example
15275 AC_CACHE_CHECK(for EMX OS/2 environment,
15276 ac_cv_emxos2,
15277 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
15278 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
15279 @end example
15280
15281 @noindent
15282 write
15283
15284 @example
15285 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15286 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15287 [ac_cv_emxos2=yes],
15288 [ac_cv_emxos2=no])])
15289 @end example
15290
15291 @noindent
15292 or even
15293
15294 @example
15295 AC_CACHE_CHECK([for EMX OS/2 environment],
15296 [ac_cv_emxos2],
15297 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
15298 [return __EMX__;])],
15299 [ac_cv_emxos2=yes],
15300 [ac_cv_emxos2=no])])
15301 @end example
15302
15303 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
15304 cross-compiling, provide a pessimistic value (typically @samp{no}).
15305
15306 Feel free to use various tricks to prevent auxiliary tools, such as
15307 syntax-highlighting editors, from behaving improperly. For instance,
15308 instead of:
15309
15310 @example
15311 m4_bpatsubst([$1], [$"])
15312 @end example
15313
15314 @noindent
15315 use
15316
15317 @example
15318 m4_bpatsubst([$1], [$""])
15319 @end example
15320
15321 @noindent
15322 so that Emacsen do not open an endless ``string'' at the first quote.
15323 For the same reasons, avoid:
15324
15325 @example
15326 test $[#] != 0
15327 @end example
15328
15329 @noindent
15330 and use:
15331
15332 @example
15333 test $[@@%:@@] != 0
15334 @end example
15335
15336 @noindent
15337 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
15338 breaking the bracket-matching highlighting from Emacsen. Note the
15339 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc. Do
15340 not escape when it is unnecessary. Common examples of useless quotation
15341 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
15342 etc.
15343
15344 When using @command{sed}, don't use @option{-e} except for indenting
15345 purposes. With the @code{s} and @code{y} commands, the preferred
15346 separator is @samp{/} unless @samp{/} itself might appear in the pattern
15347 or replacement, in which case you should use @samp{|}, or optionally
15348 @samp{,} if you know the pattern and replacement cannot contain a file
15349 name. If none of these characters will do, choose a printable character
15350 that cannot appear in the pattern or replacement. Characters from the
15351 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
15352 replacement might contain a file name, since they have special meaning
15353 to the shell and are less likely to occur in file names.
15354
15355 @xref{Macro Definitions}, for details on how to define a macro. If a
15356 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
15357 of an @code{AC_REQUIRE} directive, and macros required by other macros
15358 inside arguments do not need to be expanded before this macro, then
15359 use @code{m4_define}. In case of doubt, use @code{AC_DEFUN}.
15360 Also take into account that public third-party macros need to use
15361 @code{AC_DEFUN} in order to be found by @command{aclocal}
15362 (@pxref{Extending aclocal,,, automake, GNU Automake}).
15363 All the @code{AC_REQUIRE} statements should be at the beginning of the
15364 macro, and each statement should be followed by @code{dnl}.
15365
15366 You should not rely on the number of arguments: instead of checking
15367 whether an argument is missing, test that it is not empty. It provides
15368 both a simpler and a more predictable interface to the user, and saves
15369 room for further arguments.
15370
15371 Unless the macro is short, try to leave the closing @samp{])} at the
15372 beginning of a line, followed by a comment that repeats the name of the
15373 macro being defined. This introduces an additional newline in
15374 @command{configure}; normally, that is not a problem, but if you want to
15375 remove it you can use @samp{[]dnl} on the last line. You can similarly
15376 use @samp{[]dnl} after a macro call to remove its newline. @samp{[]dnl}
15377 is recommended instead of @samp{dnl} to ensure that M4 does not
15378 interpret the @samp{dnl} as being attached to the preceding text or
15379 macro output. For example, instead of:
15380
15381 @example
15382 AC_DEFUN([AC_PATH_X],
15383 [AC_MSG_CHECKING([for X])
15384 AC_REQUIRE_CPP()
15385 @r{# @dots{}omitted@dots{}}
15386 AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15387 fi])
15388 @end example
15389
15390 @noindent
15391 you would write:
15392
15393 @example
15394 AC_DEFUN([AC_PATH_X],
15395 [AC_REQUIRE_CPP()[]dnl
15396 AC_MSG_CHECKING([for X])
15397 @r{# @dots{}omitted@dots{}}
15398 AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15399 fi[]dnl
15400 ])# AC_PATH_X
15401 @end example
15402
15403 If the macro is long, try to split it into logical chunks. Typically,
15404 macros that check for a bug in a function and prepare its
15405 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
15406 this setup. Do not hesitate to introduce auxiliary macros to factor
15407 your code.
15408
15409 In order to highlight the recommended coding style, here is a macro
15410 written the old way:
15411
15412 @example
15413 dnl Check for EMX on OS/2.
15414 dnl _AC_EMXOS2
15415 AC_DEFUN(_AC_EMXOS2,
15416 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
15417 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
15418 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
15419 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
15420 @end example
15421
15422 @noindent
15423 and the new way:
15424
15425 @example
15426 # _AC_EMXOS2
15427 # ----------
15428 # Check for EMX on OS/2.
15429 m4_define([_AC_EMXOS2],
15430 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15431 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15432 [ac_cv_emxos2=yes],
15433 [ac_cv_emxos2=no])])
15434 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
15435 ])# _AC_EMXOS2
15436 @end example
15437
15438
15439
15440
15441 @c ============================================= Portable Shell Programming
15442
15443 @node Portable Shell
15444 @chapter Portable Shell Programming
15445 @cindex Portable shell programming
15446
15447 When writing your own checks, there are some shell-script programming
15448 techniques you should avoid in order to make your code portable. The
15449 Bourne shell and upward-compatible shells like the Korn shell and Bash
15450 have evolved over the years, and many features added to the original
15451 System7 shell are now supported on all interesting porting targets.
15452 However, the following discussion between Russ Allbery and Robert Lipe
15453 is worth reading:
15454
15455 @noindent
15456 Russ Allbery:
15457
15458 @quotation
15459 The GNU assumption that @command{/bin/sh} is the one and only shell
15460 leads to a permanent deadlock. Vendors don't want to break users'
15461 existing shell scripts, and there are some corner cases in the Bourne
15462 shell that are not completely compatible with a POSIX shell. Thus,
15463 vendors who have taken this route will @emph{never} (OK@dots{}``never say
15464 never'') replace the Bourne shell (as @command{/bin/sh}) with a
15465 POSIX shell.
15466 @end quotation
15467
15468 @noindent
15469 Robert Lipe:
15470
15471 @quotation
15472 This is exactly the problem. While most (at least most System V's) do
15473 have a Bourne shell that accepts shell functions most vendor
15474 @command{/bin/sh} programs are not the POSIX shell.
15475
15476 So while most modern systems do have a shell @emph{somewhere} that meets the
15477 POSIX standard, the challenge is to find it.
15478 @end quotation
15479
15480 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15481 is to find such a shell. But to prevent trouble, if you're not using
15482 M4sh you should not take advantage of features that were added after Unix
15483 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15484 negated character classes, or even @command{unset}. @code{#} comments,
15485 while not in Unix version 7, were retrofitted in the original Bourne
15486 shell and can be assumed to be part of the least common denominator.
15487
15488 On the other hand, if you're using M4sh you can assume that the shell
15489 has the features that were added in SVR2 (circa 1984), including shell
15490 functions,
15491 @command{return}, @command{unset}, and I/O redirection for builtins. For
15492 more information, refer to @uref{https://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15493 However, some pitfalls have to be avoided for portable use of these
15494 constructs; these will be documented in the rest of this chapter.
15495 See in particular @ref{Shell Functions} and @ref{Limitations of
15496 Builtins, , Limitations of Shell Builtins}.
15497
15498 The set of external programs you should run in a @command{configure} script
15499 is fairly small. @xref{Utilities in Makefiles, , Utilities in
15500 Makefiles, standards, The GNU Coding Standards}, for the list. This
15501 restriction allows users to start out with a fairly small set of
15502 programs and build the rest, avoiding too many interdependencies between
15503 packages.
15504
15505 Some of these external utilities have a portable subset of features; see
15506 @ref{Limitations of Usual Tools}.
15507
15508 There are other sources of documentation about shells. The
15509 specification for the POSIX
15510 @uref{https://@/pubs.opengroup.org/@/onlinepubs/@/9699919799/@/utilities/@/V3_chap02.html,
15511 Shell Command Language}, though more generous than the restrictive shell
15512 subset described above, is fairly portable nowadays. Also please see
15513 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15514
15515 @menu
15516 * Systemology:: A zoology of operating systems
15517 * Shellology:: A zoology of shells
15518 * Invoking the Shell:: Invoking the shell as a command
15519 * Here-Documents:: Quirks and tricks
15520 * File Descriptors:: FDs and redirections
15521 * Signal Handling:: Shells, signals, and headaches
15522 * File System Conventions:: File names
15523 * Shell Pattern Matching:: Pattern matching
15524 * Shell Substitutions:: Variable and command expansions
15525 * Assignments:: Varying side effects of assignments
15526 * Parentheses:: Parentheses in shell scripts
15527 * Special Shell Variables:: Variables you should not change
15528 * Shell Functions:: What to look out for if you use them
15529 * Limitations of Builtins:: Portable use of not so portable /bin/sh
15530 * Limitations of Usual Tools:: Portable use of portable tools
15531 @end menu
15532
15533
15534 @node Systemology
15535 @section Systemology
15536 @cindex Systemology
15537
15538 This section aims at presenting some systems and pointers to
15539 documentation. It may help you addressing particular problems reported
15540 by users.
15541
15542 @uref{https://@/en.wikipedia.org/@/wiki/@/POSIX, POSIX-conforming
15543 systems} are derived from the
15544 @uref{https://@/en.wikipedia.org/@/wiki/@/Unix, Unix operating system}.
15545
15546 The @uref{https://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
15547 contains a table correlating the features of various POSIX-conforming
15548 systems. @uref{https://@/www.levenez.com/@/unix/, Unix History} is a
15549 simplified diagram of how many Unix systems were derived from each
15550 other.
15551
15552 @uref{https://@/heirloom.sourceforge.net/, The Heirloom Project}
15553 provides some variants of traditional implementations of Unix utilities.
15554
15555 @table @asis
15556 @item Darwin
15557 @cindex Darwin
15558 @cindex macOS
15559 @cindex Mac OS X
15560 Darwin is a partially proprietary operating system maintained by Apple
15561 Computer and used by most of their products. It is also known as macOS,
15562 iOS, etc.@: depending on the exact variant. Older versions were called
15563 ``Mac OS X.''
15564
15565 By default the file system will be case insensitive, albeit case
15566 preserving. This can cause nasty problems: for instance, the
15567 installation attempt for a package having an @file{INSTALL} file can
15568 result in @samp{make install} reporting that nothing is to be done!
15569
15570 Darwin does support case-sensitive file systems, but they must be
15571 formatted specially as such, and Apple discourages use of a
15572 case-sensitive volume for the base operating system. To build software
15573 that expects case-sensitive filenames, it is best to create a separate
15574 disk volume or disk image formatted as case sensitive; this can be done
15575 using the @command{diskutil} command or the Disk Utility application.
15576
15577 @item QNX
15578 @cindex QNX
15579 @c FIXME: Please, if you feel like writing something more precise,
15580 @c it'd be great. In particular, I can't understand the difference with
15581 @c QNX Neutrino.
15582 QNX is a realtime operating system running on Intel architecture
15583 meant to be scalable from the small embedded systems to the hundred
15584 processor super-computer. More
15585 information is available on the
15586 @uref{https://@/blackberry.qnx.com/@/en, QNX home page}.
15587
15588 @item Unix version 7
15589 @cindex Unix version 7
15590 @cindex V7
15591 Officially this was called the ``Seventh Edition'' of ``the UNIX
15592 time-sharing system'' but we use the more-common name ``Unix version 7''.
15593 Documentation is available in the
15594 @uref{https://@/s3.amazonaws.com/@/plan9-bell-labs/@/7thEdMan/@/index.html,
15595 Unix Seventh Edition Manual}.
15596 Previous versions of Unix are called ``Unix version 6'', etc., but
15597 they were not as widely used.
15598 @end table
15599
15600
15601 @node Shellology
15602 @section Shellology
15603 @cindex Shellology
15604
15605 There are several families of shells, most prominently the Bourne family
15606 and the C shell family which are deeply incompatible. If you want to
15607 write portable shell scripts, avoid members of the C shell family. The
15608 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15609 Shell difference FAQ} includes a small history of POSIX shells, and a
15610 comparison between several of them.
15611
15612 Below we describe some of the members of the Bourne shell family.
15613
15614 @table @asis
15615 @item Ash
15616 @cindex Ash
15617 Ash is often used on GNU/Linux and BSD
15618 systems as a light-weight Bourne-compatible shell. Ash 0.2 has some
15619 bugs that are fixed in the 0.3.x series, but portable shell scripts
15620 should work around them, since version 0.2 is still shipped with many
15621 GNU/Linux distributions.
15622
15623 To be compatible with Ash 0.2:
15624
15625 @itemize @minus
15626 @item
15627 don't use @samp{$?} after expanding empty or unset variables,
15628 or at the start of an @command{eval}:
15629
15630 @example
15631 foo=
15632 false
15633 $foo
15634 echo "Do not use it: $?"
15635 false
15636 eval 'echo "Do not use it: $?"'
15637 @end example
15638
15639 @item
15640 don't use command substitution within variable expansion:
15641
15642 @example
15643 cat $@{FOO=`bar`@}
15644 @end example
15645
15646 @item
15647 beware that single builtin substitutions are not performed by a
15648 subshell, hence their effect applies to the current shell! @xref{Shell
15649 Substitutions}, item ``Command Substitution''.
15650 @end itemize
15651
15652 @item Bash
15653 @cindex Bash
15654 To detect whether you are running Bash, test whether
15655 @code{BASH_VERSION} is set. To require
15656 POSIX compatibility, run @samp{set -o posix}. @xref{Bash POSIX
15657 Mode, , Bash POSIX Mode, bash, The GNU Bash Reference
15658 Manual}, for details.
15659
15660 @item Bash 2.05 and later
15661 @cindex Bash 2.05 and later
15662 Versions 2.05 and later of Bash use a different format for the
15663 output of the @command{set} builtin, designed to make evaluating its
15664 output easier. However, this output is not compatible with earlier
15665 versions of Bash (or with many other shells, probably). So if
15666 you use Bash 2.05 or higher to execute @command{configure},
15667 you'll need to use Bash 2.05 for all other build tasks as well.
15668
15669 @item Ksh
15670 @cindex Ksh
15671 @cindex Korn shell
15672 @prindex @samp{ksh}
15673 @prindex @samp{ksh88}
15674 @prindex @samp{ksh93}
15675 The Korn shell is compatible with the Bourne family and it mostly
15676 conforms to POSIX@. It has two major variants commonly
15677 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15678 release. It is usually called @command{ksh}, but is called @command{sh}
15679 on some hosts if you set your path appropriately.
15680
15681 On Solaris 11, @command{/bin/sh} and @command{/usr/bin/ksh} are both
15682 @samp{ksh93}. On Solaris 10 and earlier, @command{/bin/sh} is a
15683 pre-POSIX Bourne shell and the Korn shell is found elsewhere:
15684 @prindex @command{/usr/bin/ksh} on Solaris
15685 @command{/usr/bin/ksh} is @samp{ksh88} on Solaris 10,
15686 @prindex @command{/usr/xpg4/bin/sh} on Solaris
15687 @command{/usr/xpg4/bin/sh} is a POSIX-compliant variant of
15688 @samp{ksh88} on Solaris 10 and later,
15689 @prindex @command{/usr/dt/bin/dtksh} on Solaris
15690 and @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15691 Variants that are not standard may be parts of optional
15692 packages. There is no extra charge for these packages, but they are
15693 not part of a minimal OS install and therefore some installations may
15694 not have it.
15695
15696 @item Pdksh
15697 @prindex @samp{pdksh}
15698 A public-domain clone of the Korn shell called @command{pdksh} is widely
15699 available: it has most of the @samp{ksh88} features along with a few of
15700 its own. It usually sets @code{KSH_VERSION}, except if invoked as
15701 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15702 POSIX compatibility by running @samp{set -o posix}. Unfortunately, with
15703 @command{pdksh} 5.2.14 (the latest stable version as of 2025)
15704 POSIX mode is buggy and causes @command{pdksh} to depart from POSIX in
15705 at least one respect, see @ref{Shell Substitutions}.
15706
15707 @item Zsh
15708 @cindex Zsh
15709 To detect whether you are running @command{zsh}, test whether
15710 @code{ZSH_VERSION} is set. By default @command{zsh} is @emph{not}
15711 compatible with the Bourne shell: you must execute @samp{emulate sh},
15712 and for @command{zsh} versions before 3.1.6-dev-18 you must also
15713 set @code{NULLCMD} to @samp{:}. @xref{Compatibility, , Compatibility,
15714 zsh, The Z Shell Manual}, for details.
15715
15716 The default Mac OS X @command{sh} was originally Zsh; it was changed to
15717 Bash in Mac OS X 10.2 (2002) and changed back to Zsh in macOS 10.15 (2019).
15718 @end table
15719
15720 @node Invoking the Shell
15721 @section Invoking the Shell
15722 @cindex invoking the shell
15723 @cindex shell invocation
15724
15725 The Korn shell (up to at least version M-12/28/93d) has a bug when
15726 invoked on a file whose name does not contain a slash. It first
15727 searches for the file's name in @env{PATH}, and if found it executes
15728 that rather than the original file. For example, assuming there is a
15729 binary executable @file{/usr/bin/script} in your @env{PATH}, the last
15730 command in the following example fails because the Korn shell finds
15731 @file{/usr/bin/script} and refuses to execute it as a shell script:
15732
15733 @example
15734 $ @kbd{touch xxyzzyz script}
15735 $ @kbd{ksh xxyzzyz}
15736 $ @kbd{ksh ./script}
15737 $ @kbd{ksh script}
15738 ksh: script: cannot execute
15739 @end example
15740
15741 Bash 2.03 has a bug when invoked with the @option{-c} option: if the
15742 option-argument ends in backslash-newline, Bash incorrectly reports a
15743 syntax error. The problem does not occur if a character follows the
15744 backslash:
15745
15746 @example
15747 $ @kbd{$ bash -c 'echo foo \}
15748 > @kbd{'}
15749 bash: -c: line 2: syntax error: unexpected end of file
15750 $ @kbd{bash -c 'echo foo \}
15751 > @kbd{ '}
15752 foo
15753 @end example
15754
15755 @noindent
15756 @xref{Backslash-Newline-Empty}, for how this can cause problems in makefiles.
15757
15758 @node Here-Documents
15759 @section Here-Documents
15760 @cindex Here-documents
15761 @cindex Shell here-documents
15762
15763 Because unquoted here-documents are subject to parameter expansion and
15764 command substitution, the characters @samp{$} and @samp{`} are special
15765 in unquoted here-documents and should be escaped by @samp{\} if you want
15766 them as-is. Also, @samp{\} is special if it precedes @samp{$},
15767 @samp{`}, newline or @samp{\} itself, so @samp{\} should be doubled if
15768 it appears before these characters and you want it as-is.
15769
15770 Using command substitutions in a here-document that is fed to a shell
15771 function is not portable. For example, with Solaris 10 @command{/bin/sh}:
15772
15773 @example
15774 $ @kbd{kitty () @{ cat; @}}
15775 $ @kbd{kitty <<EOF
15776 > `echo ok`
15777 > EOF}
15778 /tmp/sh199886: cannot open
15779 $ @kbd{echo $?}
15780 1
15781 @end example
15782
15783 Some shells mishandle large here-documents: for example,
15784 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 POSIX shell, which are
15785 derived from Korn shell version M-12/28/93d, mishandle braced variable
15786 expansion that crosses a 1024- or 4096-byte buffer boundary
15787 within a here-document. Only the part of the variable name after the boundary
15788 is used. For example, @code{$@{variable@}} could be replaced by the expansion
15789 of @code{$@{ble@}}. If the end of the variable name is aligned with the block
15790 boundary, the shell reports an error, as if you used @code{$@{@}}.
15791 Instead of @code{$@{variable-default@}}, the shell may expand
15792 @code{$@{riable-default@}}, or even @code{$@{fault@}}. This bug can often
15793 be worked around by omitting the braces: @code{$variable}. The bug was
15794 fixed in
15795 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15796 still shipping older versions with the bug.
15797
15798 Empty here-documents are not portable either; with the following code,
15799 @command{zsh} up to at least version 4.3.10 creates a file with a single
15800 newline, whereas other shells create an empty file:
15801
15802 @example
15803 cat >file <<EOF
15804 EOF
15805 @end example
15806
15807 Many shells (including the Bourne shell) implement here-documents
15808 inefficiently. In particular, some shells can be extremely inefficient when
15809 a single statement contains many here-documents. For instance if your
15810 @file{configure.ac} includes something like:
15811
15812 @example
15813 @group
15814 AS_IF([<cross_compiling>],
15815 [assume this and that],
15816 [check this
15817 check that
15818 check something else
15819 @dots{}
15820 on and on forever
15821 @dots{}])
15822 @end group
15823 @end example
15824
15825 A shell parses the whole @code{if}/@code{fi} construct generated by
15826 @code{AS_IF}, creating
15827 temporary files for each here-document in it. Some shells create links
15828 for such here-documents on every @code{fork}, so that the clean-up code
15829 they had installed correctly removes them. It is creating the links
15830 that can take the shell forever.
15831
15832 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15833 @code{if}/@code{fi} constructs, would improve the performance
15834 significantly. Anyway, this kind of construct is not exactly the
15835 typical use of Autoconf. In fact, it's even not recommended, because M4
15836 macros can't look into shell conditionals, so we may fail to expand a
15837 macro when it was expanded before in a conditional path, and the
15838 condition turned out to be false at runtime, and we end up not
15839 executing the macro at all.
15840
15841 Be careful with the use of @samp{<<-} to unindent here-documents. The
15842 behavior is only portable for stripping leading @key{TAB}s, and things
15843 can silently break if an overzealous editor converts to using leading
15844 spaces (not all shells are nice enough to warn about unterminated
15845 here-documents).
15846
15847 @example
15848 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
15849 1
15850 2
15851 done
15852 $ @kbd{printf 'cat <<-x\n 1\n 2\n x\n' | bash-3.2 && echo done}
15853 1
15854 2
15855 x
15856 done
15857 @end example
15858
15859 @node File Descriptors
15860 @section File Descriptors
15861 @cindex Descriptors
15862 @cindex File descriptors
15863 @cindex Shell file descriptors
15864
15865 Most shells, if not all (including Bash, Zsh, Ash), output traces on
15866 stderr, even for subshells. This might result in undesirable content
15867 if you meant to capture the standard-error output of the inner command:
15868
15869 @example
15870 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15871 $ @kbd{cat stderr}
15872 + eval echo foo >&2
15873 + echo foo
15874 foo
15875 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15876 $ @kbd{cat stderr}
15877 + eval 'echo foo >&2'
15878 ++ echo foo
15879 foo
15880 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15881 @i{# Traces on startup files deleted here.}
15882 $ @kbd{cat stderr}
15883 +zsh:1> eval echo foo >&2
15884 +zsh:1> echo foo
15885 foo
15886 @end example
15887
15888 @noindent
15889 One workaround is to grep out uninteresting lines, hoping not to remove
15890 good ones.
15891
15892 If you intend to redirect both standard error and standard output,
15893 redirect standard output first. This works better with AIX,
15894 since its shell mishandles tracing if standard error is redirected
15895 first:
15896
15897 @example
15898 $ @kbd{sh -x -c ': 2>err >out'}
15899 + :
15900 + 2> err $ @kbd{cat err}
15901 1> out
15902 @end example
15903
15904 Don't try to redirect the standard error of a command substitution. It
15905 must be done @emph{inside} the command substitution. When running
15906 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15907 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15908
15909 On the other hand, some shells, such as Solaris or FreeBSD
15910 @command{/bin/sh}, warn about missing programs before performing
15911 redirections. Therefore, to silently check whether a program exists, it
15912 is necessary to perform redirections on a subshell or brace group:
15913 @example
15914 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15915 nosuch: not found
15916 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15917 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15918 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15919 @end example
15920
15921 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15922 shell pipeline.
15923
15924 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15925 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15926
15927 Some shells, like @command{ash}, don't recognize bi-directional
15928 redirection (@samp{<>}). And even on shells that recognize it, it is
15929 not portable to use on fifos: POSIX does not require read-write support
15930 for named pipes, and Cygwin does not support it:
15931
15932 @example
15933 $ @kbd{mkfifo fifo}
15934 $ @kbd{exec 5<>fifo}
15935 $ @kbd{echo hi >&5}
15936 bash: echo: write error: Communication error on send
15937 @end example
15938
15939 @noindent
15940 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15941 regular files when using @samp{<>}:
15942
15943 @example
15944 $ @kbd{echo a > file}
15945 $ @kbd{bash -c ': 1<>file'; cat file}
15946 a
15947 $ @kbd{dash -c ': 1<>file'; cat file}
15948 $ rm a
15949 @end example
15950
15951 Solaris 10 @code{/bin/sh} executes redirected compound commands
15952 in a subshell, while other shells don't:
15953
15954 @example
15955 $ @kbd{/bin/sh -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15956 0
15957 $ @kbd{ksh -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15958 1
15959 $ @kbd{bash -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15960 1
15961 @end example
15962
15963 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15964 (even if it is redirected) in a loop after the first iteration, or in a
15965 shell function after the first call:
15966
15967 @example
15968 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15969 $ @kbd{ls x*}
15970 x1
15971 $ @kbd{f () @{ : >$1; @}; f y1; f y2; f y3;}
15972 $ @kbd{ls y*}
15973 y1
15974 @end example
15975
15976 @noindent
15977 As a workaround, @command{echo} or @command{eval} can be used.
15978
15979 When running a subsidiary program be careful if descriptor 0 is not open
15980 for reading or decriptors 1 and 2 are not open for writing,
15981 as the subsidiary program might not behave as expected.
15982 In particular, don't rely on file descriptors 0, 1, and 2 remaining closed in a
15983 subsidiary program. If any of these descriptors is closed, the
15984 operating system may open an unspecified file for the descriptor in the
15985 newly created process.
15986
15987 If you want a file descriptor above 2 to be inherited into a child
15988 process, then you must use redirections specific to that command or a
15989 containing subshell or command group, rather than relying on
15990 @command{exec} in the shell. In @command{ksh} as well as HP-UX
15991 @command{sh}, file descriptors above 2 which are opened using
15992 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15993 that involved in the fork-and-exec which runs a program or script):
15994
15995 @example
15996 $ @kbd{echo 'echo hello >&5' >k}
15997 $ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15998 hello
15999 $ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
16000 hello
16001 $ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
16002 ./k[1]: 5: cannot open [Bad file number]
16003 $ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
16004 hello
16005 $ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
16006 hello
16007 $ @kbd{ksh -c '5>t ksh ./k; cat t}
16008 hello
16009 @end example
16010
16011 Don't rely on duplicating a closed file descriptor to cause an
16012 error. With Solaris 10 @command{/bin/sh}, failed duplication is silently
16013 ignored, which can cause unintended leaks to the original file
16014 descriptor. In this example, observe the leak to standard output:
16015
16016 @example
16017 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
16018 bash: 3: Bad file descriptor
16019 1
16020 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
16021 hi
16022 0
16023 @end example
16024
16025 Fortunately, an attempt to close an already closed file descriptor will
16026 portably succeed. Likewise, it is safe to use either style of
16027 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
16028 even if it doesn't match the read/write mode that the file descriptor
16029 was opened with.
16030
16031 DOS variants cannot rename or remove open files, such as in
16032 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
16033 perfectly portable among POSIX hosts.
16034
16035 A few ancient systems reserved some file descriptors. By convention,
16036 file descriptor 3 was opened to @file{/dev/tty} when you logged into
16037 Eighth Edition (1985) through Tenth Edition Unix (1989). File
16038 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
16039 1990), though we don't now remember what it was. Both these systems are
16040 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
16041 other file descriptors.
16042
16043 On the other hand, you can't portably use multi-digit file descriptors.
16044 @command{dash} and Solaris @command{ksh} don't understand any file
16045 descriptor larger than @samp{9}:
16046
16047 @example
16048 $ @kbd{bash -c 'exec 10>&-'; echo $?}
16049 0
16050 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
16051 0
16052 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
16053 ksh[1]: exec: 10: not found
16054 127
16055 $ @kbd{dash -c 'exec 9>&-'; echo $?}
16056 0
16057 $ @kbd{dash -c 'exec 10>&-'; echo $?}
16058 exec: 1: 10: not found
16059 2
16060 @end example
16061
16062 @c <https://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
16063 @node Signal Handling
16064 @section Signal Handling
16065 @cindex Signal handling in the shell
16066 @cindex Signals, shells and
16067
16068 Portable handling of signals within the shell is another major source of
16069 headaches. This is worsened by the fact that various different, mutually
16070 incompatible approaches are possible in this area, each with its
16071 distinctive merits and demerits. A detailed description of these possible
16072 approaches, as well as of their pros and cons, can be found in
16073 @uref{https://www.cons.org/cracauer/sigint.html, this article}.
16074
16075 Solaris 10 @command{/bin/sh} automatically traps most signals by default;
16076 the shell still exits with error upon termination by one of those signals,
16077 but in such a case the exit status might be somewhat unexpected (even if
16078 allowed by POSIX, strictly speaking):
16079 @c FIXME: We had a reference for this behavior but the website no longer
16080 @c exists and the page is not in the Internet Archive. --zw 2020-07-10.
16081
16082 @example
16083 $ @kbd{bash -c 'kill -1 $$'; echo $?} # Will exit 128 + (signal number).
16084 Hangup
16085 129
16086 $ @kbd{/bin/ksh -c 'kill -15 $$'; echo $?} # Likewise.
16087 Terminated
16088 143
16089 $ @kbd{for sig in 1 2 3 15; do}
16090 > @kbd{ echo $sig:}
16091 > @kbd{ /bin/sh -c "kill -$s \$\$"; echo $?}
16092 > @kbd{done}
16093 signal 1:
16094 Hangup
16095 129
16096 signal 2:
16097 208
16098 signal 3:
16099 208
16100 signal 15:
16101 208
16102 @end example
16103
16104 This gets even worse if one is using the POSIX ``wait'' interface to get
16105 details about the shell process terminations: it will result in the shell
16106 having exited normally, rather than by receiving a signal.
16107
16108 @example
16109 $ @kbd{cat > foo.c <<'END'}
16110 #include <stdio.h> /* for printf */
16111 #include <stdlib.h> /* for system */
16112 #include <sys/wait.h> /* for WIF* macros */
16113 int main(void)
16114 @{
16115 int status = system ("kill -15 $$");
16116 printf ("Terminated by signal: %s\n",
16117 WIFSIGNALED (status) ? "yes" : "no");
16118 printf ("Exited normally: %s\n",
16119 WIFEXITED (status) ? "yes" : "no");
16120 return 0;
16121 @}
16122 END
16123 @c $$ font-lock
16124 $ @kbd{cc -o foo foo.c}
16125 $ @kbd{./a.out} # On GNU/Linux
16126 Terminated by signal: no
16127 Exited normally: yes
16128 $ @kbd{./a.out} # On Solaris 10
16129 Terminated by signal: yes
16130 Exited normally: no
16131 @end example
16132
16133 Various shells seem to handle @code{SIGQUIT} specially: they ignore it even
16134 if it is not blocked, and even if the shell is not running interactively
16135 (in fact, even if the shell has no attached tty); among these shells
16136 are at least Bash (from version 2 onward), Zsh 4.3.12, Solaris 10
16137 @code{/bin/ksh} and @code{/usr/xpg4/bin/sh}, and AT&T @code{ksh93} (2011).
16138 Still, @code{SIGQUIT} seems to be trappable quite portably within all
16139 these shells. OTOH, some other shells doesn't special-case the handling
16140 of @code{SIGQUIT}; among these shells are at least @code{pdksh} 5.2.14,
16141 Solaris 10 and NetBSD 5.1 @code{/bin/sh}, and the Almquist Shell 0.5.5.1.
16142
16143 Some shells (especially Korn shells and derivatives) might try to
16144 propagate to themselves a signal that has killed a child process; this is
16145 not a bug, but a conscious design choice (although its overall value might
16146 be debatable). The exact details of how this is attained vary from shell
16147 to shell. For example, upon running @code{perl -e 'kill 2, $$'}, after
16148 the perl process has been interrupted, AT&T @code{ksh93} (2011) will
16149 proceed to send itself a @code{SIGINT}, while Solaris 10 @code{/bin/ksh}
16150 and @code{/usr/xpg4/bin/sh} will proceed to exit with status 130 (i.e.,
16151 128 + 2). In any case, if there is an active trap associated with
16152 @code{SIGINT}, those shells will correctly execute it.
16153
16154 @c See: <https://www.austingroupbugs.net/view.php?id=51>
16155 Some Korn shells, when a child process die due receiving a signal with
16156 signal number @var{n}, can leave in @samp{$?} an exit status of
16157 256+@var{n} instead of the more common 128+@var{n}. Observe the
16158 difference between AT&T @code{ksh93} (2011) and @code{bash} 4.1.5 on
16159 Debian:
16160
16161 @example
16162 $ @kbd{/bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?'}
16163 /bin/ksh: line 1: 7837: Hangup
16164 257
16165 $ @kbd{/bin/bash -c 'sh -c "kill -1 \$\$"; echo $?'}
16166 /bin/bash: line 1: 7861 Hangup (sh -c "kill -1 \$\$")
16167 129
16168 @end example
16169
16170 @noindent
16171 This @command{ksh} behavior is allowed by POSIX, if implemented with
16172 due care; see this @uref{https://www.austingroupbugs.net/view.php?id=51,
16173 Austin Group discussion} for more background. However, if it is not
16174 implemented with proper care, such a behavior might cause problems
16175 in some corner cases. To see why, assume we have a ``wrapper'' script
16176 like this:
16177
16178 @example
16179 #!/bin/sh
16180 # Ignore some signals in the shell only, not in its child processes.
16181 trap : 1 2 13 15
16182 wrapped_command "$@@"
16183 ret=$?
16184 other_command
16185 exit $ret
16186 @end example
16187
16188 @noindent
16189 If @command{wrapped_command} is interrupted by a @code{SIGHUP} (which
16190 has signal number 1), @code{ret} will be set to 257. Unless the
16191 @command{exit} shell builtin is smart enough to understand that such
16192 a value can only have originated from a signal, and adjust the final
16193 wait status of the shell appropriately, the value 257 will just get
16194 truncated to 1 by the closing @code{exit} call, so that a caller of
16195 the script will have no way to determine that termination by a signal
16196 was involved. Observe the different behavior of AT&T @code{ksh93}
16197 (2011) and @code{bash} 4.1.5 on Debian:
16198
16199 @example
16200 $ @kbd{cat foo.sh}
16201 #!/bin/sh
16202 sh -c 'kill -1 $$'
16203 ret=$?
16204 echo $ret
16205 exit $ret
16206 $ @kbd{/bin/ksh foo.sh; echo $?}
16207 foo.sh: line 2: 12479: Hangup
16208 257
16209 1
16210 $ @kbd{/bin/bash foo.sh; echo $?}
16211 foo.sh: line 2: 12487 Hangup (sh -c 'kill -1 $$')
16212 129
16213 129
16214 @end example
16215
16216 @node File System Conventions
16217 @section File System Conventions
16218 @cindex File system conventions
16219
16220 Autoconf uses shell-script processing extensively, so the file names
16221 that it processes should not contain characters that are special to the
16222 shell. Special characters include space, tab, newline, NUL, and
16223 the following:
16224
16225 @example
16226 " # $ & ' ( ) * ; < = > ? [ \ ` |
16227 @end example
16228
16229 Also, file names should not begin with @samp{~} or @samp{-}, and should
16230 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
16231 immediately after @samp{:}. On POSIX-like platforms, directory names
16232 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
16233 path separator.
16234
16235 These restrictions apply not only to the files that you distribute, but
16236 also to the absolute file names of your source, build, and destination
16237 directories.
16238
16239 On some POSIX-like platforms, @samp{!} and @samp{^} are special too, so
16240 they should be avoided.
16241
16242 POSIX lets implementations treat leading @file{//} specially, but
16243 requires leading @file{///} and beyond to be equivalent to @file{/}.
16244 Most Unix variants treat @file{//} like @file{/}. However, some treat
16245 @file{//} as a ``super-root'' that can provide access to files that are
16246 not otherwise reachable from @file{/}. The super-root tradition began
16247 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
16248 has revived it.
16249
16250 While @command{autoconf} and friends are usually run on some POSIX
16251 variety, they can be used on other systems, most notably DOS
16252 variants. This impacts several assumptions regarding file names.
16253
16254 @noindent
16255 For example, the following code:
16256
16257 @example
16258 case $foo_dir in
16259 /*) # Absolute
16260 ;;
16261 *)
16262 foo_dir=$dots$foo_dir ;;
16263 esac
16264 @end example
16265
16266 @noindent
16267 fails to properly detect absolute file names on those systems, because
16268 they can use a drivespec, and usually use a backslash as directory
16269 separator. If you want to be portable to DOS variants (at the
16270 price of rejecting valid but oddball POSIX file names like @file{a:\b}),
16271 you can check for absolute file names like this:
16272
16273 @cindex absolute file names, detect
16274 @example
16275 case $foo_dir in
16276 [\\/]* | ?:[\\/]* ) # Absolute
16277 ;;
16278 *)
16279 foo_dir=$dots$foo_dir ;;
16280 esac
16281 @end example
16282
16283 @noindent
16284 Make sure you quote the brackets if appropriate and keep the backslash as
16285 first character. @xref{case, , Limitations of Shell Builtins}.
16286
16287 Also, because the colon is used as part of a drivespec, these systems don't
16288 use it as path separator. When creating or accessing paths, you can use the
16289 @code{PATH_SEPARATOR} output variable instead. @command{configure} sets this
16290 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
16291 starts up.
16292
16293 File names need extra care as well. While DOS variants
16294 that are POSIXy enough to run @command{autoconf} (such as DJGPP)
16295 are usually able to handle long file names properly, there are still
16296 limitations that can seriously break packages. Several of these issues
16297 can be easily detected by the
16298 @uref{https://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
16299 package.
16300
16301 A short overview follows; problems are marked with SFN/LFN to
16302 indicate where they apply: SFN means the issues are only relevant to
16303 plain DOS, not to DOS under Microsoft Windows
16304 variants, while LFN identifies problems that exist even under
16305 Microsoft Windows variants.
16306
16307 @table @asis
16308 @item No multiple dots (SFN)
16309 DOS cannot handle multiple dots in file names. This is an especially
16310 important thing to remember when building a portable configure script,
16311 as @command{autoconf} uses a .in suffix for template files.
16312
16313 This is perfectly OK on POSIX variants:
16314
16315 @example
16316 AC_CONFIG_HEADERS([config.h])
16317 AC_CONFIG_FILES([source.c foo.bar])
16318 AC_OUTPUT
16319 @end example
16320
16321 @noindent
16322 but it causes problems on DOS, as it requires @samp{config.h.in},
16323 @samp{source.c.in} and @samp{foo.bar.in}. To make your package more portable
16324 to DOS-based environments, you should use this instead:
16325
16326 @example
16327 AC_CONFIG_HEADERS([config.h:config.hin])
16328 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
16329 AC_OUTPUT
16330 @end example
16331
16332 @item No leading dot (SFN)
16333 DOS cannot handle file names that start with a dot. This is usually
16334 not important for @command{autoconf}.
16335
16336 @item Case insensitivity (LFN)
16337 DOS is case insensitive, so you cannot, for example, have both a
16338 file called @samp{INSTALL} and a directory called @samp{install}. This
16339 also affects @command{make}; if there's a file called @samp{INSTALL} in
16340 the directory, @samp{make install} does nothing (unless the
16341 @samp{install} target is marked as PHONY).
16342
16343 @item The 8+3 limit (SFN)
16344 Because the DOS file system only stores the first 8 characters of
16345 the file name and the first 3 of the extension, those must be unique.
16346 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
16347 @file{foobar-prettybird.c} all resolve to the same file name
16348 (@file{FOOBAR-P.C}). The same goes for @file{foo.bar} and
16349 @file{foo.bartender}.
16350
16351 The 8+3 limit is not usually a problem under Microsoft Windows, as it
16352 uses numeric
16353 tails in the short version of file names to make them unique. However, a
16354 registry setting can turn this behavior off. While this makes it
16355 possible to share file trees containing long file names between SFN
16356 and LFN environments, it also means the above problem applies there
16357 as well.
16358
16359 @item Invalid characters (LFN)
16360 Some characters are invalid in DOS file names, and should therefore
16361 be avoided. In a LFN environment, these are @samp{/}, @samp{\},
16362 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
16363 In a SFN environment, other characters are also invalid. These
16364 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
16365
16366 @item Invalid names (LFN)
16367 Some DOS file names are reserved, and cause problems if you
16368 try to use files with those names. These names include @file{CON},
16369 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
16370 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
16371 File names are case insensitive, so even names like
16372 @file{aux/config.guess} are disallowed.
16373
16374 @end table
16375
16376 @node Shell Pattern Matching
16377 @section Shell Pattern Matching
16378 @cindex Shell pattern matching
16379
16380 Portable patterns should avoid the following constructs:
16381
16382 @itemize @bullet
16383 @item
16384 A bracket expression like @samp{[a-z]} outside the C locale.
16385 This pattern may match characters that are not lower-case letters.
16386 Outside the C locale, use @samp{[[:lower:]]} instead,
16387 or to match just lower-case ASCII letters use
16388 @samp{[abcdefghijklmnopqrstuvwxyz]}.
16389
16390 @item
16391 A bracket expression starting with @samp{^}.
16392 For example, @samp{[!-aeiou]} is portable, but @samp{[^-aeiou]} is not.
16393
16394 @item
16395 When matching file names, a pattern containing @samp{*}, @samp{?} or
16396 @samp{[...]} that might match the file names @samp{.} or @samp{..}.
16397 For example @samp{.*} might match @samp{.} and @samp{..}, but it might not.
16398
16399 @item
16400 Any of the following characters,
16401 unless quoted or escaped or in a bracket expression:
16402
16403 @example
16404 ! # % = [ ] ^ @{ @} ~
16405 @end example
16406
16407 An unescaped @samp{[} that does not introduce a bracket expression is
16408 problematic because, for example, @samp{a*[} might match the file name
16409 @samp{abc[}, but it might not.
16410
16411 Curly braces are problematic because POSIX allows but does not require
16412 brace expansion. For example, the shell command @samp{echo a@{b,c,d@}e}
16413 outputs @samp{abe ace ade} with Bash, but @samp{a@{b,c,d@}e} with Dash.
16414
16415 @item
16416 Backlashes in bracket expressions, unless doubled.
16417 For example, @samp{[\\^]} is portable, but @samp{[\^]} is not.
16418
16419 @item
16420 An unescaped backslash at pattern end.
16421
16422 @item
16423 A NUL byte.
16424 More generally, a NUL byte should never appear anywhere
16425 in a portable shell script.
16426 @end itemize
16427
16428 @node Shell Substitutions
16429 @section Shell Substitutions
16430 @cindex Shell substitutions
16431
16432 Contrary to a persistent urban legend, the Bourne shell does not
16433 systematically split variables and back-quoted expressions, in particular
16434 on the right-hand side of assignments and in the argument of @code{case}.
16435 For instance, the following code:
16436
16437 @example
16438 case "$given_srcdir" in
16439 .) top_srcdir="`printf '%s\n' "$dots" | sed 's|/$||'`" ;;
16440 *) top_srcdir="$dots$given_srcdir" ;;
16441 esac
16442 @end example
16443
16444 @noindent
16445 is more readable when written as:
16446
16447 @example
16448 case $given_srcdir in
16449 .) top_srcdir=`printf '%s\n' "$dots" | sed 's|/$||'` ;;
16450 *) top_srcdir=$dots$given_srcdir ;;
16451 esac
16452 @end example
16453
16454 @noindent
16455 and in fact it is even @emph{more} portable: in the first case of the
16456 first attempt, the computation of @code{top_srcdir} is not portable,
16457 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
16458 for example Solaris 10 @command{ksh}:
16459
16460 @example
16461 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
16462 ksh: : cannot execute
16463 ksh: bar | sed 's, ,,': cannot execute
16464 @end example
16465
16466 @noindent
16467 POSIX does not specify behavior for this sequence. On the other hand,
16468 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by POSIX,
16469 but in practice, not all shells understand it the same way: pdksh 5.2.14
16470 prints spurious quotes when in POSIX mode:
16471
16472 @example
16473 $ @kbd{echo "`echo \"hello\"`"}
16474 hello
16475 $ @kbd{set -o posix}
16476 $ @kbd{echo "`echo \"hello\"`"}
16477 "hello"
16478 @end example
16479
16480 @noindent
16481 There is just no portable way to use double-quoted strings inside
16482 double-quoted back-quoted expressions (pfew!).
16483
16484 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
16485 parameter expansions are elided during word splitting. Meanwhile, zsh
16486 does not perform word splitting except when in Bourne compatibility
16487 mode. In the example below, the correct behavior is to have five
16488 arguments to the function, and exactly two spaces on either side of the
16489 middle @samp{-}, since word splitting collapses multiple spaces in
16490 @samp{$f} but leaves empty arguments intact.
16491
16492 @example
16493 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16494 3- - -
16495 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16496 5- - -
16497 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16498 3- - -
16499 $ @kbd{zsh -c 'emulate sh;}
16500 > @kbd{n() @{ echo "$#$@@"; @}; f=" - "; n - ""$f"" -'}
16501 5- - -
16502 @end example
16503
16504 @noindent
16505 You can work around this by doing manual word splitting, such as using
16506 @samp{"$str" $list} rather than @samp{"$str"$list}.
16507
16508 There are also portability pitfalls with particular expansions:
16509
16510 @table @code
16511 @item $@@
16512 @cindex @code{"$@@"}
16513 Autoconf macros often use the @command{set} command to update
16514 @samp{$@@}, so if you are writing shell code intended for
16515 @command{configure} you should not assume that the value of @samp{$@@}
16516 persists for any length of time.
16517
16518 You may see usages like @samp{$@{1+"$@@"@}} in older shell scripts
16519 designed to work around a portability problem in ancient shells.
16520 Unfortunately this runs afoul of bugs in more-recent shells, and
16521 nowadays it is better to use plain @samp{"$@@"} instead.
16522
16523 The portability problem with ancient shells was significant.
16524 When there are no positional arguments @samp{"$@@"} should be discarded,
16525 but the original Unix version 7 Bourne shell mistakenly treated it as
16526 equivalent to @samp{""} instead, and many ancient shells followed its lead.
16527
16528 For many years shell scripts worked around this portability problem by
16529 using @samp{$@{1+"$@@"@}} instead of @samp{"$@@"}, and you may see this
16530 usage in older scripts. Unfortunately, @samp{$@{1+"$@@"@}} does not
16531 work with @command{ksh93} M 93t+ (2009) as shipped in AIX 7.2 (2015),
16532 as this shell drops a trailing empty argument:
16533
16534 @example
16535 $ @kbd{set a b c ""}
16536 $ @kbd{set $@{1+"$@@"@}}
16537 $ @kbd{echo $#}
16538 3
16539 @end example
16540
16541 Also, @samp{$@{1+"$@@"@}} does not work with Zsh 4.2.6 (2005) and
16542 earlier, as shipped in Mac OS X releases before 10.5, as this old Zsh
16543 incorrectly word splits the result:
16544
16545 @example
16546 zsh $ @kbd{emulate sh}
16547 zsh $ @kbd{for i in "$@@"; do echo $i; done}
16548 Hello World
16549 !
16550 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
16551 Hello
16552 World
16553 !
16554 @end example
16555
16556 To work around these problems Autoconf does two things. First, in the
16557 shell code that it generates Autoconf avoids @samp{"$@@"} if it is
16558 possible that there may be no positional arguments. You can use this
16559 workaround in your own code, too, if you want it to be portable to
16560 ancient shells. For example, instead of:
16561
16562 @example
16563 cat conftest.c "$@@"
16564 @end example
16565
16566 you can use this:
16567
16568 @example
16569 case $# in
16570 0) cat conftest.c;;
16571 *) cat conftest.c "$@@";;
16572 esac
16573 @end example
16574
16575 @noindent
16576 Second, Autoconf-generated @command{configure} scripts work around most
16577 of the old Zsh problem by using Zsh's ``global aliases'' to convert
16578 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
16579
16580 @example
16581 test $@{ZSH_VERSION+y@} && alias -g '$@{1+"$@@"@}'='"$@@"'
16582 @end example
16583
16584 This workaround is for the benefit of any instances of
16585 @samp{$@{1+"$@@"@}} in user-written code appearing in
16586 @command{configure} scripts. However, it is not a complete solution, as
16587 Zsh recognizes the alias only when a shell word matches it exactly,
16588 which means older Zsh still mishandles more-complicated cases like
16589 @samp{"foo"$@{1+"$@@"@}}.
16590
16591 @item $@{10@}
16592 @cindex positional parameters
16593 The 10th, 11th, @dots{} positional parameters can be accessed only after
16594 a @code{shift}. The 7th Edition shell reported an error if given
16595 @code{$@{10@}}, and
16596 Solaris 10 @command{/bin/sh} still acts that way:
16597
16598 @example
16599 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
16600 $ @kbd{echo $@{10@}}
16601 bad substitution
16602 @end example
16603
16604 Conversely, not all shells obey the POSIX rule that when braces are
16605 omitted, multiple digits beyond a @samp{$} imply the single-digit
16606 positional parameter expansion concatenated with the remaining literal
16607 digits. To work around the issue, you must use braces.
16608
16609 @example
16610 $ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16611 a0 a0
16612 $ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16613 j a0
16614 @end example
16615
16616 @item $@{@var{var}-@var{value}@}
16617 @itemx $@{@var{var}:-@var{value}@}
16618 @itemx $@{@var{var}=@var{value}@}
16619 @itemx $@{@var{var}:=@var{value}@}
16620 @itemx $@{@var{var}?@var{value}@}
16621 @itemx $@{@var{var}:?@var{value}@}
16622 @itemx $@{@var{var}+@var{value}@}
16623 @itemx $@{@var{var}:+@var{value}@}
16624 @cindex @code{$@{@var{var}-@var{value}@}}
16625 @cindex @code{$@{@var{var}=@var{value}@}}
16626 @cindex @code{$@{@var{var}?@var{value}@}}
16627 @cindex @code{$@{@var{var}+@var{value}@}}
16628 @c Info cannot handle ':' in index entries.
16629 @ifnotinfo
16630 @cindex @code{$@{@var{var}:-@var{value}@}}
16631 @cindex @code{$@{@var{var}:=@var{value}@}}
16632 @cindex @code{$@{@var{var}:?@var{value}@}}
16633 @cindex @code{$@{@var{var}:+@var{value}@}}
16634 @end ifnotinfo
16635 When using @samp{$@{@var{var}-@var{value}@}} or
16636 similar notations that modify a parameter expansion,
16637 POSIX requires that @var{value} must be a single shell word,
16638 which can contain quoted strings but cannot contain unquoted spaces.
16639 If this requirement is not met Solaris 10 @command{/bin/sh}
16640 sometimes complains, and anyway the behavior is not portable.
16641
16642 @example
16643 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
16644 /bin/sh: bad substitution
16645 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
16646 b c
16647 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
16648 b c
16649 $ @kbd{/bin/sh -c 'cat <<EOF
16650 $@{a-b c@}
16651 EOF}
16652 b c
16653 @end example
16654
16655 Most shells treat the special parameters @code{*} and @code{@@} as being
16656 unset if there are no positional parameters. However, some shells treat
16657 them as being set to the empty string. POSIX does not clearly specify
16658 either behavior.
16659
16660 @example
16661 $ @kbd{bash -c 'echo "* is $@{*-unset@}."'}
16662 * is unset.
16663 $ @kbd{dash -c 'echo "* is $@{*-unset@}."'}
16664 * is .
16665 @end example
16666
16667 According to POSIX, if an expansion occurs inside double quotes, then
16668 the use of unquoted double quotes within @var{value} is unspecified, and
16669 any single quotes become literal characters; in that case, escaping must
16670 be done with backslash. Likewise, the use of unquoted here-documents is
16671 a case where double quotes have unspecified results:
16672
16673 @example
16674 $ @kbd{/bin/sh -c 'echo "$@{a-"b c"@}"'}
16675 /bin/sh: bad substitution
16676 $ @kbd{ksh -c 'echo "$@{a-"b c"@}"'}
16677 b c
16678 $ @kbd{bash -c 'echo "$@{a-"b c"@}"'}
16679 b c
16680 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b c'\''@}'}
16681 b c
16682 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b c'\''@}"'}
16683 'b c'
16684 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b c\"@}"'}
16685 "b c"
16686 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b c@}"'}
16687 b c
16688 $ @kbd{/bin/sh -c 'cat <<EOF
16689 $@{a-"b c"@}
16690 EOF'}
16691 "b c"
16692 $ @kbd{/bin/sh -c 'cat <<EOF
16693 $@{a-'b c'@}
16694 EOF'}
16695 'b c'
16696 $ @kbd{bash -c 'cat <<EOF
16697 $@{a-"b c"@}
16698 EOF'}
16699 b c
16700 $ @kbd{bash -c 'cat <<EOF
16701 $@{a-'b c'@}
16702 EOF'}
16703 'b c'
16704 @end example
16705
16706 Perhaps the easiest way to work around quoting issues in a manner
16707 portable to all shells is to place the results in a temporary variable,
16708 then use @samp{$t} as the @var{value}, rather than trying to inline
16709 the expression needing quoting.
16710
16711 @example
16712 $ @kbd{/bin/sh -c 't="b c\"'\''@}\\"; echo "$@{a-$t@}"'}
16713 b c"'@}\
16714 $ @kbd{ksh -c 't="b c\"'\''@}\\"; echo "$@{a-$t@}"'}
16715 b c"'@}\
16716 $ @kbd{bash -c 't="b c\"'\''@}\\"; echo "$@{a-$t@}"'}
16717 b c"'@}\
16718 @end example
16719
16720 @item $@{@var{var}=@var{value}@}
16721 @cindex @code{$@{@var{var}=@var{value}@}}
16722 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
16723 to @var{var}, remember that even though the assignment to @var{var} does
16724 not undergo file name expansion, the result of the variable expansion
16725 does unless the expansion occurred within double quotes. In particular,
16726 when using @command{:} followed by unquoted variable expansion for the
16727 side effect of setting a default value, if the final value of
16728 @samp{$var} contains any globbing characters (either from @var{value} or
16729 from prior contents), the shell has to spend time performing file name
16730 expansion and field splitting even though those results will not be
16731 used. Therefore, it is a good idea to consider double quotes when performing
16732 default initialization; while remembering how this impacts any quoting
16733 characters appearing in @var{value}.
16734
16735 @example
16736 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
16737 /usr/bin/*
16738
16739 real 0m0.005s
16740 user 0m0.002s
16741 sys 0m0.003s
16742 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
16743 /usr/bin/*
16744
16745 real 0m0.039s
16746 user 0m0.026s
16747 sys 0m0.009s
16748 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
16749 /usr/bin/*
16750
16751 real 0m0.031s
16752 user 0m0.020s
16753 sys 0m0.010s
16754
16755 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
16756 /usr/bin/*
16757
16758 real 0m0.006s
16759 user 0m0.002s
16760 sys 0m0.003s
16761 @end example
16762
16763 As with @samp{+} and @samp{-}, @var{value} must be a single shell word,
16764 otherwise some shells, such as Solaris 10 @command{/bin/sh} or on Digital
16765 Unix V 5.0, die because of a ``bad substitution''. Meanwhile, POSIX
16766 requires that with @samp{=}, quote removal happens prior to the
16767 assignment, and the expansion be the final contents of @var{var} without
16768 quoting (and thus subject to field splitting), in contrast to the
16769 behavior with @samp{-} passing the quoting through to the final
16770 expansion. However, @command{bash} 4.1 does not obey this rule.
16771
16772 @example
16773 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16774 a b
16775 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16776 a b
16777 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16778 a b
16779 @end example
16780
16781 Finally, POSIX states that when mixing @samp{$@{a=b@}} with regular
16782 commands, it is unspecified whether the assignments affect the parent
16783 shell environment. It is best to perform assignments independently from
16784 commands, to avoid the problems demonstrated in this example running on
16785 Solaris 10:
16786
16787 @example
16788 $ @kbd{cmd='x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";printf "%s\\n" -$x-'}
16789 $ @kbd{bash -c "$cmd"}
16790 +b+b+
16791 -b-
16792 $ @kbd{/bin/sh -c "$cmd"}
16793 ++b+
16794 --
16795 $ @kbd{ksh -c "$cmd"}
16796 +b+b+
16797 --
16798 @end example
16799
16800 @item $@{@var{var}=@var{value}@}
16801 @cindex @code{$@{@var{var}=@var{literal}@}}
16802 Solaris 10 @command{/bin/sh} has a frightening bug in its handling of
16803 literal assignments. Imagine you need set a variable to a string containing
16804 @samp{@}}. This @samp{@}} character confuses Solaris 10 @command{/bin/sh}
16805 when the affected variable was already set. This bug can be exercised
16806 by running:
16807
16808 @example
16809 $ @kbd{unset foo}
16810 $ @kbd{foo=$@{foo='@}'@}}
16811 $ @kbd{echo $foo}
16812 @}
16813 $ @kbd{foo=$@{foo='@}' # no error; this hints to what the bug is}
16814 $ @kbd{echo $foo}
16815 @}
16816 $ @kbd{foo=$@{foo='@}'@}}
16817 $ @kbd{echo $foo}
16818 @}@}
16819 ^ ugh!
16820 @end example
16821
16822 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16823 though it is enclosed in single quotes. The problem doesn't happen
16824 using double quotes, or when using a temporary variable holding the
16825 problematic string.
16826
16827 @item $@{@var{var}=@var{expanded-value}@}
16828 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
16829 On shells so old that they are no longer relevant, the command
16830
16831 @example
16832 # Set the shell variable to a default value
16833 # if it is not already set.
16834 : $@{var="$default"@}
16835 @end example
16836
16837 @noindent
16838 misbehaved badly in some cases. Older scripts worked around the bugs by
16839 using one of following two lines, the latter of which was more portable:
16840
16841 @example
16842 var=$@{var="$default"@}
16843 test $@{var+y@} || var=$default
16844 @end example
16845
16846 @noindent
16847 However, these workarounds are no longer needed.
16848
16849 @item $@{#@var{var}@}
16850 @itemx $@{@var{var}%@var{word}@}
16851 @itemx $@{@var{var}%%@var{word}@}
16852 @itemx $@{@var{var}#@var{word}@}
16853 @itemx $@{@var{var}##@var{word}@}
16854 @cindex @code{$@{#@var{var}@}}
16855 @cindex @code{$@{@var{var}%@var{word}@}}
16856 @cindex @code{$@{@var{var}%%@var{word}@}}
16857 @cindex @code{$@{@var{var}#@var{word}@}}
16858 @cindex @code{$@{@var{var}##@var{word}@}}
16859 POSIX requires support for these usages, but they do not work with many
16860 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16861
16862 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms. For
16863 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16864 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16865 yields the empty string.
16866
16867
16868 @item `@var{commands}`
16869 @cindex @code{`@var{commands}`}
16870 @cindex Command Substitution
16871 POSIX requires shells to trim all trailing newlines from command
16872 output before substituting it, so assignments like
16873 @samp{dir=`printf '%s\n' "$file" | tr a A`} do not work as expected if
16874 @samp{$file} ends in a newline.
16875
16876 While in general it makes no sense, do not substitute a single builtin
16877 with side effects, because Ash 0.2, trying to optimize, does not fork a
16878 subshell to perform the command.
16879 For instance, if you wanted to check that @command{cd} is silent, do not
16880 use @samp{test -z "`cd /`"} because the following can happen:
16881
16882 @example
16883 $ @kbd{pwd}
16884 /tmp
16885 $ @kbd{test -z "`cd /`" && pwd}
16886 /
16887 @end example
16888
16889 @noindent
16890 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16891
16892 The MSYS shell leaves a stray byte in the expansion of a double-quoted
16893 command substitution of a native program, if the end of the substitution
16894 is not aligned with the end of the double quote. This may be worked
16895 around by inserting another pair of quotes:
16896
16897 @example
16898 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16899 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16900 - broken differ: char 4, line 1
16901 @end example
16902
16903 Upon interrupt or SIGTERM, some shells may abort a command substitution,
16904 replace it with a null string, and wrongly evaluate the enclosing
16905 command before entering the trap or ending the script. This can lead to
16906 spurious errors:
16907
16908 @example
16909 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16910 $ @kbd{^C}
16911 sh: test: hi: unexpected operator/operand
16912 @end example
16913
16914 @noindent
16915 You can avoid this by assigning the command substitution to a temporary
16916 variable:
16917
16918 @example
16919 $ @kbd{sh -c 'res=`sleep 5; echo hi`
16920 if test "x$res" = xhi; then echo yes; fi'}
16921 $ @kbd{^C}
16922 @end example
16923
16924 @item $(@var{commands})
16925 @cindex @code{$(@var{commands})}
16926 This construct is meant to replace @samp{`@var{commands}`},
16927 and it has most of the problems listed under @code{`@var{commands}`}.
16928
16929 This construct can be
16930 nested while this is impossible to do portably with back quotes.
16931 Although it is almost universally supported, unfortunately Solaris 10
16932 and earlier releases lack it:
16933
16934 @example
16935 $ @kbd{showrev -c /bin/sh | grep version}
16936 Command version: SunOS 5.10 Generic 142251-02 Sep 2010
16937 $ @kbd{echo $(echo blah)}
16938 syntax error: `(' unexpected
16939 @end example
16940
16941 If you do use @samp{$(@var{commands})}, make sure that the commands
16942 do not start with a parenthesis, as that would cause confusion with
16943 a different notation @samp{$((@var{expression}))} that in modern
16944 shells is an arithmetic expression not a command. To avoid the
16945 confusion, insert a space between the two opening parentheses.
16946
16947 Avoid @var{commands} that contain unbalanced parentheses in
16948 here-documents, comments, or case statement patterns, as many shells
16949 mishandle them. For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
16950 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16951
16952 @example
16953 echo $(case x in x) echo hello;; esac)
16954 @end example
16955
16956
16957 @item $((@var{expression}))
16958 @cindex @code{$((@var{expression}))}
16959 Arithmetic expansion is not portable as some shells (most
16960 notably Solaris 10 @command{/bin/sh}) don't support it.
16961
16962 Among shells that do support @samp{$(( ))}, not all of them obey the
16963 POSIX rule that octal and hexadecimal constants must be recognized:
16964
16965 @example
16966 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
16967 24
16968 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
16969 26
16970 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
16971 24
16972 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16973 pdksh: 010 + 0x10 : bad number `0x10'
16974 $ @kbd{pdksh -c 'echo $(( 010 ))'}
16975 10
16976 @end example
16977
16978 When it is available, using arithmetic expansion provides a noticeable
16979 speedup in script execution; but testing for support requires
16980 @command{eval} to avoid syntax errors. The following construct is used
16981 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16982 arguments are decimal integers without leading zeros, and all
16983 operators are properly quoted and appear as distinct arguments:
16984
16985 @example
16986 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16987 eval 'func_arith ()
16988 @{
16989 func_arith_result=$(( $* ))
16990 @}'
16991 else
16992 func_arith ()
16993 @{
16994 func_arith_result=`expr "$@@"`
16995 @}
16996 fi
16997 func_arith 1 + 1
16998 foo=$func_arith_result
16999 @end example
17000
17001
17002 @item ^
17003 @cindex @code{^} quoting
17004 Always quote @samp{^}, otherwise traditional shells such as
17005 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
17006
17007 @end table
17008
17009
17010 @node Assignments
17011 @section Assignments
17012 @cindex Shell assignments
17013
17014 When setting several variables in a row, be aware that the order of the
17015 evaluation is undefined. For instance @samp{foo=1 foo=2; echo $foo}
17016 gives @samp{1} with Solaris 10 @command{/bin/sh}, but @samp{2} with Bash.
17017 You must use
17018 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
17019
17020 Don't rely on the following to find @file{subdir/program}:
17021
17022 @example
17023 PATH=subdir$PATH_SEPARATOR$PATH program
17024 @end example
17025
17026 @noindent
17027 as this does not work with Zsh 3.0.6. Use something like this
17028 instead:
17029
17030 @example
17031 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
17032 @end example
17033
17034 Don't rely on the exit status of an assignment: Ash 0.2 does not change
17035 the status and propagates that of the last statement:
17036
17037 @example
17038 $ @kbd{false || foo=bar; echo $?}
17039 1
17040 $ @kbd{false || foo=`:`; echo $?}
17041 0
17042 @end example
17043
17044 @noindent
17045 and to make things even worse, QNX 4.25 just sets the exit status
17046 to 0 in any case:
17047
17048 @example
17049 $ @kbd{foo=`exit 1`; echo $?}
17050 0
17051 @end example
17052
17053 To assign default values, follow this algorithm:
17054
17055 @enumerate
17056 @item
17057 If the default value is a literal and does not contain any closing
17058 brace, use:
17059
17060 @example
17061 : "$@{var='my literal'@}"
17062 @end example
17063
17064 @item
17065 If the default value contains no closing brace, has to be expanded, and
17066 the variable being initialized is not intended to be IFS-split
17067 (i.e., it's not a list), then use:
17068
17069 @example
17070 : $@{var="$default"@}
17071 @end example
17072
17073 @item
17074 If the default value contains no closing brace, has to be expanded, and
17075 the variable being initialized is intended to be IFS-split (i.e., it's a list),
17076 then use:
17077
17078 @example
17079 var=$@{var="$default"@}
17080 @end example
17081
17082 @item
17083 If the default value contains a closing brace, then use:
17084
17085 @example
17086 test $@{var+y@} || var="has a '@}'"
17087 @end example
17088 @end enumerate
17089
17090 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
17091 doubt, just use the last form. @xref{Shell Substitutions}, items
17092 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
17093 for the rationale.
17094
17095 @node Parentheses
17096 @section Parentheses in Shell Scripts
17097 @cindex Shell parentheses
17098
17099 Beware of two opening parentheses in a row, as many shell
17100 implementations treat them specially, and POSIX says that a portable
17101 script cannot use @samp{((} outside the @samp{$((} form used for shell
17102 arithmetic. In traditional shells, @samp{((cat))} behaves like
17103 @samp{(cat)}; but many shells, including
17104 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
17105 expression equivalent to @samp{let "cat"}, and may or may not report an
17106 error when they detect that @samp{cat} is not a number. As another
17107 example, @samp{pdksh} 5.2.14 does not treat the following code
17108 as a traditional shell would:
17109
17110 @example
17111 if ((true) || false); then
17112 echo ok
17113 fi
17114 @end example
17115
17116 @noindent
17117 To work around this problem, insert a space between the two opening
17118 parentheses. There is a similar problem and workaround with
17119 @samp{$((}; see @ref{Shell Substitutions}.
17120
17121 @node Special Shell Variables
17122 @section Special Shell Variables
17123 @cindex Shell variables
17124 @cindex Special shell variables
17125
17126 Some shell variables should not be used, since they can have a deep
17127 influence on the behavior of the shell. In order to recover a sane
17128 behavior from the shell, some variables should be unset; M4sh takes
17129 care of this and provides fallback values, whenever needed, to cater
17130 for a very old @file{/bin/sh} that does not support @command{unset}.
17131 (@pxref{Portable Shell, , Portable Shell Programming}).
17132
17133 As a general rule, shell variable names containing a lower-case letter
17134 are safe; you can define and use these variables without worrying about
17135 their effect on the underlying system, and without worrying about
17136 whether the shell changes them unexpectedly. (The exception is the
17137 shell variable @code{status}, as described below.)
17138
17139 Here is a list of names that are known to cause trouble. This list is
17140 not exhaustive, but you should be safe if you avoid the name
17141 @code{status} and names containing only upper-case letters and
17142 underscores.
17143
17144 @c Alphabetical order, case insensitive, 'A' before 'a'.
17145 @table @code
17146 @item ?
17147 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
17148 , Limitations of Shell Builtins}). Not all shells manage @samp{$?}
17149 correctly in shell functions (@pxref{Shell Functions}) or in traps
17150 (@pxref{trap, , Limitations of Shell Builtins}). Not all shells reset
17151 @samp{$?} to zero after an empty command.
17152
17153 @example
17154 $ @kbd{bash -c 'false; $empty; echo $?'}
17155 0
17156 $ @kbd{zsh -c 'false; $empty; echo $?'}
17157 1
17158 @end example
17159
17160 @item _
17161 @evindex _
17162 Many shells reserve @samp{$_} for various purposes, e.g., the name of
17163 the last command executed.
17164
17165 @item CDPATH
17166 @evindex CDPATH
17167 When this variable is set it specifies a list of directories to search
17168 when invoking @code{cd} with a relative file name that did not start
17169 with @samp{./} or @samp{../}. POSIX
17170 says that if a nonempty directory name from @env{CDPATH}
17171 is used successfully, @code{cd} prints the resulting absolute
17172 file name. Unfortunately this output can break idioms like
17173 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
17174 Also, many shells do not conform to this part of POSIX; for
17175 example, @command{zsh} prints the result only if a directory name
17176 other than @file{.} was chosen from @env{CDPATH}.
17177
17178 In practice the shells that have this problem also support
17179 @command{unset}, so you can work around the problem as follows:
17180
17181 @example
17182 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
17183 @end example
17184
17185 You can also avoid output by ensuring that your directory name is
17186 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
17187
17188 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
17189 possible, so you need not worry about this problem in those scripts.
17190
17191 @item CLICOLOR_FORCE
17192 @evindex CLICOLOR_FORCE
17193 When this variable is set, some implementations of tools like
17194 @command{ls} attempt to add color to their output via terminal escape
17195 sequences, even when the output is not directed to a terminal, and can
17196 thus cause spurious failures in scripts. Configure scripts use M4sh,
17197 which automatically unsets this variable.
17198
17199 @item DUALCASE
17200 @evindex DUALCASE
17201 In the MKS shell, case statements and file name generation are
17202 case-insensitive unless @env{DUALCASE} is nonzero.
17203 Autoconf-generated scripts export this variable when they start up.
17204
17205 @item ENV
17206 @itemx MAIL
17207 @itemx MAILPATH
17208 @itemx PS1
17209 @itemx PS2
17210 @itemx PS4
17211 @evindex ENV
17212 @evindex MAIL
17213 @evindex MAILPATH
17214 @evindex PS1
17215 @evindex PS2
17216 @evindex PS4
17217 These variables should not matter for shell scripts, since they are
17218 supposed to affect only interactive shells. However, at least one
17219 shell (the pre-3.0 UWIN Korn shell) gets confused about
17220 whether it is interactive, which means that (for example) a @env{PS1}
17221 with a side effect can unexpectedly modify @samp{$?}. To work around
17222 this bug, M4sh scripts (including @file{configure} scripts) do something
17223 like this:
17224
17225 @example
17226 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
17227 PS1='$ '
17228 PS2='> '
17229 PS4='+ '
17230 @end example
17231
17232 @noindent
17233 (actually, there is some complication due to bugs in @command{unset};
17234 @pxref{unset, , Limitations of Shell Builtins}).
17235
17236 @item FPATH
17237 @evindex FPATH
17238 The Korn shell uses @env{FPATH} to find shell functions, so avoid
17239 @env{FPATH} in portable scripts. @env{FPATH} is consulted after
17240 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
17241 to find whether a command exists, since they might report the wrong
17242 result if @env{FPATH} is also set.
17243
17244 @item GREP_OPTIONS
17245 @evindex GREP_OPTIONS
17246 When this variable is set, some implementations of @command{grep} honor
17247 these options, even if the options include direction to enable colored
17248 output via terminal escape sequences, and the result can cause spurious
17249 failures when the output is not directed to a terminal. Configure
17250 scripts use M4sh, which automatically unsets this variable.
17251
17252 @item HOME
17253 @evindex HOME
17254 Strange things can happen if @env{HOME} is unset or empty.
17255 For example, plain @command{cd} (with no arguments) has unspecified behavior.
17256 Also, @env{HOME} should be absolute, not relative.
17257
17258 @item IFS
17259 @evindex IFS
17260 Long ago, shell scripts inherited @env{IFS} from the environment,
17261 but this caused many problems so modern shells ignore any environment
17262 settings for @env{IFS}.
17263
17264 Don't set the first character of @env{IFS} to backslash. Indeed,
17265 Bourne shells use the first character (backslash) when joining the
17266 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
17267 backslash escapes, so you can end up with backspace and other strange
17268 characters.
17269
17270 The proper value for @env{IFS} (in regular code, not when performing
17271 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}. The first character is
17272 especially important, as it is used to join the arguments in @samp{$*};
17273 however, note that traditional shells, but also bash-2.04, fail to adhere
17274 to this and join with a space anyway.
17275
17276 M4sh guarantees that @env{IFS} will have the default value at the
17277 beginning of a script, and many macros within autoconf rely on this
17278 setting. It is okay to use blocks of shell code that temporarily change
17279 the value of @env{IFS} in order to split on another character, but
17280 remember to restore it before expanding further macros.
17281
17282 Unsetting @code{IFS} instead of resetting it to the default sequence
17283 is not suggested, since code that tries to save and restore the
17284 variable's value will incorrectly reset it to an empty value, thus
17285 disabling field splitting:
17286
17287 @example
17288 unset IFS
17289 # default separators used for field splitting
17290
17291 save_IFS=$IFS
17292 IFS=:
17293 # ...
17294 IFS=$save_IFS
17295 # no field splitting performed
17296 @end example
17297
17298 @item LANG
17299 @itemx LC_ALL
17300 @itemx LC_COLLATE
17301 @itemx LC_CTYPE
17302 @itemx LC_MESSAGES
17303 @itemx LC_MONETARY
17304 @itemx LC_NUMERIC
17305 @itemx LC_TIME
17306 @evindex LANG
17307 @evindex LC_ALL
17308 @evindex LC_COLLATE
17309 @evindex LC_CTYPE
17310 @evindex LC_MESSAGES
17311 @evindex LC_MONETARY
17312 @evindex LC_NUMERIC
17313 @evindex LC_TIME
17314
17315 You should set all these variables to @samp{C} because so much
17316 configuration code assumes the C locale and POSIX requires that locale
17317 environment variables be set to @samp{C} if the C locale is desired;
17318 @file{configure} scripts and M4sh do that for you.
17319 Export these variables after setting them.
17320
17321 @item LANGUAGE
17322 @evindex LANGUAGE
17323
17324 @env{LANGUAGE} is not specified by POSIX, but it is a GNU
17325 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
17326 should set it too.
17327
17328 @item LC_ADDRESS
17329 @itemx LC_IDENTIFICATION
17330 @itemx LC_MEASUREMENT
17331 @itemx LC_NAME
17332 @itemx LC_PAPER
17333 @itemx LC_TELEPHONE
17334 @evindex LC_ADDRESS
17335 @evindex LC_IDENTIFICATION
17336 @evindex LC_MEASUREMENT
17337 @evindex LC_NAME
17338 @evindex LC_PAPER
17339 @evindex LC_TELEPHONE
17340
17341 These locale environment variables are GNU extensions. They
17342 are treated like their POSIX brethren (@env{LC_COLLATE},
17343 etc.)@: as described above.
17344
17345 @item LINENO
17346 @evindex LINENO
17347 Most modern shells provide the current line number in @code{LINENO}.
17348 Its value is the line number of the beginning of the current command.
17349 M4sh, and hence Autoconf, attempts to execute @command{configure} with
17350 a shell that supports @code{LINENO}. If no such shell is available, it
17351 attempts to implement @code{LINENO} with a Sed prepass that replaces each
17352 instance of the string @code{$LINENO} (not followed by an alphanumeric
17353 character) with the line's number. In M4sh scripts you should execute
17354 @code{AS_LINENO_PREPARE} so that these workarounds are included in
17355 your script; configure scripts do this automatically in @code{AC_INIT}.
17356
17357 You should not rely on @code{LINENO} within @command{eval} or shell
17358 functions, as the behavior differs in practice. The presence of a
17359 quoted newline within simple commands can alter which line number is
17360 used as the starting point for @code{$LINENO} substitutions within that
17361 command. Also, the possibility of the Sed prepass means that you should
17362 not rely on @code{$LINENO} when quoted, when in here-documents, or when
17363 line continuations are used. Subshells should be OK, though. In the
17364 following example, lines 1, 9, and 14 are portable, but the other
17365 instances of @code{$LINENO} do not have deterministic values:
17366
17367 @example
17368 @group
17369 $ @kbd{cat lineno}
17370 echo 1. $LINENO
17371 echo "2. $LINENO
17372 3. $LINENO"
17373 cat <<EOF
17374 5. $LINENO
17375 6. $LINENO
17376 7. \$LINENO
17377 EOF
17378 ( echo 9. $LINENO )
17379 eval 'echo 10. $LINENO'
17380 eval 'echo 11. $LINENO
17381 echo 12. $LINENO'
17382 echo 13. '$LINENO'
17383 echo 14. $LINENO '
17384 15.' $LINENO
17385 f () @{ echo $1 $LINENO;
17386 echo $1 $LINENO @}
17387 f 18.
17388 echo 19. \
17389 $LINENO
17390 @end group
17391 @group
17392 $ @kbd{bash-3.2 ./lineno}
17393 1. 1
17394 2. 3
17395 3. 3
17396 5. 4
17397 6. 4
17398 7. $LINENO
17399 9. 9
17400 10. 10
17401 11. 12
17402 12. 13
17403 13. $LINENO
17404 14. 14
17405 15. 14
17406 18. 16
17407 18. 17
17408 19. 19
17409 @end group
17410 @group
17411 $ @kbd{zsh-4.3.4 ./lineno}
17412 1. 1
17413 2. 2
17414 3. 2
17415 5. 4
17416 6. 4
17417 7. $LINENO
17418 9. 9
17419 10. 1
17420 11. 1
17421 12. 2
17422 13. $LINENO
17423 14. 14
17424 15. 14
17425 18. 0
17426 18. 1
17427 19. 19
17428 @end group
17429 @group
17430 $ @kbd{pdksh-5.2.14 ./lineno}
17431 1. 1
17432 2. 2
17433 3. 2
17434 5. 4
17435 6. 4
17436 7. $LINENO
17437 9. 9
17438 10. 0
17439 11. 0
17440 12. 0
17441 13. $LINENO
17442 14. 14
17443 15. 14
17444 18. 16
17445 18. 17
17446 19. 19
17447 @end group
17448 @group
17449 $ @kbd{sed '=' <lineno |}
17450 > @kbd{ sed '}
17451 > @kbd{ N}
17452 > @kbd{ s,$,-,}
17453 > @kbd{ t loop}
17454 > @kbd{ :loop}
17455 > @kbd{ s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
17456 > @kbd{ t loop}
17457 > @kbd{ s,-$,,}
17458 > @kbd{ s,^[0-9]*\n,,}
17459 > @kbd{ ' |}
17460 > @kbd{ sh}
17461 1. 1
17462 2. 2
17463 3. 3
17464 5. 5
17465 6. 6
17466 7. \7
17467 9. 9
17468 10. 10
17469 11. 11
17470 12. 12
17471 13. 13
17472 14. 14
17473 15. 15
17474 18. 16
17475 18. 17
17476 19. 20
17477 @end group
17478 @end example
17479
17480 In particular, note that @file{config.status} (and any other subsidiary
17481 script created by @code{AS_INIT_GENERATED}) might report line numbers
17482 relative to the parent script as a result of the potential Sed pass.
17483
17484 @item NULLCMD
17485 @evindex NULLCMD
17486 When executing the command @samp{>foo}, @command{zsh} executes
17487 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
17488 compatibility mode and the @command{zsh} version is newer
17489 than 3.1.6-dev-18. If you are using an older @command{zsh}
17490 and forget to set @env{NULLCMD},
17491 your script might be suspended waiting for data on its standard input.
17492
17493 @item OLDPWD
17494 @evindex OLDPWD
17495 POSIX requires that @command{cd} must update the @env{OLDPWD}
17496 environment variable, if set, to point to the name of the previous
17497 directory, but Solaris 10 @command{/bin/sh} does not support this.
17498
17499 @item options
17500 @evindex options
17501 For @command{zsh} 4.3.10, @env{options} is treated as an associative
17502 array even after @code{emulate sh}, so it should not be used.
17503
17504 @item PATH_SEPARATOR
17505 @evindex PATH_SEPARATOR
17506 On DJGPP systems, the @env{PATH_SEPARATOR} environment
17507 variable can be set to either @samp{:} or @samp{;} to control the path
17508 separator Bash uses to set up certain environment variables (such as
17509 @env{PATH}). You can set this variable to @samp{;} if you want
17510 @command{configure} to use @samp{;} as a separator; this might be useful
17511 if you plan to use non-POSIX shells to execute files. @xref{File System
17512 Conventions}, for more information about @code{PATH_SEPARATOR}.
17513
17514 @item POSIXLY_CORRECT
17515 @evindex POSIXLY_CORRECT
17516 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
17517 (even empty) causes programs to try harder to conform to POSIX@.
17518 Autoconf does not directly manipulate this variable, but @command{bash}
17519 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
17520 running in POSIX mode. Therefore, take care when exporting or unsetting
17521 this variable, so as not to change whether @command{bash} is in POSIX
17522 mode.
17523
17524 @example
17525 $ @kbd{bash --posix -c 'set -o | grep posix}
17526 > @kbd{unset POSIXLY_CORRECT}
17527 > @kbd{set -o | grep posix'}
17528 posix on
17529 posix off
17530 @end example
17531
17532 @item PWD
17533 @evindex PWD
17534 POSIX requires that @command{cd}
17535 must update the @env{PWD} environment variable to point
17536 to the name of the current directory, but traditional shells
17537 do not support this. This can cause confusion if one shell instance
17538 maintains @env{PWD} but a subsidiary and different shell does not know
17539 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
17540 points to the wrong directory. Use @samp{`pwd`} rather than
17541 @samp{$PWD}.
17542
17543 @item RANDOM
17544 @evindex RANDOM
17545 Many shells provide @code{RANDOM}, a variable that returns a different
17546 integer each time it is used. It is common
17547 practice to use @code{$RANDOM} as part of a file name, but code
17548 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
17549
17550 @item status
17551 @evindex status
17552 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
17553 hence read-only. Do not use it.
17554 @end table
17555
17556 @node Shell Functions
17557 @section Shell Functions
17558 @cindex Shell Functions
17559
17560 Nowadays, it is difficult to find a shell that does not support
17561 shell functions at all. However, some differences should be expected.
17562
17563 When declaring a shell function, you must include whitespace between the
17564 @samp{)} after the function name and the start of the compound
17565 expression, to avoid upsetting @command{ksh}. While it is possible to
17566 use any compound command, most scripts use @samp{@{@dots{}@}}.
17567
17568 @example
17569 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
17570 hi
17571 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
17572 ksh: syntax error at line 1: `@}' unexpected
17573 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
17574 hi
17575 @end example
17576
17577 Inside a shell function, you should not rely on the error status of a
17578 subshell if the last command of that subshell was @code{exit} or
17579 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
17580 find a shell that does not exhibit the bug, zsh might be the only shell
17581 present on the user's machine.
17582
17583 Likewise, the state of @samp{$?} is not reliable when entering a shell
17584 function. This has the effect that using a function as the first
17585 command in a @command{trap} handler can cause problems.
17586
17587 @example
17588 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17589 2
17590 2
17591 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17592 0
17593 2
17594 @end example
17595
17596 DJGPP bash 2.04 has a bug in that @command{return} from a
17597 shell function which also used a command substitution causes a
17598 segmentation fault. To work around the issue, you can use
17599 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
17600 in the execution flow of the function (@pxref{Common Shell Constructs}).
17601
17602 Not all shells treat shell functions as simple commands impacted by
17603 @samp{set -e}, for example with Solaris 10 @command{/bin/sh}:
17604
17605 @example
17606 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17607 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17608 oops
17609 @end example
17610
17611 Shell variables and functions may share the same namespace, for example
17612 with Solaris 10 @command{/bin/sh}:
17613
17614 @example
17615 $ @kbd{f () @{ :; @}; f=; f}
17616 f: not found
17617 @end example
17618
17619 @noindent
17620 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
17621 uses the prefix @samp{as_fn_} for its functions.
17622
17623 Handling of positional parameters and shell options varies among shells.
17624 For example, Korn shells reset and restore trace output (@samp{set -x})
17625 and other options upon function entry and exit.
17626
17627 It is not portable to pass temporary environment variables to shell
17628 functions. Solaris 10 @command{/bin/sh} does not see the variable.
17629 Meanwhile, not all shells follow the POSIX rule that the assignment must
17630 affect the current environment in the same manner as special built-ins.
17631
17632 @example
17633 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17634 @result{}
17635 @result{}
17636 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17637 @result{}1
17638 @result{}
17639 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
17640 @result{}1
17641 @result{}1
17642 @end example
17643
17644 Some ancient Bourne shell variants with function support did not reset
17645 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
17646 arguments of the script were lost after the first function invocation.
17647 It is probably not worth worrying about these shells any more.
17648
17649 With AIX sh, a @command{trap} on 0 installed in a shell function
17650 triggers at function exit rather than at script exit. @xref{trap, ,
17651 Limitations of Shell Builtins}.
17652
17653 @node Limitations of Builtins
17654 @section Limitations of Shell Builtins
17655 @cindex Shell builtins
17656 @cindex Limitations of shell builtins
17657
17658 No, no, we are serious: some shells do have limitations! :)
17659
17660 You should always keep in mind that any builtin or command may support
17661 options, and therefore differ in behavior with arguments
17662 starting with a dash. For instance, even the innocent @samp{echo "$word"}
17663 can give unexpected results when @code{word} starts with a dash. To avoid
17664 this problem, use @samp{printf '%s\n' "$word"}. Many of these limitations
17665 can be worked around using M4sh (@pxref{Programming in M4sh}).
17666
17667 @c This table includes things like '@command{test} (files)', so we can't
17668 @c use @table @command.
17669 @table @asis
17670 @item @command{.}
17671 @c --------------
17672 @prindex @command{.}
17673 Use @command{.} only with regular files (use @samp{test -f}). Bash
17674 2.03, for instance, chokes on @samp{. /dev/null}. Remember that
17675 @command{.} uses @env{PATH} if its argument contains no slashes. Also,
17676 some shells, including bash 3.2, implicitly append the current directory
17677 to this @env{PATH} search, even though POSIX forbids it. So if you want
17678 to use @command{.} on a file @file{foo} in the current directory, you
17679 must use @samp{. ./foo}.
17680
17681 Not all shells gracefully handle syntax errors within a sourced file.
17682 On one extreme, some non-interactive shells abort the entire script. On
17683 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17684 syntax error.
17685
17686 @example
17687 $ @kbd{echo 'fi' > syntax}
17688 $ @kbd{bash -c '. ./syntax; echo $?'}
17689 ./syntax: line 1: syntax error near unexpected token `fi'
17690 ./syntax: line 1: `fi'
17691 2
17692 $ @kbd{ash -c '. ./syntax; echo $?'}
17693 ./syntax: 1: Syntax error: "fi" unexpected
17694 $ @kbd{zsh -c '. ./syntax; echo $?'}
17695 ./syntax:1: parse error near `fi'
17696 0
17697 @end example
17698
17699 @anchor{!}
17700 @item @command{!}
17701 @c --------------
17702 @prindex @command{!}
17703 The Unix version 7 shell did not support
17704 negating the exit status of commands with @command{!}, and this feature
17705 is still absent from some shells (e.g., Solaris 10 @command{/bin/sh}).
17706 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17707 bugs when using @command{!}:
17708
17709 @example
17710 $ @kbd{sh -c '! : | :'; echo $?}
17711 1
17712 $ @kbd{ash -c '! : | :'; echo $?}
17713 0
17714 $ @kbd{sh -c '! @{ :; @}'; echo $?}
17715 1
17716 $ @kbd{ash -c '! @{ :; @}'; echo $?}
17717 @{: not found
17718 Syntax error: "@}" unexpected
17719 2
17720 @end example
17721
17722 Shell code like this:
17723
17724 @example
17725 if ! cmp file1 file2 >/dev/null 2>&1; then
17726 echo files differ or trouble
17727 fi
17728 @end example
17729
17730 is therefore not portable in practice. Typically it is easy to rewrite
17731 such code, e.g.:
17732
17733 @example
17734 cmp file1 file2 >/dev/null 2>&1 ||
17735 echo files differ or trouble
17736 @end example
17737
17738 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17739 of conditionals:
17740
17741 @example
17742 AS_IF([cmp -s file file.new], [],
17743 [echo files differ or trouble])
17744 @end example
17745
17746 This kind of rewriting is needed in code outside macro definitions that
17747 calls other macros. @xref{Common Shell Constructs}. It is also useful
17748 inside macro definitions, where the @dfn{then} and @dfn{else} branches
17749 might contain macro arguments.
17750
17751 More generally, one can always rewrite @samp{! @var{command}} as:
17752
17753 @example
17754 AS_IF([@var{command}], [(exit 1)])
17755 @end example
17756
17757 @item @command{&&} and @command{||}
17758 @c --------------------------------
17759 @prindex @command{&&}
17760 @prindex @command{||}
17761 If an AND-OR list is not inside @code{AC_DEFUN}, and it contains
17762 calls to Autoconf macros, it should be rewritten using @code{AS_IF}.
17763 @xref{Common Shell Constructs}. The operators @code{&&} and @code{||}
17764 have equal precedence and are left associative, so instead of:
17765
17766 @example
17767 # This is dangerous outside AC_DEFUN.
17768 cmp a b >/dev/null 2>&1 &&
17769 AS_ECHO([files are same]) >$tmpfile ||
17770 AC_MSG_NOTICE([files differ, or echo failed])
17771 @end example
17772
17773 you can use:
17774
17775 @example
17776 # This is OK outside AC_DEFUN.
17777 AS_IF([AS_IF([cmp a b >/dev/null 2>&1],
17778 [AS_ECHO([files are same]) >$tmpfile],
17779 [false])],
17780 [AC_MSG_NOTICE([files differ, or echo failed])])
17781 @end example
17782
17783 @item @command{@{...@}}
17784 @c --------------------
17785 @prindex @command{@{...@}}
17786 Bash 3.2 (and earlier versions) sometimes does not properly set
17787 @samp{$?} when failing to write redirected output of a compound command.
17788 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17789 not occur with @samp{(@dots{})}. For example:
17790
17791 @example
17792 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17793 bash: line 1: /bad: Permission denied
17794 0
17795 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17796 bash: line 1: /bad: Permission denied
17797 0
17798 @end example
17799
17800 To work around the bug, prepend @samp{:;}:
17801
17802 @example
17803 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17804 bash: line 1: /bad: Permission denied
17805 1
17806 @end example
17807
17808 POSIX requires a syntax error if a brace list has no contents. However,
17809 not all shells obey this rule; and on shells where empty lists are
17810 permitted, the effect on @samp{$?} is inconsistent. To avoid problems,
17811 ensure that a brace list is never empty.
17812
17813 @example
17814 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17815 bash: line 1: syntax error near unexpected token `@}'
17816 bash: line 1: `false; @{ @}; echo $?'
17817 2
17818 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
17819 1
17820 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
17821 0
17822 @end example
17823
17824
17825 @item @command{break}
17826 @c ------------------
17827 @prindex @command{break}
17828 The use of @samp{break 2} etc.@: is safe.
17829
17830
17831 @anchor{case}
17832 @item @command{case}
17833 @c -----------------
17834 @prindex @command{case}
17835 If a @code{case} command is not inside @code{AC_DEFUN}, and it contains
17836 calls to Autoconf macros, it should be rewritten using @code{AS_CASE}.
17837 @xref{Common Shell Constructs}. Instead of:
17838
17839 @example
17840 # This is dangerous outside AC_DEFUN.
17841 case $filename in
17842 *.[ch]) AC_MSG_NOTICE([C source file]);;
17843 esac
17844 @end example
17845
17846 @noindent
17847 use:
17848
17849 @example
17850 # This is OK outside AC_DEFUN.
17851 AS_CASE([$filename],
17852 [[*.[ch]]], [AC_MSG_NOTICE([C source file])])
17853 @end example
17854
17855 You don't need to quote the argument; no splitting is performed.
17856
17857 You don't need the final @samp{;;}, but you should use it.
17858
17859 POSIX requires support for @code{case} patterns with opening
17860 parentheses like this:
17861
17862 @example
17863 case $file_name in
17864 (*.c) echo "C source code";;
17865 esac
17866 @end example
17867
17868 @noindent
17869 but the @code{(} in this example is not portable to a few obsolescent Bourne
17870 shell implementations, which is a pity for those of us using tools that
17871 rely on balanced parentheses. For instance, with Solaris 10
17872 @command{/bin/sh}:
17873
17874 @example
17875 $ @kbd{case foo in (foo) echo foo;; esac}
17876 @error{}syntax error: `(' unexpected
17877 @end example
17878
17879 @noindent
17880 The leading @samp{(} can be omitted safely. Unfortunately, there are
17881 contexts where unbalanced parentheses cause other problems, such as when
17882 using a syntax-highlighting editor that searches for the balancing
17883 counterpart, or more importantly, when using a case statement as an
17884 underquoted argument to an Autoconf macro. @xref{Balancing
17885 Parentheses}, for trade-offs involved in various styles of dealing with
17886 unbalanced @samp{)}.
17887
17888 Zsh handles pattern fragments derived from parameter expansions or
17889 command substitutions as though quoted:
17890
17891 @example
17892 $ pat=\?; case aa in ?$pat) echo match;; esac
17893 $ pat=\?; case a? in ?$pat) echo match;; esac
17894 match
17895 @end example
17896
17897 @noindent
17898 Because of a bug in its @code{fnmatch}, Bash fails to properly
17899 handle backslashes in character classes:
17900
17901 @example
17902 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17903 bash-2.02$
17904 @end example
17905
17906 @noindent
17907 This is extremely unfortunate, since you are likely to use this code to
17908 handle POSIX or MS-DOS absolute file names. To work around this
17909 bug, always put the backslash first:
17910
17911 @example
17912 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17913 OK
17914 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17915 OK
17916 @end example
17917
17918 Many Bourne shells cannot handle closing brackets in character classes
17919 correctly.
17920
17921 Some shells also have problems with backslash escaping in case you do not want
17922 to match the backslash: both a backslash and the escaped character match this
17923 pattern. To work around this, specify the character class in a variable, so
17924 that quote removal does not apply afterwards, and the special characters don't
17925 have to be backslash-escaped:
17926
17927 @example
17928 $ @kbd{case '\' in [\<]) echo OK;; esac}
17929 OK
17930 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17931 $
17932 @end example
17933
17934 Even with this, Solaris @command{ksh} matches a backslash if the set
17935 contains any
17936 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17937
17938 Some shells, such as Ash 0.3.8, are confused by an empty
17939 @code{case}/@code{esac}:
17940
17941 @example
17942 ash-0.3.8 $ @kbd{case foo in esac;}
17943 @error{}Syntax error: ";" unexpected (expecting ")")
17944 @end example
17945
17946 POSIX requires @command{case} to give an exit status of 0 if no cases
17947 match. However, @command{/bin/sh} in Solaris 10 does not obey this
17948 rule. Meanwhile, it is unclear whether a case that matches, but
17949 contains no statements, must also change the exit status to 0. The M4sh
17950 macro @code{AS_CASE} works around these inconsistencies.
17951
17952 @example
17953 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
17954 0
17955 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17956 255
17957 @end example
17958
17959
17960 @item @command{cd}
17961 @c ---------------
17962 @prindex @command{cd}
17963 POSIX requires that @command{cd} must support
17964 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17965 with @option{-L} being the default. However, traditional shells do
17966 not support these options, and their @command{cd} command has the
17967 @option{-P} behavior.
17968
17969 Portable scripts should assume neither option is supported, and should
17970 assume neither behavior is the default. This can be a bit tricky,
17971 since the POSIX default behavior means that, for example,
17972 @samp{ls ..} and @samp{cd ..} may refer to different directories if
17973 the current logical directory is a symbolic link. It is safe to use
17974 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17975 Also, Autoconf-generated scripts check for this problem when computing
17976 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17977 so it is safe to @command{cd} to these variables.
17978
17979 POSIX specifies an @option{-e} option that affects the exit status
17980 when the @option{-P} option is in effect. Portable scripts should
17981 avoid it for the same reason they avoid @option{-P}.
17982
17983 @evindex OLDPWD
17984 @evindex PWD
17985 POSIX says that a successful @command{cd} updates the values of the
17986 @env{OLDPWD} and @env{PWD} variables, and that @command{cd -} acts like
17987 @command{cd "$OLDPWD"}. Older shells, such as Solaris 10
17988 @command{/bin/sh}, do not support this and portable scripts should not
17989 rely on it.
17990
17991 @evindex HOME
17992 If @env{HOME} is unset or empty, the behavior of @command{cd} with no
17993 arguments is implementation-defined, so portable scripts should avoid it
17994 in that case.
17995
17996 POSIX 1003.1-2024 states that @command{cd} must fail if given an
17997 explicit empty argument. However, earlier POSIX editions did not
17998 specify the behavior and some shells do nothing, some change to the
17999 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
18000 the shell rather than returning an error. Unfortunately, this means
18001 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
18002 than @samp{cd $var} (at least the latter is well-behaved in all shells
18003 at changing to @env{HOME}, although this is probably not what you wanted
18004 in a script). You should check that a directory name was supplied
18005 before trying to change locations.
18006
18007 If @command{cd} fails, POSIX requires the invoking shell to behave as if
18008 @command{cd} exited with status 1, which means the invoking shell can continue.
18009 However, Solaris 10 @command{/bin/sh} aborts the containing command if
18010 interactive, and exits otherwise.
18011
18012 @xref{Special Shell Variables}, for portability problems involving
18013 @command{cd} and the @env{CDPATH} environment variable.
18014 Also please see the discussion of the @command{pwd} command.
18015
18016
18017 @anchor{echo}
18018 @item @command{echo}
18019 @c -----------------
18020 @prindex @command{echo}
18021 The simple @command{echo} is probably the most surprising source of
18022 portability troubles. It is not possible to use @samp{echo} portably
18023 unless both options and escape sequences are omitted.
18024
18025 Do not use options, as some shells support them and others do not.
18026 For example, POSIX says that the behavior of @samp{echo -n foo} is
18027 implementation-defined. On some platforms the output is @samp{foo}
18028 without a trailing newline, on others it is @samp{-n foo} with a
18029 trailing newline, and POSIX allows even other behavior.
18030
18031 Do not use backslashes in the arguments, as there is no consensus on
18032 their handling. For @samp{echo '\n' | wc -l}, the @command{sh} of
18033 Solaris 10 outputs 2,
18034 but Bash and Zsh (in @command{sh} emulation mode) output 1.
18035 The problem is truly @command{echo}: all the shells
18036 understand @samp{'\n'} as the string composed of a backslash and an
18037 @samp{n}.
18038
18039 Because of these problems, do not pass a string containing arbitrary
18040 characters to @command{echo}. For example, @samp{echo "$foo"} is safe
18041 only if you know that @var{foo}'s value cannot contain backslashes and
18042 cannot start with @samp{-}.
18043
18044 Normally, @command{printf} is safer and easier to use than @command{echo}
18045 and @command{echo -n}. Thus, you should use @command{printf '%s\n'}
18046 instead of @command{echo}, and similarly use @command{printf %s} instead
18047 of @command{echo -n}.
18048
18049 Older scripts, written before @command{printf} was portable,
18050 sometimes used a here-document as a safer alternative to @command{echo},
18051 like this:
18052
18053 @example
18054 cat <<EOF
18055 $foo
18056 EOF
18057 @end example
18058
18059 @noindent
18060 However, this usage is problematic, as even some modern shells have
18061 hard-to-reproduce bugs when dealing with here-documents.
18062
18063
18064 @item @command{eval}
18065 @c -----------------
18066 @prindex @command{eval}
18067 The @command{eval} command is useful in limited circumstances, e.g.,
18068 using commands like @samp{eval table_$key=\$value} and @samp{eval
18069 value=table_$key} to simulate a hash table when the key is known to be
18070 alphanumeric.
18071
18072 You should also be wary of common bugs in @command{eval} implementations.
18073 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
18074 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
18075 4.2.5), the arguments of @samp{eval} are evaluated in a context where
18076 @samp{$?} is 0, so they exhibit behavior like this:
18077
18078 @example
18079 $ @kbd{false; eval 'echo $?'}
18080 0
18081 @end example
18082
18083 The correct behavior here is to output a nonzero value,
18084 but portable scripts should not rely on this.
18085
18086 You should not rely on @code{LINENO} within @command{eval}.
18087 @xref{Special Shell Variables}.
18088
18089 Note that, even though these bugs are easily avoided,
18090 @command{eval} is tricky to use on arbitrary arguments.
18091 It is obviously unwise to use @samp{eval $cmd} if the string value of
18092 @samp{cmd} was derived from an untrustworthy source. But even if the
18093 string value is valid, @samp{eval $cmd} might not work as intended,
18094 since it causes field splitting and file name expansion to occur twice,
18095 once for the @command{eval} and once for the command itself. It is
18096 therefore safer to use @samp{eval "$cmd"}. For example, if @var{cmd}
18097 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
18098 equivalent of @samp{cat test;.c} if there happens to be a file named
18099 @file{test;.c} in the current directory; and this in turn
18100 mistakenly attempts to invoke @command{cat} on the file @file{test} and
18101 then execute the command @command{.c}. To avoid this problem, use
18102 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
18103
18104 However, suppose that you want to output the text of the evaluated
18105 command just before executing it. Assuming the previous example,
18106 @samp{printf '%s\n' "Executing: $cmd"} outputs @samp{Executing: cat test?.c},
18107 but this output doesn't show the user that @samp{test;.c} is the actual
18108 name of the copied file.
18109 Conversely, @samp{printf 'Executing:'; eval "printf ' %s' $cmd"; printf '\n'}
18110 works on this example, but it fails with @samp{cmd='cat foo >bar'},
18111 since it mistakenly replaces the contents of @file{bar} by the
18112 string @samp{ cat foo}. No simple, general, and portable solution to
18113 this problem is known.
18114
18115 @item @command{exec}
18116 @c -----------------
18117 @prindex @command{exec}
18118 POSIX describes several categories of shell built-ins. Special
18119 built-ins (such as @command{exit}) must impact the environment of the
18120 current shell, and need not be available through @command{exec}. All
18121 other built-ins are regular, and must not propagate variable assignments
18122 to the environment of the current shell. However, the group of regular
18123 built-ins is further distinguished by commands that do not require a
18124 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
18125 are offered as a more efficient version of something that must still be
18126 found in a @env{PATH} search (such as @command{echo}). POSIX is not
18127 clear on whether @command{exec} must work with the list of 17 utilities
18128 that are invoked without a @env{PATH} search, and many platforms lack an
18129 executable for some of those built-ins:
18130
18131 @example
18132 $ @kbd{sh -c 'exec cd /tmp'}
18133 sh: line 0: exec: cd: not found
18134 @end example
18135
18136 All other built-ins that provide utilities specified by POSIX must have
18137 a counterpart executable that exists on @env{PATH}, although POSIX
18138 allows @command{exec} to use the built-in instead of the executable.
18139 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
18140
18141 @example
18142 $ @kbd{bash -c 'pwd --version' | head -n1}
18143 bash: line 0: pwd: --: invalid option
18144 pwd: usage: pwd [-LP]
18145 $ @kbd{bash -c 'exec pwd --version' | head -n1}
18146 pwd (GNU coreutils) 6.10
18147 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
18148 pdksh: pwd: --: unknown option
18149 @end example
18150
18151 When it is desired to avoid a regular shell built-in, the workaround is
18152 to use some other forwarding command, such as @command{env} or
18153 @command{nice}, that will ensure a path search:
18154
18155 @example
18156 $ @kbd{pdksh -c 'exec true --version' | head -n1}
18157 $ @kbd{pdksh -c 'nice true --version' | head -n1}
18158 true (GNU coreutils) 6.10
18159 $ @kbd{pdksh -c 'env true --version' | head -n1}
18160 true (GNU coreutils) 6.10
18161 @end example
18162
18163 @item @command{exit}
18164 @c -----------------
18165 @prindex @command{exit}
18166 The default value of @command{exit} is supposed to be @code{$?};
18167 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
18168 perform @samp{exit 0}.
18169
18170 @example
18171 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
18172 fail
18173 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
18174 fail
18175 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
18176 bash-2.04$
18177 @end example
18178
18179 Using @samp{exit $?} restores the expected behavior.
18180
18181 Some shell scripts, such as those generated by @command{autoconf}, use a
18182 trap to clean up before exiting. If the last shell command exited with
18183 nonzero status, the trap also exits with nonzero status so that the
18184 invoker can tell that an error occurred.
18185
18186 Unfortunately, in some shells, such as Solaris 10 @command{/bin/sh}, an exit
18187 trap ignores the @code{exit} command's argument. In these shells, a trap
18188 cannot determine whether it was invoked by plain @code{exit} or by
18189 @code{exit 1}. Instead of calling @code{exit} directly, use the
18190 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
18191
18192
18193 @anchor{export}
18194 @item @command{export}
18195 @c -------------------
18196 @prindex @command{export}
18197 The builtin @command{export} dubs a shell variable @dfn{environment
18198 variable}. Each update of exported variables corresponds to an update
18199 of the environment variables. Conversely, each environment variable
18200 received by the shell when it is launched should be imported as a shell
18201 variable marked as exported.
18202
18203 Alas, some older shells, such as Solaris 10 @command{/bin/sh}, forget to
18204 @command{export} the environment variables they receive. As a result,
18205 two variables coexist: the environment variable and the shell
18206 variable. The following code demonstrates this failure:
18207
18208 @example
18209 #!/bin/sh
18210 echo $FOO
18211 FOO=bar
18212 echo $FOO
18213 exec /bin/sh $0
18214 @end example
18215
18216 @noindent
18217 when run with @samp{FOO=foo} in the environment, these shells print
18218 alternately @samp{foo} and @samp{bar}, although they should print only
18219 @samp{foo} and then a sequence of @samp{bar}s.
18220
18221 Therefore you should @command{export} again each environment variable
18222 that you update; the export can occur before or after the assignment.
18223
18224 POSIX is not clear on whether the @command{export} of an undefined
18225 variable causes the variable to be defined with the value of an empty
18226 string, or merely marks any future definition of a variable by that name
18227 for export. Various shells behave differently in this regard:
18228
18229 @example
18230 $ @kbd{sh -c 'export foo; env | grep foo'}
18231 $ @kbd{ash -c 'export foo; env | grep foo'}
18232 foo=
18233 @end example
18234
18235 POSIX requires @command{export} to honor assignments made as arguments,
18236 but older shells do not support this, including @command{/bin/sh} in
18237 Solaris 10. Portable scripts should separate assignments and exports
18238 into different statements.
18239
18240 @example
18241 $ @kbd{bash -c 'export foo=bar; echo $foo'}
18242 bar
18243 $ @kbd{/bin/sh -c 'export foo=bar; echo $foo'}
18244 /bin/sh: foo=bar: is not an identifier
18245 $ @kbd{/bin/sh -c 'export foo; foo=bar; echo $foo'}
18246 bar
18247 @end example
18248
18249 POSIX requires @command{export} to work with any arbitrary value for the
18250 contents of the variable being exported, as long as the total size of
18251 the environment combined with arguments doesn't exceed @code{ARG_MAX}
18252 when executing a child process. However, some shells have extensions
18253 that involve interpreting some environment values specially, regardless
18254 of the variable name. We currently know of one case: all versions of
18255 Bash released prior to 27 September 2014 interpret an environment
18256 variable with an initial content substring of @code{() @{} as an
18257 exported function definition (this is the ``Shellshock'' remote
18258 execution bug, CVE-2014-6271 and friends, where it was possible to
18259 exploit the function parser to cause remote code execution on child bash
18260 startup; newer versions of Bash use special environment variable
18261 @emph{names} instead of values to implement the same feature).
18262
18263 There may be entries inherited into the environment that are not valid
18264 as shell variable names; POSIX states that processes should be tolerant
18265 of these names. Some shells such as @command{dash} do this by removing
18266 those names from the environment at startup, while others such as
18267 @command{bash} hide the entry from shell access but still pass it on to
18268 child processes. While you can set such names using @command{env} for a
18269 direct child process, you cannot rely on them being preserved through an
18270 intermediate pass through the shell.
18271
18272 @item @command{false}
18273 @c ------------------
18274 @prindex @command{false}
18275 Don't expect @command{false} to exit with status 1: in native
18276 Solaris @file{/bin/false} exits with status 255.
18277
18278
18279 @item @command{for}
18280 @c ----------------
18281 @prindex @command{for}
18282 To loop over positional arguments, use:
18283
18284 @example
18285 for arg
18286 do
18287 printf '%s\n' "$arg"
18288 done
18289 @end example
18290
18291 @noindent
18292 You may @emph{not} leave the @code{do} on the same line as @code{for},
18293 since some shells improperly grok:
18294
18295 @example
18296 for arg; do
18297 printf '%s\n' "$arg"
18298 done
18299 @end example
18300
18301 If you want to explicitly refer to the positional arguments, use:
18302
18303 @example
18304 for arg in "$@@"; do
18305 printf '%s\n' "$arg"
18306 done
18307 @end example
18308
18309 POSIX requires support for a @command{for} loop with no list after
18310 @code{in}. However, Solaris 10 @command{/bin/sh} treats that as a syntax
18311 error. It is possible to work around this by providing any shell word
18312 that expands to nothing, or by ignoring an obvious sentinel.
18313
18314 @example
18315 $ @kbd{/bin/sh -c 'for a in $empty; do echo hi; done'}
18316 $ @kbd{/bin/sh -c 'for a in ; do echo hi; done'}
18317 /bin/sh: syntax error at line 1: `;' unexpected
18318 @end example
18319
18320 This syntax problem is most frequently encountered in code that goes
18321 through several layers of expansion, such as an m4 macro or makefile
18322 variable used as a list body, where the first layer of expansion (m4 or
18323 make) can end up expanding to nothing in the version handed to the
18324 shell. In the makefile context, one common workaround is to use a shell
18325 variable rather than a make variable as the source of the list.
18326
18327 @example
18328 $ @kbd{cat Makefile}
18329 list =
18330 bad:
18331 @@for arg in $(list); do \
18332 printf '%s\n' $$arg; \
18333 done
18334 good:
18335 @@list='$(list)'; \
18336 for arg in $$list; do \
18337 printf '%s\n' $$arg; \
18338 done
18339 $ @kbd{make bad 2&>1 | head -n1}
18340 sh: syntax error at line 1: `;' unexpected
18341 $ @kbd{make bad list='a b'}
18342 a
18343 b
18344 $ @kbd{make good}
18345 $ @kbd{make good list='a b'}
18346 a
18347 b
18348 @end example
18349
18350 In Solaris 10 @command{/bin/sh}, when the list of arguments of a
18351 @command{for} loop starts with @emph{unquoted} tokens looking like
18352 variable assignments, the loop is not executed on those tokens:
18353
18354 @example
18355 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
18356 x
18357 e=f
18358 @end example
18359
18360 @noindent
18361 Thankfully, quoting the assignment-like tokens, or starting the list
18362 with other tokens (including unquoted variable expansion that results in
18363 an assignment-like result), avoids the problem, so it is easy to work
18364 around:
18365
18366 @example
18367 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
18368 a=b
18369 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
18370 a=b
18371 c=d
18372 @end example
18373
18374 @anchor{if}
18375 @item @command{if}
18376 @c ---------------
18377 @prindex @command{if}
18378 If an @code{if} command is not inside @code{AC_DEFUN}, and it contains
18379 calls to Autoconf macros, it should be rewritten using @code{AS_IF}.
18380 @xref{Common Shell Constructs}.
18381
18382 Using @code{if ! @dots{}} is not portable. @xref{!,,@command{!} notes}.
18383
18384 Some very old shells did not reset the exit status from an @command{if}
18385 with no @command{else}:
18386
18387 @example
18388 $ @kbd{if (exit 42); then true; fi; echo $?}
18389 42
18390 @end example
18391
18392 @noindent
18393 whereas a proper shell should have printed @samp{0}. Although this is no
18394 longer a portability problem, as any shell that supports functions gets it
18395 correct, it explains why some makefiles have lengthy
18396 constructs:
18397
18398 @example
18399 if test -f "$file"; then
18400 install "$file" "$dest"
18401 else
18402 :
18403 fi
18404 @end example
18405
18406
18407 @item @command{printf}
18408 @c ------------------
18409 @prindex @command{printf}
18410 A format string starting with a @samp{-} can cause problems.
18411 Bash interprets it as an option and
18412 gives an error. And @samp{--} to mark the end of options is not good
18413 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
18414 literally as the format string. Putting the @samp{-} in a @samp{%c}
18415 or @samp{%s} is probably easiest:
18416
18417 @example
18418 printf %s -foo
18419 @end example
18420
18421 AIX 7.2 @command{sh} mishandles octal escapes in multi-byte locales by
18422 treating them as characters instead of bytes. For example, in a locale
18423 using the UTF-8 encoding, @samp{printf '\351'} outputs the two bytes C3,
18424 A9 (the UTF-8 encoding for U+00E9) instead of the desired single byte E9.
18425 To work around the bug, use the C locale.
18426
18427 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
18428
18429 @example
18430 $ @kbd{printf '\045'}
18431 bash: printf: `%': missing format character
18432 @end example
18433
18434 Large outputs may cause trouble. On Solaris 10, for
18435 example, @file{/usr/bin/printf} is buggy, so when using
18436 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
18437 core.
18438
18439 Since @command{printf} is not always a shell builtin, there is a
18440 potential speed penalty for using @code{printf '%s\n'} as a replacement
18441 for an @command{echo} that does not interpret @samp{\} or leading
18442 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
18443 -r --} for this role instead.
18444
18445 @xref{echo, , Limitations of Shell Builtins}, for a discussion of
18446 portable alternatives to both @command{printf} and @command{echo}.
18447
18448
18449 @item @command{pwd}
18450 @c ----------------
18451 @prindex @command{pwd}
18452 With modern shells, plain @command{pwd} outputs a ``logical''
18453 directory name, some of whose components may be symbolic links. These
18454 directory names are in contrast to ``physical'' directory names, whose
18455 components are all directories.
18456
18457 POSIX requires that @command{pwd} must support
18458 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
18459 with @option{-L} being the default. However, traditional shells do
18460 not support these options, and their @command{pwd} command has the
18461 @option{-P} behavior.
18462
18463 Portable scripts should assume neither option is supported, and should
18464 assume neither behavior is the default. Also, on many hosts
18465 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but POSIX
18466 does not require this behavior and portable scripts should not rely on
18467 it.
18468
18469 Typically it's best to use plain @command{pwd}. On modern hosts this
18470 outputs logical directory names, which have the following advantages:
18471
18472 @itemize @bullet
18473 @item
18474 Logical names are what the user specified.
18475 @item
18476 Physical names may not be portable from one installation
18477 host to another due to network file system gymnastics.
18478 @item
18479 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
18480 some parent directory, but plain @command{pwd} cannot fail for this
18481 reason.
18482 @end itemize
18483
18484 Also please see the discussion of the @command{cd} command.
18485
18486
18487 @item @command{read}
18488 @c -----------------
18489 @prindex @command{read}
18490 No options are portable, not even support @option{-r} (Solaris 10
18491 @command{/bin/sh} for example).
18492
18493
18494 @anchor{set}
18495 @item @command{set}
18496 @c ----------------
18497 @prindex @command{set}
18498 With the FreeBSD 6.0 shell, the @command{set} command (without
18499 any options) does not sort its output.
18500
18501 The @command{set} builtin faces the usual problem with arguments
18502 starting with a
18503 dash. Modern shells understand @option{--} to specify
18504 the end of the options (any argument after @option{--} is a parameter,
18505 even @samp{-x} for instance), but some ancient shells stop option
18506 processing only after a non-option argument is found. Therefore, use
18507 @samp{dummy} or simply @samp{x} to end the option processing, and use
18508 @command{shift} to pop it out:
18509
18510 @example
18511 set x $my_list; shift
18512 @end example
18513
18514 Avoid @samp{set -}, e.g., @samp{set - $my_list}. POSIX no
18515 longer requires support for this command, and in traditional shells
18516 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
18517 makes scripts harder to debug.
18518
18519 Some nonstandard shells do not recognize more than one option
18520 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line). It is
18521 better to combine them:
18522
18523 @example
18524 set -ex
18525 @end example
18526
18527 @cindex @command{set -e}
18528 The @option{-e} option has historically been under-specified, with enough
18529 ambiguities to cause numerous differences across various shell
18530 implementations; see for example
18531 @uref{https://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
18532 or @uref{https://www.austingroupbugs.net/@/view.php?id=52, this link},
18533 documenting a change to POSIX 2008 to match @command{ksh88} behavior.
18534 Note that mixing @code{set -e} and shell functions is asking for surprises:
18535
18536 @example
18537 set -e
18538 doit()
18539 @{
18540 rm file
18541 echo one
18542 @}
18543 doit || echo two
18544 @end example
18545
18546 @noindent
18547 According to the recommendation, @samp{one} should always be output
18548 regardless of whether the @command{rm} failed, because it occurs within
18549 the body of the shell function @samp{doit} invoked on the left side of
18550 @samp{||}, where the effects of @samp{set -e} are not enforced.
18551 Likewise, @samp{two} should never be printed, since the failure of
18552 @command{rm} does not abort the function, such that the status of
18553 @samp{doit} is 0.
18554
18555 The BSD shell has had several problems with the @option{-e}
18556 option. Older versions of the BSD
18557 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
18558 @samp{case} when @option{-e} was in effect, causing the shell to exit
18559 unexpectedly in some cases. This was particularly a problem with
18560 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
18561 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
18562 wrapper works around the bug (@pxref{Failure in Make Rules}).
18563
18564 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
18565 wrongly exit with @option{-e} if the last command within a compound
18566 statement fails and is guarded by an @samp{&&} only. For example:
18567
18568 @example
18569 #! /bin/sh
18570 set -e
18571 foo=''
18572 test -n "$foo" && exit 1
18573 echo one
18574 if :; then
18575 test -n "$foo" && exit 1
18576 echo two
18577 test -n "$foo" && exit 1
18578 fi
18579 echo three
18580 @end example
18581
18582 @noindent
18583 does not print @samp{three}. One workaround is to change the last
18584 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
18585 "$foo"; then exit 1; fi} instead. Another possibility is to warn BSD
18586 users not to use @samp{sh -e}.
18587
18588 When @samp{set -e} is in effect, a failed command substitution in
18589 Solaris 10 @command{/bin/sh} cannot be ignored, even with @samp{||}.
18590
18591 @example
18592 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
18593 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
18594 foo
18595 bar
18596 @end example
18597
18598 @noindent
18599 Moreover, a command substitution, successful or not, causes this shell to
18600 exit from a failing outer command even in presence of an @samp{&&} list:
18601
18602 @example
18603 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
18604 ok
18605 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
18606 $
18607 @end example
18608
18609 @cindex @command{set -b}
18610 @cindex @command{set -m}
18611 Job control is not provided by all shells, so the use of @samp{set -m}
18612 or @samp{set -b} must be done with care. When using @command{zsh} in
18613 native mode, asynchronous notification (@samp{set -b}) is enabled by
18614 default, and using @samp{emulate sh} to switch to POSIX mode does not
18615 clear this setting (although asynchronous notification has no impact
18616 unless job monitoring is also enabled). Also, @command{zsh} 4.3.10 and
18617 earlier have a bug where job control can be manipulated in interactive
18618 shells, but not in subshells or scripts. Furthermore, some shells, like
18619 @command{pdksh}, fail to treat subshells as interactive, even though the
18620 parent shell was.
18621
18622 @example
18623 $ @kbd{echo $ZSH_VERSION}
18624 4.3.10
18625 $ @kbd{set -m; echo $?}
18626 0
18627 $ @kbd{zsh -c 'set -m; echo $?'}
18628 set: can't change option: -m
18629 $ @kbd{(set -m); echo $?}
18630 set: can't change option: -m
18631 1
18632 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
18633 cim
18634 c
18635 @end example
18636
18637 @cindex @command{set -n}
18638 Use of @command{set -n} (typically via @command{sh -n script}) to
18639 validate a script is not foolproof. Modern @command{ksh93} tries to be
18640 helpful by informing you about better syntax, but switching the script
18641 to use the suggested syntax in order to silence the warnings would
18642 render the script no longer portable to older shells:
18643
18644 @example
18645 $ @kbd{ksh -nc '``'}
18646 ksh: warning: line 1: `...` obsolete, use $(...)
18647 0
18648 @end example
18649
18650 Autoconf
18651 itself uses @command{sh -n} within its testsuite to check that correct
18652 scripts were generated, but only after first probing for other shell
18653 features (such as @code{test $@{BASH_VERSION+y@}}) that indicate
18654 a reasonably fast and working implementation.
18655
18656 @item @command{shift}
18657 @c ------------------
18658 @prindex @command{shift}
18659 Not only is @command{shift}ing a bad idea when there is nothing left to
18660 shift, but in addition it is not portable: the shell of MIPS
18661 RISC/OS 4.52 refuses to do it.
18662
18663 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
18664 it is also absent in many pre-POSIX shells.
18665
18666
18667 @item @command{source}
18668 @c -------------------
18669 @prindex @command{source}
18670 This command is not portable, as POSIX does not require it; use
18671 @command{.} instead.
18672
18673
18674 @item @command{test}
18675 @c -----------------
18676 @prindex @command{test}
18677 The @code{test} program is the way to perform many file and string
18678 tests. It is often invoked by the alternate name @samp{[}, but using
18679 that name in Autoconf code is asking for trouble since it is an M4 quote
18680 character.
18681
18682 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
18683 present in all implementations, and have been marked obsolete by POSIX
18684 2008. This is because there are inherent ambiguities in using them.
18685 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
18686 check whether two strings are both non-empty, but if @samp{$1} is the
18687 literal @samp{!}, then some implementations of @command{test} treat it
18688 as a negation of the unary operator @option{-a}.
18689
18690 Thus, portable uses of @command{test} should never have more than four
18691 arguments, and scripts should use shell constructs like @samp{&&} and
18692 @samp{||} instead. If you combine @samp{&&} and @samp{||} in the same
18693 statement, keep in mind that they have equal precedence, so it is often
18694 better to parenthesize even when this is redundant. For example:
18695
18696 @smallexample
18697 # Not portable:
18698 test "X$a" = "X$b" -a \
18699 '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
18700
18701 # Portable:
18702 test "X$a" = "X$b" &&
18703 @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
18704 @end smallexample
18705
18706 @command{test} does not process options like most other commands do; for
18707 example, it does not recognize the @option{--} argument as marking the
18708 end of options.
18709
18710 It is safe to use @samp{!} as a @command{test} operator. For example,
18711 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
18712 -d foo; @dots{}} is not.
18713
18714
18715 @item @command{test} (files)
18716 @c -------------------------
18717 To enable @command{configure} scripts to support cross-compilation, they
18718 shouldn't do anything that tests features of the build system instead of
18719 the host system. But occasionally you may find it necessary to check
18720 whether some arbitrary file exists. To do so, use @samp{test -f},
18721 @samp{test -r}, or @samp{test -x}. Do not use @samp{test -e}, because
18722 Solaris 10 @command{/bin/sh}
18723 lacks it.
18724
18725 To test for symbolic links on systems that have them, use
18726 @samp{test -h} rather than @samp{test -L}; either form conforms to
18727 POSIX, but @option{-h} has been around longer.
18728
18729 The commands @samp{test A -ot B} and @samp{test A -nt B} are not reliable
18730 on macOS @command{sh} through at least macOS Sequoia 15.1.1 (2024),
18731 where @samp{test} ignores the subsecond part of file timestamps.
18732 To work around this bug, arrange for the timestamps to be at least one
18733 second apart.
18734
18735 For historical reasons, POSIX reluctantly allows implementations of
18736 @samp{test -x} that will succeed for the root user, even if no execute
18737 permissions are present. Furthermore, shells do not all agree on
18738 whether Access Control Lists should affect @samp{test -r}, @samp{test
18739 -w}, and @samp{test -x}; some shells base test results strictly on the
18740 current user id compared to file owner and mode, as if by
18741 @code{stat(2)}; while other shells base test results on whether the
18742 current user has the given right, even if that right is only granted by
18743 an ACL, as if by @code{faccessat(2)}. Furthermore, there is a classic
18744 time of check to time of use race between any use of @command{test}
18745 followed by operating on the just-checked file. Therefore, it is a good
18746 idea to write scripts that actually attempt an operation, and are
18747 prepared for the resulting failure if permission is denied, rather than
18748 trying to avoid an operation based solely on whether @command{test}
18749 guessed that it might not be permitted.
18750
18751 @item @command{test} (strings)
18752 @c ---------------------------
18753 POSIX says that @samp{test "@var{string}"} succeeds if @var{string} is
18754 not null, but this usage is not portable to traditional platforms like
18755 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
18756 @samp{-n}. However, it @emph{is} portable to test if a variable is set
18757 to a non-empty value, by using @samp{test $@{var+y@}}, since all known
18758 implementations properly distinguish between no arguments and a
18759 known-safe string of @samp{y}.
18760
18761 POSIX also says that @samp{test ! "@var{string}"},
18762 @samp{test -n "@var{string}"} and
18763 @samp{test -z "@var{string}"} work with any string, but some
18764 shells (such as Solaris 10) get confused if
18765 @var{string} looks like an operator:
18766
18767 @example
18768 $ @kbd{test -n =}
18769 test: argument expected
18770 $ @kbd{test ! -n}
18771 test: argument expected
18772 $ @kbd{test -z ")"; echo $?}
18773 0
18774 @end example
18775
18776 Similarly, POSIX says that both @samp{test "@var{string1}" = "@var{string2"}}
18777 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
18778 strings, but in practice this is not true for troublesome strings that
18779 look like operators or parentheses, or that begin with @samp{-}.
18780
18781 It is best to protect such strings with a leading @samp{X}, e.g.,
18782 @samp{test "X@var{string}" != X} rather than @samp{test -n
18783 "@var{string}"} or @samp{test ! "@var{string}"}.
18784
18785 It is common to find variations of the following idiom:
18786
18787 @example
18788 test -n "`echo $ac_feature | sed 's/[a-zA-Z0-9_-]//g'`" &&
18789 @var{action}
18790 @end example
18791
18792 @noindent
18793 to take an action when a token matches a given pattern. Such constructs
18794 should be avoided by using:
18795
18796 @example
18797 AS_CASE([$ac_feature],
18798 [[*[!-a-zA-Z0-9_]*]], [@var{action}])
18799 @end example
18800
18801 If the pattern is a complicated regular expression that cannot be
18802 expressed as a shell pattern, use something like this instead:
18803
18804 @example
18805 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
18806 @var{action}
18807 @end example
18808
18809 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
18810 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
18811 @samp{@var{foo}} contains backslashes.
18812
18813
18814 @anchor{trap}
18815 @item @command{trap}
18816 @c -----------------
18817 @prindex @command{trap}
18818 It is safe to trap at least the signals 1, 2, 13, and 15. You can also
18819 trap 0, i.e., have the @command{trap} run when the script ends (either via an
18820 explicit @command{exit}, or the end of the script). The trap for 0 should be
18821 installed outside of a shell function, or AIX 7.3 @command{/bin/sh}
18822 will invoke the trap at the end of this function.
18823
18824 POSIX says that @samp{trap - 1 2 13 15} resets the traps for the
18825 specified signals to their default values, but many common shells (e.g.,
18826 Solaris 10 @command{/bin/sh}) misinterpret this and attempt to execute a
18827 ``command'' named @command{-} when the specified conditions arise.
18828 POSIX 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18829 reset traps, as this is supported by a larger set of shells, but there
18830 are still shells like @command{dash} that mistakenly try to execute
18831 @command{1} instead of resetting the traps. Therefore, there is no
18832 portable workaround, except for @samp{trap - 0}, for which
18833 @samp{trap '' 0} is a portable substitute.
18834
18835 Although POSIX is not absolutely clear on this point, it is widely
18836 admitted that when entering the trap @samp{$?} should be set to the exit
18837 status of the last command run before the trap. The ambiguity can be
18838 summarized as: ``when the trap is launched by an @command{exit}, what is
18839 the @emph{last} command run: that before @command{exit}, or
18840 @command{exit} itself?''
18841
18842 Bash considers @command{exit} to be the last command, while Zsh and
18843 Solaris 10 @command{/bin/sh} consider that when the trap is run it is
18844 @emph{still} in the @command{exit}, hence it is the previous exit status
18845 that the trap receives:
18846
18847 @example
18848 $ @kbd{cat trap.sh}
18849 trap 'echo $?' 0
18850 (exit 42); exit 0
18851 $ @kbd{zsh trap.sh}
18852 42
18853 $ @kbd{bash trap.sh}
18854 0
18855 @end example
18856
18857 The portable solution is then simple: when you want to @samp{exit 42},
18858 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18859 set the exit status to 42 for Zsh, and the second to trigger the trap
18860 and pass 42 as exit status for Bash. In M4sh, this is covered by using
18861 @code{AS_EXIT}.
18862
18863 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18864 reset to 0 by empty lines if the code is inside @command{trap}.
18865
18866 @example
18867 $ @kbd{trap 'false}
18868
18869 echo $?' 0
18870 $ @kbd{exit}
18871 0
18872 @end example
18873
18874 @noindent
18875 Fortunately, this bug only affects @command{trap}.
18876
18877 Several shells fail to execute an exit trap that is defined inside a
18878 subshell, when the last command of that subshell is not a builtin. A
18879 workaround is to use @samp{exit $?} as the shell builtin.
18880
18881 @example
18882 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18883 hi
18884 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18885 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18886 hi
18887 @end example
18888
18889 @noindent
18890 Likewise, older implementations of @command{bash} failed to preserve
18891 @samp{$?} across an exit trap consisting of a single cleanup command.
18892
18893 @example
18894 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
18895 2
18896 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
18897 0
18898 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
18899 2
18900 @end example
18901
18902 Be aware that a trap can be called from any number of places in your
18903 script, and therefore the trap handler should not make assumptions about
18904 shell state. For some examples, if your script temporarily modifies
18905 @env{IFS}, then the trap should include an initialization back to its
18906 typical value of space-tab-newline (autoconf does this for generated
18907 @file{configure} files). Likewise, if your script changes the current
18908 working directory at some point after the trap is installed, then your
18909 trap cannot assume which directory it is in, and should begin by
18910 changing directories to an absolute path if that is important to the
18911 cleanup efforts (autotest does this for generated @file{testsuite}
18912 files).
18913
18914 @item @command{true}
18915 @c -----------------
18916 @prindex @command{true}
18917 @c Info cannot handle ':' in index entries.
18918 @c @prindex @command{:}
18919 Don't worry: as far as we know @command{true} is portable.
18920 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18921 portable shell community tends to prefer using @command{:}. This has a
18922 funny side effect: when asked whether @command{false} is more portable
18923 than @command{true} Alexandre Oliva answered:
18924
18925 @quotation
18926 In a sense, yes, because if it doesn't exist, the shell will produce an
18927 exit status of failure, which is correct for @command{false}, but not
18928 for @command{true}.
18929 @end quotation
18930
18931 Remember that even though @samp{:} ignores its arguments, it still takes
18932 time to compute those arguments. It is a good idea to use double quotes
18933 around any arguments to @samp{:} to avoid time spent in field splitting
18934 and file name expansion.
18935
18936
18937 @anchor{unset}
18938 @item @command{unset}
18939 @c ------------------
18940 @prindex @command{unset}
18941 In some nonconforming shells (e.g., Solaris 10 @command{/bin/ksh} and
18942 @command{/usr/xpg4/bin/sh}, NetBSD 5.99.43 sh, or Bash 2.05a),
18943 @code{unset FOO} fails when @code{FOO} is not set. This can interfere
18944 with @code{set -e} operation. You can use
18945
18946 @smallexample
18947 FOO=; unset FOO
18948 @end smallexample
18949
18950 @noindent
18951 if you are not sure that @code{FOO} is set.
18952
18953 A few ancient shells lack @command{unset} entirely. For some variables
18954 such as @code{PS1}, you can use a neutralizing value instead:
18955
18956 @smallexample
18957 PS1='$ '
18958 @end smallexample
18959
18960 Usually, shells that do not support @command{unset} need less effort to
18961 make the environment sane, so for example is not a problem if you cannot
18962 unset @command{CDPATH} on those shells. However, Bash 2.01 mishandles
18963 @code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18964 So, you should do something like
18965
18966 @smallexample
18967 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18968 @end smallexample
18969
18970 @noindent
18971 @xref{Special Shell Variables}, for some neutralizing values. Also, see
18972 @ref{export, , Limitations of Builtins}, for
18973 the case of environment variables.
18974
18975 @item @command{wait}
18976 @c -----------------
18977 @prindex @command{wait}
18978 The exit status of @command{wait} is not always reliable.
18979 @end table
18980
18981 @node Limitations of Usual Tools
18982 @section Limitations of Usual Tools
18983 @cindex Limitations of usual tools
18984
18985 The small set of tools you can expect to find on any machine can still
18986 include some limitations you should be aware of.
18987
18988 @comment Between this list and the list of builtins above, we should
18989 @comment mention all the tools in GNU Coding Standards ``Utilities in
18990 @comment Makefiles''.
18991
18992 @c This table includes things like '@command{expr} (|)', so we can't
18993 @c use @table @command.
18994 @table @asis
18995 @anchor{awk}
18996 @item @command{awk}
18997 @c ----------------
18998 @prindex @command{awk}
18999 Don't leave white space before the opening parenthesis in a user function call.
19000 POSIX does not allow this and GNU Awk rejects it:
19001
19002 @example
19003 $ @kbd{gawk 'function die () @{ print "Aaaaarg!" @}
19004 BEGIN @{ die () @}'}
19005 gawk: cmd. line:2: BEGIN @{ die () @}
19006 gawk: cmd. line:2: ^ parse error
19007 $ @kbd{gawk 'function die () @{ print "Aaaaarg!" @}
19008 BEGIN @{ die() @}'}
19009 Aaaaarg!
19010 @end example
19011
19012 POSIX says that if a program contains only @samp{BEGIN} actions, and
19013 contains no instances of @code{getline}, then the program merely
19014 executes the actions without reading input. However, traditional Awk
19015 implementations (such as Solaris 10 @command{awk}) read and discard
19016 input in this case. Portable scripts can redirect input from
19017 @file{/dev/null} to work around the problem. For example:
19018
19019 @example
19020 awk 'BEGIN @{print "hello world"@}' </dev/null
19021 @end example
19022
19023 POSIX says that in an @samp{END} action, @samp{$NF} (and presumably,
19024 @samp{$1}) retain their value from the last record read, if no
19025 intervening @samp{getline} occurred. However, some implementations
19026 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
19027 @samp{awk}) reset these variables. A workaround is to use an
19028 intermediate variable prior to the @samp{END} block. For example:
19029
19030 @example
19031 $ @kbd{cat end.awk}
19032 @{ tmp = $1 @}
19033 END @{ print "a", $1, $NF, "b", tmp @}
19034 $ @kbd{echo 1 | awk -f end.awk}
19035 a b 1
19036 $ @kbd{echo 1 | gawk -f end.awk}
19037 a 1 1 b 1
19038 @end example
19039
19040 If you want your program to be deterministic, don't depend on @code{for}
19041 on arrays:
19042
19043 @example
19044 $ @kbd{cat for.awk}
19045 END @{
19046 arr["foo"] = 1
19047 arr["bar"] = 1
19048 for (i in arr)
19049 print i
19050 @}
19051 $ @kbd{gawk -f for.awk </dev/null}
19052 foo
19053 bar
19054 $ @kbd{nawk -f for.awk </dev/null}
19055 bar
19056 foo
19057 @end example
19058
19059 Some Awk implementations, such as HP-UX 11.0's native one,
19060 mishandle anchors:
19061
19062 @example
19063 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
19064 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
19065 bar
19066 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
19067 xfoo
19068 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
19069 bar
19070 @end example
19071
19072 @noindent
19073 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
19074 or use a simple test to reject such implementations.
19075
19076 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
19077 after @code{%u}:
19078
19079 @example
19080 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
19081 0 0
19082 @end example
19083
19084 AIX version 5.2 has an arbitrary limit of 399 on the
19085 length of regular expressions and literal strings in an Awk program.
19086
19087 Traditional Awk implementations derived from Unix version 7, such as
19088 Solaris @command{/bin/awk}, have many limitations and do not
19089 conform to POSIX@. Nowadays @code{AC_PROG_AWK} (@pxref{Particular
19090 Programs}) finds you an Awk that doesn't have these problems, but if
19091 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
19092 address them. For more detailed descriptions, see @ref{Language
19093 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
19094
19095 Traditional Awk does not support multidimensional arrays or user-defined
19096 functions.
19097
19098 Traditional Awk does not support the @option{-v} option. You can use
19099 assignments after the program instead, e.g., @code{$AWK '@{print v
19100 $1@}' v=x}; however, don't forget that such assignments are not
19101 evaluated until they are encountered (e.g., after any @code{BEGIN}
19102 action).
19103
19104 Traditional Awk does not support the keywords @code{delete} or @code{do}.
19105
19106 Traditional Awk does not support the expressions
19107 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
19108 or @code{@var{a}^=@var{b}}.
19109
19110 Traditional Awk does not support the predefined @code{CONVFMT} or
19111 @code{ENVIRON} variables.
19112
19113 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
19114 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
19115 @code{sqrt}, and @code{substr}.
19116
19117 Traditional Awk @code{getline} is not at all compatible with POSIX;
19118 avoid it.
19119
19120 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
19121 @code{in} keyword. For example, it lacks @code{if (i in a) @dots{}}.
19122
19123 In code portable to both traditional and modern Awk, @code{FS} must be a
19124 string containing just one ordinary character, and similarly for the
19125 field-separator argument to @code{split}.
19126
19127 Traditional Awk has a limit of 99 fields in a record
19128 and splits the input even if you don't refer to any field in the script.
19129 To circumvent this problem, set @samp{FS}
19130 to an unusual character and use @code{split}.
19131
19132 Traditional Awk has a limit of at most 99 bytes in a number formatted by
19133 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
19134 dumps core.
19135
19136 The original version of Awk had a limit of at most 99 bytes per
19137 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
19138 per run of non-special characters in a @code{printf} format, but these
19139 bugs have been fixed on all practical hosts that we know of.
19140
19141 HP-UX 11.00 Awk requires that input files have a line length
19142 of at most 3070 bytes.
19143
19144 @item @command{basename}
19145 @c ---------------------
19146 @prindex @command{basename}
19147 Long ago some hosts lacked a working @command{basename},
19148 and portable scripts needed to use @command{expr} instead.
19149 Nowadays it is safe to use @command{basename}. For example:
19150
19151 @example
19152 base=`basename -- "$file"`
19153 @end example
19154
19155 @c AS_BASENAME is to be replaced by a better API.
19156 @ignore
19157 Not all hosts have a working @command{basename}, and you should instead
19158 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
19159 @command{expr} if you need to strip a suffix. For example:
19160
19161 @example
19162 a=`basename "$aname"` # This is not portable.
19163 a=`AS_BASENAME(["$aname"])` # This is more portable.
19164
19165 # This is not portable.
19166 c=`basename "$cname" .c`
19167
19168 # This is more portable.
19169 c=`AS_BASENAME(["$cname"])`
19170 case $c in
19171 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
19172 esac
19173 @end example
19174 @end ignore
19175
19176
19177 @item @command{cat}
19178 @c ----------------
19179 @prindex @command{cat}
19180 Don't rely on any option.
19181
19182
19183 @item @command{cc}
19184 @c ---------------
19185 @prindex @command{cc}
19186 The command @samp{cc -c foo.c} traditionally produces an object file
19187 named @file{foo.o}. Most compilers allow @option{-c} to be combined
19188 with @option{-o} to specify a different object file name, but
19189 POSIX does not require this combination and a few compilers
19190 lack support for it. @xref{C Compiler}, for how GNU Make
19191 tests for this feature with @code{AC_PROG_CC_C_O}.
19192
19193 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
19194 (such as CDS on Reliant Unix) leave a @file{foo.o}.
19195
19196 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
19197 assemble. @samp{cc -c foo.S} appears to succeed, but in fact does
19198 nothing.
19199
19200 The default executable, produced by @samp{cc foo.c}, can be
19201
19202 @itemize
19203 @item @file{a.out} -- usual POSIX convention.
19204 @item @file{b.out} -- i960 compilers (including @command{gcc}).
19205 @item @file{a.exe} -- DJGPP port of @command{gcc}.
19206 @item @file{a_out.exe} -- GNV @command{cc} wrapper for DEC C on OpenVMS.
19207 @item @file{foo.exe} -- various MS-DOS compilers.
19208 @end itemize
19209
19210 The C compiler's traditional name is @command{cc}, but other names like
19211 @command{gcc} are common. POSIX 1003.1-2024 specifies the
19212 name @command{c17}, but older POSIX editions specified
19213 @command{c99} or @command{c89}, future POSIX standards will likely specify
19214 other commands, and anyway these standard names are rarely used in
19215 practice. Typically the C compiler is invoked from makefiles that use
19216 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
19217 compiler name.
19218
19219 @item @command{chgrp}
19220 @itemx @command{chown}
19221 @c -------------------
19222 @prindex @command{chgrp}
19223 @prindex @command{chown}
19224 It is not portable to change a file's group to a group that the owner
19225 does not belong to.
19226
19227 @item @command{chmod}
19228 @c ------------------
19229 @prindex @command{chmod}
19230 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
19231 instead, for two reasons. First, plain @option{-w} does not necessarily
19232 make the file unwritable, since it does not affect mode bits that
19233 correspond to bits in the file mode creation mask. Second,
19234 POSIX says that the @option{-w} might be interpreted as an
19235 implementation-specific option, not as a mode; POSIX suggests
19236 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
19237 @samp{--} does not work on some older hosts.
19238
19239
19240 @item @command{cmp}
19241 @c ----------------
19242 @prindex @command{cmp}
19243 @command{cmp} performs a raw data comparison of two files, while
19244 @command{diff} compares two text files. Therefore, if you might compare
19245 DOS files, even if only checking whether two files are different, use
19246 @command{diff} to avoid spurious differences due to differences of
19247 newline encoding.
19248
19249
19250 @item @command{cp}
19251 @c ---------------
19252 @prindex @command{cp}
19253 The @option{-i}, @option{-f}, @option{-p} and @option{-R} options are
19254 widely used. POSIX also specifies @option{-H}, @option{-L}, and
19255 @option{-P}. Avoid other options in portable scripts.
19256
19257 @cindex timestamp resolution
19258 Traditionally, file timestamps had 1-second resolution, and @samp{cp
19259 -p} copied the timestamps exactly. However, many modern file systems
19260 have timestamps with 1-nanosecond resolution. Unfortunately, some older
19261 @samp{cp -p} implementations truncate timestamps when copying files,
19262 which can cause the destination file to appear to be older than the
19263 source. The exact amount of truncation depends on the resolution of
19264 the system calls that @command{cp} uses. Traditionally this was
19265 @code{utime}, which has 1-second resolution. Since
19266 GNU Core Utilities 6.12 (2008), GNU @command{cp} can set timestamps to
19267 the full nanosecond resolution, using the system calls
19268 @code{futimens} and @code{utimensat} when they are available. As of
19269 2024, though, some platforms (such as AIX 7.3) still have @samp{cp -p}
19270 that supports only 1-second resolution, and some operating systems
19271 and file systems have similar limitations even when running
19272 GNU @command{cp}.
19273
19274 Although @samp{cp -p} always @emph{tries} to copy
19275 ownerships, whether it actually does so is a
19276 system dependent policy decision implemented by the kernel. If the
19277 kernel allows it then it happens. If the kernel does not allow it then
19278 it does not happen. It is not something @command{cp} itself has control
19279 over.
19280
19281 In Unix System V any user can chown files to any other user, and System
19282 V also has a non-sticky @file{/tmp}. That probably derives from the
19283 heritage of System V in a business environment without hostile users.
19284 BSD changed this
19285 to be a more secure model where only root can @command{chown} files and
19286 a sticky @file{/tmp} is used. That undoubtedly derives from the heritage
19287 of BSD in a campus environment.
19288
19289 GNU/Linux and Solaris by default follow BSD, but
19290 can be configured to allow a System V style @command{chown}. On the
19291 other hand, HP-UX follows System V, but can
19292 be configured to use the modern security model and disallow
19293 @command{chown}. Since it is an administrator-configurable parameter
19294 you can't use the name of the kernel as an indicator of the behavior.
19295
19296
19297
19298 @item @command{date}
19299 @c -----------------
19300 @prindex @command{date}
19301 When most versions of @command{date} do not recognize a @samp{%}
19302 conversion specification, they quietly pass it through,
19303 and exit with success:
19304
19305 @example
19306 $ @kbd{date --version | head -n 1}
19307 date (GNU coreutils) 9.5
19308 $ @kbd{date +'%H:%M %Q'}
19309 17:25 %Q
19310 @end example
19311
19312 @noindent
19313 However, this behavior is not required by POSIX.
19314
19315
19316 @item @command{dirname}
19317 @c --------------------
19318 @prindex @command{dirname}
19319 Long ago some hosts lacked a working @command{dirname} and portable
19320 scripts needed to use use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).
19321 Nowadays @command{dirname} suffices and the following are equivalent:
19322
19323 @example
19324 dir=`dirname -- "$file"`
19325 dir=`AS_DIRNAME(["$file"])`
19326 @end example
19327
19328
19329 @item @command{egrep}
19330 @c ------------------
19331 @prindex @command{egrep}
19332 Although POSIX stopped requiring @command{egrep} in 2001,
19333 a few traditional hosts (notably Solaris 11) do not support the POSIX
19334 replacement @code{grep -E}. Also, some traditional implementations do
19335 not work on long input lines. To work around these problems, invoke
19336 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
19337
19338 Portable extended regular expressions should use @samp{\} only to escape
19339 characters in the string @samp{$()*+.?[\^@{|}. For example, @samp{\@}}
19340 is not portable, even though it typically matches @samp{@}}.
19341
19342 The empty alternative is not portable. Use @samp{?} instead. For
19343 instance with Digital Unix v5.0:
19344
19345 @example
19346 > printf 'foo\n|foo\n' | $EGREP '^(|foo|bar)$'
19347 |foo
19348 > printf 'bar\nbar|\n' | $EGREP '^(foo|bar|)$'
19349 bar|
19350 > printf 'foo\nfoo|\n|bar\nbar\n' | $EGREP '^(foo||bar)$'
19351 foo
19352 |bar
19353 @end example
19354
19355 For more information about what can appear in portable extended regular
19356 expressions, @pxref{Problematic Expressions,,,grep, GNU Grep}.
19357
19358 @command{$EGREP} also suffers the limitations of @command{grep}
19359 (@pxref{grep, , Limitations of Usual Tools}).
19360
19361 @item @command{expr}
19362 @c -----------------
19363 @prindex @command{expr}
19364 Not all implementations obey the POSIX rule that @samp{--} separates
19365 options from arguments; likewise, not all implementations provide the
19366 extension to POSIX that the first argument can be treated as part of a
19367 valid expression rather than an invalid option if it begins with
19368 @samp{-}. When performing arithmetic, use @samp{expr 0 + $var} if
19369 @samp{$var} might be a negative number, to keep @command{expr} from
19370 interpreting it as an option.
19371
19372 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
19373 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
19374 misinterpreting @var{word}.
19375
19376 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
19377
19378 @item @command{expr} (@samp{|})
19379 @prindex @command{expr} (@samp{|})
19380 You can use @samp{|}. Although POSIX does require that @samp{expr
19381 ''} return the empty string, it does not specify the result when you
19382 @samp{|} together the empty string (or zero) with the empty string. For
19383 example:
19384
19385 @example
19386 expr '' \| ''
19387 @end example
19388
19389 POSIX 1003.2-1992 returns the empty string
19390 for this case, but traditional Unix returns @samp{0} (Solaris is
19391 one such example). In POSIX 1003.1-2001, the specification was
19392 changed to match traditional Unix's behavior (which is
19393 bizarre, but it's too late to fix this). Please note that the same
19394 problem does arise when the empty string results from a computation,
19395 as in:
19396
19397 @example
19398 expr bar : foo \| foo : bar
19399 @end example
19400
19401 @noindent
19402 Avoid this portability problem by avoiding the empty string.
19403
19404
19405 @item @command{expr} (@samp{:})
19406 @c ----------------------------
19407 @prindex @command{expr}
19408 Portable @command{expr} regular expressions should use @samp{\} to
19409 escape only characters in the string @samp{$()*.123456789[\^@{@}}.
19410 For example, alternation, @samp{\|}, is common but POSIX does not
19411 require its support, so it should be avoided in portable scripts.
19412 Similarly, @samp{\+} and @samp{\?} should be avoided.
19413
19414 Portable @command{expr} regular expressions should not begin with
19415 @samp{^}. Patterns are automatically anchored so leading @samp{^} is
19416 not needed anyway.
19417
19418 On the other hand, the behavior of the @samp{$} anchor is not portable
19419 on multi-line strings. POSIX is ambiguous whether the anchor applies to
19420 each line, as was done in older versions of the GNU Core Utilities, or
19421 whether it applies only to the end of the overall string, as in
19422 Coreutils 6.0 and most other implementations.
19423
19424 @example
19425 $ @kbd{baz='foo}
19426 > @kbd{bar'}
19427 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
19428
19429 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
19430 foo
19431 @end example
19432
19433 The POSIX standard is ambiguous as to whether
19434 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
19435 In practice, it outputs the empty string on most platforms, but portable
19436 scripts should not assume this. For instance, the QNX 4.25 native
19437 @command{expr} returns @samp{0}.
19438
19439 One might think that a way to get a uniform behavior would be to use
19440 the empty string as a default value:
19441
19442 @example
19443 expr a : '\(b\)' \| ''
19444 @end example
19445
19446 @noindent
19447 Unfortunately this behaves exactly as the original expression; see the
19448 @command{expr} (@samp{|}) entry for more information.
19449
19450 Some ancient @command{expr} implementations (e.g.,
19451 Solaris 10 @command{/usr/ucb/expr}) have a silly length limit that causes
19452 @command{expr} to fail if the matched substring is longer than 120
19453 bytes. In this case, you might want to fall back on @samp{printf|sed} if
19454 @command{expr} fails. Nowadays this is of practical importance only for
19455 the rare installer who mistakenly puts @file{/usr/ucb} before
19456 @file{/usr/bin} in @env{PATH} on Solaris 10.
19457
19458 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
19459 some cases. For example, the command
19460 @example
19461 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
19462 @end example
19463
19464 @noindent
19465 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
19466 This particular case can be worked around by substituting @samp{[^--]}
19467 for @samp{[^-]}.
19468
19469 Don't leave, there is some more!
19470
19471 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
19472 the empty string, has a funny behavior in its exit status: it's always 1
19473 when parentheses are used!
19474
19475 @example
19476 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
19477 0: 1
19478 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
19479 1: 0
19480
19481 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
19482 1: a
19483 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
19484 1: 0
19485 @end example
19486
19487 @noindent
19488 In practice this can be a big problem if you are ready to catch failures
19489 of @command{expr} programs with some other method (such as using
19490 @command{sed}), since you may get twice the result. For instance
19491
19492 @example
19493 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
19494 @end example
19495
19496 @noindent
19497 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25. A
19498 simple workaround consists of testing @command{expr} and using a variable
19499 set to @command{expr} or to @command{false} according to the result.
19500
19501 On HP-UX 11, @command{expr} supports only a single
19502 sub-expression.
19503
19504 @example
19505 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
19506 expr: More than one '\(' was used.
19507 @end example
19508
19509
19510 @item @command{fgrep}
19511 @c ------------------
19512 @prindex @command{fgrep}
19513 Although POSIX stopped requiring @command{fgrep} in 2001,
19514 a few traditional hosts (notably Solaris 11) do not support the POSIX
19515 replacement @code{grep -F}. Also, some traditional implementations do
19516 not work on long input lines. To work around these problems, invoke
19517 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
19518
19519
19520 @item @command{find}
19521 @c -----------------
19522 @prindex @command{find}
19523 Many operands of GNU @command{find} are not standardized by POSIX and
19524 are missing on many platforms. These nonportable operands include
19525 @option{-follow}, @option{-maxdepth}, @option{-mindepth},
19526 @option{-printf}, and @option{,}. See the
19527 @uref{https://@/pubs.opengroup.org/@/onlinepubs/@/9699919799/@/utilities/@/find.html,
19528 POSIX spec for @command{find}} for @command{find} operands that
19529 should be portable nowadays.
19530
19531 The replacement of @samp{@{@}} is guaranteed only if the argument is
19532 exactly @samp{@{@}}, not if @samp{@{@}} only a part of a larger argument.
19533 For instance, on AIX 7.3:
19534
19535 @example
19536 $ @kbd{touch foo}
19537 $ @kbd{find . -name foo -exec echo '@{@}-@{@}' \;}
19538 @{@}-@{@}
19539 @end example
19540
19541 @noindent
19542 while GNU @command{find} reports @samp{./foo-./foo}.
19543 POSIX allows either behavior.
19544
19545 AIX 7.3 @samp{find ... -exec @var{command} +} incorrectly fails if
19546 @var{command} is not executed. For example, @samp{find . -name '*.tmp'
19547 -exec rm @{@} +} incorrectly outputs a diagnostic and fails if no file
19548 names end in @samp{.tmp}. To work around this problem you can use a
19549 circumlocution like @samp{find . -name '*.tmp' -exec rm -f @{@} + -o
19550 -exec true ';'}.
19551
19552 @anchor{grep}
19553 @item @command{grep}
19554 @c -----------------
19555 @prindex @command{grep}
19556 Portable scripts can rely on the @command{grep} options @option{-c},
19557 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
19558 options. For example, don't use @option{-w}, as POSIX does not require it.
19559 Also, portable scripts should not combine @option{-c} with @option{-l},
19560 as POSIX does not allow this.
19561
19562 Some of the options required by POSIX are not portable in practice.
19563 Don't use @samp{grep -q} to suppress output, because traditional @command{grep}
19564 implementations (e.g., Solaris 10) do not support @option{-q}.
19565 Don't use @samp{grep -s} to suppress output either, because POSIX
19566 says @option{-s} does not suppress output, only some error messages;
19567 also, the @option{-s} option of traditional @command{grep} behaved
19568 like @option{-q} does in most modern implementations. Instead,
19569 redirect the standard output and standard error (in case the file
19570 doesn't exist) of @code{grep} to @file{/dev/null}. Check the exit
19571 status of @code{grep} to determine whether it found a match.
19572
19573 The QNX4 implementation fails to count lines with @code{grep -c '$'},
19574 but works with @code{grep -c '^'}. Other alternatives for counting
19575 lines are to use @code{sed -n '$='} or @code{wc -l}.
19576
19577 Some traditional @command{grep} implementations do not work on long
19578 input lines. On AIX the default @code{grep} silently truncates long
19579 lines on the input before matching.
19580
19581 Also, Solaris 11 @command{grep} does not support @option{-e}.
19582 To work around this, invoke @code{AC_PROG_GREP} and then use @code{$GREP}.
19583
19584 Another possible workaround for the multiple @option{-e} problem is to
19585 separate the patterns by newlines, for example:
19586
19587 @example
19588 grep 'foo
19589 bar' in.txt
19590 @end example
19591
19592 @noindent
19593 except that this fails with traditional @command{grep}
19594 implementations and with OpenBSD 3.8 @command{grep}.
19595
19596 Traditional @command{grep} implementations (e.g., Solaris 11) do not
19597 support the @option{-E} or @option{-F} options. To work around these
19598 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
19599 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}. Even if you are
19600 willing to require support for POSIX @command{grep}, your script should
19601 not use both @option{-E} and @option{-F}, since POSIX does not allow
19602 this combination.
19603
19604 Portable @command{grep} regular expressions should use @samp{\} only to
19605 escape characters in the string @samp{$()*.123456789[\^@{@}}. For example,
19606 alternation, @samp{\|}, is common but POSIX does not require its
19607 support in basic regular expressions, so it should be avoided in
19608 portable scripts. Solaris and HP-UX @command{grep} do not support it.
19609 Similarly, the following escape sequences should also be avoided:
19610 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
19611 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
19612 For more information about what can appear in portable regular expressions,
19613 @pxref{Problematic Expressions,,, grep, GNU Grep}.
19614
19615 POSIX does not specify the behavior of @command{grep} on binary files.
19616 An example where this matters is using BSD @command{grep} to
19617 search text that includes embedded ANSI escape sequences for
19618 colored output to terminals (@samp{\033[m} is the sequence to restore
19619 normal output); the behavior depends on whether input is seekable:
19620
19621 @example
19622 $ @kbd{printf 'esc\033[mape\n' > sample}
19623 $ @kbd{grep . sample}
19624 Binary file sample matches
19625 $ @kbd{cat sample | grep .}
19626 escape
19627 @end example
19628
19629
19630 @item @command{join}
19631 @c -----------------
19632 @prindex @command{join}
19633 On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
19634 @command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
19635 the workaround is to use @command{join -a1 file1 file2} instead.
19636
19637 On some circa-2020 BSD-based systems @command{join} mishandles inputs
19638 with missing fields. For example, an empty line is not treated as
19639 containing an empty join field. As a workaround, input lines should
19640 always have a join field.
19641
19642 On platforms with the BusyBox tools, the @command{join} command is
19643 entirely missing. As a workaround, you can simulate special cases of the
19644 @command{join} command using an @command{awk} script. For an example,
19645 see @url{https://lists.gnu.org/r/bug-gnulib/2021-04/msg00054.html}.
19646
19647
19648 @item @command{ln}
19649 @c ---------------
19650 @prindex @command{ln}
19651 The @option{-f} option is portable nowadays.
19652
19653 @cindex Symbolic links
19654 Symbolic links are not available on some systems; use @samp{$(LN_S)} as
19655 a portable substitute.
19656
19657 For versions of the DJGPP before 2.04,
19658 @command{ln} emulates symbolic links
19659 to executables by generating a stub that in turn calls the real
19660 program. This feature also works with nonexistent files like in the
19661 POSIX spec. So @samp{ln -s file link} generates @file{link.exe},
19662 which attempts to call @file{file.exe} if run. But this feature only
19663 works for executables, so @samp{cp -p} is used instead for these
19664 systems. DJGPP versions 2.04 and later have full support
19665 for symbolic links.
19666
19667
19668 @item @command{ls}
19669 @c ---------------
19670 @prindex @command{ls}
19671 @cindex Listing directories
19672 The portable options are @option{-acdilrtu}. Current practice is for
19673 @option{-l} to output both owner and group, even though ancient versions
19674 of @command{ls} omitted the group.
19675
19676 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
19677 to standard output if @file{foo} did not exist. Hence a shell command
19678 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
19679 was equivalent to @samp{sources='*.c not found'} in the absence of
19680 @samp{.c} files. This is no longer a practical problem, since current
19681 @command{ls} implementations send diagnostics to standard error.
19682
19683 The behavior of @command{ls} on a directory that is being concurrently
19684 modified is not always predictable, because of a data race where cached
19685 information returned by @code{readdir} does not match the current
19686 directory state. In fact, Mac OS X 10.5 had an intermittent bug where
19687 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
19688 once if other files were added or removed from the directory immediately
19689 prior to the @command{ls} call. Since @command{ls} already sorts its
19690 output, the duplicate entries can be avoided by piping the results
19691 through @code{uniq}.
19692
19693 @anchor{mkdir}
19694 @item @command{mkdir}
19695 @c ------------------
19696 @prindex @command{mkdir}
19697 @cindex Making directories
19698 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
19699 go-w -p @var{dir}}, often leads to trouble. FreeBSD
19700 @command{mkdir} incorrectly attempts to change the permissions of
19701 @var{dir} even if it already exists. HP-UX 11.23
19702 @command{mkdir} often assigns the wrong permissions to
19703 any newly-created parents of @var{dir}.
19704
19705 POSIX does not clearly specify whether @samp{mkdir -p foo}
19706 should succeed when @file{foo} is a symbolic link to an already-existing
19707 directory. The GNU @command{mkdir}
19708 succeeds, but Solaris 10 @command{mkdir} fails.
19709
19710 Traditional @code{mkdir -p} implementations suffer from race conditions.
19711 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
19712 at the same time, both processes might detect that @file{a} is missing,
19713 one might create @file{a}, then the other might try to create @file{a}
19714 and fail with a @code{File exists} diagnostic. Solaris 10 @command{mkdir}
19715 is vulnerable, and other traditional Unix systems are
19716 probably vulnerable too. This possible race is harmful in parallel
19717 builds when several Make rules call @code{mkdir -p} to
19718 construct directories. You may use
19719 @code{install-sh -d} as a safe replacement, for example by setting
19720 @samp{MKDIR_P='/path/to/install-sh -d'} in the environment of
19721 @command{configure}, assuming the package distributes @file{install-sh}.
19722
19723 @item @command{mkfifo}
19724 @itemx @command{mknod}
19725 @c -------------------
19726 @prindex @command{mkfifo}
19727 @prindex @command{mknod}
19728 The GNU Coding Standards state that @command{mknod} is safe to use on
19729 platforms where it has been tested to exist; but it is generally portable
19730 only for creating named FIFOs, since device numbers are
19731 platform-specific. Autotest uses @command{mkfifo} to implement parallel
19732 testsuites. POSIX states that behavior is unspecified when opening a
19733 named FIFO for both reading and writing; on at least Cygwin, this
19734 results in failure on any attempt to read or write to that file
19735 descriptor.
19736
19737 @item @command{mktemp}
19738 @c -------------------
19739 @prindex @command{mktemp}
19740 @cindex Creating temporary files
19741 Shell scripts can use temporary files safely with @command{mktemp}, but
19742 it does not exist on all systems. A portable way to create a safe
19743 temporary file name is to create a temporary directory with mode 700 and
19744 use a file inside this directory. Both methods prevent attackers from
19745 gaining control, though @command{mktemp} is far less likely to fail
19746 gratuitously under attack.
19747
19748 Here is sample code to create a new temporary directory @samp{$dir} safely:
19749
19750 @example
19751 # Create a temporary directory $dir in $TMPDIR (default /tmp).
19752 # Use mktemp if possible; otherwise fall back on mkdir,
19753 # with $RANDOM to make collisions less likely.
19754 : "$@{TMPDIR:=/tmp@}"
19755 @{
19756 dir=`
19757 (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
19758 ` &&
19759 test -d "$dir"
19760 @} || @{
19761 dir=$TMPDIR/foo$$-$RANDOM
19762 @c $$ restore font-lock
19763 (umask 077 && mkdir "$dir")
19764 @} || exit $?
19765 @end example
19766
19767
19768 @item @command{mv}
19769 @c ---------------
19770 @prindex @command{mv}
19771 @cindex Moving open files
19772 The only portable options are @option{-f} and @option{-i}.
19773
19774 Moving individual files between file systems is portable (it was in Unix
19775 version 6),
19776 but it is not always atomic: when doing @samp{mv new existing}, there's
19777 a critical section where neither the old nor the new version of
19778 @file{existing} actually exists.
19779
19780 On some systems moving files from @file{/tmp} can sometimes cause
19781 undesirable (but perfectly valid) warnings, even if you created these
19782 files. This is because @file{/tmp} belongs to a group that ordinary
19783 users are not members of, and files created in @file{/tmp} inherit
19784 the group of @file{/tmp}. When the file is copied, @command{mv} issues
19785 a diagnostic without failing:
19786
19787 @smallexample
19788 $ @kbd{touch /tmp/foo}
19789 $ @kbd{mv /tmp/foo .}
19790 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
19791 $ @kbd{echo $?}
19792 0
19793 $ @kbd{ls foo}
19794 foo
19795 @end smallexample
19796
19797 @noindent
19798 This annoying behavior conforms to POSIX, unfortunately.
19799
19800 Moving directories across mount points is not portable, use @command{cp}
19801 and @command{rm}.
19802
19803 DOS variants cannot rename or remove open files, and do not
19804 support commands like @samp{mv foo bar >foo}, even though this is
19805 perfectly portable among POSIX hosts.
19806
19807
19808 @item @command{od}
19809 @c ---------------
19810 @prindex @command{od}
19811
19812 In Mac OS X versions prior to 10.4.3, @command{od} does not support the
19813 standard POSIX options @option{-A}, @option{-j}, @option{-N}, or
19814 @option{-t}, or the XSI option, @option{-s}. The only
19815 supported POSIX option is @option{-v}, and the only supported
19816 XSI options are those in @option{-bcdox}. The BSD
19817 @command{hexdump} program can be used instead.
19818
19819 In some versions of some operating systems derived from Solaris 11,
19820 @command{od} prints decimal byte values padded with zeros rather than
19821 with spaces:
19822
19823 @smallexample
19824 $ @kbd{printf '#!' | od -A n -t d1 -N 2}
19825 035 033
19826 @end smallexample
19827
19828 @noindent
19829 instead of
19830
19831 @smallexample
19832 $ @kbd{printf '#!' | od -A n -t d1 -N 2}
19833 35 33
19834 @end smallexample
19835
19836 We have observed this on both OpenIndiana and OmniOS;
19837 Illumos may also be affected.
19838 As a workaround, you can use octal output (option @code{-t o1}).
19839
19840
19841 @item @command{rm}
19842 @c ---------------
19843 @prindex @command{rm}
19844 The @option{-f} and @option{-r} options are portable.
19845
19846 It is not portable to invoke @command{rm} without options or operands.
19847 On the other hand, POSIX now requires @command{rm -f} to silently
19848 succeed when there are no operands (useful for constructs like
19849 @command{rm -rf $filelist} without first checking if @samp{$filelist}
19850 was empty). But this was not always portable; at least NetBSD
19851 @command{rm} built before 2008 would fail with a diagnostic.
19852
19853 A file might not be removed even if its parent directory is writable
19854 and searchable. Many POSIX hosts cannot remove a mount point, a named
19855 stream, a working directory, or a last link to a file that is being
19856 executed.
19857
19858 DOS variants cannot rename or remove open files, and do not
19859 support commands like @samp{rm foo >foo}, even though this is
19860 perfectly portable among POSIX hosts.
19861
19862 @item @command{rmdir}
19863 @c ------------------
19864 @prindex @command{rmdir}
19865 Just as with @command{rm}, some platforms refuse to remove a working
19866 directory.
19867
19868 @anchor{sed}
19869 @item @command{sed}
19870 @c ----------------
19871 @prindex @command{sed}
19872 The portable options are @option{-e}, @option{-f}, and @option{-n}.
19873 POSIX standardized @option{-E} in 2024 but some older implementations lack it.
19874 Although GNU @command{sed} supports other options like @option{-i},
19875 these can be missing or have different meanings elsewhere.
19876
19877 Patterns should not include the separator (unless escaped), even as part
19878 of a character class.
19879 Even when escaped, patterns should not include separators that are also
19880 used as @command{sed} metacharacters. For example, GNU sed 4.0.9 rejects
19881 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19882 before evaluating the basic regular expression.
19883
19884 Avoid empty patterns, such as the parenthesized empty pattern in @samp{\(\)}
19885 or the empty pattern followed by an interval expression in @samp{\@{2\@}}.
19886 POSIX does not require support for empty patterns.
19887
19888 Comments in Sed scripts should not contain @samp{n} immediately after
19889 the leading @samp{#}. Although POSIX.1-2024 says this is equivalent to the
19890 @option{-n} option, earlier POSIX editions said that
19891 the equivalence occurs only if the comment is the first line of the script,
19892 and many @command{sed} implementations are confused about this.
19893 It is more portable to use @option{-n}.
19894
19895 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
19896 48 labels, which cannot be circumvented by using more than one script
19897 file. It can execute up to 19 reads with the @samp{r} command per cycle.
19898 Solaris 10 @command{/usr/ucb/sed} rejects usages that exceed a limit of
19899 about 6000 bytes for the internal representation of commands.
19900
19901 Some @command{sed} implementations have a buffer limited to 4000 bytes,
19902 and this limits the size of input lines, output lines, and internal
19903 buffers that can be processed portably. Likewise,
19904 not all @command{sed} implementations can handle embedded @code{NUL} or
19905 a missing trailing newline.
19906
19907 Ranges within a bracket expression of a regular expression
19908 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19909 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19910 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19911 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19912 than to rely on @samp{[A-Z]}.
19913
19914 Additionally, POSIX states that regular expressions are only
19915 well-defined on characters. Unfortunately, there exist platforms such
19916 as Mac OS X 10.5 where not all 8-bit byte values are valid characters,
19917 even though that platform has a single-byte @samp{C} locale. Although
19918 this practice was disallowed by recent releases of POSIX, it means that
19919 in the @samp{C} locale not all bytes will be matched by the regular
19920 expression @samp{.}:
19921
19922 @example
19923 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
19924 0
19925 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
19926 1
19927 @end example
19928
19929 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19930
19931 Some @command{sed} implementations, e.g., Solaris 11.4, restrict the special
19932 role of the asterisk @samp{*} to one-character regular expressions and
19933 back-references, and the special role of interval expressions
19934 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19935 to one-character regular expressions. This may lead to unexpected behavior:
19936
19937 @example
19938 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19939 x2x4
19940 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19941 x
19942 @end example
19943
19944 In the normal case when @option{-E} is not used,
19945 portable @command{sed} regular expressions should use @samp{\} only to escape
19946 characters in the string @samp{$*.123456789[\^n}. For example,
19947 POSIX.1-2024 says it is implementation-defined
19948 whether @samp{\|} means alternation or simply matches @samp{|},
19949 so it should be avoided in portable scripts. Solaris
19950 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19951 deletes only lines that contain the literal string @samp{a|b}.
19952 Similarly, @samp{\+} and @samp{\?} should be avoided.
19953
19954 Portable @command{sed} replacement strings should use @samp{\} only to
19955 escape the delimiter character, newline, and characters in the string
19956 @samp{&123456789\}. For example, although in GNU @command{sed}
19957 the command @samp{s/AB/\n/} replaces the first @samp{AB} with a newline,
19958 in OpenBSD and Solaris @command{sed} it acts like @samp{s/AB/n/}.
19959 To be portable, escape a newline instead:
19960
19961 @example
19962 # This is portable; "sed 's/AB/\n/'" is not.
19963 sed 's/AB/\
19964 /'
19965 @end example
19966
19967 The @option{-e} option is mostly portable.
19968 However, its argument cannot be empty, as this fails on AIX 7.3.
19969 Some people prefer to use @samp{-e}:
19970
19971 @example
19972 sed -e '@var{command-1}' \
19973 -e '@var{command-2}'
19974 @end example
19975
19976 @noindent
19977 as opposed to the equivalent:
19978
19979 @example
19980 sed '
19981 @var{command-1}
19982 @var{command-2}
19983 '
19984 @end example
19985
19986 @noindent
19987 The following usage is sometimes equivalent:
19988
19989 @example
19990 sed '@var{command-1};@var{command-2}'
19991 @end example
19992
19993 but POSIX says that this use of a semicolon has undefined effect if
19994 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
19995 @samp{i}, @samp{r}, @samp{t}, @samp{w} or @samp{:},
19996 or if @var{command-1} is an @samp{s} with the @samp{w} option, so you
19997 should use semicolon only with simple scripts that do not use these
19998 constructs.
19999
20000 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
20001 NetBSD 1.4.2's, incorrectly try to interpret the second
20002 @samp{;} as a command:
20003
20004 @example
20005 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
20006 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
20007 @end example
20008
20009 POSIX requires each @option{-e} and @option{-f} option to specify a
20010 syntactically complete script. Although GNU @command{sed} also allows
20011 @option{-e} and @option{-f} options to specify script fragments
20012 that it assembles into a full script, this is not portable. For
20013 example, the @command{sed} programs on Solaris 11, HP-UX 11, and AIX
20014 do not allow script fragments:
20015
20016 @example
20017 $ @kbd{sed -e 'i\' -e ouch}
20018 Unrecognized command: ouch
20019 @end example
20020
20021 @noindent
20022 In practice, however, this technique of joining fragments
20023 through @option{-e} works for multiple @command{sed} functions within
20024 @samp{@{} and @samp{@}}, even if that is not specified by POSIX:
20025
20026 @example
20027 @c The quote around the closing brace silences interactive zsh.
20028 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
20029 b
20030 @end example
20031
20032 Commands should not be followed by white space.
20033 Although trailing white space often works,
20034 it can be dicey in some situations and
20035 it is simpler to avoid it entirely.
20036
20037 Commands inside @{ @} brackets are further restricted. POSIX.1-2004 says that
20038 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
20039 each command must be followed immediately by a newline, without any
20040 intervening blanks or semicolons. The closing bracket must be alone on
20041 a line, other than white space preceding or following it. Although these
20042 restrictions were lifted in POSIX.1-2008, it is more portable to
20043 respect them.
20044
20045 Contrary to yet another urban legend, you may portably use @samp{&} in
20046 the replacement part of the @code{s} command to mean ``what was
20047 matched''. All descendants of Unix version 7 @command{sed}
20048 (at least; we
20049 don't have first hand experience with older @command{sed} implementations) have
20050 supported it.
20051
20052 POSIX requires that you must not have any white space between
20053 @samp{!} and the following command. It is OK to have blanks between
20054 the address and the @samp{!}. For instance, on Solaris:
20055
20056 @example
20057 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
20058 @error{}Unrecognized command: /bar/ ! p
20059 $ @kbd{echo "foo" | sed -n '/bar/! p'}
20060 @error{}Unrecognized command: /bar/! p
20061 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
20062 foo
20063 @end example
20064
20065 POSIX also says that you should not combine @samp{!} and @samp{;}. If
20066 you use @samp{!}, it is best to put it on a command that is delimited by
20067 newlines rather than @samp{;}.
20068
20069 POSIX requires that the @samp{b}, @samp{t}, @samp{r}, and
20070 @samp{w} commands be followed by exactly one space before their argument.
20071 On the other hand, no white space is allowed between @samp{:} and the
20072 subsequent label. Branch labels should contain at most 8 bytes,
20073 each of which should be an ASCII graphical character.
20074 Do not put trailing white space after a branch label.
20075
20076 If a sed script is specified on the command line and ends in an
20077 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
20078 should be followed by a newline. Otherwise some @command{sed}
20079 implementations (e.g., OpenBSD 3.9) do not append a newline to the
20080 inserted text.
20081
20082 Many @command{sed} implementations (e.g., Mac OS X 10.4,
20083 OpenBSD 3.9, Solaris 11
20084 @command{/usr/ucb/sed}) strip leading white space from the text of
20085 @samp{a}, @samp{c}, and @samp{i} commands. Prepend a backslash to
20086 work around this incompatibility with POSIX:
20087
20088 @example
20089 $ @kbd{echo flushleft | sed 'a\}
20090 > @kbd{ indented}
20091 > @kbd{'}
20092 flushleft
20093 indented
20094 $ @kbd{echo foo | sed 'a\}
20095 > @kbd{\ indented}
20096 > @kbd{'}
20097 flushleft
20098 indented
20099 @end example
20100
20101 POSIX requires that with a missing regular expression, the last
20102 regular expression from either an address specification or substitution
20103 command is used. However, busybox 1.6.1 complains when using a
20104 substitution command with a replacement containing a back-reference to
20105 a missing regular expression; the workaround is repeating the regular
20106 expression.
20107
20108 @example
20109 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
20110 sed: No previous regexp.
20111 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
20112 b
20113 @end example
20114
20115 Portable scripts should be aware of the inconsistencies and options for
20116 handling word boundaries, as these are not specified by POSIX.
20117
20118 @example
20119 \< \b [[:<:]]
20120 Solaris 11 yes no no
20121 Solaris XPG4 yes no error
20122 NetBSD 5.1 no no yes
20123 FreeBSD 9.1 no no yes
20124 GNU yes yes error
20125 busybox yes yes error
20126 @end example
20127
20128 @item @command{sed} (@samp{t})
20129 @c ---------------------------
20130 @prindex @command{sed} (@samp{t})
20131 There are two things one should remember about @samp{t} in @command{sed}.
20132 First, @samp{t} jumps if @emph{some} substitution
20133 succeeded, not only the immediately preceding substitution. Therefore,
20134 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
20135 line, to reset the @samp{t} flag where needed.
20136
20137 Second, do not rely on @command{sed} to clear the flag at each new cycle.
20138
20139 For example, the following script replaces all instances of ``keep me''
20140 with ``kept'', and replaces the contents of all lines that did not
20141 contain ``keep me'' with ``deleted''.
20142
20143 @example
20144 t clear
20145 :clear
20146 s/keep me/kept/g
20147 t end
20148 s/.*/deleted/g
20149 :end
20150 @end example
20151
20152 @item @command{sed} (@samp{w})
20153 @c ---------------------------
20154 @prindex @command{sed} (@samp{w})
20155
20156 When a script contains multiple commands to write lines to the same
20157 output file, BusyBox @command{sed} mistakenly opens a separate output
20158 stream for each command. This can cause one of the commands to ``win''
20159 and the others to ``lose'', in the sense that their output is discarded.
20160 For example:
20161
20162 @example
20163 sed -n -e '
20164 /a/w xxx
20165 /b/w xxx
20166 ' <<EOF
20167 a
20168 b
20169 EOF
20170 @end example
20171
20172 This might output only @samp{a} to @file{xxx}; the @samp{b} is lost.
20173 To avoid the problem, a portable script should contain at most one
20174 @samp{w} or @samp{s/.../.../w} command per output file.
20175
20176 @item @command{sleep}
20177 @c ------------------
20178 @prindex @command{sleep}
20179 Using @command{sleep} is generally portable. However, remember that
20180 adding a @command{sleep} to work around timestamp issues, with a minimum
20181 granularity of one second, doesn't scale well for parallel builds on
20182 modern machines with sub-second process completion.
20183
20184 @item @command{sort}
20185 @c -----------------
20186 @prindex @command{sort}
20187 Remember that sort order is influenced by the current locale. Inside
20188 @file{configure}, the C locale is in effect, but in Makefile snippets,
20189 you may need to specify @code{LC_ALL=C sort}.
20190
20191 @item @command{tar}
20192 @c ----------------
20193 @prindex @command{tar}
20194 There are multiple file formats for @command{tar}; if you use Automake,
20195 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
20196 level of portability to use.
20197
20198 @anchor{touch}
20199 @item @command{touch}
20200 @c ------------------
20201 @prindex @command{touch}
20202 @cindex timestamp resolution
20203 If you specify the desired timestamp (e.g., with the @option{-r}
20204 option), older @command{touch} implementations use the @code{utime} or
20205 @code{utimes} system call, which can result in the same kind of
20206 timestamp truncation problems that @samp{cp -p} has.
20207
20208 @item @command{tr}
20209 @c ---------------
20210 @prindex @command{tr}
20211
20212 Many @command{tr} implementations do not support multi-byte locales
20213 well. For example, Solaris 10 @command{tr} rejects character classes in
20214 multi-byte locales. Also, ranges have well-defined behavior only in the
20215 @samp{C} (or @samp{POSIX}) locale, so if you cannot guarantee the
20216 setting of @env{LC_ALL} it is better to spell out a range
20217 @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]} than to rely on @samp{[A-Z]}.
20218
20219 @cindex carriage return, deleting
20220 @cindex newline, deleting
20221 @cindex deleting carriage return
20222 Not all versions of @command{tr} handle all backslash character escapes.
20223 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
20224 Solaris contains more modern @command{tr} in other locations.
20225 Using octal escapes is more portable for carriage returns, since
20226 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
20227 literal carriage returns in scripts causes a number of other problems.
20228 But for other characters, like newline, using octal escapes ties the
20229 operation to ASCII, so it is better to use literal characters.
20230
20231 @example
20232 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
20233 moo
20234 light
20235 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
20236 moonlight
20237 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
20238 moonlight
20239 $ @kbd{nl='}
20240 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
20241 moonlight
20242 @end example
20243
20244 Not all versions of @command{tr} recognize direct ranges of characters: at
20245 least Solaris @command{/usr/bin/tr} still fails to do so. But you can
20246 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in POSIX
20247 transliterate to themselves).
20248
20249 @example
20250 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
20251 HAZy FAntAZy
20252 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
20253 HAZY FANTAZY
20254 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
20255 HAZY FANTAZY
20256 @end example
20257
20258 When providing two arguments, be sure the second string is at least as
20259 long as the first.
20260
20261 @example
20262 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
20263 adc
20264 $ @kbd{echo abc | coreutils/tr bc d}
20265 add
20266 @end example
20267
20268 On platforms with the BusyBox tools, @command{tr} does not support the
20269 @code{[@var{x}*@var{n}]} option syntax.
20270
20271 @example
20272 $ @kbd{echo abc | tr 'abcd' '[A*4]'}
20273 [A*
20274 $ @kbd{echo abc | coreutils/tr 'abcd' '[A*4]'}
20275 AAA
20276 $ @kbd{echo xyz | tr 'a-z' '[A*]'}
20277 ]]]
20278 $ @kbd{echo xyz | coreutils/tr 'a-z' '[A*]'}
20279 AAA
20280 @end example
20281
20282 POSIX requires @command{tr} to operate on binary files. But at least
20283 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
20284 @code{NUL} in the input prior to doing any translation. When using
20285 @command{tr} to process a binary file that may contain @code{NUL} bytes,
20286 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
20287 @command{/usr/xpg6/bin/tr} if that is available.
20288
20289 @example
20290 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
20291 61 62
20292 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
20293 61 62
20294 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
20295 61 00 62
20296 @end example
20297
20298 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
20299 octal escape for @code{NUL}.
20300
20301 @example
20302 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
20303 61 62 63
20304 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
20305 61 00 64
20306 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
20307 61 00 64
20308 @end example
20309
20310 @end table
20311
20312
20313 @node Portable Make
20314 @chapter Portable Make Programming
20315 @prindex @command{make}
20316 @cindex Limitations of @command{make}
20317
20318 Writing portable makefiles is an art. Since a makefile's commands are
20319 executed by the shell, you must consider the shell portability issues
20320 already mentioned. However, other issues are specific to @command{make}
20321 itself.
20322
20323 @menu
20324 * $< in Ordinary Make Rules:: $< in ordinary rules
20325 * Failure in Make Rules:: Failing portably in rules
20326 * Command Line Prefixes:: What's at the start of makefile command lines
20327 * Special Chars in Names:: Special characters in macro names
20328 * Backslash-Newline-Empty:: Empty lines after backslash-newline
20329 * Backslash-Newline Comments:: Spanning comments across line boundaries
20330 * Macros and Submakes:: @code{make macro=value} and submakes
20331 * The Make Macro MAKEFLAGS:: @code{$(MAKEFLAGS)} portability issues
20332 * The Make Macro SHELL:: @code{$(SHELL)} portability issues
20333 * Parallel Make:: Parallel @command{make} quirks
20334 * Comments in Make Rules:: Other problems with Make comments
20335 * Newlines in Make Rules:: Using literal newlines in rules
20336 * Comments in Make Macros:: Other problems with Make comments in macros
20337 * Trailing whitespace in Make Macros:: Macro substitution problems
20338 * Command-line Macros and whitespace:: Whitespace trimming of values
20339 * obj/ and Make:: Don't name a subdirectory @file{obj}
20340 * make -k Status:: Exit status of @samp{make -k}
20341 * VPATH and Make:: @code{VPATH} woes
20342 * Single Suffix Rules:: Single suffix rules and separated dependencies
20343 * Timestamps and Make:: Sub-second timestamp resolution
20344 @end menu
20345
20346 @node $< in Ordinary Make Rules
20347 @section @code{$<} in Ordinary Make Rules
20348
20349 POSIX says that the @samp{$<} construct in makefiles can be
20350 used only in inference rules and in the @samp{.DEFAULT} rule; its
20351 meaning in ordinary rules is unspecified. Solaris @command{make}
20352 for instance replaces it with the empty string. OpenBSD (3.0 and
20353 later) @command{make} diagnoses these uses and errors out.
20354
20355 @node Failure in Make Rules
20356 @section Failure in Make Rules
20357
20358 Unless errors are being ignored
20359 (e.g., because a makefile command line is preceded by a @samp{-} prefix),
20360 POSIX 2008 requires that @command{make} must invoke each command with
20361 the equivalent of a @samp{sh -e -c} subshell, which causes the
20362 subshell to exit immediately if a subsidiary simple-command fails,
20363 with some complicated exceptions.
20364 Historically not all @command{make} implementations
20365 followed this rule. For
20366 example, the command @samp{touch T; rm -f U} may attempt to
20367 remove @file{U} even if the @command{touch} fails, although this is not
20368 permitted with POSIX make. One way to work around failures in simple
20369 commands is to reword them so that they always succeed, e.g., @samp{touch
20370 T || :; rm -f U}.
20371 However, even this approach can run into common bugs in BSD
20372 implementations of the @option{-e} option of @command{sh} and
20373 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
20374 are worried
20375 about porting to buggy BSD shells it may be simpler to migrate
20376 complicated @command{make} actions into separate scripts.
20377
20378 @node Command Line Prefixes
20379 @section Makefile Command Line Prefixes
20380
20381 Makefile command lines can be preceded by zero or more of
20382 the command line prefixes @samp{-}, @samp{@@}, and @samp{+},
20383 which modify how @command{make} processes the command.
20384 Although POSIX says these are the only command line prefixes,
20385 some @command{make} implementations, such as Solaris @command{make},
20386 support the additional prefixes @samp{!} and @samp{?}.
20387 Portable makefiles should therefore avoid using these two characters at
20388 the start of a makefile command line.
20389 For example:
20390
20391 @example
20392 mishandled-by-Solaris-make:; ! grep FIXME foo.c
20393 portable-to-Solaris-make:; :;! grep FIXME foo.c
20394 @end example
20395
20396 @node Special Chars in Names
20397 @section Special Characters in Make Macro Names
20398
20399 POSIX limits macro names to nonempty strings containing only
20400 ASCII letters and digits, @samp{.}, and @samp{_}. Many
20401 @command{make} implementations allow a wider variety of characters, but
20402 portable makefiles should avoid them. It is portable to start a name
20403 with a special character, e.g., @samp{$(.FOO)}.
20404
20405 Some ancient @command{make} implementations don't support leading
20406 underscores in macro names. An example is NEWS-OS 4.2R.
20407
20408 @example
20409 $ @kbd{cat Makefile}
20410 _am_include = #
20411 _am_quote =
20412 all:; @@echo this is test
20413 $ @kbd{make}
20414 Make: Must be a separator on rules line 2. Stop.
20415 $ @kbd{cat Makefile2}
20416 am_include = #
20417 am_quote =
20418 all:; @@echo this is test
20419 $ @kbd{make -f Makefile2}
20420 this is test
20421 @end example
20422
20423 @noindent
20424 However, this problem is no longer of practical concern.
20425
20426 @node Backslash-Newline-Empty
20427 @section Backslash-Newline Before Empty Lines
20428
20429 @c This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
20430 @c but another hppa hpux 10.20 didn't have it. Bob Proulx
20431 @c <[email protected]> thinks it was in hpux 8.0 too.
20432 On some versions of HP-UX, @command{make} reads multiple newlines
20433 following a backslash, continuing to the next non-empty line. For
20434 example,
20435
20436 @example
20437 FOO = one \
20438
20439 BAR = two
20440
20441 test:
20442 : FOO is "$(FOO)"
20443 : BAR is "$(BAR)"
20444 @end example
20445
20446 @noindent
20447 shows @code{FOO} equal to @code{one BAR = two}. Other implementations
20448 sensibly let a backslash continue only to the immediately following
20449 line.
20450
20451 @node Backslash-Newline Comments
20452 @section Backslash-Newline in Make Comments
20453
20454 According to POSIX, Make comments start with @code{#}
20455 and continue until an unescaped newline is reached.
20456
20457 @example
20458 $ @kbd{cat Makefile}
20459 # A = foo \
20460 bar \
20461 baz
20462
20463 all:
20464 @@echo ok
20465 $ @kbd{make} # GNU make
20466 ok
20467 @end example
20468
20469 @noindent
20470 However this is not always the case. Some implementations
20471 discard everything from @code{#} through the end of the line, ignoring any
20472 trailing backslash.
20473
20474 @example
20475 $ @kbd{pmake} # BSD make
20476 "Makefile", line 3: Need an operator
20477 Fatal errors encountered -- cannot continue
20478 @end example
20479
20480 @noindent
20481 Therefore, if you want to comment out a multi-line definition, prefix each
20482 line with @code{#}, not only the first.
20483
20484 @example
20485 # A = foo \
20486 # bar \
20487 # baz
20488 @end example
20489
20490 @node Macros and Submakes
20491 @section @code{make macro=value} and Submakes
20492
20493 A command-line variable definition such as @code{foo=bar} overrides any
20494 definition of @code{foo} in a makefile. Some @command{make}
20495 implementations (such as GNU @command{make}) propagate this
20496 override to subsidiary invocations of @command{make}. Some other
20497 implementations do not pass the substitution along to submakes.
20498
20499 @example
20500 $ @kbd{cat Makefile}
20501 foo = foo
20502 one:
20503 @@printf '%s\n' $(foo)
20504 $(MAKE) two
20505 two:
20506 @@printf '%s\n' $(foo)
20507 $ @kbd{make foo=bar} # GNU make 3.79.1
20508 bar
20509 make two
20510 make[1]: Entering directory `/home/adl'
20511 bar
20512 make[1]: Leaving directory `/home/adl'
20513 $ @kbd{pmake foo=bar} # BSD make
20514 bar
20515 pmake two
20516 foo
20517 @end example
20518
20519 You have a few possibilities if you do want the @code{foo=bar} override
20520 to propagate to submakes. One is to use the @option{-e}
20521 option, which causes all environment variables to have precedence over
20522 the makefile macro definitions, and declare foo as an environment
20523 variable:
20524
20525 @example
20526 $ @kbd{env foo=bar make -e}
20527 @end example
20528
20529 The @option{-e} option is propagated to submakes automatically,
20530 and since the environment is inherited between @command{make}
20531 invocations, the @code{foo} macro is overridden in
20532 submakes as expected.
20533
20534 This syntax (@code{foo=bar make -e}) is portable only when used
20535 outside of a makefile, for instance from a script or from the
20536 command line. When run inside a @command{make} rule, GNU
20537 @command{make} 3.80 and prior versions forget to propagate the
20538 @option{-e} option to submakes.
20539
20540 Moreover, using @option{-e} could have unexpected side effects if your
20541 environment contains some other macros usually defined by the
20542 makefile. (See also the note about @code{make -e} and @code{SHELL}
20543 below.)
20544
20545 If you can foresee all macros that a user might want to override, then
20546 you can propagate them to submakes manually, from your makefile:
20547
20548 @example
20549 foo = foo
20550 one:
20551 @@printf '%s\n' $(foo)
20552 $(MAKE) foo=$(foo) two
20553 two:
20554 @@printf '%s\n' $(foo)
20555 @end example
20556
20557 Another way to propagate a variable to submakes in a portable way is to
20558 expand an extra variable in every invocation of @samp{$(MAKE)} within
20559 your makefile:
20560
20561 @example
20562 foo = foo
20563 one:
20564 @@printf '%s\n' $(foo)
20565 $(MAKE) $(SUBMAKEFLAGS) two
20566 two:
20567 @@printf '%s\n' $(foo)
20568 @end example
20569
20570 Users must be aware that this technique is in use to take advantage of
20571 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
20572 allows any macro to be overridden. Makefiles generated by
20573 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
20574 on the command lines of submakes (@pxref{Subdirectories, , Automake,
20575 automake, GNU Automake}).
20576
20577 @node The Make Macro MAKEFLAGS
20578 @section The Make Macro MAKEFLAGS
20579 @cindex @code{MAKEFLAGS} and @command{make}
20580 @cindex @command{make} and @code{MAKEFLAGS}
20581
20582 POSIX requires @command{make} to use @code{MAKEFLAGS} to affect the
20583 current and recursive invocations of make, but allows implementations
20584 several formats for the variable. It is tricky to parse
20585 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
20586 or @option{-k} for continued execution are in effect. For example, you
20587 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
20588 contains single-letter options, since in the Cygwin version of
20589 GNU @command{make} it is either @option{--unix} or
20590 @option{--win32} with the second word containing single-letter options.
20591
20592 @example
20593 $ @kbd{cat Makefile}
20594 all:
20595 @@printf 'MAKEFLAGS = %s\n' '$(MAKEFLAGS)'
20596 $ @kbd{make}
20597 MAKEFLAGS = --unix
20598 $ @kbd{make -k}
20599 MAKEFLAGS = --unix -k
20600 @end example
20601
20602 @node The Make Macro SHELL
20603 @section The Make Macro @code{SHELL}
20604 @cindex @code{SHELL} and @command{make}
20605 @cindex @command{make} and @code{SHELL}
20606
20607 Many @command{make} implementations use the @code{$(SHELL)}
20608 macro to spawn shell processes and execute Make rules. This
20609 is a builtin macro with a default value upplied by @command{make};
20610 the default can be overridden by a makefile or by a command-line argument,
20611 though not by the environment.
20612
20613 Other @command{make} implementations use other ways to spawn shell
20614 processes, and the POSIX standard for @command{make} says that portable
20615 makefiles should neither define nor use the @code{$(SHELL)} macro.
20616
20617 Despite this prohibition, in practice it does not hurt to define and
20618 then possibly use @code{SHELL} in your makefiles and in some cases it
20619 can help your builds use a better shell to spawn shell processes.
20620 So it's a good idea to define @code{SHELL} in
20621 your makefiles. If you use Autoconf, you can use
20622 its standard output variable @code{SHELL} as follows:
20623
20624 @example
20625 SHELL = @@SHELL@@
20626 @end example
20627
20628 @noindent
20629 If you use Automake, this is done for you.
20630
20631 Do not force @code{SHELL = /bin/sh} because that is not correct
20632 everywhere. Remember, @file{/bin/sh} is not POSIX compliant on some
20633 systems, such as Solaris 10.
20634 Additionally, DJGPP lacks @code{/bin/sh}, and when its
20635 GNU @command{make} port sees such a setting it enters a
20636 special emulation mode where features like pipes and redirections are
20637 emulated on top of DOS's @command{command.com}. Unfortunately this
20638 emulation is incomplete; for instance it does not handle command
20639 substitutions. Using @code{@@SHELL@@} means that your makefile will
20640 benefit from the same improved shell, such as @command{bash} or
20641 @command{ksh}, that was discovered during @command{configure}, so that
20642 you aren't fighting two different sets of shell bugs between the two
20643 contexts.
20644
20645 Do not rely on whether @command{make}'s @code{SHELL} settings are
20646 exported to subprocesses, as implementations differ:
20647
20648 @example
20649 $ @kbd{cat Makefile}
20650 all:
20651 @@printf '%s\n' '$(SHELL)'
20652 @@printenv SHELL
20653 $ @kbd{env SHELL=/bin/sh make -e SHELL=/bin/ksh} # BSD make, AIX make
20654 /bin/ksh
20655 /bin/ksh
20656 $ @kbd{env SHELL=/bin/sh make -e SHELL=/bin/ksh} # GNU make
20657 /bin/ksh
20658 sh
20659 @end example
20660
20661 @node Parallel Make
20662 @section Parallel Make
20663 @cindex Parallel @command{make}
20664
20665 Support for parallel execution in @command{make} implementation varies.
20666 Generally, using GNU make is your best bet.
20667
20668 When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
20669 reuse the same shell for multiple commands within one recipe. This can
20670 have various unexpected consequences. For example, changes of directories
20671 or variables persist between recipes, so that:
20672
20673 @example
20674 all:
20675 @@var=value; cd /; pwd; echo $$var; echo $$$$
20676 @@pwd; echo $$var; echo $$$$
20677 @end example
20678
20679 @noindent
20680 may output the following with @code{make -j1}, at least on NetBSD up to
20681 5.1 and FreeBSD up to 8.2:
20682
20683 @example
20684 /
20685 value
20686 32235
20687 /
20688 value
20689 32235
20690 @end example
20691
20692 @noindent
20693 while without @option{-j1}, or with @option{-B}, the output looks less
20694 surprising:
20695
20696 @example
20697 /
20698 value
20699 32238
20700 /tmp
20701
20702 32239
20703 @end example
20704
20705 @noindent
20706 Another consequence is that, if one command in a recipe uses @code{exit 0}
20707 to indicate a successful exit, the shell will be gone and the remaining
20708 commands of this recipe will not be executed.
20709
20710 The BSD @command{make} implementations, when run in parallel mode,
20711 will also pass the @command{Makefile} recipes to the shell through
20712 its standard input, thus making it unusable from the recipes:
20713
20714 @example
20715 $ @kbd{cat Makefile}
20716 read:
20717 @@read line; echo LINE: $$line
20718 @c $$ @c restore font-lock
20719 $ @kbd{echo foo | make read}
20720 LINE: foo
20721 $ @kbd{echo foo | make -j1 read} # NetBSD 5.1 and FreeBSD 8.2
20722 LINE:
20723 @end example
20724
20725 @noindent
20726 Moreover, when FreeBSD @command{make} (up at least to 8.2) is run in
20727 parallel mode, it implements the @code{@@} and @code{-} ``recipe
20728 modifiers'' by dynamically modifying the active shell flags. This
20729 behavior has the effects of potentially clobbering the exit status
20730 of recipes silenced with the @code{@@} modifier if they also unset
20731 the @option{errexit} shell flag, and of mangling the output in
20732 unexpected ways:
20733
20734 @example
20735 $ @kbd{cat Makefile}
20736 a:
20737 @@echo $$-; set +e; false
20738 b:
20739 -echo $$-; false; echo set -
20740 $ @kbd{make a; echo status: $?}
20741 ehBc
20742 *** Error code 1
20743 status: 1
20744 $ @kbd{make -j1 a; echo status: $?}
20745 ehB
20746 status: 0
20747 $ @kbd{make b}
20748 echo $-; echo set -
20749 hBc
20750 set -
20751 $ @kbd{make -j1 b}
20752 echo $-; echo hvB
20753 @end example
20754
20755 @noindent
20756 You can avoid all these issues by using the @option{-B} option to enable
20757 compatibility semantics. However, that will effectively also disable
20758 all parallelism as that will cause prerequisites to be updated in the
20759 order they are listed in a rule.
20760
20761 Some make implementations (among them, FreeBSD @command{make}, NetBSD
20762 @command{make}, and Solaris @command{dmake}), when invoked with a
20763 @option{-j@var{N}} option, connect the standard output and standard
20764 error of all their child processes to pipes or temporary regular
20765 files. This can lead to subtly different semantics in the behavior
20766 of the spawned processes. For example, even if the @command{make}
20767 standard output is connected to a tty, the recipe command will not be:
20768
20769 @example
20770 $ @kbd{cat Makefile}
20771 all:
20772 @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
20773 $ @kbd{make -j 2} # FreeBSD 8.2 make
20774 Is not a tty
20775 $ @kbd{make -j 2} # NetBSD 5.1 make
20776 --- all ---
20777 Is not a tty
20778 $ @kbd{dmake -j 2} # Solaris 10 dmake
20779 @var{hostname} --> 1 job
20780 @var{hostname} --> Job output
20781 Is not a tty
20782 @end example
20783
20784 @noindent
20785 On the other hand:
20786
20787 @example
20788 $ @kbd{make -j 2} # GNU make, Heirloom make
20789 Is a tty
20790 @end example
20791
20792 @noindent
20793 The above examples also show additional status output produced in parallel
20794 mode for targets being updated by Solaris @command{dmake} and NetBSD
20795 @command{make} (but @emph{not} by FreeBSD @command{make}).
20796
20797 Furthermore, parallel runs of those @command{make} implementations will
20798 route standard error from commands that they spawn into their own
20799 standard output, and may remove leading whitespace from output lines.
20800
20801
20802 @node Comments in Make Rules
20803 @section Comments in Make Rules
20804 @cindex Comments in @file{Makefile} rules
20805 @cindex @file{Makefile} rules and comments
20806
20807 Do not try to put comments (lines beginning with @samp{#}) in a rule, as
20808 they end the rule. It is OK for a rule line to start with a tab
20809 followed by @samp{#}, as a comment passed to a shell that does nothing.
20810
20811 To use the @samp{#} character in a command, put it in a rule not a
20812 macro, as the character cannot portably appear in macros
20813 (@pxref{Comments in Make Macros}). So for example, assuming the output
20814 variable @code{COMMENT_CHAR} stands for @samp{#}, the following replaces
20815 @samp{@@COMMENT_CHAR@@} by @samp{#} in a generated header:
20816
20817 @example
20818 foo.h: foo.h.in
20819 sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
20820 '$(srcdir)/foo.h.in' > $@@
20821 @end example
20822
20823 The funny shell quoting avoids a substitution at @command{config.status}
20824 run time of the left-hand side of the @command{sed} @samp{s} command.
20825
20826 @node Newlines in Make Rules
20827 @section Newlines in Make Rules
20828 @cindex Newlines in @file{Makefile} rules
20829 @cindex @file{Makefile} rules and newlines
20830
20831 In shell scripts, newlines can be used inside string literals. But in
20832 the shell statements of @file{Makefile} rules, this is not possible:
20833 a newline not preceded by a backslash separates commands, whereas a
20834 newline preceded by a backslash becomes part of the shell statement.
20835 So, how can a newline be used in a string literal?
20836
20837 The trick is to set up a shell variable @code{nl} that contains a newline.
20838 For example, the following uses a multi-line @samp{sed} expression that
20839 appends an empty line after every line of a file:
20840
20841 @example
20842 output: input
20843 eval "$$(printf 'nl="\n"\n')"; \
20844 sed "a\\$$nl" input >$@@
20845 @end example
20846
20847 @node Comments in Make Macros
20848 @section Comments in Make Macros
20849 @cindex Comments in @file{Makefile} macros
20850 @cindex @file{Makefile} macros and comments
20851
20852 In macro definitions, text from @samp{#} until line end is ignored,
20853 which has the unfortunate effect of disallowing @samp{#} even in quotes.
20854 Thus, the following does not work:
20855
20856 @example
20857 CPPFLAGS = "-DCOMMENT_CHAR='#'"
20858 @end example
20859
20860 @noindent
20861 as @samp{CPPFLAGS} is expanded to @samp{"-DCOMMENT_CHAR='}.
20862
20863 GNU @command{make}, when not in POSIX mode, lets you put
20864 @samp{#} into a macro value by escaping it with a backslash, i.e.,
20865 @samp{\#}. However, this usage is not portable.
20866 @xref{Comments in Make Rules}, for a portable alternative.
20867
20868 Even without quoting involved, comments can have surprising effects,
20869 because the whitespace before them is part of the variable value:
20870
20871 @example
20872 foo = bar # trailing comment
20873 print: ; @@echo "$(foo)."
20874 @end example
20875
20876 @noindent
20877 prints @samp{bar .}, which is usually not intended, and can expose
20878 @command{make} bugs as described below.
20879
20880 @node Trailing whitespace in Make Macros
20881 @section Trailing whitespace in Make Macros
20882 @cindex whitespace in @file{Makefile} macros
20883 @cindex @file{Makefile} macros and whitespace
20884
20885 GNU @command{make} 3.80 mistreats trailing whitespace in macro
20886 substitutions and appends another spurious suffix:
20887
20888 @example
20889 empty =
20890 foo = bar $(empty)
20891 print: ; @@echo $(foo:=.test)
20892 @end example
20893
20894 @noindent
20895 prints @samp{bar.test .test}.
20896
20897 BSD and Solaris @command{make} implementations do not honor trailing
20898 whitespace in macro definitions as POSIX requires:
20899
20900 @example
20901 foo = bar # Note the space after "bar".
20902 print: ; @@echo $(foo)t
20903 @end example
20904
20905 @noindent
20906 prints @samp{bart} instead of @samp{bar t}. To work around this, you
20907 can use a helper macro as in the previous example.
20908
20909
20910 @node Command-line Macros and whitespace
20911 @section Command-line Macros and whitespace
20912 @cindex whitespace in command-line macros
20913 @cindex command-line, macros set on
20914 @cindex environment, macros set from
20915
20916 Some @command{make} implementations may strip trailing whitespace off
20917 of macros set on the command line in addition to leading whitespace.
20918 Further, some may strip leading whitespace off of macros set from
20919 environment variables:
20920
20921 @example
20922 $ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
20923 foo=' f f ' make -f - bar=' b b '}
20924 x f f xb b x # AIX, BSD, GNU make
20925 xf f xb b x # HP-UX
20926 x f f xb bx # Solaris make
20927 @end example
20928
20929
20930 @node obj/ and Make
20931 @section The @file{obj/} Subdirectory and Make
20932 @cindex @file{obj/}, subdirectory
20933 @cindex BSD @command{make} and @file{obj/}
20934
20935 Never name one of your subdirectories @file{obj/} if you don't like
20936 surprises.
20937
20938 If an @file{obj/} directory exists, BSD @command{make} enters it
20939 before reading the makefile. Hence the makefile in the
20940 current directory is not read.
20941
20942 @example
20943 $ @kbd{cat Makefile}
20944 all:
20945 echo Hello
20946 $ @kbd{cat obj/Makefile}
20947 all:
20948 echo World
20949 $ @kbd{make} # GNU make
20950 echo Hello
20951 Hello
20952 $ @kbd{pmake} # BSD make
20953 echo World
20954 World
20955 @end example
20956
20957 @node make -k Status
20958 @section Exit Status of @code{make -k}
20959 @cindex @code{make -k}
20960
20961 Do not rely on the exit status of @code{make -k}. Some implementations
20962 reflect whether they encountered an error in their exit status; other
20963 implementations always succeed.
20964
20965 @example
20966 $ @kbd{cat Makefile}
20967 all:
20968 false
20969 $ @kbd{make -k; echo exit status: $?} # GNU make
20970 false
20971 make: *** [all] Error 1
20972 exit status: 2
20973 $ @kbd{pmake -k; echo exit status: $?} # BSD make
20974 false
20975 *** Error code 1 (continuing)
20976 exit status: 0
20977 @end example
20978
20979 @node VPATH and Make
20980 @section @code{VPATH} and Make
20981 @cindex @code{VPATH}
20982
20983 POSIX does not specify the semantics of @code{VPATH}. Typically,
20984 @command{make} supports @code{VPATH}, but its implementation is not
20985 consistent.
20986
20987 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
20988 portable to recent-enough popular implementations of @command{make}, but
20989 to keep the resulting makefiles portable, a package's makefile
20990 prototypes must take the following issues into account. These issues
20991 are complicated and are often poorly understood, and installers who use
20992 @code{VPATH} should expect to find many bugs in this area. If you use
20993 @code{VPATH}, the simplest way to avoid these portability bugs is to
20994 stick with GNU @command{make}, since it is the most
20995 commonly-used @command{make} among Autoconf users.
20996
20997 Here are some known issues with some @code{VPATH}
20998 implementations.
20999
21000 @menu
21001 * Variables listed in VPATH:: @code{VPATH} must be literal on ancient hosts
21002 * VPATH and Double-colon:: Problems with @samp{::} on ancient hosts
21003 * $< in Explicit Rules:: @code{$<} does not work in ordinary rules
21004 * Automatic Rule Rewriting:: @code{VPATH} goes wild on Solaris
21005 * Make Target Lookup:: More details about @code{VPATH} lookup
21006 @end menu
21007
21008 @node Variables listed in VPATH
21009 @subsection Variables listed in @code{VPATH}
21010 @cindex @code{VPATH} and variables
21011 @cindex variables and @code{VPATH}
21012
21013 Do not set @code{VPATH} to the value of another variable, for example
21014 @samp{VPATH = $(srcdir)}, because some ancient versions of
21015 @command{make} do not do variable substitutions on the value of
21016 @code{VPATH}. For example, use this
21017
21018 @example
21019 srcdir = @@srcdir@@
21020 VPATH = @@srcdir@@
21021 @end example
21022
21023 @noindent
21024 rather than @samp{VPATH = $(srcdir)}. Note that with GNU
21025 Automake, there is no need to set this yourself.
21026
21027 @node VPATH and Double-colon
21028 @subsection @code{VPATH} and Double-colon Rules
21029 @cindex @code{VPATH} and double-colon rules
21030 @cindex double-colon rules and @code{VPATH}
21031
21032 With ancient versions of Sun @command{make},
21033 any assignment to @code{VPATH} causes @command{make} to execute only
21034 the first set of double-colon rules.
21035 However, this problem is no longer of practical concern.
21036
21037 @node $< in Explicit Rules
21038 @subsection @code{$<} Not Supported in Explicit Rules
21039 @cindex explicit rules, @code{$<}, and @code{VPATH}
21040 @cindex @code{$<}, explicit rules, and @code{VPATH}
21041 @cindex @code{VPATH}, explicit rules, and @code{$<}
21042
21043 Using @code{$<} in explicit rules is not portable.
21044 The prerequisite file must be named explicitly in the rule. If you want
21045 to find the prerequisite via a @code{VPATH} search, you have to code the
21046 whole thing manually. @xref{Build Directories}.
21047
21048 @node Automatic Rule Rewriting
21049 @subsection Automatic Rule Rewriting
21050 @cindex @code{VPATH} and automatic rule rewriting
21051 @cindex automatic rule rewriting and @code{VPATH}
21052
21053 Some @command{make} implementations, such as Solaris,
21054 search for prerequisites in @code{VPATH} and
21055 then rewrite each occurrence as a plain word in the rule.
21056 For instance:
21057
21058 @example
21059 # This isn't portable to GNU make.
21060 VPATH = ../pkg/src
21061 f.c: if.c
21062 cp if.c f.c
21063 @end example
21064
21065 @noindent
21066 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
21067 found in @file{../pkg/src}.
21068
21069 However, this rule leads to real problems in practice. For example, if
21070 the source directory contains an ordinary file named @file{test} that is
21071 used in a dependency, Solaris @command{make} rewrites commands like
21072 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
21073 @dots{}}, which is typically undesirable. In fact, @command{make} is
21074 completely unaware of shell syntax used in the rules, so the VPATH
21075 rewrite can potentially apply to @emph{any} whitespace-separated word
21076 in a rule, including shell variables, functions, and keywords.
21077
21078 @example
21079 $ @kbd{mkdir build}
21080 $ @kbd{cd build}
21081 $ @kbd{cat > Makefile <<'END'}
21082 VPATH = ..
21083 all: arg func for echo
21084 func () @{ for arg in "$$@@"; do echo $$arg; done; @}; \
21085 func "hello world"
21086 END
21087 $ @kbd{touch ../arg ../func ../for ../echo}
21088 $ @kbd{make}
21089 ../func () @{ ../for ../arg in "$@@"; do ../echo $arg; done; @}; \
21090 ../func "hello world"
21091 sh: syntax error at line 1: `do' unexpected
21092 *** Error code 2
21093 @end example
21094
21095 @noindent
21096 To avoid this problem, portable makefiles should never mention a source
21097 file or dependency whose name is that of a shell keyword like @file{for}
21098 or @file{until}, a shell command like @command{cat} or @command{gcc} or
21099 @command{test}, or a shell function or variable used in the corresponding
21100 @command{Makefile} recipe.
21101
21102 Because of these problems GNU @command{make} and many other @command{make}
21103 implementations do not rewrite commands, so portable makefiles should
21104 search @code{VPATH} manually. It is tempting to write this:
21105
21106 @smallexample
21107 # This isn't portable to Solaris make.
21108 VPATH = ../pkg/src
21109 f.c: if.c
21110 cp `test -f if.c || echo $(VPATH)/`if.c f.c
21111 @end smallexample
21112
21113 @noindent
21114 However, the ``prerequisite rewriting'' still applies here. So if
21115 @file{if.c} is in @file{../pkg/src}, Solaris @command{make}
21116 executes
21117
21118 @smallexample
21119 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
21120 @end smallexample
21121
21122 @noindent
21123 which reduces to
21124
21125 @example
21126 cp if.c f.c
21127 @end example
21128
21129 @noindent
21130 and thus fails. Oops.
21131
21132 A simple workaround, and good practice anyway, is to use @samp{$?} and
21133 @samp{$@@} when possible:
21134
21135 @smallexample
21136 VPATH = ../pkg/src
21137 f.c: if.c
21138 cp $? $@@
21139 @end smallexample
21140
21141 @noindent
21142 but this does not generalize well to commands with multiple
21143 prerequisites. A more general workaround is to rewrite the rule so that
21144 the prerequisite @file{if.c} never appears as a plain word. For
21145 example, these three rules would be safe, assuming @file{if.c} is in
21146 @file{../pkg/src} and the other files are in the working directory:
21147
21148 @smallexample
21149 VPATH = ../pkg/src
21150 f.c: if.c f1.c
21151 cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
21152 g.c: if.c g1.c
21153 cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
21154 h.c: if.c h1.c
21155 cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
21156 @end smallexample
21157
21158 Things get worse when your prerequisites are in a macro.
21159
21160 @example
21161 VPATH = ../pkg/src
21162 HEADERS = f.h g.h h.h
21163 install-HEADERS: $(HEADERS)
21164 for i in $(HEADERS); do \
21165 $(INSTALL) -m 644 \
21166 `test -f $$i || echo $(VPATH)/`$$i \
21167 $(DESTDIR)$(includedir)/$$i; \
21168 @c $$ restore font-lock
21169 done
21170 @end example
21171
21172 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
21173 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
21174 where @code{f.h} and @code{g.h} are plain words and are hence
21175 subject to @code{VPATH} adjustments.
21176
21177 If the three files are in @file{../pkg/src}, the rule is run as:
21178
21179 @example
21180 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
21181 install -m 644 \
21182 `test -f $i || echo ../pkg/src/`$i \
21183 /usr/local/include/$i; \
21184 done
21185 @end example
21186
21187 where the two first @command{install} calls fail. For instance,
21188 consider the @code{f.h} installation:
21189
21190 @example
21191 install -m 644 \
21192 `test -f ../pkg/src/f.h || \
21193 echo ../pkg/src/ \
21194 `../pkg/src/f.h \
21195 /usr/local/include/../pkg/src/f.h;
21196 @end example
21197
21198 @noindent
21199 It reduces to:
21200
21201 @example
21202 install -m 644 \
21203 ../pkg/src/f.h \
21204 /usr/local/include/../pkg/src/f.h;
21205 @end example
21206
21207 Note that the manual @code{VPATH} search did not cause any problems here;
21208 however this command installs @file{f.h} in an incorrect directory.
21209
21210 Trying to quote @code{$(HEADERS)} in some way, as we did for
21211 @code{foo.c} a few makefiles ago, does not help:
21212
21213 @example
21214 install-HEADERS: $(HEADERS)
21215 headers='$(HEADERS)'; \
21216 for i in $$headers; do \
21217 $(INSTALL) -m 644 \
21218 `test -f $$i || echo $(VPATH)/`$$i \
21219 $(DESTDIR)$(includedir)/$$i; \
21220 done
21221 @end example
21222
21223 Now, @code{headers='$(HEADERS)'} macro-expands to:
21224
21225 @example
21226 headers='f.h g.h h.h'
21227 @end example
21228
21229 @noindent
21230 but @code{g.h} is still a plain word. (As an aside, the idiom
21231 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
21232 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
21233 syntax error on @code{for i in;}.)
21234
21235 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
21236
21237 @example
21238 VPATH = ../pkg/src
21239 HEADERS = f.h g.h h.h
21240 install-HEADERS: $(HEADERS)
21241 headers='$(HEADERS)'; \
21242 for i in $$headers; do \
21243 i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
21244 $(INSTALL) -m 644 \
21245 `test -f $$i || echo $(VPATH)/`$$i \
21246 $(DESTDIR)$(includedir)/$$i; \
21247 @c $$ restore font-lock
21248 done
21249 @end example
21250
21251 @noindent
21252 Automake does something similar.
21253
21254 @node Make Target Lookup
21255 @subsection Make Target Lookup
21256 @cindex @code{VPATH}, resolving target pathnames
21257
21258 GNU @command{make} uses a complex algorithm to decide when it
21259 should use files found via a @code{VPATH} search. @xref{Search
21260 Algorithm, , How Directory Searches are Performed, make, The GNU Make
21261 Manual}.
21262
21263 If a target needs to be rebuilt, GNU @command{make} discards the
21264 file name found during the @code{VPATH} search for this target, and
21265 builds the file locally using the file name given in the makefile.
21266 If a target does not need to be rebuilt, GNU @command{make} uses the
21267 file name found during the @code{VPATH} search.
21268
21269 Other @command{make} implementations, like NetBSD @command{make}, are
21270 easier to describe: the file name found during the @code{VPATH} search
21271 is used whether the target needs to be rebuilt or not. Therefore
21272 new files are created locally, but existing files are updated at their
21273 @code{VPATH} location.
21274
21275 OpenBSD and FreeBSD @command{make}, however,
21276 never perform a
21277 @code{VPATH} search for a dependency that has an explicit rule.
21278 This is extremely annoying.
21279
21280 When attempting a @code{VPATH} build for an autoconfiscated package
21281 (e.g., @code{mkdir build && cd build && ../configure}), this means
21282 GNU
21283 @command{make} builds everything locally in the @file{build}
21284 directory, while BSD @command{make} builds new files locally and
21285 updates existing files in the source directory.
21286
21287 @example
21288 $ @kbd{cat Makefile}
21289 VPATH = ..
21290 all: foo.x bar.x
21291 foo.x bar.x: newer.x
21292 @@echo Building $@@
21293 $ @kbd{touch ../bar.x}
21294 $ @kbd{touch ../newer.x}
21295 $ @kbd{make} # GNU make
21296 Building foo.x
21297 Building bar.x
21298 $ @kbd{pmake} # NetBSD make
21299 Building foo.x
21300 Building ../bar.x
21301 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21302 Building foo.x
21303 Building bar.x
21304 $ @kbd{make} # GNU make
21305 Building foo.x
21306 $ @kbd{pmake} # NetBSD make
21307 Building foo.x
21308 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21309 Building foo.x
21310 Building bar.x
21311 @end example
21312
21313 Note how NetBSD @command{make} updates @file{../bar.x} in its
21314 VPATH location, and how FreeBSD and OpenBSD
21315 @command{make} always
21316 update @file{bar.x}, even when @file{../bar.x} is up to date.
21317
21318 Another point worth mentioning is that once GNU @command{make} has
21319 decided to ignore a @code{VPATH} file name (e.g., it ignored
21320 @file{../bar.x} in the above example) it continues to ignore it when
21321 the target occurs as a prerequisite of another rule.
21322
21323 The following example shows that GNU @command{make} does not look up
21324 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
21325 because it ignored the @code{VPATH} result of @file{bar.x} while running
21326 the @code{bar.x: newer.x} rule.
21327
21328 @example
21329 $ @kbd{cat Makefile}
21330 VPATH = ..
21331 all: bar.y
21332 bar.x: newer.x
21333 @@echo Building $@@
21334 .SUFFIXES: .x .y
21335 .x.y:
21336 cp $< $@@
21337 $ @kbd{touch ../bar.x}
21338 $ @kbd{touch ../newer.x}
21339 $ @kbd{make} # GNU make
21340 Building bar.x
21341 cp bar.x bar.y
21342 cp: cannot stat 'bar.x': No such file or directory
21343 make: *** [bar.y] Error 1
21344 $ @kbd{pmake} # NetBSD make
21345 Building ../bar.x
21346 cp ../bar.x bar.y
21347 $ @kbd{rm bar.y}
21348 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21349 echo Building bar.x
21350 cp bar.x bar.y
21351 cp: cannot stat 'bar.x': No such file or directory
21352 *** Error code 1
21353 @end example
21354
21355 Note that if you drop away the command from the @code{bar.x: newer.x}
21356 rule, GNU @command{make} magically starts to work: it
21357 knows that @code{bar.x} hasn't been updated, therefore it doesn't
21358 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
21359 uses. FreeBSD and OpenBSD still don't work, though.
21360
21361 @example
21362 $ @kbd{cat Makefile}
21363 VPATH = ..
21364 all: bar.y
21365 bar.x: newer.x
21366 .SUFFIXES: .x .y
21367 .x.y:
21368 cp $< $@@
21369 $ @kbd{touch ../bar.x}
21370 $ @kbd{touch ../newer.x}
21371 $ @kbd{make} # GNU make
21372 cp ../bar.x bar.y
21373 $ @kbd{rm bar.y}
21374 $ @kbd{pmake} # NetBSD make
21375 cp ../bar.x bar.y
21376 $ @kbd{rm bar.y}
21377 $ @kbd{fmake} # FreeBSD make, OpenBSD make
21378 cp bar.x bar.y
21379 cp: cannot stat 'bar.x': No such file or directory
21380 *** Error code 1
21381 @end example
21382
21383 It seems the sole solution that would please every @command{make}
21384 implementation is to never rely on @code{VPATH} searches for targets.
21385 In other words, @code{VPATH} should be reserved to sources that are not built.
21386
21387
21388 @node Single Suffix Rules
21389 @section Single Suffix Rules and Separated Dependencies
21390 @cindex Single Suffix Inference Rule
21391 @cindex Rule, Single Suffix Inference
21392 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
21393 (@samp{.from.to:}), but which @emph{destination} suffix is empty
21394 (@samp{.from:}).
21395
21396 @cindex Separated Dependencies
21397 @dfn{Separated dependencies} simply refers to listing the prerequisite
21398 of a target, without defining a rule. Usually one can list on the one
21399 hand side, the rules, and on the other hand side, the dependencies.
21400
21401 Solaris @command{make} does not support separated dependencies for
21402 targets defined by single suffix rules:
21403
21404 @example
21405 $ @kbd{cat Makefile}
21406 .SUFFIXES: .in
21407 foo: foo.in
21408 .in:
21409 cp $< $@@
21410 $ @kbd{touch foo.in}
21411 $ @kbd{make}
21412 $ @kbd{ls}
21413 Makefile foo.in
21414 @end example
21415
21416 @noindent
21417 while GNU Make does:
21418
21419 @example
21420 $ @kbd{gmake}
21421 cp foo.in foo
21422 $ @kbd{ls}
21423 Makefile foo foo.in
21424 @end example
21425
21426 Note it works without the @samp{foo: foo.in} dependency.
21427
21428 @example
21429 $ @kbd{cat Makefile}
21430 .SUFFIXES: .in
21431 .in:
21432 cp $< $@@
21433 $ @kbd{make foo}
21434 cp foo.in foo
21435 @end example
21436
21437 @noindent
21438 and it works with double suffix inference rules:
21439
21440 @example
21441 $ @kbd{cat Makefile}
21442 foo.out: foo.in
21443 .SUFFIXES: .in .out
21444 .in.out:
21445 cp $< $@@
21446 $ @kbd{make}
21447 cp foo.in foo.out
21448 @end example
21449
21450 As a result, in such a case, you have to write target rules.
21451
21452 @node Timestamps and Make
21453 @section Timestamp Resolution and Make
21454 @cindex timestamp resolution
21455 Traditionally, file timestamps had 1-second resolution, and
21456 @command{make} used those timestamps to determine whether one file was
21457 newer than the other. However, many modern file systems have
21458 timestamps with 1-nanosecond resolution. Some @command{make}
21459 implementations look at the entire timestamp; others ignore the
21460 fractional part, which can lead to incorrect results. Normally this
21461 is not a problem, but in some extreme cases you may need to use tricks
21462 like @samp{sleep 1} to work around timestamp truncation bugs.
21463
21464 Traditionally, commands like @samp{cp -p} and @samp{touch -r} did not copy
21465 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
21466 Tools}). Hence you should be wary of rules like this:
21467
21468 @example
21469 dest: src
21470 cp -p src dest
21471 @end example
21472
21473 as @file{dest} often appears to be older than @file{src} after the
21474 timestamp is truncated, and this can cause @command{make} to do
21475 needless rework the next time it is invoked. To work around this
21476 problem, you can use a timestamp file, e.g.:
21477
21478 @example
21479 dest-stamp: src
21480 cp -p src dest
21481 echo >dest-stamp
21482 @end example
21483
21484 Apart from timestamp resolution, there are also differences in handling
21485 equal timestamps. Although POSIX suggests that @command{make} update a
21486 target with the same timestamp as its newest prerequisite, only
21487 HP-UX @command{make} is known to do so; GNU and other @command{make}
21488 implementations do not update, a behavior that POSIX also allows.
21489
21490 The HP-UX behavior can cause spurious rebuilds
21491 and this in turn can cause @command{make} to fail if it tries to rebuild
21492 generated files in a possibly read-only source tree with tools not
21493 present on the build machine. Conversely, if a source file is updated
21494 immediately after running @command{make} in a file system with
21495 low-resolution timestamps, the GNU behavior can cause a later
21496 @command{make} to neglect rebuilds and quietly generate incorrect results.
21497 To avoid both these problems, use GNU @command{make} on a platform
21498 with high-resolution timestamps.
21499
21500
21501 @c ======================================== Portable C and C++ Programming
21502
21503 @node Portable C and C++
21504 @chapter Portable C and C++ Programming
21505 @cindex Portable C and C++ programming
21506
21507 C and C++ programs often use low-level features of the underlying
21508 system, and therefore are often more difficult to make portable to other
21509 platforms.
21510
21511 Several standards have been developed to help make your programs more
21512 portable. If you write programs with these standards in mind, you can
21513 have greater confidence that your programs work on a wide variety
21514 of systems.
21515 @ifhtml
21516 @uref{https://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
21517 Standards Supported by GCC}
21518 @end ifhtml
21519 @ifnothtml
21520 @xref{Standards, , Language Standards Supported by
21521 GCC, gcc, Using the GNU Compiler Collection
21522 (GCC)},
21523 @end ifnothtml
21524 for a list of C-related standards. Many programs also assume the
21525 @uref{https://@/en.wikipedia.org/@/wiki/@/POSIX, POSIX standard}.
21526
21527 @cindex K&R C
21528 @cindex C89, C99, C11, C17, and C23
21529 The first widely used C variant was K&R C, which predates any C
21530 standard. K&R C compilers are no longer of practical interest, though,
21531 and Autoconf assumes at least C89, the first C standard,
21532 which is sometimes called ``C90'' due to a delay in standardization.
21533 C has since gone through the standards C99, C11, C17, and C23, and
21534 Autoconf is compatible with all these standards.
21535
21536 Program portability is a huge topic, and this section can only briefly
21537 introduce common pitfalls. @xref{System Portability, , Portability
21538 between System Types, standards, The GNU Coding Standards}, for
21539 more information.
21540
21541 @menu
21542 * Varieties of Unportability:: How to make your programs unportable
21543 * Integer Overflow:: When integers get too large
21544 * Preprocessor Arithmetic:: @code{#if} expression problems
21545 * Null Pointers:: Properties of null pointers
21546 * Buffer Overruns:: Subscript errors and the like
21547 * Volatile Objects:: @code{volatile} and signals
21548 * Floating Point Portability:: Portable floating-point arithmetic
21549 * Exiting Portably:: Exiting and the exit status
21550 @end menu
21551
21552 @node Varieties of Unportability
21553 @section Varieties of Unportability
21554 @cindex portability
21555
21556 Autoconf tests and ordinary programs often need to test what is allowed
21557 on a system, and therefore they may need to deliberately exceed the
21558 boundaries of what the standards allow, if only to see whether an
21559 optional feature is present. When you write such a program, you should
21560 keep in mind the difference between constraints, unspecified behavior,
21561 and undefined behavior.
21562
21563 In C, a @dfn{constraint} is a rule that the compiler must enforce. An
21564 example constraint is that C programs must not declare a bit-field with
21565 negative width. Tests can therefore reliably assume that programs with
21566 negative-width bit-fields are rejected by a compiler that conforms
21567 to the standard.
21568
21569 @dfn{Unspecified behavior} is valid behavior, where the standard allows
21570 multiple possibilities. For example, the order of evaluation of
21571 function arguments is unspecified. Some unspecified behavior is
21572 @dfn{implementation-defined}, i.e., documented by the implementation,
21573 but since Autoconf tests cannot read the documentation they cannot
21574 distinguish between implementation-defined and other unspecified
21575 behavior. It is common for Autoconf tests to probe implementations to
21576 determine otherwise-unspecified behavior.
21577
21578 @dfn{Undefined behavior} is invalid behavior, where the standard allows
21579 the implementation to do anything it pleases. For example,
21580 dereferencing a null pointer leads to undefined behavior. If possible,
21581 test programs should avoid undefined behavior, since a program with
21582 undefined behavior might succeed on a test that should fail.
21583
21584 The above rules apply to programs that are intended to conform to the
21585 standard. However, strictly-conforming programs are quite rare, since
21586 the standards are so limiting. A major goal of Autoconf is to support
21587 programs that use implementation features not described by the standard,
21588 and it is fairly common for test programs to violate the above rules, if
21589 the programs work well enough in practice.
21590
21591 @node Integer Overflow
21592 @section Integer Overflow
21593 @cindex integer overflow
21594 @cindex overflow, signed integer
21595 @cindex signed integer overflow
21596 @cindex wraparound arithmetic
21597
21598 Although some traditional C programs assume that signed integer overflow
21599 wraps around reliably using two's complement arithmetic, the C standard
21600 says that program behavior is undefined on overflow, and these C
21601 programs may not work on many modern implementations.
21602
21603 @menu
21604 * Integer Overflow Basics:: Why integer overflow is a problem
21605 * Signed Overflow Examples:: Examples of code assuming wraparound
21606 * Optimization and Wraparound:: Optimizations that break uses of wraparound
21607 * Signed Overflow Advice:: Practical advice for signed overflow issues
21608 * Signed Integer Division:: @code{INT_MIN / -1} and @code{INT_MIN % -1}
21609 @end menu
21610
21611 @node Integer Overflow Basics
21612 @subsection Basics of Integer Overflow
21613 @cindex integer overflow
21614 @cindex overflow, signed integer
21615 @cindex signed integer overflow
21616 @cindex wraparound arithmetic
21617
21618 In languages like C, integer overflow wraps around for unsigned
21619 integer types that are at least as wide as @code{unsigned int};
21620 e.g., @code{UINT_MAX + 1} yields zero.
21621 This is guaranteed by the C standard and is
21622 portable in practice, unless you specify aggressive,
21623 nonstandard optimization options
21624 suitable only for special applications.
21625
21626 In contrast, the C standard says that signed integer overflow leads to
21627 undefined behavior where a program can do anything, including dumping
21628 core or overrunning a buffer. The misbehavior can even precede the
21629 overflow. Such an overflow can occur during addition, subtraction,
21630 multiplication, division, and left shift. It can even occur for
21631 unsigned types like @code{unsigned short int} that are narrower
21632 than @code{int}, as values of these types are widened to @code{int}
21633 before computation.
21634
21635 Despite this requirement of the standard, some C programs assume that
21636 signed integer overflow silently wraps around modulo a power of two,
21637 using two's complement arithmetic, so long as you convert the resulting
21638 value to a signed integer type. These programs can have problems,
21639 especially when optimization is enabled. If you assume a GCC-like
21640 compiler, you can work around the problems by compiling with GCC's
21641 @code{-fwrapv} option; however, this is not portable.
21642
21643 For historical reasons C17 and earlier also allowed implementations with
21644 ones' complement or signed magnitude arithmetic, but C23 requires
21645 two's complement and it is safe to assume two's complement nowadays.
21646
21647 Also, overflow can occur when converting an out-of-range value to a
21648 signed integer type. Here a standard implementation must define what
21649 happens, and this can include raising an exception. Although practical
21650 implementations typically wrap around silently in this case, a few
21651 debugging implementations trap instead.
21652
21653 @node Signed Overflow Examples
21654 @subsection Examples of Code Assuming Wraparound Overflow
21655 @cindex integer overflow
21656 @cindex overflow, signed integer
21657 @cindex signed integer overflow
21658 @cindex wraparound arithmetic
21659
21660 There was long a tension between what the C standard requires for signed
21661 integer overflow, and what traditional C programs commonly assumed. The
21662 standard allows aggressive optimizations based on assumptions that
21663 overflow never occurs, but traditionally many C programs relied on overflow
21664 wrapping around. Although these programs did not conform to the standard,
21665 they formerly worked in practice because traditionally compilers did not
21666 optimize in such a way that would break the programs. Nowadays, though,
21667 compilers do perform these optimizations, so portable programs can no
21668 longer assume reliable wraparound on signed integer overflow.
21669
21670 The C Standard says that if a program has signed integer overflow its
21671 behavior is undefined, and the undefined behavior can even precede the
21672 overflow. To take an extreme example:
21673
21674 @c Inspired by Robert Dewar's example in
21675 @c <https://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
21676 @example
21677 if (password == expected_password)
21678 allow_superuser_privileges ();
21679 else if (counter++ == INT_MAX)
21680 abort ();
21681 else
21682 printf ("%d password mismatches\n", counter);
21683 @end example
21684
21685 @noindent
21686 If the @code{int} variable @code{counter} equals @code{INT_MAX},
21687 @code{counter++} must overflow and the behavior is undefined, so the C
21688 standard allows the compiler to optimize away the test against
21689 @code{INT_MAX} and the @code{abort} call.
21690 Worse, if an earlier bug in the program lets the compiler deduce that
21691 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
21692 the C standard allows the compiler to optimize away the password test
21693 and generate code that allows superuser privileges unconditionally.
21694
21695 Here is an example derived from the 7th Edition Unix implementation of
21696 @code{atoi} (1979-01-10):
21697
21698 @example
21699 char *p;
21700 int f, n;
21701 @dots{}
21702 while (*p >= '0' && *p <= '9')
21703 n = n * 10 + *p++ - '0';
21704 return (f ? -n : n);
21705 @end example
21706
21707 @noindent
21708 Even if the input string is in range, on most modern machines this has
21709 signed overflow when computing the most negative integer (the @code{-n}
21710 overflows) or a value near an extreme integer (the @code{+}
21711 overflows).
21712
21713 Here is another example, derived from the 7th Edition implementation of
21714 @code{rand} (1979-01-10). Here the programmer expects both
21715 multiplication and addition to wrap on overflow:
21716
21717 @example
21718 static long int randx = 1;
21719 @dots{}
21720 randx = randx * 1103515245 + 12345;
21721 return (randx >> 16) & 077777;
21722 @end example
21723
21724 In the following example, derived from the GNU C Library 2.15
21725 implementation of @code{mktime} (2012-03-21), the code assumes
21726 wraparound arithmetic in @code{+} to detect signed overflow:
21727
21728 @example
21729 time_t t, t1, t2;
21730 int sec_requested, sec_adjustment;
21731 @dots{}
21732 t1 = t + sec_requested;
21733 t2 = t1 + sec_adjustment;
21734 if (((t1 < t) != (sec_requested < 0))
21735 | ((t2 < t1) != (sec_adjustment < 0)))
21736 return -1;
21737 @end example
21738
21739 Although some of these examples will likely behave as if signed integer
21740 overflow wraps around reliably, other examples are likely to misbehave
21741 when optimization is enabled. All these examples should be avoided in
21742 portable code because signed integer overflow is not reliable on modern
21743 systems, and it's not worth worrying about which of these examples
21744 happen to work on most platforms and which do not.
21745
21746 @node Optimization and Wraparound
21747 @subsection Optimizations That Break Wraparound Arithmetic
21748 @cindex loop induction
21749
21750 Compilers sometimes generate code that is incompatible with wraparound
21751 integer arithmetic. A simple example is an algebraic simplification: a
21752 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
21753 because it assumes that @code{i * 2000} does not overflow. The
21754 translation is not equivalent to the original when overflow occurs:
21755 e.g., in the typical case of 32-bit signed two's complement wraparound
21756 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
21757 the original expression returns @minus{}2147483 but the optimized
21758 version returns the mathematically correct value 2147484.
21759
21760 More subtly, loop induction optimizations often exploit the undefined
21761 behavior of signed overflow. Consider the following contrived function
21762 @code{sumc}:
21763
21764 @example
21765 int
21766 sumc (int lo, int hi)
21767 @{
21768 int sum = 0;
21769 for (int i = lo; i <= hi; i++)
21770 sum ^= i * 53;
21771 return sum;
21772 @}
21773 @end example
21774
21775 @noindent
21776 To avoid multiplying by 53 each time through the loop, an optimizing
21777 compiler might internally transform @code{sumc} to the equivalent of the
21778 following:
21779
21780 @example
21781 int
21782 transformed_sumc (int lo, int hi)
21783 @{
21784 int sum = 0;
21785 int hic = hi * 53;
21786 for (int ic = lo * 53; ic <= hic; ic += 53)
21787 sum ^= ic;
21788 return sum;
21789 @}
21790 @end example
21791
21792 @noindent
21793 This transformation is allowed by the C standard, but it is invalid for
21794 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
21795 overflow in computing expressions like @code{hi * 53} can cause the
21796 expression @code{i <= hi} to yield a different value from the
21797 transformed expression @code{ic <= hic}.
21798
21799 For this reason, compilers that use loop induction and similar
21800 techniques often do not support reliable wraparound arithmetic when a
21801 loop induction variable like @code{ic} is involved. Since loop
21802 induction variables are generated by the compiler, and are not visible
21803 in the source code, it is not always trivial to say whether the problem
21804 affects your code.
21805
21806 Hardly any code actually depends on wraparound arithmetic in cases like
21807 these, so in practice these loop induction optimizations are almost
21808 always useful. However, edge cases in this area can cause problems.
21809 For example:
21810
21811 @example
21812 for (int j = 1; 0 < j; j *= 2)
21813 test (j);
21814 @end example
21815
21816 @noindent
21817 Here, the loop attempts to iterate through all powers of 2 that
21818 @code{int} can represent, but the C standard allows a compiler to
21819 optimize away the comparison and generate an infinite loop,
21820 under the argument that behavior is undefined on overflow. As of this
21821 writing this optimization is done on some platforms by
21822 GCC with @option{-O2}, so this code is not portable in practice.
21823
21824 @node Signed Overflow Advice
21825 @subsection Practical Advice for Signed Overflow Issues
21826 @cindex integer overflow
21827 @cindex overflow, signed integer
21828 @cindex signed integer overflow
21829 @cindex wraparound arithmetic
21830
21831 Ideally the safest approach is to avoid signed integer overflow
21832 entirely. For example, instead of multiplying two signed integers, you
21833 can convert them to double-width integers, multiply the wider values,
21834 then test whether the result is in the narrower range. Or you can use
21835 more-complicated code employing unsigned integers of the same width.
21836
21837 Rewriting code in this way will be inconvenient, though, especially if
21838 the signed values might be negative and no wider type is available.
21839 Using unsigned arithmetic to check for overflow is
21840 particularly painful to do portably and efficiently when dealing with an
21841 integer type like @code{uid_t} whose width and signedness vary from
21842 platform to platform. Also, this approach may hurt performance.
21843
21844 Hence it is often useful to maintain code that needs
21845 wraparound on overflow, instead of rewriting the code. The rest of this
21846 section attempts to give practical advice for this situation.
21847
21848 To detect integer overflow portably when attempting operations like
21849 @code{sum = a + b}, you can use the C23 @code{<stdckdint.h>} macros
21850 @code{ckd_add}, @code{ckd_sub}, and @code{ckd_mul}.
21851 The following code adds two integers with overflow wrapping around
21852 reliably in the sum:
21853
21854 @example
21855 #include <stdckdint.h>
21856 ...
21857 /* Set sum = a + b, with wraparound. */
21858 if (ckd_add (&sum, a, b))
21859 /* 'sum' has just the low order bits. */;
21860 else
21861 /* 'sum' is the correct answer. */;
21862 @end example
21863
21864 To be portable to pre-C23 platforms you can use Gnulib's
21865 @code{stdckdint} module, which emulates this part of C23 (@pxref{Gnulib}).
21866 Invoking the @code{stdckdint} macros typically costs just one machine
21867 instruction for the arithmetic and another instruction for the rare
21868 branch on overflow.
21869
21870 If your code uses a signed loop index, make sure that the index cannot
21871 overflow, along with all signed expressions derived from the index.
21872 Here is a contrived example of problematic code with two instances of
21873 overflow.
21874
21875 @example
21876 for (int i = INT_MAX - 10; i <= INT_MAX; i++)
21877 if (i + 1 < 0)
21878 @{
21879 report_overflow ();
21880 break;
21881 @}
21882 @end example
21883
21884 @noindent
21885 Because of the two overflows, a compiler might optimize away or
21886 transform the two comparisons in a way that is incompatible with the
21887 wraparound assumption.
21888
21889 If your code is intended to be compiled only by GCC and
21890 assumes wraparound behavior, and you want to insulate it
21891 against any GCC optimizations that would fail to support that
21892 behavior, you should use GCC's @option{-fwrapv} option, which
21893 causes signed overflow to wrap around reliably (except for division and
21894 remainder, as discussed in the next section).
21895
21896 If you need to write portable code and therefore cannot assume that
21897 signed integer overflow wraps around reliably, you should consider
21898 debugging with a GCC option that causes signed overflow to raise an
21899 exception. These options include @option{-fsanitize=undefined} and
21900 @option{-ftrapv}.
21901
21902 @node Signed Integer Division
21903 @subsection Signed Integer Division and Integer Overflow
21904 @cindex division, integer
21905
21906 Overflow in signed
21907 integer division is not always harmless: for example, on CPUs of the
21908 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
21909 which by default terminates the program. Worse, taking the remainder
21910 of these two values typically yields the same signal on these CPUs,
21911 behavior that the C standard allows.
21912
21913 @node Preprocessor Arithmetic
21914 @section Preprocessor Arithmetic
21915 @cindex preprocessor arithmetic
21916
21917 In C99 and later, preprocessor arithmetic, used for @code{#if}
21918 expressions, must
21919 be evaluated as if all signed values are of type @code{intmax_t} and all
21920 unsigned values of type @code{uintmax_t}. Many compilers are buggy in
21921 this area, though. For example, as of 2007, Sun C mishandles @code{#if
21922 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
21923 @code{long long int}. Also, some older preprocessors mishandle
21924 constants ending in @code{LL}. To work around these problems, you can
21925 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
21926 @code{configure}-time rather than at @code{#if}-time.
21927
21928 @node Null Pointers
21929 @section Properties of Null Pointers
21930 @cindex null pointers
21931
21932 Most modern hosts reliably fail when you attempt to dereference a null
21933 pointer.
21934
21935 On almost all modern hosts, null pointers use an all-bits-zero internal
21936 representation, so you can reliably use @code{memset} with 0 to set all
21937 the pointers in an array to null values.
21938
21939 If @code{p} is a null pointer to an object type, the C expression
21940 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
21941 the standard says that it has undefined behavior.
21942
21943 @node Buffer Overruns
21944 @section Buffer Overruns and Subscript Errors
21945 @cindex buffer overruns
21946
21947 Buffer overruns and subscript errors are the most common dangerous
21948 errors in C programs. They result in undefined behavior because storing
21949 outside an array typically modifies storage that is used by some other
21950 object, and most modern systems lack runtime checks to catch these
21951 errors. Programs should not rely on buffer overruns being caught.
21952
21953 There is one exception to the usual rule that a portable program cannot
21954 address outside an array. In C, it is valid to compute the address just
21955 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
21956 so long as you do not dereference the resulting pointer. But it is not
21957 valid to compute the address just before an object, e.g., @code{&a[-1]};
21958 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}. On
21959 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
21960 reliable in general, and it is usually easy enough to avoid the
21961 potential portability problem, e.g., by allocating an extra unused array
21962 element at the start or end.
21963
21964 @uref{https://@/www.valgrind.org/, Valgrind} can catch many overruns.
21965 GCC users might also consider using the @option{-fsanitize=} options to
21966 catch overruns. @xref{Instrumentation Options,,Program Instrumentation
21967 Options,gcc,Using the GNU Compiler Collection (GCC)}.
21968
21969 Buffer overruns are usually caused by off-by-one errors, but there are
21970 more subtle ways to get them.
21971
21972 Using @code{int} values to index into an array or compute array sizes
21973 causes problems on typical 64-bit hosts where an array index might
21974 be @math{2^{31}} or larger. Index values of type @code{size_t} avoid this
21975 problem, but cannot be negative. Index values of type @code{ptrdiff_t}
21976 are signed, and are wide enough in practice.
21977
21978 If you add or multiply two numbers to calculate an array size, e.g.,
21979 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
21980 multiplication overflows.
21981
21982 Many implementations of the @code{alloca} function silently misbehave
21983 and can generate buffer overflows if given sizes that are too large.
21984 The size limits are implementation dependent, but are at least 4000
21985 bytes on all platforms that we know about.
21986
21987 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
21988 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
21989 portable code should not use them unless the inputs are known to be
21990 within certain limits. The time-related functions can overflow their
21991 buffers if given timestamps out of range (e.g., a year less than -999
21992 or greater than 9999). Time-related buffer overflows cannot happen with
21993 recent-enough versions of the GNU C library, but are possible
21994 with other
21995 implementations. The @code{gets} function is the worst, since it almost
21996 invariably overflows its buffer when presented with an input line larger
21997 than the buffer.
21998
21999 @node Volatile Objects
22000 @section Volatile Objects
22001 @cindex volatile objects
22002
22003 The keyword @code{volatile} is often misunderstood in portable code.
22004 Its use inhibits some memory-access optimizations, but programmers often
22005 wish that it had a different meaning than it actually does.
22006
22007 @code{volatile} was designed for code that accesses special objects like
22008 memory-mapped device registers whose contents spontaneously change.
22009 Such code is inherently low-level, and it is difficult to specify
22010 portably what @code{volatile} means in these cases. The C standard
22011 says, ``What constitutes an access to an object that has
22012 volatile-qualified type is implementation-defined,'' so in theory each
22013 implementation is supposed to fill in the gap by documenting what
22014 @code{volatile} means for that implementation. In practice, though,
22015 this documentation is usually absent or incomplete.
22016
22017 One area of confusion is the distinction between objects defined with
22018 volatile types, and volatile lvalues. From the C standard's point of
22019 view, an object defined with a volatile type has externally visible
22020 behavior. You can think of such objects as having little oscilloscope
22021 probes attached to them, so that the user can observe some properties of
22022 accesses to them, just as the user can observe data written to output
22023 files. However, accesses via volatile lvalues to ordinary objects
22024 are merely side effects (i.e., changes to the state of the execution
22025 environment), and the implementation is not required to document
22026 their visibility any further. For example:
22027
22028 @example
22029 /* Declare and access a volatile object.
22030 Accesses to X are "visible" to users. */
22031 static int volatile x;
22032 x = 1;
22033
22034 /* Access two ordinary objects via a volatile lvalue.
22035 Although each read and write is a side effect,
22036 the accesses are not directly "visible" to users. */
22037 int y = 0;
22038 int *z = malloc (sizeof *z);
22039 *z = 7;
22040 int volatile *p;
22041 p = &y;
22042 *p = *p + 1;
22043 p = z;
22044 *p = *p + 1;
22045 @end example
22046
22047 Programmers often wish that @code{volatile} meant ``Perform the memory
22048 access here and now, without merging several memory accesses, without
22049 changing the memory word size, and without reordering.'' But the C
22050 standard does not require this. For objects defined with a volatile
22051 type, accesses must be done before the next sequence point; but
22052 otherwise merging, reordering, and word-size change is allowed.
22053
22054 Even when accessing objects defined with a volatile type,
22055 the C standard allows only
22056 extremely limited signal handlers: in C23 the behavior is undefined if a
22057 signal handler refers to any non-local object that is not a lock-free
22058 atomic object and that is not @code{constexpr} (other than by writing to
22059 a @code{sig_atomic_t volatile} object), or calls any standard library
22060 function other than from a small set that includes @code{abort},
22061 @code{_Exit}, @code{quick_exit}, some @code{<stdatomic.h>} functions,
22062 and @code{signal}. Hence C compilers need not worry about a signal
22063 handler disturbing ordinary computation. POSIX allows some additional
22064 behavior in a portable signal handler, but is still quite restrictive.
22065 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
22066 GNU Compiler Collection (GCC)}, for some
22067 restrictions imposed by GCC. @xref{Defining Handlers, ,
22068 Defining Signal Handlers, libc, The GNU C Library}, for some
22069 restrictions imposed by the GNU C library. Restrictions
22070 differ on other platforms.
22071
22072 If possible, it is best to use a signal handler that fits within the
22073 limits imposed by the C and POSIX standards.
22074
22075 If this is not practical, you can try the following rules of thumb. A
22076 signal handler should access only volatile lvalues, preferably lvalues
22077 that refer to objects defined with a volatile type, and should not
22078 assume that the accessed objects have an internally consistent state
22079 if they are larger than a machine word. Furthermore, installers
22080 should employ compilers and compiler options that are commonly used
22081 for building operating system kernels, because kernels often need more
22082 from @code{volatile} than the C Standard requires, and installers who
22083 compile an application in a similar environment can sometimes benefit
22084 from the extra constraints imposed by kernels on compilers.
22085 Admittedly we are hand-waving somewhat here, as there are few
22086 guarantees in this area; the rules of thumb may help to fix some bugs
22087 but there is a good chance that they will not fix them all.
22088
22089 For @code{volatile}, C++ has the same problems that C does.
22090 Multithreaded applications have even more problems with @code{volatile},
22091 but they are beyond the scope of this section.
22092
22093 The bottom line is that using @code{volatile} typically hurts
22094 performance but should not hurt correctness. In some cases its use
22095 does help correctness, but these cases are often so poorly understood
22096 that all too often adding @code{volatile} to a data structure merely
22097 alleviates some symptoms of a bug while not fixing the bug in general.
22098
22099 @node Floating Point Portability
22100 @section Floating Point Portability
22101 @cindex floating point
22102
22103 Almost all modern systems use IEEE-754 floating point, and it is safe to
22104 assume IEEE-754 in most portable code these days. For more information,
22105 please see David Goldberg's classic paper
22106 @uref{https://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
22107 Scientist Should Know About Floating-Point Arithmetic}.
22108
22109 @node Exiting Portably
22110 @section Exiting Portably
22111 @cindex exiting portably
22112
22113 A C or C++ program can exit with status @var{N} by returning
22114 @var{N} from the @code{main} function. Portable programs are supposed
22115 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
22116 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
22117 fail by exiting with status 1, and test programs that assume POSIX can
22118 fail by exiting with status values from 1 through 255.
22119
22120 A program can also exit with status @var{N} by passing @var{N} to the
22121 @code{exit} function, and a program can fail by calling the @code{abort}
22122 function. If a program is specialized to just some platforms, it can fail
22123 by calling functions specific to those platforms, e.g., @code{_exit}
22124 (POSIX). However, like other functions, an exit
22125 function should be declared, typically by including a header. For
22126 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
22127 either directly or via the default includes (@pxref{Default Includes}).
22128
22129 A program can fail due to undefined behavior such as dereferencing a null
22130 pointer, but this is not recommended as undefined behavior allows an
22131 implementation to do whatever it pleases and this includes exiting
22132 successfully.
22133
22134
22135 @c ================================================== Manual Configuration
22136
22137 @node Manual Configuration
22138 @chapter Manual Configuration
22139
22140 A few kinds of features can't be guessed automatically by running test
22141 programs. For example, the details of the object-file format, or
22142 special options that need to be passed to the compiler or linker.
22143 Autoconf provides a uniform method for handling unguessable features,
22144 by giving each operating system a @dfn{canonical system type}, also
22145 known as a @dfn{canonical name} or @dfn{target triplet}.
22146
22147 @prindex @command{config.guess}
22148 @prindex @command{config.sub}
22149
22150 If you use any of the macros described in this chapter, you must
22151 distribute the helper scripts @command{config.guess} and
22152 @command{config.sub} along with your source code. Some Autoconf macros
22153 use these macros internally, so you may need to distribute these scripts
22154 even if you do not use any of these macros yourself. @xref{Input}, for
22155 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
22156 to control in which directory @command{configure} looks for helper
22157 scripts, and where to get the scripts from.
22158
22159 @menu
22160 * Specifying Target Triplets:: Specifying target triplets
22161 * Canonicalizing:: Getting the canonical system type
22162 * Using System Type:: What to do with the system type
22163 @end menu
22164
22165 @node Specifying Target Triplets
22166 @section Specifying target triplets
22167 @cindex System type
22168 @cindex Target triplet
22169 @c This node used to be named Specifying Names. The @anchor allows old
22170 @c links to still work.
22171 @anchor{Specifying Names}
22172
22173 Autoconf-generated
22174 @command{configure} scripts can make decisions based on a canonical name
22175 for the system type, or @dfn{target triplet}, which has the form:
22176 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
22177 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
22178
22179 @command{configure} can usually guess the canonical name for the type of
22180 system it's running on. To do so it runs a script called
22181 @command{config.guess}, which infers the name using the @code{uname}
22182 command or symbols predefined by the C preprocessor.
22183
22184 Alternately, the user can specify the system type with command line
22185 arguments to @command{configure} (@pxref{System Types}. Doing so is
22186 necessary when
22187 cross-compiling. In the most complex case of cross-compiling, three
22188 system types are involved. The options to specify them are:
22189
22190 @table @option
22191 @item --build=@var{build-type}
22192 the type of system on which the package is being configured and
22193 compiled. It defaults to the result of running @command{config.guess}.
22194 Specifying a @var{build-type} that differs from @var{host-type} enables
22195 cross-compilation mode.
22196
22197 @item --host=@var{host-type}
22198 the type of system on which the package runs. By default it is the
22199 same as the build machine. The tools that get used to build and
22200 manipulate binaries will, by default, all be prefixed with
22201 @code{@var{host-type}-}, such as @code{@var{host-type}-gcc},
22202 @code{@var{host-type}-g++}, @code{@var{host-type}-ar}, and
22203 @code{@var{host-type}-nm}. If the binaries produced by these tools can
22204 be executed by the build system, the configure script will make use of
22205 it in @code{AC_RUN_IFELSE} invocations; otherwise, cross-compilation
22206 mode is enabled. Specifying a @var{host-type} that differs
22207 from @var{build-type}, when @var{build-type} was also explicitly
22208 specified, equally enables cross-compilation mode.
22209
22210 @item --target=@var{target-type}
22211 the type of system for which any compiler tools in the package
22212 produce code (rarely needed). By default, it is the same as host.
22213 @end table
22214
22215 If you mean to override the result of @command{config.guess} but
22216 still produce binaries for the build machine, use @option{--build},
22217 not @option{--host}.
22218
22219 So, for example, to produce binaries for 64-bit MinGW, use a command
22220 like this:
22221
22222 @example
22223 ./configure --host=x86_64-w64-mingw64
22224 @end example
22225
22226 If your system has the ability to execute MinGW binaries but you don't
22227 want to make use of this feature and instead prefer cross-compilation
22228 guesses, use a command like this:
22229
22230 @example
22231 ./configure --build=x86_64-pc-linux-gnu --host=x86_64-w64-mingw64
22232 @end example
22233
22234 @noindent
22235 Note that if you do not specify @option{--host}, @command{configure}
22236 fails if it can't run the code generated by the specified compiler. For
22237 example, configuring as follows fails:
22238
22239 @example
22240 ./configure CC=x86_64-w64-mingw64-gcc
22241 @end example
22242
22243 When cross-compiling, @command{configure} will warn about any tools
22244 (compilers, linkers, assemblers) whose name is not prefixed with the
22245 host type. This is an aid to users performing cross-compilation.
22246 Continuing the example above, if a cross-compiler named @command{cc} is
22247 used with a native @command{pkg-config}, then libraries found by
22248 @command{pkg-config} will likely cause subtle build failures; but using
22249 the names @command{x86_64-w64-mingw64-gcc} and
22250 @command{x86_64-w64-mingw64-pkg-config}
22251 avoids any confusion. Avoiding the warning is as simple as creating the
22252 correct symlinks naming the cross tools.
22253
22254 @cindex @command{config.sub}
22255 @command{configure} recognizes short aliases for some system types; for
22256 example, @samp{mingw64} can be used instead of
22257 @samp{x86_64-pc-mingw64}. @command{configure} runs a script called
22258 @command{config.sub} to canonicalize system type aliases.
22259
22260 This section deliberately omits the description of the obsolete
22261 interface; see @ref{Hosts and Cross-Compilation}.
22262
22263
22264 @node Canonicalizing
22265 @section Getting the Canonical System Type
22266 @cindex System type
22267 @cindex Canonical system type
22268
22269 The following macros make the system type available to @command{configure}
22270 scripts.
22271
22272 @ovindex build_alias
22273 @ovindex host_alias
22274 @ovindex target_alias
22275
22276 The variables @samp{build_alias}, @samp{host_alias}, and
22277 @samp{target_alias} are always exactly the arguments of @option{--build},
22278 @option{--host}, and @option{--target}; in particular, they are left empty
22279 if the user did not use them, even if the corresponding
22280 @code{AC_CANONICAL} macro was run. Any configure script may use these
22281 variables anywhere. These are the variables that should be used when in
22282 interaction with the user.
22283
22284 If you need to recognize some special environments based on their system
22285 type, run the following macros to get canonical system names. These
22286 variables are not set before the macro call.
22287
22288 @defmac AC_CANONICAL_BUILD
22289 @acindex{CANONICAL_BUILD}
22290 @ovindex build
22291 @ovindex build_cpu
22292 @ovindex build_vendor
22293 @ovindex build_os
22294 Compute the canonical build-system type variable, @code{build}, and its
22295 three individual parts @code{build_cpu}, @code{build_vendor}, and
22296 @code{build_os}.
22297
22298 If @option{--build} was specified, then @code{build} is the
22299 canonicalization of @code{build_alias} by @command{config.sub},
22300 otherwise it is determined by the shell script @command{config.guess}.
22301 @end defmac
22302
22303 @defmac AC_CANONICAL_HOST
22304 @acindex{CANONICAL_HOST}
22305 @ovindex host
22306 @ovindex host_cpu
22307 @ovindex host_vendor
22308 @ovindex host_os
22309 Compute the canonical host-system type variable, @code{host}, and its
22310 three individual parts @code{host_cpu}, @code{host_vendor}, and
22311 @code{host_os}.
22312
22313 If @option{--host} was specified, then @code{host} is the
22314 canonicalization of @code{host_alias} by @command{config.sub},
22315 otherwise it defaults to @code{build}.
22316 @end defmac
22317
22318 @defmac AC_CANONICAL_TARGET
22319 @acindex{CANONICAL_TARGET}
22320 @ovindex target
22321 @ovindex target_cpu
22322 @ovindex target_vendor
22323 @ovindex target_os
22324 Compute the canonical target-system type variable, @code{target}, and its
22325 three individual parts @code{target_cpu}, @code{target_vendor}, and
22326 @code{target_os}.
22327
22328 If @option{--target} was specified, then @code{target} is the
22329 canonicalization of @code{target_alias} by @command{config.sub},
22330 otherwise it defaults to @code{host}.
22331 @end defmac
22332
22333 Note that there can be artifacts due to the backward compatibility
22334 code. @xref{Hosts and Cross-Compilation}, for more.
22335
22336 @node Using System Type
22337 @section Using the System Type
22338
22339 In @file{configure.ac} the system type is generally used by one or more
22340 @code{case} statements to select system-specifics. Shell wildcards can
22341 be used to match a group of system types.
22342
22343 For example, an extra assembler code object file could be chosen, giving
22344 access to a CPU cycle counter register. @code{$(CYCLE_OBJ)} in the
22345 following would be used in a makefile to add the object to a
22346 program or library.
22347
22348 @example
22349 AS_CASE([$host],
22350 [aarch64*-*-*], [CYCLE_OBJ=pmccntr.o],
22351 [i?86-*-*], [CYCLE_OBJ=rdtsc.o],
22352 [CYCLE_OBJ=""])
22353 AC_SUBST([CYCLE_OBJ])
22354 @end example
22355
22356 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
22357 to select variant source files, for example optimized code for some
22358 CPUs. The configured CPU type doesn't always indicate exact CPU types,
22359 so some runtime capability checks may be necessary too.
22360
22361 @example
22362 AS_CASE([$host],
22363 [aarch64*-*-*], [AC_CONFIG_LINKS([dither.c:aarch64/dither.c])],
22364 [powerpc*-*-*], [AC_CONFIG_LINKS([dither.c:powerpc/dither.c])],
22365 [AC_CONFIG_LINKS([dither.c:generic/dither.c])])
22366 @end example
22367
22368 The host system type can also be used to find cross-compilation tools
22369 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
22370
22371 The above examples all show @samp{$host}, since this is where the code
22372 is going to run. Only rarely is it necessary to test @samp{$build}
22373 (which is where the build is being done).
22374
22375 Whenever you're tempted to use @samp{$host} it's worth considering
22376 whether some sort of probe would be better. New system types come along
22377 periodically or previously missing features are added. Well-written
22378 probes can adapt themselves to such things, but hard-coded lists of
22379 names can't. Here are some guidelines,
22380
22381 @itemize @bullet
22382 @item
22383 Availability of libraries and library functions should always be checked
22384 by probing.
22385 @item
22386 Variant behavior of system calls is best identified with runtime tests
22387 if possible, but bug workarounds or obscure difficulties might have to
22388 be driven from @samp{$host}.
22389 @item
22390 Assembler code is inevitably highly CPU-specific and is best selected
22391 according to @samp{$host_cpu}.
22392 @item
22393 Assembler variations like underscore prefix on globals or ELF versus
22394 COFF type directives are however best determined by probing, perhaps
22395 even examining the compiler output.
22396 @end itemize
22397
22398 @samp{$target} is for use by a package creating a compiler or similar.
22399 For ordinary packages it's meaningless and should not be used. It
22400 indicates what the created compiler should generate code for, if it can
22401 cross-compile. @samp{$target} generally selects various hard-coded CPU
22402 and system conventions, since usually the compiler or tools under
22403 construction themselves determine how the target works.
22404
22405
22406 @c ===================================================== Site Configuration.
22407
22408 @node Site Configuration
22409 @chapter Site Configuration
22410
22411 @command{configure} scripts support several kinds of local configuration
22412 decisions. There are ways for users to specify where external software
22413 packages are, include or exclude optional features, install programs
22414 under modified names, and set default values for @command{configure}
22415 options.
22416
22417 @menu
22418 * Help Formatting:: Customizing @samp{configure --help}
22419 * External Software:: Working with other optional software
22420 * Package Options:: Selecting optional features
22421 * Pretty Help Strings:: Formatting help string
22422 * Option Checking:: Controlling checking of @command{configure} options
22423 * Site Details:: Configuring site details
22424 * Transforming Names:: Changing program names when installing
22425 * Site Defaults:: Giving @command{configure} local defaults
22426 @end menu
22427
22428 @node Help Formatting
22429 @section Controlling Help Output
22430
22431 Users consult @samp{configure --help} to learn of configuration
22432 decisions specific to your package. By default, @command{configure}
22433 breaks this output into sections for each type of option; within each
22434 section, help strings appear in the order @file{configure.ac} defines
22435 them:
22436
22437 @example
22438 Optional Features:
22439 @dots{}
22440 --enable-bar include bar
22441
22442 Optional Packages:
22443 @dots{}
22444 --with-foo use foo
22445 @end example
22446
22447 @defmac AC_PRESERVE_HELP_ORDER
22448 @acindex{PRESERVE_HELP_ORDER}
22449
22450 Request an alternate @option{--help} format, in which options of all
22451 types appear together, in the order defined. Call this macro before any
22452 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
22453
22454 @example
22455 Optional Features and Packages:
22456 @dots{}
22457 --enable-bar include bar
22458 --with-foo use foo
22459 @end example
22460
22461 @end defmac
22462
22463 @node External Software
22464 @section Working With External Software
22465 @cindex External software
22466
22467 Some packages require, or can optionally use, other software packages
22468 that are already installed. The user can give @command{configure}
22469 command line options to specify which such external software to use.
22470 The options have one of these forms:
22471
22472 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22473 @c awful.
22474 @example
22475 --with-@var{package}@r{[}=@var{arg}@r{]}
22476 --without-@var{package}
22477 @end example
22478
22479 For example, @option{--with-gnu-ld} means work with the GNU linker
22480 instead of some other linker. @option{--with-x} means work with The X
22481 Window System.
22482
22483 The user can give an argument by following the package name with
22484 @samp{=} and the argument. Giving an argument of @samp{no} is for
22485 packages that are used by default; it says to @emph{not} use the
22486 package. An argument that is neither @samp{yes} nor @samp{no} could
22487 include a name or number of a version of the other package, to specify
22488 more precisely which other package this program is supposed to work
22489 with. If no argument is given, it defaults to @samp{yes}.
22490 @option{--without-@var{package}} is equivalent to
22491 @option{--with-@var{package}=no}.
22492
22493 Normally @command{configure} scripts complain about
22494 @option{--with-@var{package}} options that they do not support.
22495 @xref{Option Checking}, for details, and for how to override the
22496 defaults.
22497
22498 For each external software package that may be used, @file{configure.ac}
22499 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
22500 user asked to use it. Whether each package is used or not by default,
22501 and which arguments are valid, is up to you.
22502
22503 @anchor{AC_ARG_WITH}
22504 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
22505 @ovar{action-if-given}, @ovar{action-if-not-given})
22506 @acindex{ARG_WITH}
22507 If the user gave @command{configure} the option @option{--with-@var{package}}
22508 or @option{--without-@var{package}}, run shell commands
22509 @var{action-if-given}. If neither option was given, run shell commands
22510 @var{action-if-not-given}. The name @var{package} indicates another
22511 software package that this program should work with. It should consist
22512 only of alphanumeric characters, dashes, plus signs, and dots.
22513
22514 The option's argument is available to the shell commands
22515 @var{action-if-given} in the shell variable @code{withval}, which is
22516 actually just the value of the shell variable named
22517 @code{with_@var{package}}, with any non-alphanumeric characters in
22518 @var{package} changed into @samp{_}. You may use that variable instead,
22519 if you wish.
22520
22521 Note that @var{action-if-not-given} is not expanded until the point that
22522 @code{AC_ARG_WITH} was expanded. If you need the value of
22523 @code{with_@var{package}} set to a default value by the time argument
22524 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22525 diversion (@pxref{m4_divert_text}) (if done as an argument to
22526 @code{AC_ARG_WITH}, also provide non-diverted text to avoid a shell
22527 syntax error).
22528
22529 The argument @var{help-string} is a description of the option that
22530 looks like this:
22531 @example
22532 --with-readline support fancy command line editing
22533 @end example
22534
22535 @noindent
22536 @var{help-string} may be more than one line long, if more detail is
22537 needed. Just make sure the columns line up in @samp{configure
22538 --help}. Avoid tabs in the help string. The easiest way to provide the
22539 proper leading whitespace is to format your @var{help-string} with the macro
22540 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22541
22542 The following example shows how to use the @code{AC_ARG_WITH} macro in
22543 a common situation. You want to let the user decide whether to enable
22544 support for an external library (e.g., the readline library); if the user
22545 specified neither @option{--with-readline} nor @option{--without-readline},
22546 you want to enable support for readline only if the library is available
22547 on the system.
22548
22549 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22550 @example
22551 AC_ARG_WITH([readline],
22552 [AS_HELP_STRING([--with-readline],
22553 [support fancy command line editing @@<:@@default=check@@:>@@])],
22554 [],
22555 [: m4_divert_text([DEFAULTS], [with_readline=check])])
22556
22557 LIBREADLINE=
22558 AS_IF([test "x$with_readline" != xno],
22559 [AC_CHECK_LIB([readline], [main],
22560 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22561 AC_DEFINE([HAVE_LIBREADLINE], [1],
22562 [Define if you have libreadline])
22563 ],
22564 [if test "x$with_readline" != xcheck; then
22565 AC_MSG_FAILURE(
22566 [--with-readline was given, but test for readline failed])
22567 fi
22568 ], -lncurses)])
22569 @end example
22570
22571 The next example shows how to use @code{AC_ARG_WITH} to give the user the
22572 possibility to enable support for the readline library, in case it is still
22573 experimental and not well tested, and is therefore disabled by default.
22574
22575 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22576 @example
22577 AC_ARG_WITH([readline],
22578 [AS_HELP_STRING([--with-readline],
22579 [enable experimental support for readline])],
22580 [],
22581 [with_readline=no])
22582
22583 LIBREADLINE=
22584 AS_IF([test "x$with_readline" != xno],
22585 [AC_CHECK_LIB([readline], [main],
22586 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22587 AC_DEFINE([HAVE_LIBREADLINE], [1],
22588 [Define if you have libreadline])
22589 ],
22590 [AC_MSG_FAILURE(
22591 [--with-readline was given, but test for readline failed])],
22592 [-lncurses])])
22593 @end example
22594
22595 The last example shows how to use @code{AC_ARG_WITH} to give the user the
22596 possibility to disable support for the readline library, given that it is
22597 an important feature and that it should be enabled by default.
22598
22599 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22600 @example
22601 AC_ARG_WITH([readline],
22602 [AS_HELP_STRING([--without-readline],
22603 [disable support for readline])],
22604 [],
22605 [with_readline=yes])
22606
22607 LIBREADLINE=
22608 AS_IF([test "x$with_readline" != xno],
22609 [AC_CHECK_LIB([readline], [main],
22610 [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22611 AC_DEFINE([HAVE_LIBREADLINE], [1],
22612 [Define if you have libreadline])
22613 ],
22614 [AC_MSG_FAILURE(
22615 [readline test failed (--without-readline to disable)])],
22616 [-lncurses])])
22617 @end example
22618
22619 These three examples can be easily adapted to the case where
22620 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
22621 @ref{Package Options}).
22622 @end defmac
22623
22624 @node Package Options
22625 @section Choosing Package Options
22626 @cindex Package options
22627 @cindex Options, package
22628
22629 If a software package has optional compile-time features, the user can
22630 give @command{configure} command line options to specify whether to
22631 compile them. The options have one of these forms:
22632
22633 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22634 @c awful.
22635 @example
22636 --enable-@var{feature}@r{[}=@var{arg}@r{]}
22637 --disable-@var{feature}
22638 @end example
22639
22640 These options allow users to choose which optional features to build and
22641 install. @option{--enable-@var{feature}} options should never make a
22642 feature behave differently or cause one feature to replace another.
22643 They should only cause parts of the program to be built rather than left
22644 out.
22645
22646 The user can give an argument by following the feature name with
22647 @samp{=} and the argument. Giving an argument of @samp{no} requests
22648 that the feature @emph{not} be made available. A feature with an
22649 argument looks like @option{--enable-debug=stabs}. If no argument is
22650 given, it defaults to @samp{yes}. @option{--disable-@var{feature}} is
22651 equivalent to @option{--enable-@var{feature}=no}.
22652
22653 Normally @command{configure} scripts complain about
22654 @option{--enable-@var{package}} options that they do not support.
22655 @xref{Option Checking}, for details, and for how to override the
22656 defaults.
22657
22658 For each optional feature, @file{configure.ac} should call
22659 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
22660 to include it. Whether each feature is included or not by default, and
22661 which arguments are valid, is up to you.
22662
22663 @anchor{AC_ARG_ENABLE}
22664 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
22665 @ovar{action-if-given}, @ovar{action-if-not-given})
22666 @acindex{ARG_ENABLE}
22667 If the user gave @command{configure} the option
22668 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
22669 shell commands @var{action-if-given}. If neither option was given, run
22670 shell commands @var{action-if-not-given}. The name @var{feature}
22671 indicates an optional user-level facility. It should consist only of
22672 alphanumeric characters, dashes, plus signs, and dots.
22673
22674 The option's argument is available to the shell commands
22675 @var{action-if-given} in the shell variable @code{enableval}, which is
22676 actually just the value of the shell variable named
22677 @code{enable_@var{feature}}, with any non-alphanumeric characters in
22678 @var{feature} changed into @samp{_}. You may use that variable instead,
22679 if you wish. The @var{help-string} argument is like that of
22680 @code{AC_ARG_WITH} (@pxref{External Software}).
22681
22682 Note that @var{action-if-not-given} is not expanded until the point that
22683 @code{AC_ARG_ENABLE} was expanded. If you need the value of
22684 @code{enable_@var{feature}} set to a default value by the time argument
22685 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22686 diversion (@pxref{m4_divert_text}) (if done as an argument to
22687 @code{AC_ARG_ENABLE}, also provide non-diverted text to avoid a shell
22688 syntax error).
22689
22690 You should format your @var{help-string} with the macro
22691 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22692
22693 See the examples suggested with the definition of @code{AC_ARG_WITH}
22694 (@pxref{External Software}) to get an idea of possible applications of
22695 @code{AC_ARG_ENABLE}.
22696 @end defmac
22697
22698 @node Pretty Help Strings
22699 @section Making Your Help Strings Look Pretty
22700 @cindex Help strings
22701
22702 Properly formatting the @samp{help strings} which are used in
22703 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
22704 (@pxref{Package Options}) can be challenging. Specifically, you want
22705 your own @samp{help strings} to line up in the appropriate columns of
22706 @samp{configure --help} just like the standard Autoconf @samp{help
22707 strings} do. This is the purpose of the @code{AS_HELP_STRING} macro.
22708
22709 @anchor{AS_HELP_STRING}
22710 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
22711 @dvar{indent-column, 26}, @dvar{wrap-column, 79})
22712 @asindex{HELP_STRING}
22713
22714 Expands into a help string that looks pretty when the user executes
22715 @samp{configure --help}. It is typically used in @code{AC_ARG_WITH}
22716 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
22717 Options}). The following example makes this clearer.
22718
22719 @example
22720 AC_ARG_WITH([foo],
22721 [AS_HELP_STRING([--with-foo],
22722 [use foo (default is no)])],
22723 [use_foo=$withval],
22724 [use_foo=no])
22725 @end example
22726
22727 Then the last few lines of @samp{configure --help} appear like
22728 this:
22729
22730 @example
22731 --enable and --with options recognized:
22732 --with-foo use foo (default is no)
22733 @end example
22734
22735 Macro expansion is performed on the first argument. However, the second
22736 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
22737 list of text to be reformatted, and is not subject to macro expansion.
22738 Since it is not expanded, it should not be double quoted.
22739 @xref{Autoconf Language}, for a more detailed explanation.
22740
22741 The @code{AS_HELP_STRING} macro is particularly helpful when the
22742 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
22743 arguments, as shown in the following example. Be aware that
22744 @var{left-hand-side} may not expand to unbalanced quotes,
22745 although quadrigraphs can be used.
22746
22747 @example
22748 AC_DEFUN([MY_ARG_WITH],
22749 [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
22750 [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
22751 [use $1 (default is $2)])],
22752 [use_[]$1=$withval],
22753 [use_[]$1=$2])])
22754 MY_ARG_WITH([a_b], [no])
22755 @end example
22756 @noindent
22757 Here, the last few lines of @samp{configure --help} will include:
22758
22759 @example
22760 --enable and --with options recognized:
22761 --with-a-b use a_b (default is no)
22762 @end example
22763
22764 The parameters @var{indent-column} and @var{wrap-column} were introduced
22765 in Autoconf 2.62. Generally, they should not be specified; they exist
22766 for fine-tuning of the wrapping.
22767 @example
22768 AS_HELP_STRING([--option], [description of option])
22769 @result{} --option description of option
22770 AS_HELP_STRING([--option], [description of option], [15], [30])
22771 @result{} --option description of
22772 @result{} option
22773 @end example
22774 @end defmac
22775
22776
22777 @node Option Checking
22778 @section Controlling Checking of @command{configure} Options
22779 @cindex Options, Package
22780
22781 The @command{configure} script checks its command-line options against a
22782 list of known options, like @option{--help} or @option{--config-cache}.
22783 An unknown option ordinarily indicates a mistake by the user and
22784 @command{configure} halts with an error. However, by default unknown
22785 @option{--with-@var{package}} and @option{--enable-@var{feature}}
22786 options elicit only a warning, to support configuring entire source
22787 trees.
22788
22789 Source trees often contain multiple packages with a top-level
22790 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
22791 (@pxref{Subdirectories}). Because the packages generally support
22792 different @option{--with-@var{package}} and
22793 @option{--enable-@var{feature}} options, the GNU Coding
22794 Standards say they must accept unrecognized options without halting.
22795 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
22796 automatically disables the warnings.
22797
22798 This default behavior may be modified in two ways. First, the installer
22799 can invoke @code{configure --disable-option-checking} to disable
22800 these warnings, or invoke @code{configure --enable-option-checking=fatal}
22801 options to turn them into fatal errors, respectively. Second, the
22802 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
22803
22804 @defmac AC_DISABLE_OPTION_CHECKING
22805 @acindex{DISABLE_OPTION_CHECKING}
22806
22807 By default, disable warnings related to any unrecognized
22808 @option{--with-@var{package}} or @option{--enable-@var{feature}}
22809 options. This is implied by @code{AC_CONFIG_SUBDIRS}.
22810
22811 The installer can override this behavior by passing
22812 @option{--enable-option-checking} (enable warnings) or
22813 @option{--enable-option-checking=fatal} (enable errors) to
22814 @command{configure}.
22815 @end defmac
22816
22817
22818 @node Site Details
22819 @section Configuring Site Details
22820 @cindex Site details
22821
22822 Some software packages require complex site-specific information. Some
22823 examples are host names to use for certain services, company names, and
22824 email addresses to contact. Since some configuration scripts generated
22825 by Metaconfig ask for such information interactively, people sometimes
22826 wonder how to get that information in Autoconf-generated configuration
22827 scripts, which aren't interactive.
22828
22829 Such site configuration information should be put in a file that is
22830 edited @emph{only by users}, not by programs. The location of the file
22831 can either be based on the @code{prefix} variable, or be a standard
22832 location such as the user's home directory. It could even be specified
22833 by an environment variable. The programs should examine that file at
22834 runtime, rather than at compile time. Runtime configuration is more
22835 convenient for users and makes the configuration process simpler than
22836 getting the information while configuring. @xref{Directory Variables, ,
22837 Variables for Installation Directories, standards, The GNU Coding
22838 Standards}, for more information on where to put data files.
22839
22840 @node Transforming Names
22841 @section Transforming Program Names When Installing
22842 @cindex Transforming program names
22843 @cindex Program names, transforming
22844
22845 Autoconf supports changing the names of programs when installing them.
22846 In order to use these transformations, @file{configure.ac} must call the
22847 macro @code{AC_ARG_PROGRAM}.
22848
22849 @defmac AC_ARG_PROGRAM
22850 @acindex{ARG_PROGRAM}
22851 @ovindex program_transform_name
22852 Place in output variable @code{program_transform_name} a sequence of
22853 @code{sed} commands for changing the names of installed programs.
22854
22855 If any of the options described below are given to @command{configure},
22856 program names are transformed accordingly. Otherwise, if
22857 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
22858 is given, the target type followed by a dash is used as a prefix.
22859 Otherwise, no program name transformation is done.
22860 @end defmac
22861
22862 @menu
22863 * Transformation Options:: @command{configure} options to transform names
22864 * Transformation Examples:: Sample uses of transforming names
22865 * Transformation Rules:: Makefile uses of transforming names
22866 @end menu
22867
22868 @node Transformation Options
22869 @subsection Transformation Options
22870
22871 You can specify name transformations by giving @command{configure} these
22872 command line options:
22873
22874 @table @option
22875 @item --program-prefix=@var{prefix}
22876 prepend @var{prefix} to the names;
22877
22878 @item --program-suffix=@var{suffix}
22879 append @var{suffix} to the names;
22880
22881 @item --program-transform-name=@var{expression}
22882 perform @code{sed} substitution @var{expression} on the names.
22883 @end table
22884
22885 @node Transformation Examples
22886 @subsection Transformation Examples
22887
22888 These transformations are useful with programs that can be part of a
22889 cross-compilation development environment. For example, a
22890 cross-assembler running on x86-64 configured with
22891 @option{--target=aarch64-linux-gnu} is normally installed as
22892 @file{aarch64-linux-gnu-as}, rather than @file{as}, which could be confused
22893 with a native x86-64 assembler.
22894
22895 You can force a program name to begin with @file{g}, if you don't want
22896 GNU programs installed on your system to shadow other programs with
22897 the same name. For example, if you configure GNU @code{diff} with
22898 @option{--program-prefix=g}, then when you run @samp{make install} it is
22899 installed as @file{/usr/local/bin/gdiff}.
22900
22901 As a more sophisticated example, you could use
22902
22903 @example
22904 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
22905 @end example
22906 @noindent
22907
22908 to prepend @samp{g} to most of the program names in a source tree,
22909 excepting those like @code{gdb} that already have one and those like
22910 @code{less} and @code{lesskey} that aren't GNU programs. (That is
22911 assuming that you have a source tree containing those programs that is
22912 set up to use this feature.)
22913
22914 One way to install multiple versions of some programs simultaneously is
22915 to append a version number to the name of one or both. For example, if
22916 you want to keep Autoconf version 1 around for awhile, you can configure
22917 Autoconf version 2 using @option{--program-suffix=2} to install the
22918 programs as @file{/usr/local/bin/autoconf2},
22919 @file{/usr/local/bin/autoheader2}, etc. Nevertheless, pay attention
22920 that only the binaries are renamed, therefore you'd have problems with
22921 the library files which might overlap.
22922
22923 @node Transformation Rules
22924 @subsection Transformation Rules
22925
22926 Here is how to use the variable @code{program_transform_name} in a
22927 @file{Makefile.in}:
22928
22929 @example
22930 PROGRAMS = cp ls rm
22931 transform = @@program_transform_name@@
22932 install:
22933 for p in $(PROGRAMS); do \
22934 $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
22935 sed '$(transform)'`; \
22936 done
22937
22938 uninstall:
22939 for p in $(PROGRAMS); do \
22940 rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
22941 @c $$ restore font-lock
22942 done
22943 @end example
22944
22945 It is guaranteed that @code{program_transform_name} is never empty, and
22946 that there are no useless separators. Therefore you may safely embed
22947 @code{program_transform_name} within a sed program using @samp{;}:
22948
22949 @example
22950 transform = @@program_transform_name@@
22951 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
22952 @end example
22953
22954 Whether to do the transformations on documentation files (Texinfo or
22955 @code{man}) is a tricky question; there seems to be no perfect answer,
22956 due to the several reasons for name transforming. Documentation is not
22957 usually particular to a specific architecture, and Texinfo files do not
22958 conflict with system documentation. But they might conflict with
22959 earlier versions of the same files, and @code{man} pages sometimes do
22960 conflict with system documentation. As a compromise, it is probably
22961 best to do name transformations on @code{man} pages but not on Texinfo
22962 manuals.
22963
22964 @node Site Defaults
22965 @section Setting Site Defaults
22966 @cindex Site defaults
22967 @cindex config.site
22968
22969 Autoconf-generated @command{configure} scripts allow your site to provide
22970 default values for some configuration values. You do this by creating
22971 site- and system-wide initialization files.
22972
22973 @evindex CONFIG_SITE
22974 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
22975 uses its value as a space-separated list of shell scripts to read;
22976 it is recommended that these be absolute file names. Otherwise, it
22977 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
22978 then @file{@var{prefix}/etc/config.site} if it exists. Thus,
22979 settings in machine-specific files override those in machine-independent
22980 ones in case of conflict.
22981
22982 Site files can be arbitrary shell scripts, but only certain kinds of
22983 code are really appropriate to be in them. Because @command{configure}
22984 reads any cache file after it has read any site files, a site file can
22985 define a default cache file to be shared between all Autoconf-generated
22986 @command{configure} scripts run on that system (@pxref{Cache Files}). If
22987 you set a default cache file in a site file, it is a good idea to also
22988 set the output variable @code{CC} in that site file, because the cache
22989 file is only valid for a particular compiler, but many systems have
22990 several available.
22991
22992 You can examine or override the value set by a command line option to
22993 @command{configure} in a site file; options set shell variables that have
22994 the same names as the options, with any dashes turned into underscores.
22995 The exceptions are that @option{--without-} and @option{--disable-} options
22996 are like giving the corresponding @option{--with-} or @option{--enable-}
22997 option and the value @samp{no}. Thus, @option{--cache-file=localcache}
22998 sets the variable @code{cache_file} to the value @samp{localcache};
22999 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
23000 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
23001 variable @code{prefix} to the value @samp{/usr}; etc.
23002
23003 Site files are also good places to set default values for other output
23004 variables, such as @code{CFLAGS}, if you need to give them non-default
23005 values: anything you would normally do, repetitively, on the command
23006 line. If you use non-default values for @var{prefix} or
23007 @var{exec_prefix} (wherever you locate the site file), you can set them
23008 in the site file if you specify it with the @code{CONFIG_SITE}
23009 environment variable.
23010
23011 You can set some cache values in the site file itself. Doing this is
23012 useful if you are cross-compiling, where it is impossible to check features
23013 that require running a test program. You could ``prime the cache'' by
23014 setting those values correctly for that system in
23015 @file{@var{prefix}/etc/config.site}. To find out the names of the cache
23016 variables you need to set, see the documentation of the respective
23017 Autoconf macro. If the variables or their semantics are undocumented,
23018 you may need to look for shell variables with @samp{_cv_} in their names
23019 in the affected @command{configure} scripts, or in the Autoconf M4
23020 source code for those macros; but in that case, their name or semantics
23021 may change in a future Autoconf version.
23022
23023 The cache file is careful to not override any variables set in the site
23024 files. Similarly, you should not override command-line options in the
23025 site files. Your code should check that variables such as @code{prefix}
23026 and @code{cache_file} have their default values (as set near the top of
23027 @command{configure}) before changing them.
23028
23029 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}. The
23030 command @samp{configure --prefix=/usr/share/local/gnu} would read this
23031 file (if @code{CONFIG_SITE} is not set to a different file).
23032
23033 @example
23034 # /usr/share/local/gnu/share/config.site for configure
23035 #
23036 # Change some defaults.
23037 test "$prefix" = NONE && prefix=/usr/share/local/gnu
23038 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
23039 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
23040 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
23041 test "$runstatedir" = '$@{localstatedir@}/run' && runstatedir=/run
23042
23043 # Give Autoconf 2.x generated configure scripts a shared default
23044 # cache file for feature test results, architecture-specific.
23045 if test "$cache_file" = /dev/null; then
23046 cache_file="$prefix/var/config.cache"
23047 # A cache file is only valid for one C compiler.
23048 CC=gcc
23049 fi
23050 @end example
23051
23052 @c Leave this use of "File system" rendered as one word, but
23053 @c slightly obfuscated so as not to trigger the syntax-check prohibition.
23054 @cindex File@/system Hierarchy Standard
23055 @cindex FHS
23056
23057 Another use of @file{config.site} is for priming the directory variables
23058 @c "File system", but slightly obfuscated, as above.
23059 in a manner consistent with the File@/system Hierarchy Standard
23060 (FHS). Once the following file is installed at
23061 @file{/usr/share/config.site}, a user can execute simply
23062 @code{./configure --prefix=/usr} to get all the directories chosen in
23063 the locations recommended by FHS.
23064
23065 @example
23066 # /usr/share/config.site for FHS defaults when installing below /usr,
23067 # and the respective settings were not changed on the command line.
23068 if test "$prefix" = /usr; then
23069 test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
23070 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
23071 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
23072 fi
23073 @end example
23074
23075 @cindex @file{lib64}
23076 @cindex 64-bit libraries
23077 Likewise, on platforms where 64-bit libraries are built by default, then
23078 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
23079 it is appropriate to install @file{/usr/local/@/share/config.site}:
23080
23081 @example
23082 # /usr/local/share/config.site for platforms that prefer
23083 # the directory /usr/local/lib64 over /usr/local/lib.
23084 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
23085 @end example
23086
23087
23088 @c ============================================== Running configure Scripts.
23089
23090 @node Running configure Scripts
23091 @chapter Running @command{configure} Scripts
23092 @cindex @command{configure}
23093
23094 Below are instructions on how to configure a package that uses a
23095 @command{configure} script, suitable for inclusion as an @file{INSTALL}
23096 file in the package. A plain-text version of @file{INSTALL} which you
23097 may use comes with Autoconf.
23098
23099 @menu
23100 * Basic Installation:: Instructions for typical cases
23101 * Installation Prerequisites:: What you need to install
23102 * Compilers and Options:: Selecting compilers and optimization
23103 * Multiple Architectures:: Compiling for multiple architectures at once
23104 * Installation Names:: Installing in different directories
23105 * Optional Features:: Selecting optional features
23106 * System Types:: Specifying a system type
23107 * Sharing Defaults:: Setting site-wide defaults for @command{configure}
23108 * Defining Variables:: Specifying the compiler etc.
23109 * configure Invocation:: Changing how @command{configure} runs
23110 @end menu
23111
23112 @set autoconf
23113 @include install.texi
23114
23115
23116 @c ============================================== config.status Invocation
23117
23118 @node config.status Invocation
23119 @chapter config.status Invocation
23120 @cindex @command{config.status}
23121
23122 The @command{configure} script creates a file named @file{config.status},
23123 which actually configures, @dfn{instantiates}, the template files. It
23124 also records the configuration options that were specified when the
23125 package was last configured in case reconfiguring is needed.
23126
23127 Synopsis:
23128 @example
23129 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
23130 @end example
23131
23132 It configures each @var{tag}; if none are specified, all the templates
23133 are instantiated. A @var{tag} refers to a file or other tag associated
23134 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
23135 macro (@pxref{Configuration Actions}). The files must be specified
23136 without their dependencies, as in
23137
23138 @example
23139 ./config.status foobar
23140 @end example
23141
23142 @noindent
23143 not
23144
23145 @example
23146 ./config.status foobar:foo.in:bar.in
23147 @end example
23148
23149 The supported options are:
23150
23151 @table @option
23152 @item --help
23153 @itemx -h
23154 Print a summary of the command line options, the list of the template
23155 files, and exit.
23156
23157 @item --version
23158 @itemx -V
23159 Print the version number of Autoconf and the configuration settings,
23160 and exit.
23161
23162 @item --config
23163 Print the configuration settings in reusable way, quoted for the shell,
23164 and exit. For example, for a debugging build that otherwise reuses the
23165 configuration from a different build directory @var{build-dir} of a
23166 package in @var{src-dir}, you could use the following:
23167
23168 @example
23169 args=`@var{build-dir}/config.status --config`
23170 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
23171 @end example
23172
23173 @noindent
23174 Note that it may be necessary to override a @option{--srcdir} setting
23175 that was saved in the configuration, if the arguments are used in a
23176 different build directory.
23177
23178 @item --silent
23179 @itemx --quiet
23180 @itemx -q
23181 Do not print progress messages.
23182
23183 @item --debug
23184 @itemx -d
23185 Don't remove the temporary files.
23186
23187 @item --file=@var{file}[:@var{template}]
23188 Require that @var{file} be instantiated as if
23189 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used. Both
23190 @var{file} and @var{template} may be @samp{-} in which case the standard
23191 output and/or standard input, respectively, is used. If a
23192 @var{template} file name is relative, it is first looked for in the build
23193 tree, and then in the source tree. @xref{Configuration Actions}, for
23194 more details.
23195
23196 This option and the following ones provide one way for separately
23197 distributed packages to share the values computed by @command{configure}.
23198 Doing so can be useful if some of the packages need a superset of the
23199 features that one of them, perhaps a common library, does. These
23200 options allow a @file{config.status} file to create files other than the
23201 ones that its @file{configure.ac} specifies, so it can be used for a
23202 different package, or for extracting a subset of values. For example,
23203
23204 @example
23205 echo '@@CC@@' | ./config.status --file=-
23206 @end example
23207
23208 @noindent
23209 provides the value of @code{@@CC@@} on standard output.
23210
23211 @item --header=@var{file}[:@var{template}]
23212 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
23213
23214 @item --recheck
23215 Ask @file{config.status} to update itself and exit (no instantiation).
23216 This option is useful if you change @command{configure}, so that the
23217 results of some tests might be different from the previous run. The
23218 @option{--recheck} option reruns @command{configure} with the same arguments
23219 you used before, plus the @option{--no-create} option, which prevents
23220 @command{configure} from running @file{config.status} and creating
23221 @file{Makefile} and other files, and the @option{--no-recursion} option,
23222 which prevents @command{configure} from running other @command{configure}
23223 scripts in subdirectories. (This is so other Make rules can
23224 run @file{config.status} when it changes; @pxref{Automatic Remaking},
23225 for an example).
23226 @end table
23227
23228 @file{config.status} checks several optional environment variables that
23229 can alter its behavior:
23230
23231 @anchor{CONFIG_SHELL}
23232 @defvar CONFIG_SHELL
23233 @evindex CONFIG_SHELL
23234 The shell with which to run @command{configure}. It must be
23235 Bourne-compatible, and the absolute name of the shell should be passed.
23236 The default is a shell that supports @code{LINENO} if available, and
23237 @file{/bin/sh} otherwise.
23238 @end defvar
23239
23240 @defvar CONFIG_STATUS
23241 @evindex CONFIG_STATUS
23242 The file name to use for the shell script that records the
23243 configuration. The default is @file{./config.status}. This variable is
23244 useful when one package uses parts of another and the @command{configure}
23245 scripts shouldn't be merged because they are maintained separately.
23246 @end defvar
23247
23248 You can use @file{./config.status} in your makefiles. For example, in
23249 the dependencies given above (@pxref{Automatic Remaking}),
23250 @file{config.status} is run twice when @file{configure.ac} has changed.
23251 If that bothers you, you can make each run only regenerate the files for
23252 that rule:
23253 @example
23254 @group
23255 config.h: stamp-h
23256 stamp-h: config.h.in config.status
23257 ./config.status config.h
23258 echo > stamp-h
23259
23260 Makefile: Makefile.in config.status
23261 ./config.status Makefile
23262 @end group
23263 @end example
23264
23265 The calling convention of @file{config.status} has changed; see
23266 @ref{Obsolete config.status Use}, for details.
23267
23268
23269 @c =================================================== Obsolete Constructs
23270
23271 @node Obsolete Constructs
23272 @chapter Obsolete Constructs
23273 @cindex Obsolete constructs
23274
23275 Autoconf changes, and throughout the years some constructs have been
23276 obsoleted. Most of the changes involve the macros, but in some cases
23277 the tools themselves, or even some concepts, are now considered
23278 obsolete.
23279
23280 You may completely skip this chapter if you are new to Autoconf. Its
23281 intention is mainly to help maintainers updating their packages by
23282 understanding how to move to more modern constructs.
23283
23284 @menu
23285 * Obsolete config.status Use:: Obsolete convention for @command{config.status}
23286 * acconfig Header:: Additional entries in @file{config.h.in}
23287 * autoupdate Invocation:: Automatic update of @file{configure.ac}
23288 * Obsolete Macros:: Backward compatibility macros
23289 * Autoconf 1:: Tips for upgrading your files
23290 * Autoconf 2.13:: Some fresher tips
23291 @end menu
23292
23293 @node Obsolete config.status Use
23294 @section Obsolete @file{config.status} Invocation
23295
23296 @file{config.status} now supports arguments to specify the files to
23297 instantiate; see @ref{config.status Invocation}, for more details.
23298 Before, environment variables had to be used.
23299
23300 @defvar CONFIG_COMMANDS
23301 @evindex CONFIG_COMMANDS
23302 The tags of the commands to execute. The default is the arguments given
23303 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
23304 @file{configure.ac}.
23305 @end defvar
23306
23307 @defvar CONFIG_FILES
23308 @evindex CONFIG_FILES
23309 The files in which to perform @samp{@@@var{variable}@@} substitutions.
23310 The default is the arguments given to @code{AC_OUTPUT} and
23311 @code{AC_CONFIG_FILES} in @file{configure.ac}.
23312 @end defvar
23313
23314 @defvar CONFIG_HEADERS
23315 @evindex CONFIG_HEADERS
23316 The files in which to substitute C @code{#define} statements. The
23317 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
23318 macro was not called, @file{config.status} ignores this variable.
23319 @end defvar
23320
23321 @defvar CONFIG_LINKS
23322 @evindex CONFIG_LINKS
23323 The symbolic links to establish. The default is the arguments given to
23324 @code{AC_CONFIG_LINKS}; if that macro was not called,
23325 @file{config.status} ignores this variable.
23326 @end defvar
23327
23328 In @ref{config.status Invocation}, using this old interface, the example
23329 would be:
23330
23331 @example
23332 @group
23333 config.h: stamp-h
23334 stamp-h: config.h.in config.status
23335 CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
23336 CONFIG_HEADERS=config.h ./config.status
23337 echo > stamp-h
23338
23339 Makefile: Makefile.in config.status
23340 CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
23341 CONFIG_FILES=Makefile ./config.status
23342 @end group
23343 @end example
23344
23345 @noindent
23346 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
23347 no need to set @code{CONFIG_HEADERS} in the @command{make} rules. Equally
23348 for @code{CONFIG_COMMANDS}, etc.)
23349
23350
23351 @node acconfig Header
23352 @section @file{acconfig.h}
23353
23354 @cindex @file{acconfig.h}
23355 @cindex @file{config.h.top}
23356 @cindex @file{config.h.bot}
23357
23358 In order to produce @file{config.h.in}, @command{autoheader} needs to
23359 build or to find templates for each symbol. Modern releases of Autoconf
23360 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
23361 Macros}), but in older releases a file, @file{acconfig.h}, contained the
23362 list of needed templates. @command{autoheader} copied comments and
23363 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
23364 the current directory, if present. This file used to be mandatory if
23365 you @code{AC_DEFINE} any additional symbols.
23366
23367 Modern releases of Autoconf also provide @code{AH_TOP} and
23368 @code{AH_BOTTOM} if you need to prepend/append some information to
23369 @file{config.h.in}. Ancient versions of Autoconf had a similar feature:
23370 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
23371 @command{autoheader} copies the lines before the line containing
23372 @samp{@@TOP@@} into the top of the file that it generates. Similarly,
23373 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
23374 @command{autoheader} copies the lines after that line to the end of the
23375 file it generates. Either or both of those strings may be omitted. An
23376 even older alternate way to produce the same effect in ancient versions
23377 of Autoconf is to create the files @file{@var{file}.top} (typically
23378 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
23379 directory. If they exist, @command{autoheader} copies them to the
23380 beginning and end, respectively, of its output.
23381
23382 In former versions of Autoconf, the files used in preparing a software
23383 package for distribution were:
23384 @example
23385 @group
23386 configure.ac --. .------> autoconf* -----> configure
23387 +---+
23388 [aclocal.m4] --+ `---.
23389 [acsite.m4] ---' |
23390 +--> [autoheader*] -> [config.h.in]
23391 [acconfig.h] ----. |
23392 +-----'
23393 [config.h.top] --+
23394 [config.h.bot] --'
23395 @end group
23396 @end example
23397
23398 Using only the @code{AH_} macros, @file{configure.ac} should be
23399 self-contained, and should not depend upon @file{acconfig.h} etc.
23400
23401
23402 @node autoupdate Invocation
23403 @section Using @command{autoupdate} to Modernize @file{configure.ac}
23404 @cindex @command{autoupdate}
23405
23406 The @command{autoupdate} program updates a @file{configure.ac} file that
23407 calls Autoconf macros by their old names to use the current macro names.
23408 In version 2 of Autoconf, most of the macros were renamed to use a more
23409 uniform and descriptive naming scheme. @xref{Macro Names}, for a
23410 description of the new scheme. Although the old names still work
23411 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
23412 new names), you can make your @file{configure.ac} files more readable
23413 and make it easier to use the current Autoconf documentation if you
23414 update them to use the new macro names.
23415
23416 @evindex SIMPLE_BACKUP_SUFFIX
23417 If given no arguments, @command{autoupdate} updates @file{configure.ac},
23418 backing up the original version with the suffix @file{~} (or the value
23419 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
23420 set). If you give @command{autoupdate} an argument, it reads that file
23421 instead of @file{configure.ac} and writes the updated file to the
23422 standard output.
23423
23424 @noindent
23425 @command{autoupdate} accepts the following options:
23426
23427 @table @option
23428 @item --help
23429 @itemx -h
23430 Print a summary of the command line options and exit.
23431
23432 @item --version
23433 @itemx -V
23434 Print the version number of Autoconf and exit.
23435
23436 @item --verbose
23437 @itemx -v
23438 Report processing steps.
23439
23440 @item --debug
23441 @itemx -d
23442 Don't remove the temporary files.
23443
23444 @item --force
23445 @itemx -f
23446 Force the update even if the file has not changed. Disregard the cache.
23447
23448 @item --include=@var{dir}
23449 @itemx -I @var{dir}
23450 Also look for input files in @var{dir}. Multiple invocations accumulate.
23451 Directories are browsed from last to first.
23452
23453 @item --prepend-include=@var{dir}
23454 @itemx -B @var{dir}
23455 Prepend directory @var{dir} to the search path. This is used to include
23456 the language-specific files before any third-party macros.
23457 @end table
23458
23459 @node Obsolete Macros
23460 @section Obsolete Macros
23461
23462 Several macros are obsoleted in Autoconf, for various reasons (typically
23463 they failed to quote properly, couldn't be extended for more recent
23464 issues, etc.). They are still supported, but deprecated: their use
23465 should be avoided.
23466
23467 During the jump from Autoconf version 1 to version 2, most of the
23468 macros were renamed to use a more uniform and descriptive naming scheme,
23469 but their signature did not change. @xref{Macro Names}, for a
23470 description of the new naming scheme. Below, if there is just the mapping
23471 from old names to new names for these macros, the reader is invited to
23472 refer to the definition of the new macro for the signature and the
23473 description.
23474
23475 @defmac AC_AIX
23476 @acindex{AIX}
23477 @cvindex _ALL_SOURCE
23478 This macro is a platform-specific subset of
23479 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23480 @end defmac
23481
23482 @defmac AC_ALLOCA
23483 @acindex{ALLOCA}
23484 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
23485 @end defmac
23486
23487 @defmac AC_ARG_ARRAY
23488 @acindex{ARG_ARRAY}
23489 Removed because of limited usefulness.
23490 @end defmac
23491
23492 @defmac AC_C_CROSS
23493 @acindex{C_CROSS}
23494 This macro is obsolete; it does nothing.
23495 @end defmac
23496
23497 @defmac AC_C_LONG_DOUBLE
23498 @acindex{C_LONG_DOUBLE}
23499 @cvindex HAVE_LONG_DOUBLE
23500 If the C compiler supports a working @code{long double} type with more
23501 range or precision than the @code{double} type, define
23502 @code{HAVE_LONG_DOUBLE}.
23503
23504 You should use @code{AC_TYPE_LONG_DOUBLE} or
23505 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead. @xref{Particular Types}.
23506 @end defmac
23507
23508 @defmac AC_CANONICAL_SYSTEM
23509 @acindex{CANONICAL_SYSTEM}
23510 Determine the system type and set output variables to the names of the
23511 canonical system types. @xref{Canonicalizing}, for details about the
23512 variables this macro sets.
23513
23514 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
23515 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
23516 the needs. Using @code{AC_CANONICAL_TARGET} is enough to run the two
23517 other macros (@pxref{Canonicalizing}).
23518 @end defmac
23519
23520 @defmac AC_CHAR_UNSIGNED
23521 @acindex{CHAR_UNSIGNED}
23522 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
23523 @end defmac
23524
23525 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
23526 @acindex{CHECK_TYPE}
23527 Autoconf, up to 2.13, used to provide this version of
23528 @code{AC_CHECK_TYPE}, deprecated because of its flaws. First, although
23529 it is a member of the @code{CHECK} clan, it does
23530 more than just checking. Secondly, missing types are defined
23531 using @code{#define}, not @code{typedef}, and this can lead to
23532 problems in the case of pointer types.
23533
23534 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
23535 @ref{Generic Types}, for the description of the current macro.
23536
23537 If the type @var{type} is not defined, define it to be the C (or C++)
23538 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
23539
23540 This macro is equivalent to:
23541
23542 @example
23543 AC_CHECK_TYPE([@var{type}], [],
23544 [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
23545 [Define to '@var{default}'
23546 if <sys/types.h> does not define.])])
23547 @end example
23548
23549 In order to keep backward compatibility, the two versions of
23550 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
23551
23552 @enumerate
23553 @item
23554 If there are three or four arguments, the modern version is used.
23555
23556 @item
23557 If the second argument appears to be a C or C++ type, then the
23558 obsolete version is used. This happens if the argument is a C or C++
23559 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
23560 followed by one of @samp{[(* } and then by a string of zero or more
23561 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
23562
23563 @item
23564 If the second argument is spelled with the alphabet of valid C and C++
23565 types, the user is warned and the modern version is used.
23566
23567 @item
23568 Otherwise, the modern version is used.
23569 @end enumerate
23570
23571 @noindent
23572 You are encouraged either to use a valid builtin type, or to use the
23573 equivalent modern code (see above), or better yet, to use
23574 @code{AC_CHECK_TYPES} together with
23575
23576 @example
23577 #ifndef HAVE_LOFF_T
23578 typedef loff_t off_t;
23579 #endif
23580 @end example
23581 @end defmac
23582 @c end of AC_CHECK_TYPE
23583
23584 @defmac AC_CHECKING (@var{feature-description})
23585 @acindex{CHECKING}
23586 Same as
23587
23588 @example
23589 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
23590 @end example
23591
23592 @noindent
23593 @xref{AC_MSG_NOTICE}.
23594 @end defmac
23595
23596 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
23597 @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
23598 @acindex{COMPILE_CHECK}
23599 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
23600 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
23601 addition that it prints @samp{checking for @var{echo-text}} to the
23602 standard output first, if @var{echo-text} is non-empty. Use
23603 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
23604 messages (@pxref{Printing Messages}).
23605 @end defmac
23606
23607 @defmac AC_CONST
23608 @acindex{CONST}
23609 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
23610 @end defmac
23611
23612 @defmac AC_CROSS_CHECK
23613 @acindex{CROSS_CHECK}
23614 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
23615 @code{:-)}.
23616 @end defmac
23617
23618 @defmac AC_CYGWIN
23619 @acindex{CYGWIN}
23620 @evindex CYGWIN
23621 Check for the Cygwin environment in which case the shell variable
23622 @code{CYGWIN} is set to @samp{yes}. Don't use this macro, the dignified
23623 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
23624 (@pxref{Canonicalizing}). As a matter of fact this macro is defined as:
23625
23626 @example
23627 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
23628 case $host_os in
23629 *cygwin* ) CYGWIN=yes;;
23630 * ) CYGWIN=no;;
23631 esac
23632 @end example
23633
23634 Beware that the variable @env{CYGWIN} has a special meaning when
23635 running Cygwin, and should not be changed. That's yet another reason
23636 not to use this macro.
23637 @end defmac
23638
23639 @defmac AC_DECL_SYS_SIGLIST
23640 @acindex{DECL_SYS_SIGLIST}
23641 @cvindex SYS_SIGLIST_DECLARED
23642 Same as:
23643
23644 @example
23645 AC_CHECK_DECLS([sys_siglist], [], [],
23646 [#include <signal.h>
23647 /* NetBSD declares sys_siglist in unistd.h. */
23648 #ifdef HAVE_UNISTD_H
23649 # include <unistd.h>
23650 #endif
23651 ])
23652 @end example
23653
23654 @noindent
23655 @xref{AC_CHECK_DECLS}.
23656 @end defmac
23657
23658 @defmac AC_DECL_YYTEXT
23659 @acindex{DECL_YYTEXT}
23660 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23661 @end defmac
23662
23663 @defmac AC_DIAGNOSE (@var{category}, @var{message})
23664 @acindex{DIAGNOSE}
23665 Replaced by @code{m4_warn} (@pxref{m4_warn}).
23666 @end defmac
23667
23668 @defmac AC_DIR_HEADER
23669 @acindex{DIR_HEADER}
23670 @cvindex DIRENT
23671 @cvindex SYSNDIR
23672 @cvindex SYSDIR
23673 @cvindex NDIR
23674 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
23675 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
23676 (@pxref{AC_HEADER_DIRENT}),
23677 but defines a different set of C preprocessor macros to indicate which
23678 header file is found:
23679
23680 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
23681 @item Header @tab Old Symbol @tab New Symbol
23682 @item @file{dirent.h} @tab @code{DIRENT} @tab @code{HAVE_DIRENT_H}
23683 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
23684 @item @file{sys/dir.h} @tab @code{SYSDIR} @tab @code{HAVE_SYS_DIR_H}
23685 @item @file{ndir.h} @tab @code{NDIR} @tab @code{HAVE_NDIR_H}
23686 @end multitable
23687 @end defmac
23688
23689 @defmac AC_DYNIX_SEQ
23690 @acindex{DYNIX_SEQ}
23691 If on DYNIX/ptx, add @option{-lseq} to output variable
23692 @code{LIBS}. This macro used to be defined as
23693
23694 @example
23695 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
23696 @end example
23697
23698 @noindent
23699 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
23700 @end defmac
23701
23702 @defmac AC_EXEEXT
23703 @acindex{EXEEXT}
23704 @ovindex EXEEXT
23705 Defined the output variable @code{EXEEXT} based on the output of the
23706 compiler, which is now done automatically. Typically set to empty
23707 string if POSIX and @samp{.exe} if a DOS variant.
23708 @end defmac
23709
23710 @defmac AC_EMXOS2
23711 @acindex{EMXOS2}
23712 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
23713 and sets @code{EMXOS2}. Don't use this macro, the dignified means to
23714 check the nature of the host is using @code{AC_CANONICAL_HOST}
23715 (@pxref{Canonicalizing}).
23716 @end defmac
23717
23718 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
23719 @ovar{action-if-not-given})
23720 @acindex{ENABLE}
23721 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
23722 support providing a help string (@pxref{AC_ARG_ENABLE}).
23723 @end defmac
23724
23725 @defmac AC_ERROR
23726 @acindex{ERROR}
23727 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
23728 @end defmac
23729
23730 @defmac AC_FATAL (@var{message})
23731 @acindex{FATAL}
23732 Replaced by @code{m4_fatal} (@pxref{m4_fatal}).
23733 @end defmac
23734
23735 @defmac AC_FIND_X
23736 @acindex{FIND_X}
23737 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
23738 @end defmac
23739
23740 @defmac AC_FIND_XTRA
23741 @acindex{FIND_XTRA}
23742 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
23743 @end defmac
23744
23745 @defmac AC_FOREACH
23746 @acindex{FOREACH}
23747 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
23748 @end defmac
23749
23750 @defmac AC_FUNC_CHECK
23751 @acindex{FUNC_CHECK}
23752 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
23753 @end defmac
23754
23755 @anchor{AC_FUNC_SETVBUF_REVERSED}
23756 @defmac AC_FUNC_SETVBUF_REVERSED
23757 @acindex{FUNC_SETVBUF_REVERSED}
23758 @cvindex SETVBUF_REVERSED
23759 @c @fuindex setvbuf
23760 @prindex @code{setvbuf}
23761 Do nothing. Formerly, this macro checked whether @code{setvbuf} takes
23762 the buffering type as its second argument and the buffer pointer as the
23763 third, instead of the other way around, and defined
23764 @code{SETVBUF_REVERSED}. However, the last systems to have the problem
23765 were those based on SVR2, which became obsolete in 1987, and the macro
23766 is no longer needed.
23767 @end defmac
23768
23769 @defmac AC_FUNC_WAIT3
23770 @acindex{FUNC_WAIT3}
23771 @cvindex HAVE_WAIT3
23772 @c @fuindex wait3
23773 @prindex @code{wait3}
23774 If @code{wait3} is found and fills in the contents of its third argument
23775 (a @samp{struct rusage *}), which HP-UX does not do, define
23776 @code{HAVE_WAIT3}.
23777
23778 These days portable programs should use @code{waitpid}, not
23779 @code{wait3}, as @code{wait3} has been removed from POSIX.
23780 @end defmac
23781
23782 @defmac AC_GCC_TRADITIONAL
23783 @acindex{GCC_TRADITIONAL}
23784 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}),
23785 which is itself obsolete.
23786 @end defmac
23787
23788 @defmac AC_GETGROUPS_T
23789 @acindex{GETGROUPS_T}
23790 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
23791 @end defmac
23792
23793 @defmac AC_GETLOADAVG
23794 @acindex{GETLOADAVG}
23795 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
23796 @end defmac
23797
23798 @defmac AC_GNU_SOURCE
23799 @acindex{GNU_SOURCE}
23800 @cvindex _GNU_SOURCE
23801 This macro is a platform-specific subset of
23802 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23803 @end defmac
23804
23805 @defmac AC_HAVE_FUNCS
23806 @acindex{HAVE_FUNCS}
23807 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
23808 @end defmac
23809
23810 @defmac AC_HAVE_HEADERS
23811 @acindex{HAVE_HEADERS}
23812 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
23813 @end defmac
23814
23815 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
23816 @ovar{action-if-not-found}, @ovar{other-libraries})
23817 @acindex{HAVE_LIBRARY}
23818 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
23819 @var{function} argument of @code{main}. In addition, @var{library} can
23820 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}. In
23821 all of those cases, the compiler is passed @option{-lfoo}. However,
23822 @var{library} cannot be a shell variable; it must be a literal name.
23823 @xref{AC_CHECK_LIB}.
23824 @end defmac
23825
23826 @defmac AC_HAVE_POUNDBANG
23827 @acindex{HAVE_POUNDBANG}
23828 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
23829 @end defmac
23830
23831 @defmac AC_HEADER_CHECK
23832 @acindex{HEADER_CHECK}
23833 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
23834 @end defmac
23835
23836 @defmac AC_HEADER_EGREP
23837 @acindex{HEADER_EGREP}
23838 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
23839 @end defmac
23840
23841 @anchor{AC_HEADER_TIME}
23842 @defmac AC_HEADER_TIME
23843 @acindex{HEADER_TIME}
23844 @cvindex TIME_WITH_SYS_TIME
23845 @hdrindex{time.h}
23846 @hdrindex{sys/time.h}
23847 @caindex header_time
23848 This macro used to check whether it was possible to include
23849 @file{time.h} and @file{sys/time.h} in the same source file,
23850 defining @code{TIME_WITH_SYS_TIME} if so.
23851
23852 Nowadays, it is equivalent to @samp{AC_CHECK_HEADERS([sys/time.h])},
23853 although it does still define @code{TIME_WITH_SYS_TIME} for
23854 compatibility's sake. @file{time.h} is universally present, and the
23855 systems on which @file{sys/time.h} conflicted with @file{time.h} are
23856 obsolete.
23857 @end defmac
23858
23859 @defmac AC_HELP_STRING
23860 @acindex{HELP_STRING}
23861 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
23862 @end defmac
23863
23864 @defmac AC_INIT (@var{unique-file-in-source-dir})
23865 @acindex{INIT}
23866 Formerly @code{AC_INIT} used to have a single argument, and was
23867 equivalent to:
23868
23869 @example
23870 AC_INIT
23871 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
23872 @end example
23873 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
23874 @end defmac
23875
23876 @defmac AC_INLINE
23877 @acindex{INLINE}
23878 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
23879 @end defmac
23880
23881 @defmac AC_INT_16_BITS
23882 @acindex{INT_16_BITS}
23883 @cvindex INT_16_BITS
23884 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
23885 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
23886 @end defmac
23887
23888 @defmac AC_IRIX_SUN
23889 @acindex{IRIX_SUN}
23890 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
23891 @code{LIBS}. If you were using it to get @code{getmntent}, use
23892 @code{AC_FUNC_GETMNTENT} instead. If you used it for the NIS versions
23893 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
23894 getpwnam)}. Up to Autoconf 2.13, it used to be
23895
23896 @example
23897 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
23898 @end example
23899
23900 @noindent
23901 now it is defined as
23902
23903 @example
23904 AC_FUNC_GETMNTENT
23905 AC_CHECK_LIB([sun], [getpwnam])
23906 @end example
23907
23908 @noindent
23909 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
23910 @end defmac
23911
23912 @defmac AC_ISC_POSIX
23913 @acindex{ISC_POSIX}
23914 @ovindex LIBS
23915 This macro adds @option{-lcposix} to output variable @code{LIBS} if
23916 necessary for POSIX facilities. Sun dropped support for the obsolete
23917 INTERACTIVE Systems Corporation Unix on 2006-07-23. New programs
23918 need not use this macro. It is implemented as
23919 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
23920 @end defmac
23921
23922 @defmac AC_LANG_C
23923 @acindex{LANG_C}
23924 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
23925 @end defmac
23926
23927 @defmac AC_LANG_CPLUSPLUS
23928 @acindex{LANG_CPLUSPLUS}
23929 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
23930 @end defmac
23931
23932 @defmac AC_LANG_FORTRAN77
23933 @acindex{LANG_FORTRAN77}
23934 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
23935 @end defmac
23936
23937 @defmac AC_LANG_RESTORE
23938 @acindex{LANG_RESTORE}
23939 Select the @var{language} that is saved on the top of the stack, as set
23940 by @code{AC_LANG_SAVE}, remove it from the stack, and call
23941 @code{AC_LANG(@var{language})}. @xref{Language Choice}, for the
23942 preferred way to change languages.
23943 @end defmac
23944
23945 @defmac AC_LANG_SAVE
23946 @acindex{LANG_SAVE}
23947 Remember the current language (as set by @code{AC_LANG}) on a stack.
23948 The current language does not change. @code{AC_LANG_PUSH} is preferred
23949 (@pxref{AC_LANG_PUSH}).
23950 @end defmac
23951
23952 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
23953 @acindex{LINK_FILES}
23954 This is an obsolete version of @code{AC_CONFIG_LINKS}
23955 (@pxref{AC_CONFIG_LINKS}. An updated version of:
23956
23957 @example
23958 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
23959 host.h object.h)
23960 @end example
23961
23962 @noindent
23963 is:
23964
23965 @example
23966 AC_CONFIG_LINKS([host.h:config/$machine.h
23967 object.h:config/$obj_format.h])
23968 @end example
23969 @end defmac
23970
23971 @defmac AC_LN_S
23972 @acindex{LN_S}
23973 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
23974 @end defmac
23975
23976 @defmac AC_LONG_64_BITS
23977 @acindex{LONG_64_BITS}
23978 @cvindex LONG_64_BITS
23979 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
23980 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
23981 (@pxref{AC_CHECK_SIZEOF}).
23982 @end defmac
23983
23984 @defmac AC_LONG_DOUBLE
23985 @acindex{LONG_DOUBLE}
23986 If the C compiler supports a working @code{long double} type with more
23987 range or precision than the @code{double} type, define
23988 @code{HAVE_LONG_DOUBLE}.
23989
23990 You should use @code{AC_TYPE_LONG_DOUBLE} or
23991 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead. @xref{Particular Types}.
23992 @end defmac
23993
23994 @defmac AC_LONG_FILE_NAMES
23995 @acindex{LONG_FILE_NAMES}
23996 Replaced by
23997 @example
23998 AC_SYS_LONG_FILE_NAMES
23999 @end example
24000 @noindent
24001 @xref{AC_SYS_LONG_FILE_NAMES}.
24002 @end defmac
24003
24004 @defmac AC_MAJOR_HEADER
24005 @acindex{MAJOR_HEADER}
24006 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
24007 @end defmac
24008
24009 @defmac AC_MEMORY_H
24010 @acindex{MEMORY_H}
24011 @cvindex NEED_MEMORY_H
24012 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
24013 defined in @file{memory.h}. Today it is equivalent to
24014 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}). Adjust
24015 your code to get the @code{mem} functions from @file{string.h} instead.
24016 @end defmac
24017
24018 @defmac AC_MINGW32
24019 @acindex{MINGW32}
24020 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
24021 environment and sets @code{MINGW32}. Don't use this macro, the
24022 dignified means to check the nature of the host is using
24023 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24024 @end defmac
24025
24026 @defmac AC_MINIX
24027 @acindex{MINIX}
24028 @cvindex _MINIX
24029 @cvindex _POSIX_SOURCE
24030 @cvindex _POSIX_1_SOURCE
24031 This macro is a platform-specific subset of
24032 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
24033 @end defmac
24034
24035 @defmac AC_MINUS_C_MINUS_O
24036 @acindex{MINUS_C_MINUS_O}
24037 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
24038 @end defmac
24039
24040 @defmac AC_MMAP
24041 @acindex{MMAP}
24042 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
24043 @end defmac
24044
24045 @defmac AC_MODE_T
24046 @acindex{MODE_T}
24047 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
24048 @end defmac
24049
24050 @defmac AC_OBJEXT
24051 @acindex{OBJEXT}
24052 @ovindex OBJEXT
24053 Defined the output variable @code{OBJEXT} based on the output of the
24054 compiler, after .c files have been excluded. Typically set to @samp{o}
24055 if POSIX, @samp{obj} if a DOS variant.
24056 Now the compiler checking macros handle
24057 this automatically.
24058 @end defmac
24059
24060 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
24061 @acindex{OBSOLETE}
24062 Make M4 print a message to the standard error output warning that
24063 @var{this-macro-name} is obsolete, and giving the file and line number
24064 where it was called. @var{this-macro-name} should be the name of the
24065 macro that is calling @code{AC_OBSOLETE}. If @var{suggestion} is given,
24066 it is printed at the end of the warning message; for example, it can be
24067 a suggestion for what to use instead of @var{this-macro-name}.
24068
24069 For instance
24070
24071 @example
24072 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
24073 @end example
24074
24075 @noindent
24076 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
24077 services to the user (@pxref{AU_DEFUN}).
24078 @end defmac
24079
24080 @defmac AC_OFF_T
24081 @acindex{OFF_T}
24082 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
24083 @end defmac
24084
24085 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
24086 @acindex{OUTPUT}
24087 The use of @code{AC_OUTPUT} with arguments is deprecated. This obsoleted
24088 interface is equivalent to:
24089
24090 @example
24091 @group
24092 AC_CONFIG_FILES(@var{file}@dots{})
24093 AC_CONFIG_COMMANDS([default],
24094 @var{extra-cmds}, @var{init-cmds})
24095 AC_OUTPUT
24096 @end group
24097 @end example
24098
24099 @noindent
24100 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
24101 @end defmac
24102
24103 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
24104 @acindex{OUTPUT_COMMANDS}
24105 Specify additional shell commands to run at the end of
24106 @file{config.status}, and shell commands to initialize any variables
24107 from @command{configure}. This macro may be called multiple times. It is
24108 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
24109
24110 Here is an unrealistic example:
24111
24112 @example
24113 fubar=27
24114 AC_OUTPUT_COMMANDS(
24115 [AS_ECHO(["this is extra $fubar, and so on."])],
24116 [fubar=$fubar])
24117 AC_OUTPUT_COMMANDS(
24118 [AS_ECHO(["this is another, extra, bit"])],
24119 [AS_ECHO(["init bit"])])
24120 @end example
24121
24122 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
24123 additional key, an important difference is that
24124 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
24125 @code{AC_CONFIG_COMMANDS}. This means that @code{AC_CONFIG_COMMANDS}
24126 can safely be given macro calls as arguments:
24127
24128 @example
24129 AC_CONFIG_COMMANDS(foo, [my_FOO()])
24130 @end example
24131
24132 @noindent
24133 Conversely, where one level of quoting was enough for literal strings
24134 with @code{AC_OUTPUT_COMMANDS}, you need two with
24135 @code{AC_CONFIG_COMMANDS}. The following lines are equivalent:
24136
24137 @example
24138 @group
24139 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
24140 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
24141 @end group
24142 @end example
24143 @end defmac
24144
24145 @defmac AC_PID_T
24146 @acindex{PID_T}
24147 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
24148 @end defmac
24149
24150 @defmac AC_PREFIX
24151 @acindex{PREFIX}
24152 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
24153 @end defmac
24154
24155 @defmac AC_PROG_CC_C89
24156 @acindex{PROG_CC_C89}
24157 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
24158 @end defmac
24159
24160 @defmac AC_PROG_CC_C99
24161 @acindex{PROG_CC_C99}
24162 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
24163 @end defmac
24164
24165 @defmac AC_PROG_CC_STDC
24166 @acindex{PROG_CC_STDC}
24167 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
24168 @end defmac
24169
24170 @anchor{AC_PROG_GCC_TRADITIONAL}
24171 @defmac AC_PROG_GCC_TRADITIONAL
24172 @acindex{PROG_GCC_TRADITIONAL}
24173 Used to put GCC into ``traditional'' (pre-ISO C) compilation mode,
24174 on systems with headers that did not work correctly with a
24175 standard-compliant compiler. GCC has not supported traditional
24176 compilation in many years, and all of the systems that required this are
24177 long obsolete themselves. This macro is now a compatibility synonym for
24178 @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
24179
24180 @end defmac
24181
24182 @defmac AC_PROGRAMS_CHECK
24183 @acindex{PROGRAMS_CHECK}
24184 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
24185 @end defmac
24186
24187 @defmac AC_PROGRAMS_PATH
24188 @acindex{PROGRAMS_PATH}
24189 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
24190 @end defmac
24191
24192 @defmac AC_PROGRAM_CHECK
24193 @acindex{PROGRAM_CHECK}
24194 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
24195 @end defmac
24196
24197 @defmac AC_PROGRAM_EGREP
24198 @acindex{PROGRAM_EGREP}
24199 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
24200 @end defmac
24201
24202 @defmac AC_PROGRAM_PATH
24203 @acindex{PROGRAM_PATH}
24204 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
24205 @end defmac
24206
24207 @defmac AC_REMOTE_TAPE
24208 @acindex{REMOTE_TAPE}
24209 Removed because of limited usefulness.
24210 @end defmac
24211
24212 @defmac AC_RESTARTABLE_SYSCALLS
24213 @acindex{RESTARTABLE_SYSCALLS}
24214 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}. However,
24215 these days portable programs should use @code{sigaction} with
24216 @code{SA_RESTART} if they want restartable system calls. They should
24217 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
24218 system call is restartable is a dynamic issue, not a configuration-time
24219 issue.
24220 @end defmac
24221
24222 @defmac AC_RETSIGTYPE
24223 @acindex{RETSIGTYPE}
24224 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
24225 is obsolete.
24226 @end defmac
24227
24228 @defmac AC_RSH
24229 @acindex{RSH}
24230 Removed because of limited usefulness.
24231 @end defmac
24232
24233 @defmac AC_SCO_INTL
24234 @acindex{SCO_INTL}
24235 @ovindex LIBS
24236 Equivalent to the obsolescent macro @code{AC_FUNC_STRFTIME}.
24237 @xref{AC_FUNC_STRFTIME}.
24238 @end defmac
24239
24240 @defmac AC_SETVBUF_REVERSED
24241 @acindex{SETVBUF_REVERSED}
24242 Replaced by
24243 @example
24244 AC_FUNC_SETVBUF_REVERSED
24245 @end example
24246 @noindent
24247 @xref{AC_FUNC_SETVBUF_REVERSED}.
24248 @end defmac
24249
24250 @defmac AC_SET_MAKE
24251 @acindex{SET_MAKE}
24252 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
24253 @end defmac
24254
24255 @defmac AC_SIZEOF_TYPE
24256 @acindex{SIZEOF_TYPE}
24257 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
24258 @end defmac
24259
24260 @defmac AC_SIZE_T
24261 @acindex{SIZE_T}
24262 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
24263 @end defmac
24264
24265 @defmac AC_STAT_MACROS_BROKEN
24266 @acindex{STAT_MACROS_BROKEN}
24267 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
24268 @end defmac
24269
24270 @defmac AC_STDC_HEADERS
24271 @acindex{STDC_HEADERS}
24272 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}), which
24273 is itself obsolete. Nowadays it is safe to assume the facilities of C89
24274 exist.
24275 @end defmac
24276
24277 @defmac AC_STRCOLL
24278 @acindex{STRCOLL}
24279 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
24280 @end defmac
24281
24282 @defmac AC_STRUCT_ST_BLKSIZE
24283 @acindex{STRUCT_ST_BLKSIZE}
24284 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
24285 @cvindex HAVE_ST_BLKSIZE
24286 If @code{struct stat} contains an @code{st_blksize} member, define
24287 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}. The former name,
24288 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
24289 the future. This macro is obsoleted, and should be replaced by
24290
24291 @example
24292 AC_CHECK_MEMBERS([struct stat.st_blksize])
24293 @end example
24294 @noindent
24295 @xref{AC_CHECK_MEMBERS}.
24296 @end defmac
24297
24298 @defmac AC_STRUCT_ST_RDEV
24299 @acindex{STRUCT_ST_RDEV}
24300 @cvindex HAVE_ST_RDEV
24301 @cvindex HAVE_STRUCT_STAT_ST_RDEV
24302 If @code{struct stat} contains an @code{st_rdev} member, define
24303 @code{HAVE_STRUCT_STAT_ST_RDEV}. The former name for this macro,
24304 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
24305 in the future. Actually, even the new macro is obsolete and should be
24306 replaced by:
24307 @example
24308 AC_CHECK_MEMBERS([struct stat.st_rdev])
24309 @end example
24310 @noindent
24311 @xref{AC_CHECK_MEMBERS}.
24312 @end defmac
24313
24314 @defmac AC_ST_BLKSIZE
24315 @acindex{ST_BLKSIZE}
24316 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24317 @end defmac
24318
24319 @defmac AC_ST_BLOCKS
24320 @acindex{ST_BLOCKS}
24321 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
24322 @end defmac
24323
24324 @defmac AC_ST_RDEV
24325 @acindex{ST_RDEV}
24326 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24327 @end defmac
24328
24329 @defmac AC_SYS_RESTARTABLE_SYSCALLS
24330 @acindex{SYS_RESTARTABLE_SYSCALLS}
24331 @cvindex HAVE_RESTARTABLE_SYSCALLS
24332 If the system automatically restarts a system call that is interrupted
24333 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}. This macro does
24334 not check whether system calls are restarted in general---it checks whether a
24335 signal handler installed with @code{signal} (but not @code{sigaction})
24336 causes system calls to be restarted. It does not check whether system calls
24337 can be restarted when interrupted by signals that have no handler.
24338
24339 These days portable programs should use @code{sigaction} with
24340 @code{SA_RESTART} if they want restartable system calls. They should
24341 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
24342 system call is restartable is a dynamic issue, not a configuration-time
24343 issue.
24344 @end defmac
24345
24346 @defmac AC_SYS_SIGLIST_DECLARED
24347 @acindex{SYS_SIGLIST_DECLARED}
24348 This macro was renamed @code{AC_DECL_SYS_SIGLIST}. However, even that
24349 name is obsolete, as the same functionality is now achieved via
24350 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
24351 @end defmac
24352
24353 @defmac AC_TEST_CPP
24354 @acindex{TEST_CPP}
24355 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
24356 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
24357 @end defmac
24358
24359 @defmac AC_TEST_PROGRAM
24360 @acindex{TEST_PROGRAM}
24361 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
24362 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
24363 @end defmac
24364
24365 @defmac AC_TIMEZONE
24366 @acindex{TIMEZONE}
24367 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
24368 @end defmac
24369
24370 @defmac AC_TIME_WITH_SYS_TIME
24371 @acindex{TIME_WITH_SYS_TIME}
24372 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}), which is
24373 itself obsolete; nowadays one need only do
24374 @samp{AC_CHECK_HEADERS([sys/time.h])}.
24375 @end defmac
24376
24377 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
24378 @ovar{action-if-true}, @ovar{action-if-false})
24379 @acindex{TRY_COMPILE}
24380 Same as:
24381
24382 @example
24383 AC_COMPILE_IFELSE(
24384 [AC_LANG_PROGRAM([[@var{includes}]],
24385 [[@var{function-body}]])],
24386 [@var{action-if-true}],
24387 [@var{action-if-false}])
24388 @end example
24389
24390 @noindent
24391 @xref{Running the Compiler}.
24392
24393 This macro double quotes both @var{includes} and @var{function-body}.
24394
24395 For C and C++, @var{includes} is any @code{#include} statements needed
24396 by the code in @var{function-body} (@var{includes} is ignored if
24397 the currently selected language is Fortran or Fortran 77). The compiler
24398 and compilation flags are determined by the current language
24399 (@pxref{Language Choice}).
24400 @end defmac
24401
24402 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
24403 @acindex{TRY_CPP}
24404 Same as:
24405
24406 @example
24407 AC_PREPROC_IFELSE(
24408 [AC_LANG_SOURCE([[@var{input}]])],
24409 [@var{action-if-true}],
24410 [@var{action-if-false}])
24411 @end example
24412
24413 @noindent
24414 @xref{Running the Preprocessor}.
24415
24416 This macro double quotes the @var{input}.
24417 @end defmac
24418
24419 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
24420 @ovar{action-if-true}, @ovar{action-if-false})
24421 @acindex{TRY_LINK}
24422 Same as:
24423
24424 @example
24425 AC_LINK_IFELSE(
24426 [AC_LANG_PROGRAM([[@var{includes}]],
24427 [[@var{function-body}]])],
24428 [@var{action-if-true}],
24429 [@var{action-if-false}])
24430 @end example
24431
24432 @noindent
24433 @xref{Running the Linker}.
24434
24435 This macro double quotes both @var{includes} and @var{function-body}.
24436
24437 Depending on the current language (@pxref{Language Choice}), create a
24438 test program to see whether a function whose body consists of
24439 @var{function-body} can be compiled and linked. If the file compiles
24440 and links successfully, run shell commands @var{action-if-found},
24441 otherwise run @var{action-if-not-found}.
24442
24443 This macro double quotes both @var{includes} and @var{function-body}.
24444
24445 For C and C++, @var{includes} is any @code{#include} statements needed
24446 by the code in @var{function-body} (@var{includes} is ignored if
24447 the currently selected language is Fortran or Fortran 77). The compiler
24448 and compilation flags are determined by the current language
24449 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
24450 @code{LIBS} are used for linking.
24451 @end defmac
24452
24453 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
24454 @ovar{action-if-not-found})
24455 @acindex{TRY_LINK_FUNC}
24456 This macro is equivalent to
24457 @example
24458 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
24459 [@var{action-if-found}], [@var{action-if-not-found}])
24460 @end example
24461 @noindent
24462 @xref{Running the Linker}.
24463 @end defmac
24464
24465 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
24466 @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
24467 @acindex{TRY_RUN}
24468 Same as:
24469
24470 @example
24471 AC_RUN_IFELSE(
24472 [AC_LANG_SOURCE([[@var{program}]])],
24473 [@var{action-if-true}],
24474 [@var{action-if-false}],
24475 [@var{action-if-cross-compiling}])
24476 @end example
24477
24478 @noindent
24479 @xref{Runtime}.
24480 @end defmac
24481
24482 @anchor{AC_TYPE_SIGNAL}
24483 @defmac AC_TYPE_SIGNAL
24484 @acindex{TYPE_SIGNAL}
24485 @cvindex RETSIGTYPE
24486 @hdrindex{signal.h}
24487 If @file{signal.h} declares @code{signal} as returning a pointer to a
24488 function returning @code{void}, define @code{RETSIGTYPE} to be
24489 @code{void}; otherwise, define it to be @code{int}. These days, it is
24490 portable to assume C89, and that signal handlers return @code{void},
24491 without needing to use this macro or @code{RETSIGTYPE}.
24492 @end defmac
24493
24494 @defmac AC_UID_T
24495 @acindex{UID_T}
24496 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
24497 @end defmac
24498
24499 @defmac AC_UNISTD_H
24500 @acindex{UNISTD_H}
24501 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}),
24502 which is one of the tests done as a side effect by
24503 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), so usually
24504 unnecessary to write explicitly.
24505 @end defmac
24506
24507 @defmac AC_USG
24508 @acindex{USG}
24509 @cvindex USG
24510 Define @code{USG} if the BSD string functions (@code{bcopy},
24511 @code{bzero}, @code{index}, @code{rindex}, etc) are @emph{not} defined
24512 in @file{strings.h}. Modern code should assume @file{string.h} exists
24513 and should use the standard C string functions (@code{memmove}, @code{memset},
24514 @code{strchr}, @code{strrchr}, etc) unconditionally.
24515
24516 @file{strings.h} may be the only header that declares @code{strcasecmp},
24517 @code{strncasecmp}, and @code{ffs}. @code{AC_INCLUDES_DEFAULT} checks
24518 for it (@pxref{Default Includes}); test @code{HAVE_STRINGS_H}.
24519 @end defmac
24520
24521 @defmac AC_UTIME_NULL
24522 @acindex{UTIME_NULL}
24523 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
24524 @end defmac
24525
24526 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
24527 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
24528 If the cache file is inconsistent with the current host, target and
24529 build system types, it used to execute @var{cmd} or print a default
24530 error message. This is now handled by default.
24531 @end defmac
24532
24533 @defmac AC_VERBOSE (@var{result-description})
24534 @acindex{VERBOSE}
24535 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
24536 @end defmac
24537
24538 @defmac AC_VFORK
24539 @acindex{VFORK}
24540 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
24541 @end defmac
24542
24543 @defmac AC_VPRINTF
24544 @acindex{VPRINTF}
24545 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
24546 @end defmac
24547
24548 @defmac AC_WAIT3
24549 @acindex{WAIT3}
24550 This macro was renamed @code{AC_FUNC_WAIT3}. However, these days
24551 portable programs should use @code{waitpid}, not @code{wait3}, as
24552 @code{wait3} has been removed from POSIX.
24553 @end defmac
24554
24555 @defmac AC_WARN
24556 @acindex{WARN}
24557 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
24558 @end defmac
24559
24560 @defmac AC_WARNING (@var{message})
24561 @acindex{WARNING}
24562 Replaced by @code{m4_warn} (@pxref{m4_warn}).
24563 @end defmac
24564
24565 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
24566 @ovar{action-if-not-given})
24567 @acindex{WITH}
24568 This is an obsolete version of @code{AC_ARG_WITH} that does not
24569 support providing a help string (@pxref{AC_ARG_WITH}).
24570 @end defmac
24571
24572 @defmac AC_WORDS_BIGENDIAN
24573 @acindex{WORDS_BIGENDIAN}
24574 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
24575 @end defmac
24576
24577 @defmac AC_XENIX_DIR
24578 @acindex{XENIX_DIR}
24579 @ovindex LIBS
24580 This macro is equivalent to the obsolescent @code{AC_HEADER_DIRENT}
24581 macro, plus it also sets the shell variable @code{XENIX}.
24582 Don't use this macro, the dignified means to check the nature of the
24583 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24584 @end defmac
24585
24586 @defmac AC_YYTEXT_POINTER
24587 @acindex{YYTEXT_POINTER}
24588 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
24589 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
24590 @end defmac
24591
24592 @node Autoconf 1
24593 @section Upgrading From Version 1
24594 @cindex Upgrading autoconf
24595 @cindex Autoconf upgrading
24596
24597 Autoconf version 2 is mostly backward compatible with version 1.
24598 However, it introduces better ways to do some things, and doesn't
24599 support some of the ugly things in version 1. So, depending on how
24600 sophisticated your @file{configure.ac} files are, you might have to do
24601 some manual work in order to upgrade to version 2. This chapter points
24602 out some problems to watch for when upgrading. Also, perhaps your
24603 @command{configure} scripts could benefit from some of the new features in
24604 version 2; the changes are summarized in the file @file{NEWS} in the
24605 Autoconf distribution.
24606
24607 @menu
24608 * Changed File Names:: Files you might rename
24609 * Changed Makefiles:: New things to put in @file{Makefile.in}
24610 * Changed Macros:: Macro calls you might replace
24611 * Changed Results:: Changes in how to check test results
24612 * Changed Macro Writing:: Better ways to write your own macros
24613 @end menu
24614
24615 @node Changed File Names
24616 @subsection Changed File Names
24617
24618 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
24619 in a particular package's source directory), you must rename it to
24620 @file{acsite.m4}. @xref{autoconf Invocation}.
24621
24622 If you distribute @file{install.sh} with your package, rename it to
24623 @file{install-sh} so @command{make} builtin rules don't inadvertently
24624 create a file called @file{install} from it. @code{AC_PROG_INSTALL}
24625 looks for the script under both names, but it is best to use the new name.
24626
24627 If you were using @file{config.h.top}, @file{config.h.bot}, or
24628 @file{acconfig.h}, you still can, but you have less clutter if you
24629 use the @code{AH_} macros. @xref{Autoheader Macros}.
24630
24631 @node Changed Makefiles
24632 @subsection Changed Makefiles
24633
24634 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
24635 your @file{Makefile.in} files, so they can take advantage of the values
24636 of those variables in the environment when @command{configure} is run.
24637 Doing this isn't necessary, but it's a convenience for users.
24638
24639 Also add @samp{@@configure_input@@} in a comment to each input file for
24640 @code{AC_OUTPUT}, so that the output files contain a comment saying
24641 they were produced by @command{configure}. Automatically selecting the
24642 right comment syntax for all the kinds of files that people call
24643 @code{AC_OUTPUT} on became too much work.
24644
24645 Add @file{config.log} and @file{config.cache} to the list of files you
24646 remove in @code{distclean} targets.
24647
24648 If you have the following in @file{Makefile.in}:
24649
24650 @example
24651 prefix = /usr/local
24652 exec_prefix = $(prefix)
24653 @end example
24654
24655 @noindent
24656 you must change it to:
24657
24658 @example
24659 prefix = @@prefix@@
24660 exec_prefix = @@exec_prefix@@
24661 @end example
24662
24663 @noindent
24664 The old behavior of replacing those variables without @samp{@@}
24665 characters around them has been removed.
24666
24667 @node Changed Macros
24668 @subsection Changed Macros
24669
24670 Many of the macros were renamed in Autoconf version 2. You can still
24671 use the old names, but the new ones are clearer, and it's easier to find
24672 the documentation for them. @xref{Obsolete Macros}, for a table showing the
24673 new names for the old macros. Use the @command{autoupdate} program to
24674 convert your @file{configure.ac} to using the new macro names.
24675 @xref{autoupdate Invocation}.
24676
24677 Some macros have been superseded by similar ones that do the job better,
24678 but are not call-compatible. If you get warnings about calling obsolete
24679 macros while running @command{autoconf}, you may safely ignore them, but
24680 your @command{configure} script generally works better if you follow
24681 the advice that is printed about what to replace the obsolete macros with. In
24682 particular, the mechanism for reporting the results of tests has
24683 changed. If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
24684 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
24685 looks better if you switch to @code{AC_MSG_CHECKING} and
24686 @code{AC_MSG_RESULT}. @xref{Printing Messages}. Those macros work best
24687 in conjunction with cache variables. @xref{Caching Results}.
24688
24689
24690
24691 @node Changed Results
24692 @subsection Changed Results
24693
24694 If you were checking the results of previous tests by examining the
24695 shell variable @code{DEFS}, you need to switch to checking the values of
24696 the cache variables for those tests. @code{DEFS} no longer exists while
24697 @command{configure} is running; it is only created when generating output
24698 files. This difference from version 1 is because properly quoting the
24699 contents of that variable turned out to be too cumbersome and
24700 inefficient to do every time @code{AC_DEFINE} is called. @xref{Cache
24701 Variable Names}.
24702
24703 For example, here is a @file{configure.ac} fragment written for Autoconf
24704 version 1:
24705
24706 @example
24707 AC_HAVE_FUNCS(syslog)
24708 case "$DEFS" in
24709 *-DHAVE_SYSLOG*) ;;
24710 *) # syslog is not in the default libraries. See if it's in some other.
24711 saved_LIBS="$LIBS"
24712 for lib in bsd socket inet; do
24713 AC_CHECKING(for syslog in -l$lib)
24714 LIBS="-l$lib $saved_LIBS"
24715 AC_HAVE_FUNCS(syslog)
24716 case "$DEFS" in
24717 *-DHAVE_SYSLOG*) break ;;
24718 *) ;;
24719 esac
24720 LIBS="$saved_LIBS"
24721 done ;;
24722 esac
24723 @end example
24724
24725 Here is a way to write it for version 2:
24726
24727 @example
24728 AC_CHECK_FUNCS([syslog])
24729 AS_IF([test "x$ac_cv_func_syslog" = xno],
24730 [# syslog is not in the default libraries. See if it's in some other.
24731 for lib in bsd socket inet; do
24732 AC_CHECK_LIB([$lib], [syslog],
24733 [AC_DEFINE([HAVE_SYSLOG])
24734 LIBS="-l$lib $LIBS"; break])
24735 done])
24736 @end example
24737
24738 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
24739 backslashes before quotes, you need to remove them. It now works
24740 predictably, and does not treat quotes (except back quotes) specially.
24741 @xref{Setting Output Variables}.
24742
24743 All of the Boolean shell variables set by Autoconf macros now use
24744 @samp{yes} for the true value. Most of them use @samp{no} for false,
24745 though for backward compatibility some use the empty string instead. If
24746 you were relying on a shell variable being set to something like 1 or
24747 @samp{t} for true, you need to change your tests.
24748
24749 @node Changed Macro Writing
24750 @subsection Changed Macro Writing
24751
24752 When defining your own macros, you should now use @code{AC_DEFUN}
24753 instead of @code{define}. @code{AC_DEFUN} automatically calls
24754 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
24755 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
24756 messages on the screen. There's no actual harm in continuing to use the
24757 older way, but it's less convenient and attractive. @xref{Macro
24758 Definitions}.
24759
24760 You probably looked at the macros that came with Autoconf as a guide for
24761 how to do things. It would be a good idea to take a look at the new
24762 versions of them, as the style is somewhat improved and they take
24763 advantage of some new features.
24764
24765 If you were doing tricky things with undocumented Autoconf internals
24766 (macros, variables, diversions), check whether you need to change
24767 anything to account for changes that have been made. Perhaps you can
24768 even use an officially supported technique in version 2 instead of
24769 kludging. Or perhaps not.
24770
24771 To speed up your locally written feature tests, add caching to them.
24772 See whether any of your tests are of general enough usefulness to
24773 encapsulate them into macros that you can share.
24774
24775
24776 @node Autoconf 2.13
24777 @section Upgrading From Version 2.13
24778 @cindex Upgrading autoconf
24779 @cindex Autoconf upgrading
24780
24781 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
24782 suits this section@enddots{}
24783
24784 @quotation
24785 Autoconf version 2.50 is mostly backward compatible with version 2.13.
24786 However, it introduces better ways to do some things, and doesn't
24787 support some of the ugly things in version 2.13. So, depending on how
24788 sophisticated your @file{configure.ac} files are, you might have to do
24789 some manual work in order to upgrade to version 2.50. This chapter
24790 points out some problems to watch for when upgrading. Also, perhaps
24791 your @command{configure} scripts could benefit from some of the new
24792 features in version 2.50; the changes are summarized in the file
24793 @file{NEWS} in the Autoconf distribution.
24794 @end quotation
24795
24796 @menu
24797 * Changed Quotation:: Broken code which used to work
24798 * New Macros:: Interaction with foreign macros
24799 * Hosts and Cross-Compilation:: Bugward compatibility kludges
24800 * AC_LIBOBJ vs LIBOBJS:: LIBOBJS is a forbidden token
24801 * AC_ACT_IFELSE vs AC_TRY_ACT:: A more generic scheme for testing sources
24802 @end menu
24803
24804 @node Changed Quotation
24805 @subsection Changed Quotation
24806
24807 The most important changes are invisible to you: the implementation of
24808 most macros have completely changed. This allowed more factorization of
24809 the code, better error messages, a higher uniformity of the user's
24810 interface etc. Unfortunately, as a side effect, some construct which
24811 used to (miraculously) work might break starting with Autoconf 2.50.
24812 The most common culprit is bad quotation.
24813
24814 For instance, in the following example, the message is not properly
24815 quoted:
24816
24817 @example
24818 AC_INIT
24819 AC_CHECK_HEADERS(foo.h, ,
24820 AC_MSG_ERROR(cannot find foo.h, bailing out))
24821 AC_OUTPUT
24822 @end example
24823
24824 @noindent
24825 Autoconf 2.13 simply ignores it:
24826
24827 @example
24828 $ @kbd{autoconf-2.13; ./configure --silent}
24829 creating cache ./config.cache
24830 configure: error: cannot find foo.h
24831 $
24832 @end example
24833
24834 @noindent
24835 while Autoconf 2.50 produces a broken @file{configure}:
24836
24837 @example
24838 $ @kbd{autoconf-2.50; ./configure --silent}
24839 configure: error: cannot find foo.h
24840 ./configure: exit: bad non-numeric arg `bailing'
24841 ./configure: exit: bad non-numeric arg `bailing'
24842 $
24843 @end example
24844
24845 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
24846 too!
24847
24848 @example
24849 AC_INIT([Example], [1.0], [bug-example@@example.org])
24850 AC_CHECK_HEADERS([foo.h], [],
24851 [AC_MSG_ERROR([cannot find foo.h, bailing out])])
24852 AC_OUTPUT
24853 @end example
24854
24855 Many many (and many more) Autoconf macros were lacking proper quotation,
24856 including no less than@dots{} @code{AC_DEFUN} itself!
24857
24858 @example
24859 $ @kbd{cat configure.in}
24860 AC_DEFUN([AC_PROG_INSTALL],
24861 [# My own much better version
24862 ])
24863 AC_INIT
24864 AC_PROG_INSTALL
24865 AC_OUTPUT
24866 $ @kbd{autoconf-2.13}
24867 autoconf: Undefined macros:
24868 ***BUG in Autoconf--please report*** AC_FD_MSG
24869 ***BUG in Autoconf--please report*** AC_EPI
24870 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
24871 configure.in:5:AC_PROG_INSTALL
24872 $ @kbd{autoconf-2.50}
24873 $
24874 @end example
24875
24876
24877 @node New Macros
24878 @subsection New Macros
24879
24880 @cindex undefined macro
24881 @cindex @code{_m4_divert_diversion}
24882
24883 While Autoconf was relatively dormant in the late 1990s, Automake
24884 provided Autoconf-like macros for a while. Starting with Autoconf 2.50
24885 in 2001, Autoconf provided
24886 versions of these macros, integrated in the @code{AC_} namespace,
24887 instead of @code{AM_}. But in order to ease the upgrading via
24888 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
24889
24890 Unfortunately older versions of Automake (e.g., Automake 1.4)
24891 did not quote the names of these macros.
24892 Therefore, when @command{m4} finds something like
24893 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
24894 @code{AM_TYPE_PTRDIFF_T} is
24895 expanded, replaced with its Autoconf definition.
24896
24897 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
24898 complains, in its own words:
24899
24900 @example
24901 $ @kbd{cat configure.ac}
24902 AC_INIT([Example], [1.0], [bug-example@@example.org])
24903 AM_TYPE_PTRDIFF_T
24904 $ @kbd{aclocal-1.4}
24905 $ @kbd{autoconf}
24906 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
24907 aclocal.m4:17: the top level
24908 autom4te: m4 failed with exit status: 1
24909 $
24910 @end example
24911
24912 Modern versions of Automake no longer define most of these
24913 macros, and properly quote the names of the remaining macros.
24914 If you must use an old Automake, do not depend upon macros from Automake
24915 as it is simply not its job
24916 to provide macros (but the one it requires itself):
24917
24918 @example
24919 $ @kbd{cat configure.ac}
24920 AC_INIT([Example], [1.0], [bug-example@@example.org])
24921 AM_TYPE_PTRDIFF_T
24922 $ @kbd{rm aclocal.m4}
24923 $ @kbd{autoupdate}
24924 autoupdate: 'configure.ac' is updated
24925 $ @kbd{cat configure.ac}
24926 AC_INIT([Example], [1.0], [bug-example@@example.org])
24927 AC_CHECK_TYPES([ptrdiff_t])
24928 $ @kbd{aclocal-1.4}
24929 $ @kbd{autoconf}
24930 $
24931 @end example
24932
24933
24934 @node Hosts and Cross-Compilation
24935 @subsection Hosts and Cross-Compilation
24936 @cindex Cross compilation
24937
24938 Based on the experience of compiler writers, and after long public
24939 debates, many aspects of the cross-compilation chain have changed:
24940
24941 @itemize @minus
24942 @item
24943 the relationship between the build, host, and target architecture types,
24944
24945 @item
24946 the command line interface for specifying them to @command{configure},
24947
24948 @item
24949 the variables defined in @command{configure},
24950
24951 @item
24952 the enabling of cross-compilation mode.
24953 @end itemize
24954
24955 @sp 1
24956
24957 The relationship between build, host, and target have been cleaned up:
24958 the chain of default is now simply: target defaults to host, host to
24959 build, and build to the result of @command{config.guess}. Nevertheless,
24960 in order to ease the transition from 2.13 to 2.50, the following
24961 transition scheme is implemented. @emph{Do not rely on it}, as it will
24962 be completely disabled in a couple of releases (we cannot keep it, as it
24963 proves to cause more problems than it cures).
24964
24965 They all default to the result of running @command{config.guess}, unless
24966 you specify either @option{--build} or @option{--host}. In this case,
24967 the default becomes the system type you specified. If you specify both,
24968 and they're different, @command{configure} enters cross compilation
24969 mode, so it doesn't run any tests that require execution.
24970
24971 Hint: if you mean to override the result of @command{config.guess},
24972 prefer @option{--build} over @option{--host}.
24973
24974 @sp 1
24975
24976 For backward compatibility, @command{configure} accepts a system
24977 type as an option by itself. Such an option overrides the
24978 defaults for build, host, and target system types. The following
24979 configure statement configures a cross toolchain that runs on
24980 NetBSD/aarch64 but generates code for GNU Hurd/riscv64,
24981 which is also the build platform.
24982
24983 @example
24984 ./configure --host=aarch64-netbsd riscv64-gnu
24985 @end example
24986
24987 @sp 1
24988
24989 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
24990 and @code{target} had a different semantics before and after the
24991 invocation of @code{AC_CANONICAL_BUILD} etc. Now, the argument of
24992 @option{--build} is strictly copied into @code{build_alias}, and is left
24993 empty otherwise. After the @code{AC_CANONICAL_BUILD}, @code{build} is
24994 set to the canonicalized build type. To ease the transition, before,
24995 its contents is the same as that of @code{build_alias}. Do @emph{not}
24996 rely on this broken feature.
24997
24998 For consistency with the backward compatibility scheme exposed above,
24999 when @option{--host} is specified but @option{--build} isn't, the build
25000 system is assumed to be the same as @option{--host}, and
25001 @samp{build_alias} is set to that value. Eventually, this
25002 historically incorrect behavior will go away.
25003
25004 @sp 1
25005
25006 The former scheme to enable cross-compilation proved to cause more harm
25007 than good, in particular, it used to be triggered too easily, leaving
25008 regular end users puzzled in front of cryptic error messages.
25009 @command{configure} could even enter cross-compilation mode only
25010 because the compiler was not functional. This is mainly because
25011 @command{configure} used to try to detect cross-compilation, instead of
25012 waiting for an explicit flag from the user.
25013
25014 Now, @command{configure} enters cross-compilation mode if and only if
25015 @option{--host} is passed.
25016
25017 That's the short documentation. To ease the transition between 2.13 and
25018 its successors, a more complicated scheme is implemented. @emph{Do not
25019 rely on the following}, as it will be removed in the near future.
25020
25021 If you specify @option{--host}, but not @option{--build}, when
25022 @command{configure} performs the first compiler test it tries to run
25023 an executable produced by the compiler. If the execution fails, it
25024 enters cross-compilation mode. This is fragile. Moreover, by the time
25025 the compiler test is performed, it may be too late to modify the
25026 build-system type: other tests may have already been performed.
25027 Therefore, whenever you specify @option{--host}, be sure to specify
25028 @option{--build} too.
25029
25030 @example
25031 ./configure --build=x86_64-pc-linux-gnu --host=x86_64-w64-mingw64
25032 @end example
25033
25034 @noindent
25035 enters cross-compilation mode. The former interface, which
25036 consisted in setting the compiler to a cross-compiler without informing
25037 @command{configure} is obsolete. For instance, @command{configure}
25038 fails if it can't run the code generated by the specified compiler if you
25039 configure as follows:
25040
25041 @example
25042 ./configure CC=x86_64-w64-mingw64-gcc
25043 @end example
25044
25045
25046 @node AC_LIBOBJ vs LIBOBJS
25047 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
25048
25049 Up to Autoconf 2.13, the replacement of functions was triggered via the
25050 variable @code{LIBOBJS}. Since Autoconf 2.50, the macro
25051 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
25052 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
25053
25054 This change is mandated by the unification of the GNU Build System
25055 components. In particular, the various fragile techniques used to parse
25056 a @file{configure.ac} are all replaced with the use of traces. As a
25057 consequence, any action must be traceable, which obsoletes critical
25058 variable assignments. Fortunately, @code{LIBOBJS} was the only problem,
25059 and it can even be handled gracefully (read, ``without your having to
25060 change something'').
25061
25062 There were two typical uses of @code{LIBOBJS}: asking for a replacement
25063 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
25064
25065 @sp 1
25066
25067 As for function replacement, the fix is immediate: use
25068 @code{AC_LIBOBJ}. For instance:
25069
25070 @example
25071 LIBOBJS="$LIBOBJS fnmatch.o"
25072 LIBOBJS="$LIBOBJS malloc.$ac_objext"
25073 @end example
25074
25075 @noindent
25076 should be replaced with:
25077
25078 @example
25079 AC_LIBOBJ([fnmatch])
25080 AC_LIBOBJ([malloc])
25081 @end example
25082
25083 @sp 1
25084
25085 @ovindex LIBOBJDIR
25086 When used with Automake 1.10 or newer, a suitable value for
25087 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
25088 can be referenced from any @file{Makefile.am}. Even without Automake,
25089 arranging for @code{LIBOBJDIR} to be set correctly enables
25090 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
25091 The @code{LIBOBJDIR} feature is experimental.
25092
25093
25094 @node AC_ACT_IFELSE vs AC_TRY_ACT
25095 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
25096 @c the anchor keeps the old node name, to try to avoid breaking links
25097 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
25098
25099 @acindex{@var{ACT}_IFELSE}
25100 @acindex{TRY_@var{ACT}}
25101 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
25102 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
25103 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
25104 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
25105 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
25106 @code{AC_TRY_RUN}. The motivations where:
25107 @itemize @minus
25108 @item
25109 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
25110 quoting their arguments;
25111
25112 @item
25113 the combinatorial explosion is solved by decomposing on the one hand the
25114 generation of sources, and on the other hand executing the program;
25115
25116 @item
25117 this scheme helps supporting more languages than plain C and C++.
25118 @end itemize
25119
25120 In addition to the change of syntax, the philosophy has changed too:
25121 while emphasis was put on speed at the expense of accuracy, today's
25122 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
25123 expense of speed.
25124
25125
25126 As a perfect example of what is @emph{not} to be done, here is how to
25127 find out whether a header file contains a particular declaration, such
25128 as a typedef, a structure, a structure member, or a function. Use
25129 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
25130 header file; on some systems the symbol might be defined in another
25131 header file that the file you are checking includes.
25132
25133 As a (bad) example, here is how you should not check for C preprocessor
25134 symbols, either defined by header files or predefined by the C
25135 preprocessor: using @code{AC_EGREP_CPP}:
25136
25137 @example
25138 @group
25139 AC_EGREP_CPP(yes,
25140 [#ifdef _AIX
25141 yes
25142 #endif
25143 ], is_aix=yes, is_aix=no)
25144 @end group
25145 @end example
25146
25147 The above example, properly written would (i) use
25148 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
25149
25150 @example
25151 @group
25152 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
25153 [[#ifndef _AIX
25154 error: This isn't AIX!
25155 #endif
25156 ]])],
25157 [is_aix=yes],
25158 [is_aix=no])
25159 @end group
25160 @end example
25161
25162
25163 @c ============================= Generating Test Suites with Autotest
25164
25165 @node Using Autotest
25166 @chapter Generating Test Suites with Autotest
25167
25168 @cindex Autotest
25169
25170 @display
25171 @strong{N.B.: This section describes a feature which is still
25172 stabilizing. Although we believe that Autotest is useful as-is, this
25173 documentation describes an interface which might change in the future:
25174 do not depend upon Autotest without subscribing to the Autoconf mailing
25175 lists.}
25176 @end display
25177
25178 It is paradoxical that portable projects depend on nonportable tools
25179 to run their test suite. Autoconf by itself is the paragon of this
25180 problem: although it aims at perfectly portability, up to 2.13 its
25181 test suite was using DejaGNU, a rich and complex testing
25182 framework, but which is far from being standard on POSIX systems.
25183 Worse yet, it was likely to be missing on the most fragile platforms,
25184 the very platforms that are most likely to torture Autoconf and
25185 exhibit deficiencies.
25186
25187 To circumvent this problem, many package maintainers have developed their
25188 own testing framework, based on simple shell scripts whose sole outputs
25189 are exit status values describing whether the test succeeded. Most of
25190 these tests share common patterns, and this can result in lots of
25191 duplicated code and tedious maintenance.
25192
25193 Following exactly the same reasoning that yielded to the inception of
25194 Autoconf, Autotest provides a test suite generation framework, based on
25195 M4 macros building a portable shell script. The suite itself is
25196 equipped with automatic logging and tracing facilities which greatly
25197 diminish the interaction with bug reporters, and simple timing reports.
25198
25199 Autoconf itself has been using Autotest for years, and we do attest that
25200 it has considerably improved the strength of the test suite and the
25201 quality of bug reports. Other projects are known to use some generation
25202 of Autotest, such as Bison, GNU Wdiff, GNU Tar, each of
25203 them with different needs, and this usage has validated Autotest as a general
25204 testing framework.
25205
25206 Nonetheless, compared to DejaGNU, Autotest is inadequate for
25207 interactive tool testing, which is probably its main limitation.
25208
25209 @menu
25210 * Using an Autotest Test Suite:: Autotest and the user
25211 * Writing Testsuites:: Autotest macros
25212 * testsuite Invocation:: Running @command{testsuite} scripts
25213 * Making testsuite Scripts:: Using autom4te to create @command{testsuite}
25214 @end menu
25215
25216 @node Using an Autotest Test Suite
25217 @section Using an Autotest Test Suite
25218
25219 @menu
25220 * testsuite Scripts:: The concepts of Autotest
25221 * Autotest Logs:: Their contents
25222 @end menu
25223
25224 @node testsuite Scripts
25225 @subsection @command{testsuite} Scripts
25226
25227 @cindex @command{testsuite}
25228
25229 Generating testing or validation suites using Autotest is rather easy.
25230 The whole validation suite is held in a file to be processed through
25231 @command{autom4te}, itself using GNU M4 under the hood, to
25232 produce a stand-alone Bourne shell script which then gets distributed.
25233 Neither @command{autom4te} nor GNU M4 are needed at
25234 the installer's end.
25235
25236 @cindex test group
25237 Each test of the validation suite should be part of some test group. A
25238 @dfn{test group} is a sequence of interwoven tests that ought to be
25239 executed together, usually because one test in the group creates data
25240 files that a later test in the same group needs to read. Complex test
25241 groups make later debugging more tedious. It is much better to
25242 keep only a few tests per test group. Ideally there is only one test
25243 per test group.
25244
25245 For all but the simplest packages, some file such as @file{testsuite.at}
25246 does not fully hold all test sources, as these are often easier to
25247 maintain in separate files. Each of these separate files holds a single
25248 test group, or a sequence of test groups all addressing some common
25249 functionality in the package. In such cases, @file{testsuite.at}
25250 merely initializes the validation suite, and sometimes does elementary
25251 health checking, before listing include statements for all other test
25252 files. The special file @file{package.m4}, containing the
25253 identification of the package, is automatically included if found.
25254
25255 A convenient alternative consists in moving all the global issues
25256 (local Autotest macros, elementary health checking, and @code{AT_INIT}
25257 invocation) into the file @code{local.at}, and making
25258 @file{testsuite.at} be a simple list of @code{m4_include}s of sub test
25259 suites. In such case, generating the whole test suite or pieces of it
25260 is only a matter of choosing the @command{autom4te} command line
25261 arguments.
25262
25263 The validation scripts that Autotest produces are by convention called
25264 @command{testsuite}. When run, @command{testsuite} executes each test
25265 group in turn, producing only one summary line per test to say if that
25266 particular test succeeded or failed. At end of all tests, summarizing
25267 counters get printed. One debugging directory is left for each test
25268 group which failed, if any: such directories are named
25269 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
25270 the test group, and they include:
25271
25272 @itemize @bullet
25273 @item a debugging script named @file{run} which reruns the test in
25274 @dfn{debug mode} (@pxref{testsuite Invocation}). The automatic generation
25275 of debugging scripts has the purpose of easing the chase for bugs.
25276
25277 @item all the files created with @code{AT_DATA}
25278
25279 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
25280
25281 @item a log of the run, named @file{testsuite.log}
25282 @end itemize
25283
25284 In the ideal situation, none of the tests fail, and consequently no
25285 debugging directory is left behind for validation.
25286
25287 It often happens in practice that individual tests in the validation
25288 suite need to get information coming out of the configuration process.
25289 Some of this information, common for all validation suites, is provided
25290 through the file @file{atconfig}, automatically created by
25291 @code{AC_CONFIG_TESTDIR}. For configuration information which your
25292 testing environment specifically needs, you might prepare an optional
25293 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
25294 The configuration process produces @file{atconfig} and @file{atlocal}
25295 out of these two input files, and these two produced files are
25296 automatically read by the @file{testsuite} script.
25297
25298 Here is a diagram showing the relationship between files.
25299
25300 @noindent
25301 Files used in preparing a software package for distribution:
25302
25303 @example
25304 [package.m4] -->.
25305 \
25306 subfile-1.at ->. [local.at] ---->+
25307 ... \ \
25308 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
25309 ... /
25310 subfile-n.at ->'
25311 @end example
25312
25313 @noindent
25314 Files used in configuring a software package:
25315
25316 @example
25317 .--> atconfig
25318 /
25319 [atlocal.in] --> config.status* --<
25320 \
25321 `--> [atlocal]
25322 @end example
25323
25324 @noindent
25325 Files created during test suite execution:
25326
25327 @example
25328 atconfig -->. .--> testsuite.log
25329 \ /
25330 >-- testsuite* --<
25331 / \
25332 [atlocal] ->' `--> [testsuite.dir]
25333 @end example
25334
25335
25336 @node Autotest Logs
25337 @subsection Autotest Logs
25338
25339 When run, the test suite creates a log file named after itself, e.g., a
25340 test suite named @command{testsuite} creates @file{testsuite.log}. It
25341 contains a lot of information, usually more than maintainers actually
25342 need, but therefore most of the time it contains all that is needed:
25343
25344 @table @asis
25345 @item command line arguments
25346 A bad but unfortunately widespread habit consists of
25347 setting environment variables before the command, such as in
25348 @samp{CC=my-home-grown-cc ./testsuite}. The test suite does not
25349 know this change, hence (i) it cannot report it to you, and (ii)
25350 it cannot preserve the value of @code{CC} for subsequent runs.
25351 Autoconf faced exactly the same problem, and solved it by asking
25352 users to pass the variable definitions as command line arguments.
25353 Autotest requires this rule, too, but has no means to enforce it; the log
25354 then contains a trace of the variables that were changed by the user.
25355
25356 @item @file{ChangeLog} excerpts
25357 The topmost lines of all the @file{ChangeLog} files found in the source
25358 hierarchy. This is especially useful when bugs are reported against
25359 development versions of the package, since the version string does not
25360 provide sufficient information to know the exact state of the sources
25361 the user compiled. Of course, this relies on the use of a
25362 @file{ChangeLog}.
25363
25364 @item build machine
25365 Running a test suite in a cross-compile environment is not an easy task,
25366 since it would mean having the test suite run on a machine @var{build},
25367 while running programs on a machine @var{host}. It is much simpler to
25368 run both the test suite and the programs on @var{host}, but then, from
25369 the point of view of the test suite, there remains a single environment,
25370 @var{host} = @var{build}. The log contains relevant information on the
25371 state of the @var{build} machine, including some important environment
25372 variables.
25373 @c FIXME: How about having an M4sh macro to say "hey, log the value
25374 @c of '@dots{}'"? This would help both Autoconf and Autotest.
25375
25376 @item tested programs
25377 The absolute file name and answers to @option{--version} of the tested
25378 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
25379
25380 @item configuration log
25381 The contents of @file{config.log}, as created by @command{configure},
25382 are appended. It contains the configuration flags and a detailed report
25383 on the configuration itself.
25384 @end table
25385
25386
25387 @node Writing Testsuites
25388 @section Writing @file{testsuite.at}
25389
25390 The @file{testsuite.at} is a Bourne shell script making use of special
25391 Autotest M4 macros. It often contains a call to @code{AT_INIT} near
25392 its beginning followed by one call to @code{m4_include} per source file
25393 for tests. Each such included file, or the remainder of
25394 @file{testsuite.at} if include files are not used, contain a sequence of
25395 test groups. Each test group begins with a call to @code{AT_SETUP},
25396 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
25397 and then completes with a call to @code{AT_CLEANUP}. Multiple test
25398 groups can be categorized by a call to @code{AT_BANNER}.
25399
25400 All of the public Autotest macros have all-uppercase names in the
25401 namespace @samp{^AT_} to prevent them from accidentally conflicting with
25402 other text; Autoconf also reserves the namespace @samp{^_AT_} for
25403 internal macros. All shell variables used in the testsuite for internal
25404 purposes have mostly-lowercase names starting with @samp{at_}. Autotest
25405 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
25406 makes use of the file system namespace @samp{^at-}.
25407
25408 Since Autoconf is built on top of M4sugar (@pxref{Programming in
25409 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
25410 of those namespaces (@samp{^_?\(m4\|AS\)_}). In general, you
25411 @emph{should not use} the namespace of a package that does not own the
25412 macro or shell code you are writing.
25413
25414 @defmac AT_INIT (@ovar{name})
25415 @atindex{INIT}
25416 @c FIXME: Not clear, plus duplication of the information.
25417 Initialize Autotest. Giving a @var{name} to the test suite is
25418 encouraged if your package includes several test suites. Before this
25419 macro is called, @code{AT_PACKAGE_STRING} and
25420 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
25421 information about the testsuite to the user. Typically, these macros
25422 are provided by a file @file{package.m4} built by @command{make}
25423 (@pxref{Making testsuite Scripts}), in order to inherit the package
25424 name, version, and bug reporting address from @file{configure.ac}.
25425 @end defmac
25426
25427 @defmac AT_COPYRIGHT (@var{copyright-notice})
25428 @atindex{COPYRIGHT}
25429 @cindex Copyright Notice
25430 State that, in addition to the Free Software Foundation's copyright on
25431 the Autotest macros, parts of your test suite are covered by
25432 @var{copyright-notice}.
25433
25434 The @var{copyright-notice} shows up in both the head of
25435 @command{testsuite} and in @samp{testsuite --version}.
25436 @end defmac
25437
25438 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
25439 @ovar{action-if-given}, @ovar{action-if-not-given})
25440 @atindex{ARG_OPTION}
25441 @vrindex at_arg_@var{option}
25442 Accept options from the space-separated list @var{options}, a list that
25443 has leading dashes removed from the options. Long options will be
25444 prefixed with @samp{--}, single-character options with @samp{-}. The
25445 first word in this list is the primary @var{option}, any others are
25446 assumed to be short-hand aliases. The variable associated with it
25447 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
25448 with underscores.
25449
25450 If the user passes @option{--@var{option}} to the @command{testsuite},
25451 the variable will be set to @samp{:}. If the user does not pass the
25452 option, or passes @option{--no-@var{option}}, then the variable will be
25453 set to @samp{false}.
25454
25455 @vrindex at_optarg
25456 @vrindex at_optarg_@var{option}
25457 @var{action-if-given} is run each time the option is encountered; here,
25458 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
25459 appropriate. @code{at_optarg} is actually just a copy of
25460 @code{at_arg_@var{option}}.
25461
25462 @var{action-if-not-given} will be run once after option parsing is
25463 complete and if no option from @var{options} was used.
25464
25465 @var{help-text} is added to the end of the list of options shown in
25466 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25467
25468 It is recommended that you use a package-specific prefix to @var{options}
25469 names in order to avoid clashes with future Autotest built-in options.
25470 @end defmac
25471
25472 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
25473 @ovar{action-if-given}, @ovar{action-if-not-given})
25474 @atindex{ARG_OPTION_ARG}
25475 @vrindex at_arg_@var{option}
25476 Accept options with arguments from the space-separated list
25477 @var{options}, a list that has leading dashes removed from the options.
25478 Long options will be prefixed with @samp{--}, single-character options
25479 with @samp{-}. The first word in this list is the primary @var{option},
25480 any others are assumed to be short-hand aliases. The variable associated
25481 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
25482 replaced with underscores.
25483
25484 If the user passes @option{--@var{option}=@var{arg}} or
25485 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
25486 variable will be set to @samp{@var{arg}}.
25487
25488 @vrindex at_optarg
25489 @var{action-if-given} is run each time the option is encountered; here,
25490 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
25491 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
25492
25493 @var{action-if-not-given} will be run once after option parsing is
25494 complete and if no option from @var{options} was used.
25495
25496 @var{help-text} is added to the end of the list of options shown in
25497 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25498
25499 It is recommended that you use a package-specific prefix to @var{options}
25500 names in order to avoid clashes with future Autotest built-in options.
25501 @end defmac
25502
25503 @defmac AT_COLOR_TESTS
25504 @atindex{COLOR_TESTS}
25505 Enable colored test results by default when the output is connected to
25506 a terminal.
25507 @end defmac
25508
25509 @defmac AT_TESTED (@var{executables})
25510 @atindex{TESTED}
25511 Log the file name and answer to @option{--version} of each program in
25512 space-separated list @var{executables}. Several invocations register
25513 new executables, in other words, don't fear registering one program
25514 several times.
25515
25516 Autotest test suites rely on @env{PATH} to find the tested program.
25517 This avoids the need to generate absolute names of the various tools, and
25518 makes it possible to test installed programs. Therefore, knowing which
25519 programs are being exercised is crucial to understanding problems in
25520 the test suite itself, or its occasional misuses. It is a good idea to
25521 also subscribe foreign programs you depend upon, to avoid incompatible
25522 diagnostics.
25523
25524 @var{executables} is implicitly wrapped in shell double quotes, but it
25525 will still use shell variable expansion (@samp{$}), command substitution
25526 (@samp{`}), and backslash escaping (@samp{\}). In particular, the
25527 @env{EXEEXT} variable is available if it is passed to the testsuite
25528 via @file{atlocal} or @file{atconfig}.
25529 @end defmac
25530
25531 @defmac AT_PREPARE_TESTS (@var{shell-code})
25532 @atindex{PREPARE_TESTS}
25533 Execute @var{shell-code} in the main testsuite process,
25534 after initializing the test suite and processing command-line options,
25535 but before running any tests. If this macro is used several times,
25536 all of the @var{shell-code}s will be executed,
25537 in the order they appeared in @file{testsuite.at}.
25538
25539 One reason to use @code{AT_PREPARE_TESTS} is when the programs under
25540 test are sensitive to environment variables: you can unset all these
25541 variables or reset them to safe values in @var{shell-code}.
25542
25543 @var{shell-code} is only executed if at least one test is going to be
25544 run. In particular, it will not be executed if any of the @option{--help},
25545 @option{--version}, @option{--list}, or @option{--clean} options are
25546 given to @command{testsuite} (@pxref{testsuite Invocation}).
25547 @end defmac
25548
25549 @defmac AT_PREPARE_EACH_TEST (@var{shell-code})
25550 @atindex{AT_PREPARE_EACH_TEST}
25551 Execute @var{shell-code} in each test group's subshell, at the point of
25552 the @code{AT_SETUP} that starts the test group.
25553 @end defmac
25554
25555 @defmac AT_TEST_HELPER_FN (@var{name}, @var{args}, @var{description}, @var{code})
25556 Define a shell function that will be available to the code for each test
25557 group. Its name will be @code{ath_fn_@var{name}}, and its body will be
25558 @var{code}. (The prefix prevents name conflicts with shell functions
25559 defined by M4sh and Autotest.)
25560
25561 @var{args} should describe the function's arguments and @var{description}
25562 what it does; these are used only for documentation comments in the
25563 generated testsuite script.
25564 @end defmac
25565
25566 @sp 1
25567
25568 @defmac AT_BANNER (@var{test-category-name})
25569 @atindex{BANNER}
25570 This macro identifies the start of a category of related test groups.
25571 When the resulting @file{testsuite} is invoked with more than one test
25572 group to run, its output will include a banner containing
25573 @var{test-category-name} prior to any tests run from that category. The
25574 banner should be no more than about 40 or 50 characters. A blank banner
25575 indicates uncategorized tests; an empty line will be inserted after
25576 tests from an earlier category, effectively ending that category.
25577 @end defmac
25578
25579 @defmac AT_SETUP (@var{test-group-name})
25580 @atindex{SETUP}
25581 This macro starts a group of related tests, all to be executed in the
25582 same subshell. It accepts a single argument, which holds a few words
25583 (no more than about 30 or 40 characters) quickly describing the purpose
25584 of the test group being started. @var{test-group-name} must not expand
25585 to unbalanced quotes, although quadrigraphs can be used.
25586 @end defmac
25587
25588 @defmac AT_KEYWORDS (@var{keywords})
25589 @atindex{KEYWORDS}
25590 Associate the space-separated list of @var{keywords} to the enclosing
25591 test group. This makes it possible to run ``slices'' of the test suite.
25592 For instance, if some of your test groups exercise some @samp{foo}
25593 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
25594 @samp{./testsuite -k foo} to run exclusively these test groups. The
25595 @var{test-group-name} of the test group is automatically recorded to
25596 @code{AT_KEYWORDS}.
25597
25598 Several invocations within a test group accumulate new keywords. In
25599 other words, don't fear registering the same keyword several times in a
25600 test group.
25601 @end defmac
25602
25603 @defmac AT_CAPTURE_FILE (@var{file})
25604 @atindex{CAPTURE_FILE}
25605 If the current test group fails, log the contents of @var{file}.
25606 Several identical calls within one test group have no additional effect.
25607 @end defmac
25608
25609 @defmac AT_FAIL_IF (@var{shell-condition})
25610 @atindex{FAIL_IF}
25611 Make the test group fail and skip the rest of its execution, if
25612 @var{shell-condition} is true. @var{shell-condition} is a shell expression
25613 such as a @code{test} command. Tests before @command{AT_FAIL_IF}
25614 will be executed and may still cause the test group to be skipped.
25615 You can instantiate this macro many times from within the same test group.
25616
25617 You should use this macro only for very simple failure conditions. If the
25618 @var{shell-condition} could emit any kind of output you should instead
25619 use @command{AT_CHECK} like
25620 @example
25621 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
25622 @end example
25623 @noindent
25624 so that such output is properly recorded in the @file{testsuite.log}
25625 file.
25626 @end defmac
25627
25628 @defmac AT_SKIP_IF (@var{shell-condition})
25629 @atindex{SKIP_IF}
25630 Determine whether the test should be skipped because it requires
25631 features that are unsupported on the machine under test.
25632 @var{shell-condition} is a shell expression such as a @code{test}
25633 command. Tests before @command{AT_SKIP_IF} will be executed
25634 and may still cause the test group to fail. You can instantiate this
25635 macro many times from within the same test group.
25636
25637 You should use this macro only for very simple skip conditions. If the
25638 @var{shell-condition} could emit any kind of output you should instead
25639 use @command{AT_CHECK} like
25640 @example
25641 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
25642 @end example
25643 @noindent
25644 so that such output is properly recorded in the @file{testsuite.log}
25645 file.
25646 @end defmac
25647
25648 @defmac AT_XFAIL_IF (@var{shell-condition})
25649 @atindex{XFAIL_IF}
25650 Determine whether the test is expected to fail because it is a known
25651 bug (for unsupported features, you should skip the test).
25652 @var{shell-condition} is a shell expression such as a @code{test}
25653 command; you can instantiate this macro many times from within the
25654 same test group, and one of the conditions is enough to turn
25655 the test into an expected failure.
25656 @end defmac
25657
25658 @defmac AT_CLEANUP
25659 @atindex{CLEANUP}
25660 End the current test group.
25661 @end defmac
25662
25663 @sp 1
25664
25665 @defmac AT_DATA (@var{file}, @var{contents})
25666 @defmacx AT_DATA_UNQUOTED (@var{file}, @var{contents})
25667 @atindex{DATA}
25668 Initialize an input data @var{file} with given @var{contents}. Of
25669 course, the @var{contents} have to be properly quoted between square
25670 brackets to protect against included commas or spurious M4
25671 expansion. @var{contents} must be empty or end with a newline.
25672 @var{file} must
25673 be a single shell word that expands into a single file name.
25674
25675 The difference between @code{AT_DATA} and @code{AT_DATA_UNQUOTED} is
25676 that only the latter performs shell variable expansion (@samp{$}),
25677 command substitution (@samp{`}), and backslash escaping (@samp{\})
25678 on @var{contents}.
25679 @end defmac
25680
25681 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25682 @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25683 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25684 @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25685 @atindex{CHECK}
25686 @atindex{CHECK_UNQUOTED}
25687 @vrindex at_status
25688 Perform a test, by running the shell @var{commands} in a subshell.
25689 @var{commands} is output as-is, so shell expansions are honored.
25690 These commands are expected to have a final exit status of @var{status},
25691 and to produce output as described by @var{stdout} and @var{stderr}
25692 (see below).
25693
25694 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25695
25696 If @var{commands} exit with unexpected status 77, then the rest of the
25697 test group is skipped. If @var{commands} exit with unexpected status
25698 99, then the test group is immediately failed; this is called a
25699 @emph{hard failure}. Otherwise, the test is considered to have
25700 succeeded if all of the status, stdout, and stderr expectations were
25701 met.
25702
25703 If @var{run-if-fail} is nonempty, it provides extra shell commands to
25704 run when the test fails; if @var{run-if-pass} is nonempty, it provides
25705 extra shell commands to run when the test succeeds. These commands are
25706 @emph{not} run in a subshell, and they are not run when the test group
25707 is skipped (exit code 77) or hard-failed (exit code 99). They may
25708 change whether the test group is considered to have succeeded, by
25709 modifying the shell variable @code{at_failed}; set it to @code{:} to
25710 indicate that the test group has failed, or @code{false} to indicate
25711 that it has succeeded.
25712
25713 The exit status of @var{commands} is available to @var{run-if-fail} and
25714 @var{run-if-pass} commands in the @code{at_status} shell variable. The
25715 output from @var{commands} is also available, in the files named by the
25716 @code{at_stdout} and @code{at_stderr} variables.
25717
25718 If @var{status} is the literal @samp{ignore}, then the exit status of
25719 @var{commands} is not checked, except for the special cases of 77 (skip)
25720 and 99 (hard failure). The existence of hard failures allows one to
25721 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
25722 feature has not yet been implemented, but to still distinguish between
25723 gracefully handling the missing feature and dumping core.
25724
25725 If the value of the @var{stdout} or @var{stderr} parameter is one of the
25726 literals in the following table, then the test treats the output
25727 according to the rules of that literal.
25728
25729 @table @samp
25730 @item ignore
25731 The content of the output is ignored, but still captured in the test
25732 group log (if the testsuite is run with the @option{-v} option, the test
25733 group log is displayed as the test is run; if the test group later
25734 fails, the test group log is also copied into the overall testsuite
25735 log). This action is valid for both @var{stdout} and @var{stderr}.
25736
25737 @item ignore-nolog
25738 The content of the output is ignored, and nothing is captured in the log
25739 files. If @var{commands} are likely to produce binary output (including
25740 long lines) or large amounts of output, then logging the output can make
25741 it harder to locate details related to subsequent tests within the
25742 group, and could potentially corrupt terminal display of a user running
25743 @command{testsuite -v}. This action is valid for both @var{stdout} and
25744 @var{stderr}.
25745
25746 @item stdout
25747 Only valid as the @var{stdout} parameter. Capture the content of
25748 standard output in both a file named @file{stdout} and the test group log.
25749 Subsequent commands in the test group can then post-process the file.
25750 This action is often used when it is desired to use @command{grep} to
25751 look for a substring in the output, or when the output must be
25752 post-processed to normalize error messages into a common form.
25753
25754 @item stderr
25755 Only valid as the @var{stderr} parameter. Capture the content of
25756 standard error in both a file named @file{stderr} and the test group log.
25757
25758 @item stdout-nolog
25759 @itemx stderr-nolog
25760 Like @samp{stdout} or @samp{stderr}, except that the captured output is
25761 not duplicated into the test group log. This action is particularly
25762 useful for an intermediate check that produces large amounts of data,
25763 which will be followed by another check that filters down to the
25764 relevant data, as it makes it easier to locate details in the log.
25765
25766 @item expout
25767 Only valid as the @var{stdout} parameter. Compare standard output with
25768 the previously created file @file{expout}, and list any differences in
25769 the testsuite log.
25770
25771 @item experr
25772 Only valid as the @var{stderr} parameter. Compare standard error with
25773 the previously created file @file{experr}, and list any differences in
25774 the testsuite log.
25775 @end table
25776
25777 Otherwise, the values of the @var{stdout} and @var{stderr} parameters
25778 are treated as text that must exactly match the output given by
25779 @var{commands} on standard output and standard error (including an empty
25780 parameter for no output); any differences are captured in the testsuite
25781 log and the test is failed (unless an unexpected exit status of 77
25782 skipped the test instead).
25783
25784 @code{AT_CHECK_UNQUOTED} performs shell variable expansion (@samp{$}),
25785 command substitution (@samp{`}), and backslash escaping (@samp{\}) on
25786 comparison text given in the @var{stdout} and @var{stderr} parameters;
25787 @code{AT_CHECK} does not. There is no difference in the interpretation
25788 of @var{commands}.
25789 @end defmac
25790
25791 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
25792 @ovar{run-if-fail}, @ovar{run-if-pass})
25793 @atindex{CHECK_EUNIT}
25794 Initialize and execute an Erlang module named @var{module} that performs
25795 tests following the @var{test-spec} EUnit test specification.
25796 @var{test-spec} must be a valid EUnit test specification, as defined in
25797 the @uref{https://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
25798 Reference Manual}. @var{erlflags} are optional command-line options
25799 passed to the Erlang interpreter to execute the test Erlang module.
25800 Typically, @var{erlflags} defines at least the paths to directories
25801 containing the compiled Erlang modules under test, as @samp{-pa path1
25802 path2 ...}.
25803
25804 For example, the unit tests associated with Erlang module @samp{testme},
25805 which compiled code is in subdirectory @file{src}, can be performed
25806 with:
25807
25808 @example
25809 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
25810 [-pa "$@{abs_top_builddir@}/src"])
25811 @end example
25812
25813 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25814
25815 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
25816 must be defined as the path of the Erlang interpreter, the path of the
25817 Erlang compiler, and the command-line flags to pass to the compiler,
25818 respectively. Those variables should be configured in
25819 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
25820 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
25821 variables are automatically defined in the testsuite. If @code{ERL} or
25822 @code{ERLC} is not defined, the test group is skipped.
25823
25824 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
25825 be loaded, the test group is skipped. Otherwise, if @var{test-spec} is
25826 an invalid EUnit test specification, the test group fails. Otherwise,
25827 if the EUnit test passes, shell commands @var{run-if-pass} are executed
25828 or, if the EUnit test fails, shell commands @var{run-if-fail} are
25829 executed and the test group fails.
25830
25831 Only the generated test Erlang module is automatically compiled and
25832 executed. If @var{test-spec} involves testing other Erlang modules,
25833 e.g. module @samp{testme} in the example above, those modules must be
25834 already compiled.
25835
25836 If the testsuite is run in verbose mode and with the @option{--verbose} option,
25837 EUnit is also run in verbose mode to output more details about
25838 individual unit tests.
25839 @end defmac
25840
25841
25842 @node testsuite Invocation
25843 @section Running @command{testsuite} Scripts
25844 @cindex @command{testsuite}
25845
25846 Autotest test suites support the following options:
25847
25848 @table @option
25849 @item --help
25850 @itemx -h
25851 Display the list of options and exit successfully.
25852
25853 @item --version
25854 @itemx -V
25855 Display the version of the test suite and exit successfully.
25856
25857 @item --directory=@var{dir}
25858 @itemx -C @var{dir}
25859 Change the current directory to @var{dir} before creating any files.
25860 Useful for running the testsuite in a subdirectory from a top-level
25861 Makefile.
25862
25863 @item --jobs@r{[}=@var{n}@r{]}
25864 @itemx -j@ovar{n}
25865 Run @var{n} tests in parallel, if possible. If @var{n} is not given,
25866 run all given tests in parallel. Note that there should be no space
25867 before the argument to @option{-j}, as @option{-j @var{number}} denotes
25868 the separate arguments @option{-j} and @option{@var{number}}, see below.
25869
25870 In parallel mode, the standard input device of the testsuite script is
25871 not available to commands inside a test group. Furthermore, banner
25872 lines are not printed, and the summary line for each test group is
25873 output after the test group completes. Summary lines may appear
25874 unordered. If verbose and trace output are enabled (see below), they
25875 may appear intermixed from concurrently running tests.
25876
25877 Parallel mode requires the @command{mkfifo} command to work, and will be
25878 silently disabled otherwise.
25879
25880 @item --clean
25881 @itemx -c
25882 Remove all the files the test suite might have created and exit. Meant
25883 for @code{clean} Make targets.
25884
25885 @item --list
25886 @itemx -l
25887 List all the tests (or only the selection), including their possible
25888 keywords.
25889 @end table
25890
25891 @sp 1
25892
25893 By default all tests are performed (or described with @option{--list})
25894 silently in the default environment, but the environment, set of tests,
25895 and verbosity level can be tuned:
25896
25897 @table @samp
25898 @item @var{variable}=@var{value}
25899 Set the environment @var{variable} to @var{value}. Use this rather
25900 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
25901 different environment.
25902
25903 @cindex @code{AUTOTEST_PATH}
25904 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
25905 to @env{PATH}. Relative directory names (not starting with
25906 @samp{/}) are considered to be relative to the top level of the
25907 package being built. All directories are made absolute, first
25908 starting from the top level @emph{build} tree, then from the
25909 @emph{source} tree. For instance @samp{./testsuite
25910 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
25911 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
25912 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
25913 @env{PATH}.
25914
25915 @item @var{number}
25916 @itemx @var{number}-@var{number}
25917 @itemx @var{number}-
25918 @itemx -@var{number}
25919 Add the corresponding test groups, with obvious semantics, to the
25920 selection.
25921
25922 @item --keywords=@var{keywords}
25923 @itemx -k @var{keywords}
25924 Add to the selection the test groups with title or keywords (arguments
25925 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
25926 of the comma separated list @var{keywords}, case-insensitively. Use
25927 @samp{!} immediately before the keyword to invert the selection for this
25928 keyword. By default, the keywords match whole words; enclose them in
25929 @samp{.*} to also match parts of words.
25930
25931 For example, running
25932
25933 @example
25934 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
25935 @end example
25936
25937 @noindent
25938 selects all tests tagged @samp{autoupdate} @emph{and} with tags
25939 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
25940 etc.), while
25941
25942 @example
25943 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
25944 @end example
25945
25946 @noindent
25947 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
25948 containing @samp{FUNC}.
25949
25950 @item --errexit
25951 @itemx -e
25952 If any test fails, immediately abort testing. This implies
25953 @option{--debug}: post test group clean up, and top-level logging
25954 are inhibited. This option is meant for the full test
25955 suite, it is not really useful for generated debugging scripts.
25956 If the testsuite is run in parallel mode using @option{--jobs},
25957 then concurrently running tests will finish before exiting.
25958
25959 @item --verbose
25960 @itemx -v
25961 Force more verbosity in the detailed output of what is being done. This
25962 is the default for debugging scripts.
25963
25964 @item --color
25965 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
25966 Enable colored test results. Without an argument, or with @samp{always},
25967 test results will be colored. With @samp{never}, color mode is turned
25968 off. Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
25969 the testsuite author, or the argument @samp{auto} is given, then test
25970 results are colored if standard output is connected to a terminal.
25971
25972 @item --debug
25973 @itemx -d
25974 Do not remove the files after a test group was performed---but they are
25975 still removed @emph{before}, therefore using this option is sane when
25976 running several test groups. Create debugging scripts. Do not
25977 overwrite the top-level
25978 log (in order to preserve a supposedly existing full log file). This is
25979 the default for debugging scripts, but it can also be useful to debug
25980 the testsuite itself.
25981
25982 @item --recheck
25983 Add to the selection all test groups that failed or passed unexpectedly
25984 during the last non-debugging test run.
25985
25986 @item --trace
25987 @itemx -x
25988 Trigger shell tracing of the test groups.
25989 @end table
25990
25991 Besides these options accepted by every Autotest testsuite, the
25992 testsuite author might have added package-specific options
25993 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
25994 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
25995 the package documentation for details.
25996
25997
25998 @node Making testsuite Scripts
25999 @section Making @command{testsuite} Scripts
26000
26001 For putting Autotest into movement, you need some configuration and
26002 makefile machinery. We recommend, at least if your package uses deep or
26003 shallow hierarchies, that you use @file{tests/} as the name of the
26004 directory holding all your tests and their makefile. Here is a
26005 check list of things to do, followed by an example, taking into
26006 consideration whether you are also using Automake.
26007
26008 @itemize @minus
26009
26010 @item
26011 @cindex @file{package.m4}
26012 @atindex{PACKAGE_STRING}
26013 @atindex{PACKAGE_BUGREPORT}
26014 @atindex{PACKAGE_NAME}
26015 @atindex{PACKAGE_TARNAME}
26016 @atindex{PACKAGE_VERSION}
26017 @atindex{PACKAGE_URL}
26018 Make sure to create the file @file{package.m4}, which defines the
26019 identity of the package. It must define @code{AT_PACKAGE_STRING}, the
26020 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
26021 address to which bug reports should be sent. For sake of completeness,
26022 we suggest that you also define @code{AT_PACKAGE_NAME},
26023 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
26024 @code{AT_PACKAGE_URL}.
26025 @xref{Initializing configure}, for a description of these variables.
26026 Be sure to distribute @file{package.m4} and to put it into the source
26027 hierarchy: the test suite ought to be shipped! See below for an example.
26028
26029 @item
26030 Invoke @code{AC_CONFIG_TESTDIR} in your @file{configure.ac}.
26031
26032 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvarv{test-path, directory})
26033 @acindex{CONFIG_TESTDIR}
26034 An Autotest test suite is to be configured in @var{directory}. This
26035 macro causes @file{@var{directory}/atconfig} to be created by
26036 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
26037 @var{test-path} (@pxref{testsuite Invocation}).
26038 @end defmac
26039
26040 @item
26041 Still within @file{configure.ac}, as appropriate, ensure that some
26042 @code{AC_CONFIG_FILES} command includes substitution for
26043 @file{tests/atlocal}.
26044
26045 @item
26046 Also within your @file{configure.ac}, arrange for the @code{AUTOM4TE}
26047 variable to be set.
26048
26049 @item
26050 The appropriate @file{Makefile} should be modified so the validation in
26051 your package is triggered by @samp{make check}.
26052 @end itemize
26053
26054 The following example demonstrates the above checklist, first by
26055 assuming that you are using Automake (see below for tweaks to make to
26056 get the same results without Automake). Begin by adding the following
26057 lines to your @file{configure.ac}:
26058
26059 @example
26060 # Initialize the test suite.
26061 AC_CONFIG_TESTDIR([tests])
26062 AC_CONFIG_FILES([tests/Makefile tests/atlocal])
26063 AM_MISSING_PROG([AUTOM4TE], [autom4te])
26064 @end example
26065
26066 Next, add the following lines to your @file{tests/Makefile.am}, in order
26067 to link @samp{make check} with a validation suite.
26068
26069 @example
26070 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
26071 printf >'$@@' '%s\n' \
26072 '# Signature of the current package.' \
26073 'm4_define([AT_PACKAGE_NAME], [$(PACKAGE_NAME)])' \
26074 'm4_define([AT_PACKAGE_TARNAME], [$(PACKAGE_TARNAME)])' \
26075 'm4_define([AT_PACKAGE_VERSION], [$(PACKAGE_VERSION)])' \
26076 'm4_define([AT_PACKAGE_STRING], [$(PACKAGE_STRING)])' \
26077 'm4_define([AT_PACKAGE_URL], [$(PACKAGE_URL)])' \
26078 'm4_define([AT_PACKAGE_BUGREPORT], [$(PACKAGE_BUGREPORT)])'
26079
26080 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
26081 TESTSUITE = $(srcdir)/testsuite
26082
26083 check-local: atconfig atlocal $(TESTSUITE)
26084 $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
26085
26086 installcheck-local: atconfig atlocal $(TESTSUITE)
26087 $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
26088 $(TESTSUITEFLAGS)
26089
26090 clean-local:
26091 test ! -f '$(TESTSUITE)' || \
26092 $(SHELL) '$(TESTSUITE)' --clean
26093
26094 AUTOTEST = $(AUTOM4TE) --language=autotest
26095 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
26096 $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
26097 mv $@@.tmp $@@
26098 @end example
26099
26100 Note that the built testsuite is distributed; this is necessary because
26101 users might not have Autoconf installed, and thus would not be able to
26102 rebuild it. Likewise, the use of Automake's @code{AM_MISSING_PROG} will
26103 arrange for the definition of @code{$AUTOM4TE} within the Makefile to
26104 provide the user with
26105 a nicer error message if they modify a source file to the testsuite, and
26106 accidentally trigger the rebuild rules.
26107
26108 You might want to list explicitly the dependencies, i.e., the list of
26109 the files @file{testsuite.at} includes.
26110
26111 If you don't use Automake, you should make the following tweaks. In
26112 your @file{configure.ac}, replace the @code{AM_MISSING_PROG} line above
26113 with @code{AC_PATH_PROG([AUTOM4TE], [autom4te], [false])}. You are
26114 welcome to also try using the @command{missing} script from the Automake
26115 project instead of @command{false}, to try to get a nicer error message
26116 when the user modifies prerequisites but did not have Autoconf
26117 installed, but at that point you may be better off using Automake.
26118 Then, take the code suggested above for @file{tests/@/Makefile.am} and
26119 place it in your @file{tests/@/Makefile.in} instead. Add code to your
26120 @file{tests/@/Makefile.in} to ensure that @code{$(EXTRA_DIST)} files are
26121 distributed, as well as adding the following additional lines to prepare
26122 the set of needed Makefile variables:
26123
26124 @example
26125 subdir = tests
26126 PACKAGE_NAME = @@PACKAGE_NAME@@
26127 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
26128 PACKAGE_VERSION = @@PACKAGE_VERSION@@
26129 PACKAGE_STRING = @@PACKAGE_STRING@@
26130 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
26131 PACKAGE_URL = @@PACKAGE_URL@@
26132 AUTOM4TE = @@AUTOM4TE@@
26133
26134 atconfig: $(top_builddir)/config.status
26135 cd $(top_builddir) && \
26136 $(SHELL) ./config.status $(subdir)/$@@
26137
26138 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
26139 cd $(top_builddir) && \
26140 $(SHELL) ./config.status $(subdir)/$@@
26141 @end example
26142
26143 Using the above example (with or without Automake), and assuming you
26144 were careful to not initialize @samp{TESTSUITEFLAGS} within your
26145 makefile, you can now fine-tune test suite execution at runtime by
26146 altering this variable, for example:
26147
26148 @example
26149 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
26150 @end example
26151
26152
26153
26154 @c =============================== Frequent Autoconf Questions, with answers
26155
26156 @node FAQ
26157 @chapter Frequent Autoconf Questions, with answers
26158
26159 Several questions about Autoconf come up occasionally. Here some of them
26160 are addressed.
26161
26162 @menu
26163 * Distributing:: Distributing @command{configure} scripts
26164 * Why GNU M4:: Why not use the standard M4?
26165 * Bootstrapping:: Autoconf and GNU M4 require each other?
26166 * Why Not Imake:: Why GNU uses @command{configure} instead of Imake
26167 * Defining Directories:: Passing @code{datadir} to program
26168 * Autom4te Cache:: What is it? Can I remove it?
26169 * Present But Cannot Be Compiled:: Compiler and Preprocessor Disagree
26170 * Expanded Before Required:: Expanded Before Required
26171 * Debugging:: Debugging @command{configure} scripts
26172 @end menu
26173
26174 @node Distributing
26175 @section Distributing @command{configure} Scripts
26176 @cindex License
26177
26178 @display
26179 What are the restrictions on distributing @command{configure}
26180 scripts that Autoconf generates? How does that affect my
26181 programs that use them?
26182 @end display
26183
26184 There are no restrictions on how the configuration scripts that Autoconf
26185 produces may be distributed or used. In Autoconf version 1, they were
26186 covered by the GNU General Public License. We still encourage
26187 software authors to distribute their work under terms like those of the
26188 GPL, but doing so is not required to use Autoconf.
26189
26190 Of the other files that might be used with @command{configure},
26191 @file{config.h.in} is under whatever copyright you use for your
26192 @file{configure.ac}. @file{config.sub} and @file{config.guess} have an
26193 exception to the GPL when they are used with an Autoconf-generated
26194 @command{configure} script, which permits you to distribute them under the
26195 same terms as the rest of your package. @file{install-sh} is from the X
26196 Consortium and is not copyrighted.
26197
26198 @node Why GNU M4
26199 @section Why Require GNU M4?
26200
26201 @display
26202 Why does Autoconf require GNU M4?
26203 @end display
26204
26205 Many M4 implementations have hard-coded limitations on the size and
26206 number of macros that Autoconf exceeds. They also lack several
26207 builtin macros that it would be difficult to get along without in a
26208 sophisticated application like Autoconf, including:
26209
26210 @example
26211 m4_builtin
26212 m4_indir
26213 m4_bpatsubst
26214 __file__
26215 __line__
26216 @end example
26217
26218 Autoconf requires version 1.4.8 or later of GNU M4.
26219 It works better with version 1.4.16 or later.
26220
26221 Since only software maintainers need to use Autoconf, and since GNU
26222 M4 is simple to configure and install, it seems reasonable to require
26223 GNU M4 to be installed also. Many maintainers of GNU and
26224 other free software already have most of the GNU utilities
26225 installed, since they prefer them.
26226
26227 @node Bootstrapping
26228 @section How Can I Bootstrap?
26229 @cindex Bootstrap
26230
26231 @display
26232 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
26233 @command{configure} script, how do I bootstrap? It seems like a chicken
26234 and egg problem!
26235 @end display
26236
26237 This is a misunderstanding. Although GNU M4 does come with a
26238 @command{configure} script produced by Autoconf, Autoconf is not required
26239 in order to run the script and install GNU M4. Autoconf is only
26240 required if you want to change the M4 @command{configure} script, which few
26241 people have to do (mainly its maintainer).
26242
26243 @node Why Not Imake
26244 @section Why Not Imake?
26245 @cindex Imake
26246
26247 @display
26248 Why not use Imake instead of @command{configure} scripts?
26249 @end display
26250
26251 Several people have written addressing this question, so
26252 adaptations of their explanations are included here.
26253
26254 The following answer is based on one written by Richard Pixley:
26255
26256 @quotation
26257 Autoconf generated scripts frequently work on machines that it has
26258 never been set up to handle before. That is, it does a good job of
26259 inferring a configuration for a new system. Imake cannot do this.
26260
26261 Imake uses a common database of host specific data. For X11, this makes
26262 sense because the distribution is made as a collection of tools, by one
26263 central authority who has control over the database.
26264
26265 GNU tools are not released this way. Each GNU tool has a
26266 maintainer; these maintainers are scattered across the world. Using a
26267 common database would be a maintenance nightmare. Autoconf may appear
26268 to be this kind of database, but in fact it is not. Instead of listing
26269 host dependencies, it lists program requirements.
26270
26271 If you view the GNU suite as a collection of native tools, then the
26272 problems are similar. But the GNU development tools can be
26273 configured as cross tools in almost any host+target permutation. All of
26274 these configurations can be installed concurrently. They can even be
26275 configured to share host independent files across hosts. Imake doesn't
26276 address these issues.
26277
26278 Imake templates are a form of standardization. The GNU coding
26279 standards address the same issues without necessarily imposing the same
26280 restrictions.
26281 @end quotation
26282
26283
26284 Here is some further explanation, written by Per Bothner:
26285
26286 @quotation
26287 One of the advantages of Imake is that it is easy to generate large
26288 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
26289 However, @code{cpp} is not programmable: it has limited conditional
26290 facilities, and no looping. And @code{cpp} cannot inspect its
26291 environment.
26292
26293 All of these problems are solved by using @code{sh} instead of
26294 @code{cpp}. The shell is fully programmable, has macro substitution,
26295 can execute (or source) other shell scripts, and can inspect its
26296 environment.
26297 @end quotation
26298
26299
26300 Paul Eggert elaborates more:
26301
26302 @quotation
26303 With Autoconf, installers need not assume that Imake itself is already
26304 installed and working well. This may not seem like much of an advantage
26305 to people who are accustomed to Imake. But on many hosts Imake is not
26306 installed or the default installation is not working well, and requiring
26307 Imake to install a package hinders the acceptance of that package on
26308 those hosts. For example, the Imake template and configuration files
26309 might not be installed properly on a host, or the Imake build procedure
26310 might wrongly assume that all source files are in one big directory
26311 tree, or the Imake configuration might assume one compiler whereas the
26312 package or the installer needs to use another, or there might be a
26313 version mismatch between the Imake expected by the package and the Imake
26314 supported by the host. These problems are much rarer with Autoconf,
26315 where each package comes with its own independent configuration
26316 processor.
26317
26318 Also, Imake often suffers from unexpected interactions between
26319 @command{make} and the installer's C preprocessor. The fundamental problem
26320 here is that the C preprocessor was designed to preprocess C programs,
26321 not makefiles. This is much less of a problem with Autoconf,
26322 which uses the general-purpose preprocessor M4, and where the
26323 package's author (rather than the installer) does the preprocessing in a
26324 standard way.
26325 @end quotation
26326
26327
26328 Finally, Mark Eichin notes:
26329
26330 @quotation
26331 Imake isn't all that extensible, either. In order to add new features to
26332 Imake, you need to provide your own project template, and duplicate most
26333 of the features of the existing one. This means that for a sophisticated
26334 project, using the vendor-provided Imake templates fails to provide any
26335 leverage---since they don't cover anything that your own project needs
26336 (unless it is an X11 program).
26337
26338 On the other side, though:
26339
26340 The one advantage that Imake has over @command{configure}:
26341 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
26342 than @file{Makefile.in} files. There is a fix to this, however---at least
26343 for the Kerberos V5 tree, we've modified things to call in common
26344 @file{post.in} and @file{pre.in} makefile fragments for the
26345 entire tree. This means that a lot of common things don't have to be
26346 duplicated, even though they normally are in @command{configure} setups.
26347 @end quotation
26348
26349
26350 @node Defining Directories
26351 @section How Do I @code{#define} Installation Directories?
26352
26353 @display
26354 My program needs library files, installed in @code{datadir} and
26355 similar. If I use
26356
26357 @example
26358 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
26359 [Define to the read-only architecture-independent
26360 data directory.])
26361 @end example
26362
26363 @noindent
26364 I get
26365
26366 @example
26367 #define DATADIR "$@{prefix@}/share"
26368 @end example
26369 @end display
26370
26371 As already explained, this behavior is on purpose, mandated by the
26372 GNU Coding Standards, see @ref{Installation Directory
26373 Variables}. There are several means to achieve a similar goal:
26374
26375 @itemize @minus
26376 @item
26377 Do not use @code{AC_DEFINE} but use your makefile to pass the
26378 actual value of @code{datadir} via compilation flags.
26379 @xref{Installation Directory Variables}, for the details.
26380
26381 @item
26382 This solution can be simplified when compiling a program: you may either
26383 extend the @code{CPPFLAGS}:
26384
26385 @example
26386 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
26387 @end example
26388
26389 @noindent
26390 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
26391
26392 @example
26393 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
26394 @end example
26395
26396 @noindent
26397 Alternatively, create a dedicated header file:
26398
26399 @example
26400 DISTCLEANFILES = myprog-paths.h
26401 myprog-paths.h: Makefile
26402 printf '%s\n' '#define DATADIR "$(datadir)"' >$@@
26403 @end example
26404
26405 @noindent
26406 The Gnulib module @samp{configmake} provides such a header with all the
26407 standard directory variables defined, @pxref{configmake,,, gnulib, GNU
26408 Gnulib}.
26409
26410 @item
26411 Use @code{AC_DEFINE} but have @command{configure} compute the literal
26412 value of @code{datadir} and others. Many people have wrapped macros to
26413 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
26414 the @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
26415 Archive}.
26416
26417 This solution does not conform to the GNU Coding Standards.
26418
26419 @item
26420 Note that all the previous solutions hard wire the absolute name of
26421 these directories in the executables, which is not a good property. You
26422 may try to compute the names relative to @code{prefix}, and try to
26423 find @code{prefix} at runtime, this way your package is relocatable.
26424 @end itemize
26425
26426
26427 @node Autom4te Cache
26428 @section What is @file{autom4te.cache}?
26429
26430 @display
26431 What is this directory @file{autom4te.cache}? Can I safely remove it?
26432 @end display
26433
26434 In the GNU Build System, @file{configure.ac} plays a central
26435 role and is read by many tools: @command{autoconf} to create
26436 @file{configure}, @command{autoheader} to create @file{config.h.in},
26437 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
26438 check the completeness of @file{configure.ac}, @command{autoreconf} to
26439 check the GNU Build System components that are used. To
26440 ``read @file{configure.ac}'' actually means to compile it with M4,
26441 which can be a long process for complex @file{configure.ac}.
26442
26443 This is why all these tools, instead of running directly M4, invoke
26444 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
26445 a specific demand, stores additional information in
26446 @file{autom4te.cache} for future runs. For instance, if you run
26447 @command{autoconf}, behind the scenes, @command{autom4te} also
26448 stores information for the other tools, so that when you invoke
26449 @command{autoheader} or @command{automake} etc., reprocessing
26450 @file{configure.ac} is not needed. The speed up is frequently 30%,
26451 and is increasing with the size of @file{configure.ac}.
26452
26453 But it is and remains being simply a cache: you can safely remove it.
26454
26455 @sp 1
26456
26457 @display
26458 Can I permanently get rid of it?
26459 @end display
26460
26461 The creation of this cache can be disabled from
26462 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
26463 details. You should be aware that disabling the cache slows down the
26464 Autoconf test suite by 40%. The more GNU Build System
26465 components are used, the more the cache is useful; for instance
26466 running @samp{autoreconf -f} on the Core Utilities is twice slower without
26467 the cache @emph{although @option{--force} implies that the cache is
26468 not fully exploited}, and eight times slower than without
26469 @option{--force}.
26470
26471
26472 @node Present But Cannot Be Compiled
26473 @section Header Present But Cannot Be Compiled
26474
26475 The most important guideline to bear in mind when checking for
26476 features is to mimic as much as possible the intended use.
26477 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
26478 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
26479 the preprocessor, instead of the compiler, to check for headers. As a
26480 result, incompatibilities between headers went unnoticed during
26481 configuration, and maintainers finally had to deal with this issue
26482 elsewhere.
26483
26484 The transition began with Autoconf 2.56. As of Autoconf 2.64 both
26485 checks are performed, and @command{configure} complains loudly if the
26486 compiler and the preprocessor do not agree. However, only the compiler
26487 result is considered. As of Autoconf 2.70, only the compiler check is
26488 performed.
26489
26490 Consider the following example:
26491
26492 @smallexample
26493 $ @kbd{cat number.h}
26494 typedef int number;
26495 $ @kbd{cat pi.h}
26496 const number pi = 3;
26497 $ @kbd{cat configure.ac}
26498 AC_INIT([Example], [1.0], [bug-example@@example.org])
26499 AC_CHECK_HEADERS([pi.h])
26500 $ @kbd{autoconf -Wall}
26501 $ @kbd{./configure CPPFLAGS='-I.'}
26502 checking for gcc... gcc
26503 checking whether the C compiler works... yes
26504 checking for C compiler default output file name... a.out
26505 checking for suffix of executables...
26506 checking whether we are cross compiling... no
26507 checking for suffix of object files... o
26508 checking whether the compiler supports GNU C... yes
26509 checking whether gcc accepts -g... yes
26510 checking for gcc option to enable C23 features... -std=gnu23
26511 checking for sys/types.h... yes
26512 checking for sys/stat.h... yes
26513 checking for strings.h... yes
26514 checking for inttypes.h... yes
26515 checking for stdint.h... yes
26516 checking for unistd.h... yes
26517 checking for pi.h... no
26518 @end smallexample
26519
26520 @noindent
26521 The proper way to handle this case is using the fourth argument
26522 (@pxref{Generic Headers}):
26523
26524 @example
26525 $ @kbd{cat configure.ac}
26526 AC_INIT([Example], [1.0], [bug-example@@example.org])
26527 AC_CHECK_HEADERS([number.h pi.h], [], [],
26528 [[#ifdef HAVE_NUMBER_H
26529 # include <number.h>
26530 #endif
26531 ]])
26532 $ @kbd{autoconf -Wall}
26533 $ @kbd{./configure CPPFLAGS='-I.'}
26534 checking for gcc... gcc
26535 checking whether the C compiler works... yes
26536 checking for C compiler default output file name... a.out
26537 checking for suffix of executables...
26538 checking whether we are cross compiling... no
26539 checking for suffix of object files... o
26540 checking whether the compiler supports GNU C... yes
26541 checking whether gcc accepts -g... yes
26542 checking for gcc option to enable C23 features... -std=gnu23
26543 checking for number.h... yes
26544 checking for pi.h... yes
26545 @end example
26546
26547 See @ref{Particular Headers}, for a list of headers with their
26548 prerequisites.
26549
26550 @node Expanded Before Required
26551 @section Expanded Before Required
26552
26553 @cindex expanded before required
26554 Older versions of Autoconf silently built files with incorrect ordering
26555 between dependent macros if an outer macro first expanded, then later
26556 indirectly required, an inner macro. Starting with Autoconf 2.64, this
26557 situation no longer generates out-of-order code, but results in
26558 duplicate output and a syntax warning:
26559
26560 @example
26561 $ @kbd{cat configure.ac}
26562 @result{}AC_DEFUN([TESTA], [[echo in A
26563 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
26564 @result{}SEEN_A=:]])
26565 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
26566 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
26567 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
26568 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
26569 @result{}TESTA
26570 @result{}TESTC])
26571 @result{}AC_INIT
26572 @result{}OUTER
26573 @result{}AC_OUTPUT
26574 $ @kbd{autoconf}
26575 @result{}configure.ac:11: warning: AC_REQUIRE:
26576 @result{} 'TESTA' was expanded before it was required
26577 @result{}configure.ac:4: TESTB is expanded from...
26578 @result{}configure.ac:6: TESTC is expanded from...
26579 @result{}configure.ac:7: OUTER is expanded from...
26580 @result{}configure.ac:11: the top level
26581 @end example
26582
26583 @noindent
26584 To avoid this warning, decide what purpose the macro in question serves.
26585 If it only needs to be expanded once (for example, if it provides
26586 initialization text used by later macros), then the simplest fix is to
26587 change the macro to be declared with @code{AC_DEFUN_ONCE}
26588 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
26589 newer. A more portable fix is to change all
26590 instances of direct calls to instead go through @code{AC_REQUIRE}
26591 (@pxref{Prerequisite Macros}). If, instead, the macro is parameterized
26592 by arguments or by the current definition of other macros in the m4
26593 environment, then the macro should always be directly expanded instead
26594 of required.
26595
26596 For another case study, consider this example trimmed down from an
26597 actual package. Originally, the package contained shell code and
26598 multiple macro invocations at the top level of @file{configure.ac}:
26599
26600 @example
26601 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26602 foobar=
26603 AC_PROG_CC
26604 FOO
26605 @end example
26606
26607 @noindent
26608 but that was getting complex, so the author wanted to offload some of
26609 the text into a new macro in another file included via
26610 @file{aclocal.m4}. The naïve approach merely wraps the text in a new
26611 macro:
26612
26613 @example
26614 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26615 AC_DEFUN([BAR], [
26616 foobar=
26617 AC_PROG_CC
26618 FOO
26619 ])
26620 BAR
26621 @end example
26622
26623 @noindent
26624 With older versions of Autoconf, the setting of @samp{foobar=} occurs
26625 before the single compiler check, as the author intended. But with
26626 Autoconf 2.64, this issues the ``expanded before it was required''
26627 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
26628 check, one before @samp{foobar=}, and one after. To understand why this
26629 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
26630 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood. According to
26631 the documented semantics of @code{AC_REQUIRE}, this means that
26632 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
26633 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceding the
26634 use of @samp{foobar=}. The older versions of Autoconf were broken with
26635 regards to the rules of @code{AC_REQUIRE}, which explains why the code
26636 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
26637 autoconf. In other words, the author was unknowingly relying on a bug
26638 exploit to get the desired results, and that exploit broke once the bug
26639 was fixed.
26640
26641 So, what recourse does the author have, to restore their intended
26642 semantics of setting @samp{foobar=} prior to a single compiler check,
26643 regardless of whether Autoconf 2.63 or 2.64 is used? One idea is to
26644 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
26645 there is always the possibility of using the lower-level
26646 @code{m4_define}:
26647
26648 @example
26649 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26650 m4_define([BAR], [
26651 foobar=
26652 AC_PROG_CC
26653 FOO
26654 ])
26655 BAR
26656 @end example
26657
26658 @noindent
26659 This works great if everything is in the same file. However, it does
26660 not help in the case where the author wants to have @command{aclocal}
26661 find the definition of @code{BAR} from its own file, since
26662 @command{aclocal} requires the use of @code{AC_DEFUN}. In this case, a
26663 better fix is to recognize that if @code{BAR} also uses
26664 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
26665 to a subsequent require. Then, by creating yet another helper macro,
26666 the author can once again guarantee a single invocation of
26667 @code{AC_PROG_CC}, which will still occur after @code{foobar=}. The
26668 author can also use @code{AC_BEFORE} to make sure no other macro
26669 appearing before @code{BAR} has triggered an unwanted expansion of
26670 @code{AC_PROG_CC}.
26671
26672 @example
26673 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26674 AC_DEFUN([BEFORE_CC], [
26675 foobar=
26676 ])
26677 AC_DEFUN([BAR], [
26678 AC_BEFORE([$0], [AC_PROG_CC])dnl
26679 AC_REQUIRE([BEFORE_CC])dnl
26680 AC_REQUIRE([AC_PROG_CC])dnl
26681 FOO
26682 ])
26683 BAR
26684 @end example
26685
26686
26687 @node Debugging
26688 @section Debugging @command{configure} scripts
26689
26690 While in general, @command{configure} scripts generated by Autoconf
26691 strive to be fairly portable to various systems, compilers, shells, and
26692 other tools, it may still be necessary to debug a failing test, broken
26693 script or makefile, or fix or override an incomplete, faulty, or erroneous
26694 test, especially during macro development. Failures can occur at all levels,
26695 in M4 syntax or semantics, shell script issues, or due to bugs in the
26696 test or the tools invoked by @command{configure}. Together with the
26697 rather arcane error message that @command{m4} and @command{make} may
26698 produce when their input contains syntax errors, this can make debugging
26699 rather painful.
26700
26701 Nevertheless, here is a list of hints and strategies that may help:
26702
26703 @itemize
26704 @item
26705 When @command{autoconf} fails, common causes for error include:
26706
26707 @itemize
26708 @item
26709 mismatched or unbalanced parentheses or braces (@pxref{Balancing
26710 Parentheses}),
26711
26712 @item under- or over-quoted macro arguments (@pxref{Autoconf
26713 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
26714 Macros}),
26715
26716 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
26717 Language}).
26718 @end itemize
26719
26720 Typically, it helps to go back to the last working version of the input
26721 and compare the differences for each of these errors. Another
26722 possibility is to sprinkle pairs of @code{m4_traceon} and
26723 @code{m4_traceoff} judiciously in the code, either without a parameter
26724 or listing some macro names and watch @command{m4} expand its input
26725 verbosely (@pxref{Debugging via autom4te}).
26726
26727 @item
26728 Sometimes @command{autoconf} succeeds but the generated
26729 @command{configure} script has invalid shell syntax. You can detect this
26730 case by running @samp{bash -n configure} or @samp{sh -n configure}.
26731 If this command fails, the same tips apply, as if @command{autoconf} had
26732 failed.
26733
26734 @item
26735 Debugging @command{configure} script execution may be done by sprinkling
26736 pairs of @code{set -x} and @code{set +x} into the shell script before
26737 and after the region that contains a bug. Running the whole script with
26738 @samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
26739 @var{shell} may work, but produces lots of output. Here, it can help to
26740 search for markers like @samp{checking for} a particular test in the
26741 @var{log-file}.
26742
26743 @item
26744 Alternatively, you might use a shell with debugging capabilities like
26745 @uref{https://bashdb.sourceforge.net/, bashdb}.
26746
26747 @item
26748 When @command{configure} tests produce invalid results for your system,
26749 it may be necessary to override them:
26750
26751 @itemize
26752 @item
26753 For programs, tools or libraries variables, preprocessor, compiler, or
26754 linker flags, it is often sufficient to override them at @command{make}
26755 run time with some care (@pxref{Macros and Submakes}). Since this
26756 normally won't cause @command{configure} to be run again with these
26757 changed settings, it may fail if the changed variable would have caused
26758 different test results from @command{configure}, so this may work only
26759 for simple differences.
26760
26761 @item
26762 Most tests which produce their result in a substituted variable allow to
26763 override the test by setting the variable on the @command{configure}
26764 command line (@pxref{Compilers and Options}, @pxref{Defining Variables}).
26765
26766 @item
26767 Many tests store their result in a cache variable (@pxref{Caching
26768 Results}). This lets you override them either on the
26769 @command{configure} command line as above, or through a primed cache or
26770 site file (@pxref{Cache Files}, @pxref{Site Defaults}). The name of a
26771 cache variable is documented with a test macro or may be inferred from
26772 @ref{Cache Variable Names}; the precise semantics of undocumented
26773 variables are often internal details, subject to change.
26774 @end itemize
26775
26776 @item
26777 Alternatively, @command{configure} may produce invalid results because
26778 of uncaught programming errors, in your package or in an upstream
26779 library package. For example, when @code{AC_CHECK_LIB} fails to find a
26780 library with a specified function, always check @file{config.log}. This
26781 will reveal the exact error that produced the failing result: the
26782 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
26783 @end itemize
26784
26785 Conversely, as macro author, you can make it easier for users of your
26786 macro:
26787
26788 @itemize
26789 @item
26790 by minimizing dependencies between tests and between test results as far
26791 as possible,
26792
26793 @item
26794 by using @command{make} variables to factorize and allow
26795 override of settings at @command{make} run time,
26796
26797 @item
26798 by honoring the GNU Coding Standards and not overriding flags
26799 reserved for the user except temporarily during @command{configure}
26800 tests,
26801
26802 @item
26803 by not requiring users of your macro to use the cache variables.
26804 Instead, expose the result of the test via @var{run-if-true} and
26805 @var{run-if-false} parameters. If the result is not a boolean,
26806 then provide it through documented shell variables.
26807 @end itemize
26808
26809
26810 @c ===================================================== History of Autoconf.
26811
26812 @node History
26813 @chapter History of Autoconf
26814 @cindex History of autoconf
26815
26816 @emph{This chapter was written by the original author, David MacKenzie.}
26817
26818 You may be wondering, Why was Autoconf originally written? How did it
26819 get into its present form? (Why does it look like gorilla spit?) If
26820 you're not wondering, then this chapter contains no information useful
26821 to you, and you might as well skip it. If you @emph{are} wondering,
26822 then let there be light@enddots{}
26823
26824 @menu
26825 * Genesis:: Prehistory and naming of @command{configure}
26826 * Exodus:: The plagues of M4 and Perl
26827 * Leviticus:: The priestly code of portability arrives
26828 * Numbers:: Growth and contributors
26829 * Deuteronomy:: Approaching the promises of easy configuration
26830 @end menu
26831
26832 @node Genesis
26833 @section Genesis
26834
26835 In June 1991 I was maintaining many of the GNU utilities for the
26836 Free Software Foundation. As they were ported to more platforms and
26837 more programs were added, the number of @option{-D} options that users
26838 had to select in the makefile (around 20) became burdensome.
26839 Especially for me---I had to test each new release on a bunch of
26840 different systems. So I wrote a little shell script to guess some of
26841 the correct settings for the fileutils package, and released it as part
26842 of fileutils 2.0. That @command{configure} script worked well enough that
26843 the next month I adapted it (by hand) to create similar @command{configure}
26844 scripts for several other GNU utilities packages. Brian Berliner
26845 also adapted one of my scripts for his CVS revision control system.
26846
26847 Later that summer, I learned that Richard Stallman and Richard Pixley
26848 were developing similar scripts to use in the GNU compiler tools;
26849 so I adapted my @command{configure} scripts to support their evolving
26850 interface: using the file name @file{Makefile.in} as the templates;
26851 adding @samp{+srcdir}, the first option (of many); and creating
26852 @file{config.status} files.
26853
26854 @node Exodus
26855 @section Exodus
26856
26857 As I got feedback from users, I incorporated many improvements, using
26858 Emacs to search and replace, cut and paste, similar changes in each of
26859 the scripts. As I adapted more GNU utilities packages to use
26860 @command{configure} scripts, updating them all by hand became impractical.
26861 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
26862 mail saying that the @command{configure} scripts were great, and asking if
26863 I had a tool for generating them that I could send him. No, I thought,
26864 but I should! So I started to work out how to generate them. And the
26865 journey from the slavery of hand-written @command{configure} scripts to the
26866 abundance and ease of Autoconf began.
26867
26868 Cygnus @command{configure}, which was being developed at around that time,
26869 is table driven; it is meant to deal mainly with a discrete number of
26870 system types with a small number of mainly unguessable features (such as
26871 details of the object file format). The automatic configuration system
26872 that Brian Fox had developed for Bash takes a similar approach. For
26873 general use, it seems to me a hopeless cause to try to maintain an
26874 up-to-date database of which features each variant of each operating
26875 system has. It's easier and more reliable to check for most features on
26876 the fly---especially on hybrid systems that people have hacked on
26877 locally or that have patches from vendors installed.
26878
26879 I considered using an architecture similar to that of Cygnus
26880 @command{configure}, where there is a single @command{configure} script that
26881 reads pieces of @file{configure.in} when run. But I didn't want to have
26882 to distribute all of the feature tests with every package, so I settled
26883 on having a different @command{configure} made from each
26884 @file{configure.in} by a preprocessor. That approach also offered more
26885 control and flexibility.
26886
26887 I looked briefly into using the Metaconfig package, by Larry Wall,
26888 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
26889 reasons. The @command{Configure} scripts it produces are interactive,
26890 which I find quite inconvenient; I didn't like the ways it checked for
26891 some features (such as library functions); I didn't know that it was
26892 still being maintained, and the @command{Configure} scripts I had
26893 seen didn't work on many modern systems (such as System V R4 and NeXT);
26894 it wasn't flexible in what it could do in response to a feature's
26895 presence or absence; I found it confusing to learn; and it was too big
26896 and complex for my needs (I didn't realize then how much Autoconf would
26897 eventually have to grow).
26898
26899 I considered using Perl to generate my style of @command{configure}
26900 scripts, but decided that M4 was better suited to the job of simple
26901 textual substitutions: it gets in the way less, because output is
26902 implicit. Plus, everyone already has it. (Initially I didn't rely on
26903 the GNU extensions to M4.) Also, some of my friends at the
26904 University of Maryland had recently been putting M4 front ends on
26905 several programs, including @code{tvtwm}, and I was interested in trying
26906 out a new language.
26907
26908 @node Leviticus
26909 @section Leviticus
26910
26911 Since my @command{configure} scripts determine the system's capabilities
26912 automatically, with no interactive user intervention, I decided to call
26913 the program that generates them Autoconfig. But with a version number
26914 tacked on, that name would be too long for old Unix file systems,
26915 so I shortened it to Autoconf.
26916
26917 In the fall of 1991 I called together a group of fellow questers after
26918 the Holy Grail of portability (er, that is, alpha testers) to give me
26919 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
26920 and continued to add features and improve the techniques used in the
26921 checks. Prominent among the testers were François Pinard, who came up
26922 with the idea of making an Autoconf shell script to run M4
26923 and check for unresolved macro calls; Richard Pixley, who suggested
26924 running the compiler instead of searching the file system to find
26925 include files and symbols, for more accurate results; Karl Berry, who
26926 got Autoconf to configure @TeX{} and added the macro index to the
26927 documentation; and Ian Lance Taylor, who added support for creating a C
26928 header file as an alternative to putting @option{-D} options in a
26929 makefile, so he could use Autoconf for his UUCP package.
26930 The alpha testers cheerfully adjusted their files again and again as the
26931 names and calling conventions of the Autoconf macros changed from
26932 release to release. They all contributed many specific checks, great
26933 ideas, and bug fixes.
26934
26935 @node Numbers
26936 @section Numbers
26937
26938 In July 1992, after months of alpha testing, I released Autoconf 1.0,
26939 and converted many GNU packages to use it. I was surprised by how
26940 positive the reaction to it was. More people started using it than I
26941 could keep track of, including people working on software that wasn't
26942 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
26943 Autoconf continued to improve rapidly, as many people using the
26944 @command{configure} scripts reported problems they encountered.
26945
26946 Autoconf turned out to be a good torture test for M4 implementations.
26947 Unix M4 started to dump core because of the length of the
26948 macros that Autoconf defined, and several bugs showed up in GNU
26949 M4 as well. Eventually, we realized that we needed to use some
26950 features that only GNU M4 has. 4.3BSD M4, in
26951 particular, has an impoverished set of builtin macros; the System V
26952 version is better, but still doesn't provide everything we need.
26953
26954 More development occurred as people put Autoconf under more stresses
26955 (and to uses I hadn't anticipated). Karl Berry added checks for X11.
26956 david zuhn contributed C++ support. François Pinard made it diagnose
26957 invalid arguments. Jim Blandy bravely coerced it into configuring
26958 GNU Emacs, laying the groundwork for several later improvements.
26959 Roland McGrath got it to configure the GNU C Library, wrote the
26960 @command{autoheader} script to automate the creation of C header file
26961 templates, and added a @option{--verbose} option to @command{configure}.
26962 Noah Friedman added the @option{--autoconf-dir} option and
26963 @code{AC_MACRODIR} environment variable. (He also coined the term
26964 @dfn{autoconfiscate} to mean ``adapt a software package to use
26965 Autoconf''.) Roland and Noah improved the quoting protection in
26966 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
26967 dealing with portability problems from February through June, 1993.
26968
26969 @node Deuteronomy
26970 @section Deuteronomy
26971
26972 A long wish list for major features had accumulated, and the effect of
26973 several years of patching by various people had left some residual
26974 cruft. In April 1994, while working for Cygnus Support, I began a major
26975 revision of Autoconf. I added most of the features of the Cygnus
26976 @command{configure} that Autoconf had lacked, largely by adapting the
26977 relevant parts of Cygnus @command{configure} with the help of david zuhn
26978 and Ken Raeburn. These features include support for using
26979 @file{config.sub}, @file{config.guess}, @option{--host}, and
26980 @option{--target}; making links to files; and running @command{configure}
26981 scripts in subdirectories. Adding these features enabled Ken to convert
26982 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
26983 Autoconf.
26984
26985 I added more features in response to other peoples' requests. Many
26986 people had asked for @command{configure} scripts to share the results of
26987 the checks between runs, because (particularly when configuring a large
26988 source tree, like Cygnus does) they were frustratingly slow. Mike
26989 Haertel suggested adding site-specific initialization scripts. People
26990 distributing software that had to unpack on MS-DOS asked for a way to
26991 override the @file{.in} extension on the file names, which produced file
26992 names like @file{config.h.in} containing two dots. Jim Avera did an
26993 extensive examination of the problems with quoting in @code{AC_DEFINE}
26994 and @code{AC_SUBST}; his insights led to significant improvements.
26995 Richard Stallman asked that compiler output be sent to @file{config.log}
26996 instead of @file{/dev/null}, to help people debug the Emacs
26997 @command{configure} script.
26998
26999 I made some other changes because of my dissatisfaction with the quality
27000 of the program. I made the messages showing results of the checks less
27001 ambiguous, always printing a result. I regularized the names of the
27002 macros and cleaned up coding style inconsistencies. I added some
27003 auxiliary utilities that I had developed to help convert source code
27004 packages to use Autoconf. With the help of François Pinard, I made
27005 the macros not interrupt each others' messages. (That feature revealed
27006 some performance bottlenecks in GNU M4, which he hastily
27007 corrected!) I reorganized the documentation around problems people want
27008 to solve. And I began a test suite, because experience had shown that
27009 Autoconf has a pronounced tendency to regress when we change it.
27010
27011 Again, several alpha testers gave invaluable feedback, especially
27012 François Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
27013 and Mark Eichin.
27014
27015 Finally, version 2.0 was ready. And there was much rejoicing. (And I
27016 have free time again. I think. Yeah, right.)
27017
27018
27019 @c ========================================================== Appendices
27020
27021
27022 @node GNU Free Documentation License
27023 @appendix GNU Free Documentation License
27024
27025 @include fdl.texi
27026
27027 @node Indices
27028 @appendix Indices
27029
27030 @menu
27031 * Environment Variable Index:: Index of environment variables used
27032 * Output Variable Index:: Index of variables set in output files
27033 * Preprocessor Symbol Index:: Index of C preprocessor symbols defined
27034 * Cache Variable Index:: Index of documented cache variables
27035 * Autoconf Macro Index:: Index of Autoconf macros
27036 * M4 Macro Index:: Index of M4, M4sugar, and M4sh macros
27037 * Autotest Macro Index:: Index of Autotest macros
27038 * Program & Function Index:: Index of those with portability problems
27039 * Concept Index:: General index
27040 @end menu
27041
27042 @node Environment Variable Index
27043 @appendixsec Environment Variable Index
27044
27045 This is an alphabetical list of the environment variables that might
27046 influence Autoconf checks.
27047
27048 @printindex ev
27049
27050 @node Output Variable Index
27051 @appendixsec Output Variable Index
27052
27053 This is an alphabetical list of the variables that Autoconf can
27054 substitute into files that it creates, typically one or more
27055 makefiles. @xref{Setting Output Variables}, for more information
27056 on how this is done.
27057
27058 @printindex ov
27059
27060 @node Preprocessor Symbol Index
27061 @appendixsec Preprocessor Symbol Index
27062
27063 This is an alphabetical list of the C preprocessor symbols that the
27064 Autoconf macros define. To work with Autoconf, C source code needs to
27065 use these names in @code{#if} or @code{#ifdef} directives.
27066
27067 @printindex cv
27068
27069 @node Cache Variable Index
27070 @appendixsec Cache Variable Index
27071
27072 This is an alphabetical list of documented cache variables used
27073 by macros defined in Autoconf. Autoconf macros may use additional cache
27074 variables internally.
27075 @ifset shortindexflag
27076 To make the list easier to use, the variables are listed without their
27077 preceding @samp{ac_cv_}.
27078 @end ifset
27079
27080 @printindex CA
27081
27082 @node Autoconf Macro Index
27083 @appendixsec Autoconf Macro Index
27084
27085 This is an alphabetical list of the Autoconf macros.
27086 @ifset shortindexflag
27087 To make the list easier to use, the macros are listed without their
27088 preceding @samp{AC_}.
27089 @end ifset
27090
27091 @printindex AC
27092
27093 @node M4 Macro Index
27094 @appendixsec M4 Macro Index
27095
27096 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
27097 @ifset shortindexflag
27098 To make the list easier to use, the macros are listed without their
27099 preceding @samp{m4_} or @samp{AS_}. The prefix is @samp{m4_} for
27100 all-lowercase macro names and @samp{AS_} for all-uppercase macro
27101 names.
27102 @end ifset
27103
27104 @printindex MS
27105
27106 @node Autotest Macro Index
27107 @appendixsec Autotest Macro Index
27108
27109 This is an alphabetical list of the Autotest macros.
27110 @ifset shortindexflag
27111 To make the list easier to use, the macros are listed without their
27112 preceding @samp{AT_}.
27113 @end ifset
27114
27115 @printindex AT
27116
27117 @node Program & Function Index
27118 @appendixsec Program and Function Index
27119
27120 This is an alphabetical list of the programs and functions whose
27121 portability is discussed in this document.
27122
27123 @printindex pr
27124
27125 @node Concept Index
27126 @appendixsec Concept Index
27127
27128 This is an alphabetical list of the files, tools, and concepts
27129 introduced in this document.
27130
27131 @printindex cp
27132
27133 @bye
27134
27135 @c LocalWords: texinfo setfilename autoconf texi settitle setchapternewpage
27136 @c LocalWords: setcontentsaftertitlepage finalout ARG ovar varname dvar acx
27137 @c LocalWords: makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
27138 @c LocalWords: shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
27139 @c LocalWords: asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
27140 @c LocalWords: msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
27141 @c LocalWords: direntry autoscan autoreconf autoheader autoupdate config FDs
27142 @c LocalWords: testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
27143 @c LocalWords: insertcopying Autoconf's detailmenu Automake Libtool POSIX ois
27144 @c LocalWords: Systemology Checkpointing Changequote INTERCAL changequote dfn
27145 @c LocalWords: Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
27146 @c LocalWords: LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
27147 @c LocalWords: distclean uninstall noindent versioning Tromey dir vr
27148 @c LocalWords: SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
27149 @c LocalWords: evindex automake Gettext autopoint gettext symlink libtoolize
27150 @c LocalWords: defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
27151 @c LocalWords: SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
27152 @c LocalWords: builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
27153 @c LocalWords: CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
27154 @c LocalWords: datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
27155 @c LocalWords: includedir infodir libexecdir localedir localstatedir mandir
27156 @c LocalWords: oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
27157 @c LocalWords: sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
27158 @c LocalWords: undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
27159 @c LocalWords: PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
27160 @c LocalWords: inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
27161 @c LocalWords: LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
27162 @c LocalWords: inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
27163 @c LocalWords: isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
27164 @c LocalWords: ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
27165 @c LocalWords: snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
27166 @c LocalWords: strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
27167 @c LocalWords: PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
27168 @c LocalWords: closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
27169 @c LocalWords: largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
27170 @c LocalWords: SETGID getloadavg nlist GETMNTENT irix acxindex autom
27171 @c LocalWords: getmntent UnixWare GETPGRP getpgid getpgrp POSIX's pid LSTAT
27172 @c LocalWords: lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
27173 @c LocalWords: localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
27174 @c LocalWords: SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
27175 @c LocalWords: STRTOD strtod DECL STRFTIME strftime UTIME utime VPRINTF
27176 @c LocalWords: DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
27177 @c LocalWords: linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
27178 @c LocalWords: NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
27179 @c LocalWords: inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
27180 @c LocalWords: STDBOOL BOOL stdbool cplusplus bool Bool stdarg tm te
27181 @c LocalWords: ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
27182 @c LocalWords: WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
27183 @c LocalWords: DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
27184 @c LocalWords: passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
27185 @c LocalWords: gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
27186 @c LocalWords: ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
27187 @c LocalWords: varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
27188 @c LocalWords: const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
27189 @c LocalWords: xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
27190 @c LocalWords: ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
27191 @c LocalWords: fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
27192 @c LocalWords: statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
27193 @c LocalWords: GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
27194 @c LocalWords: changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
27195 @c LocalWords: Aas Wcross sep args namespace undefine bpatsubst popdef dquote
27196 @c LocalWords: bregexp Overquote overquotation meisch maisch meische maische
27197 @c LocalWords: miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
27198 @c LocalWords: EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
27199 @c LocalWords: pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
27200 @c LocalWords: drivespec POSIXy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
27201 @c LocalWords: yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
27202 @c LocalWords: CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
27203 @c LocalWords: MAILPATH scanset arg NetBSD Almquist printf expr cp pR
27204 @c LocalWords: Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM url fc
27205 @c LocalWords: sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc ing FP
27206 @c LocalWords: mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
27207 @c LocalWords: fooXXXXXX utimes hpux hppa unescaped SUBST'ed
27208 @c LocalWords: pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
27209 @c LocalWords: cpu wildcards rpcc rdtsc powerpc readline
27210 @c LocalWords: withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
27211 @c LocalWords: cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
27212 @c LocalWords: lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
27213 @c LocalWords: intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
27214 @c LocalWords: fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
27215 @c LocalWords: ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
27216 @c LocalWords: installcheck autotest indir Pixley Bothner Eichin Kerberos adl
27217 @c LocalWords: DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
27218 @c LocalWords: Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
27219 @c LocalWords: autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
27220 @c LocalWords: printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
27221 @c LocalWords: VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
27222 @c LocalWords: GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
27223 @c LocalWords: esyscmd len maketemp pushdef substr syscmd sysval translit txt
27224 @c LocalWords: sinclude foreach myvar tolower toupper uniq BASENAME STDIN
27225 @c LocalWords: Dynix basename aname cname macroexpands xno xcheck iso
27226 @c LocalWords: LIBREADLINE lreadline lncurses libreadline vrindex SYS
27227 @c LocalWords: syncodeindex define'd caindex CAindex MacKenzie DIRS
27228 @c LocalWords: Runtime runtime Submakes submakes MAKEFLAGS whitespace
27229 @c LocalWords: Timestamps Unportability Canonicalizing stdckdint dirN
27230 @c LocalWords: acinclude AMFLAGS LIBS OBJCXXFLAGS GOFLAGS runstatedir
27231 @c LocalWords: metacharacter EXPENSIVEP errno setjmp wctype sys mawk
27232 @c LocalWords: nawk ggrep egrep gegrep fgrep gfgrep LEX lex yytext nm
27233 @c LocalWords: yywrap xflex lexyy YFLAGS yacc divnum libs fuindex ffs
27234 @c LocalWords: environ sigaction extern ftello nonnull STRTOLD LLONG
27235 @c LocalWords: strtold vfprintf ULLONG strcasecmp strncasecmp MSVC th
27236 @c LocalWords: NDEBUG INO libc ISDIR ISREG Tektronix Amdahl ino
27237 @c LocalWords: typedef pxref fileblocks submembers INTMAX intmax UINT
27238 @c LocalWords: INTPTR intptr SSIZE ssize uint UINTPTR uintptr OPENMP
27239 @c LocalWords: openmp OpenMP omp Alignas Alignof Noreturn UTF vals gl
27240 @c LocalWords: offsetof VARARRAYS VLA CCC stdcxx nullptr
27241 @c LocalWords: constexpr decltype unicode fstreams iostreams iomanip
27242 @c LocalWords: stringstreams GXX OBJCPP OBJCXX objcxx GOBJCXX erlc tx
27243 @c LocalWords: OBJCXXCPP FIXEDFORM GFC argc argv shellvar fpp MODEXT
27244 @c LocalWords: freeform fixedform MODINC MODOUT gccgo GOC xmkmf fseek
27245 @c LocalWords: interpval ftell Interix macOS PTHREAD NonStop XOPEN xc
27246 @c LocalWords: IEC ATTRIBS BFP DFP O'Donell Sebor ERTS Erlang's erts
27247 @c LocalWords: erlang Wundef scalable USG NOTMAKE DOUCH
27248 @c LocalWords: IVE changesyntax ifnotinfo oline num cfg debugfile cdr
27249 @c LocalWords: debugmode traceoff traceon patsubst dumpdefs ifelse aa
27250 @c LocalWords: mkstemp undivert lifo errprintn BINSH sanitization bcd
27251 @c LocalWords: cleardivert bmatch bpatsubsts subst cond nblank ifval
27252 @c LocalWords: ifblank ifnblank ifvaln fputc fgetc argn mapall dvarv
27253 @c LocalWords: shiftn abcd elt noquote mkargs joinall SHA prereq dup
27254 @c LocalWords: listc setb seta ARITH HNUM xcurly xoccupied
27255 @c LocalWords: TESTA TESTB TESTC hoc xpg xxyzzyz dtksh nosuch fifos
27256 @c LocalWords: fifo Stardent sig WIF WIFSIGNALED SIGQUIT tty perl ret
27257 @c LocalWords: SIGINT NUL SFN PRN aeiou MSYS SIGTERM xhi arith UWIN
27258 @c LocalWords: CLICOLOR FPATH POSIXLY Shellshock CVE doit ec ci
27259 @c LocalWords: notreached cim nc ACL faccessat Alexandre getline sqrt
27260 @c LocalWords: CONVFMT FS OFMT CDS chgrp futimens utimensat oo esc od
27261 @c LocalWords: ownerships mape readdir mkfifo mknod testsuites XSI rf
27262 @c LocalWords: bcdox hexdump filelist rmdir flushleft busybox nl HAZy
27263 @c LocalWords: ABCDEFGHIJKLMNOPQRSTUVWXYZ Fantazy FAntAZy adc unix xb
27264 @c LocalWords: SUBMAKEFLAGS ehBc ehB hBc hvB dmake hostname nlinit xf
27265 @c LocalWords: DCOMMENT bart pathnames ifhtml randx
27266 @c LocalWords: sumc hic ic fwrapv ftrapv SIGFPE memset fmudflap ctime
27267 @c LocalWords: asctime lvalues lvalue Multithreaded decstation gdb na
27268 @c LocalWords: enableval lesskey FHS superset waitpid libfoo cposix
27269 @c LocalWords: mem RESTARTABLE bzero DejaGNU EUNIT subfile optarg ive
27270 @c LocalWords: nolog expout experr erlflags EUnit testme eunit myprog
27271 @c LocalWords: configmake vx bashdb tvtwm questers UUCP McGrath
27272 @c LocalWords: ispell
27273 @c Local Variables:
27274 @c coding: utf-8
27275 @c fill-column: 72
27276 @c ispell-local-dictionary: "american"
27277 @c indent-tabs-mode: nil
27278 @c whitespace-check-buffer-indent: nil
27279 @c End: