Document AC_RUN_IFELSE([], ...) etc.
[autoconf.git] / doc / autoconf.texi
blob245fbe87f5e38f94e4db70d68ebc8936b3801686
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 @setchapternewpage odd
11 @finalout
13 @c @ovar(ARG)
14 @c ----------
15 @c The ARG is an optional argument.  To be used for macro arguments in
16 @c their documentation (@defmac).
17 @macro ovar{varname}
18 @r{[}@var{\varname\}@r{]}
19 @end macro
21 @c @dvar(ARG, DEFAULT)
22 @c -------------------
23 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
24 @c for macro arguments in their documentation (@defmac).
25 @macro dvar{varname, default}
26 @r{[}@var{\varname\} = @samp{\default\}@r{]}
27 @end macro
29 @c @dvarv(ARG, DEFAULT-VAR)
30 @c ------------------------
31 @c Same as @dvar{ARG, DEFAULT-VAR}, but with @var instead of @samp
32 @c around DEFAULT-VAR.
33 @macro dvarv{varname, default}
34 @r{[}@var{\varname\} = @var{\default\}@r{]}@c
35 @end macro
37 @c Handling the indexes with Texinfo yields several different problems.
39 @c Because we want to drop out the AC_ part of the macro names in the
40 @c printed manual, but not in the other outputs, we need a layer above
41 @c the usual @acindex{} etc.  That's why we first define indexes such as
42 @c acx meant to become the macro @acindex.  First of all, using 'ac_'
43 @c does not work with makeinfo, and using 'ac1' doesn't work with TeX.
44 @c So use something more regular 'acx'.  Then you finish with a printed
45 @c index saying 'index is not existent'.  Of course: you ought to use
46 @c two letters :(  So you use capitals.
48 @c Second, when defining a macro in the TeX world, following spaces are
49 @c eaten.  But then, since we embed @acxindex commands that use the end
50 @c of line as an end marker, the whole things wrecks itself.  So make
51 @c sure you do *force* an additional end of line, add a '@c'.
53 @c Finally, you might want to get rid of TeX expansion, using --expand
54 @c with texi2dvi.  But then you wake up an old problem: we use macros
55 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
57 @c Define an environment variable index, for variables users may set
58 @c in their environment or on the configure command line.
59 @defcodeindex ev
60 @c Define an output variable index, for commonly AC_SUBST'ed variables.
61 @defcodeindex ov
62 @c Define a cache variable index, for variables matching *_cv_*.
63 @defcodeindex CA
64 @c Other shell variables not fitting the above categories should be
65 @c listed in the predefined vrindex, which we merge in the concept index.
66 @syncodeindex vr cp
67 @c Define a CPP preprocessor macro index, for #define'd strings.
68 @defcodeindex cv
69 @c Define an Autoconf macro index that @defmac doesn't write to.
70 @defcodeindex AC
71 @c Define an Autotest macro index that @defmac doesn't write to.
72 @defcodeindex AT
73 @c Define an M4sugar macro index that @defmac doesn't write to.
74 @defcodeindex MS
75 @c Define an index for *foreign* programs: 'mv' etc.  Used for the
76 @c portability sections and so on.
77 @defindex pr
79 @c shortindexflag
80 @c --------------
81 @c Shall we factor AC_ out of the Autoconf macro index etc.?
82 @iftex
83 @set shortindexflag
84 @end iftex
86 @c @acindex{MACRO}
87 @c ---------------
88 @c Registering an AC_\MACRO\.
89 @ifset shortindexflag
90 @macro acindex{macro}
91 @ACindex \macro\
93 @end macro
94 @end ifset
95 @ifclear shortindexflag
96 @macro acindex{macro}
97 @ACindex AC_\macro\
98 @end macro
99 @end ifclear
101 @c @ahindex{MACRO}
102 @c ---------------
103 @c Registering an AH_\MACRO\.
104 @macro ahindex{macro}
105 @ACindex AH_\macro\
107 @end macro
109 @c @asindex{MACRO}
110 @c ---------------
111 @c Registering an AS_\MACRO\.
112 @ifset shortindexflag
113 @macro asindex{macro}
114 @MSindex \macro\
116 @end macro
117 @end ifset
118 @ifclear shortindexflag
119 @macro asindex{macro}
120 @MSindex AS_\macro\
121 @end macro
122 @end ifclear
124 @c @atindex{MACRO}
125 @c ---------------
126 @c Registering an AT_\MACRO\.
127 @ifset shortindexflag
128 @macro atindex{macro}
129 @ATindex \macro\
131 @end macro
132 @end ifset
133 @ifclear shortindexflag
134 @macro atindex{macro}
135 @ATindex AT_\macro\
136 @end macro
137 @end ifclear
139 @c @auindex{MACRO}
140 @c ---------------
141 @c Registering an AU_\MACRO\.
142 @macro auindex{macro}
143 @ACindex AU_\macro\
145 @end macro
147 @c @hdrindex{MACRO}
148 @c ----------------
149 @c Indexing a header.
150 @macro hdrindex{macro}
151 @prindex @file{\macro\}
153 @end macro
155 @c @msindex{MACRO}
156 @c ---------------
157 @c Registering an m4_\MACRO\.
158 @ifset shortindexflag
159 @macro msindex{macro}
160 @MSindex \macro\
162 @end macro
163 @end ifset
164 @ifclear shortindexflag
165 @macro msindex{macro}
166 @MSindex m4_\macro\
167 @end macro
168 @end ifclear
171 @c @caindex{VARIABLE}
172 @c ------------------
173 @c Registering an ac_cv_\VARIABLE\ cache variable.
174 @ifset shortindexflag
175 @macro caindex{macro}
176 @CAindex \macro\
177 @end macro
178 @end ifset
179 @ifclear shortindexflag
180 @macro caindex{macro}
181 @CAindex ac_cv_\macro\
182 @end macro
183 @end ifclear
185 @c Define an index for functions: 'alloca' etc.  Used for the
186 @c portability sections and so on.  We can't use 'fn' (aka 'fnindex'),
187 @c since '@defmac' goes into it => we'd get all the macros too.
189 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
191 @c   ! No room for a new @write .
192 @c   l.112 @defcodeindex fu
194 @c   so don't define yet another one :(  Just put some tags before each
195 @c   @prindex which is actually a @funindex.
197 @c   @defcodeindex fu
200 @c   @c Put the programs and functions into their own index.
201 @c   @syncodeindex fu pr
203 @comment %**end of header
204 @comment ========================================================
206 @copying
208 This manual (@value{UPDATED}) is for GNU Autoconf
209 (version @value{VERSION}),
210 a package for creating scripts to configure source code packages using
211 templates and an M4 macro package.
213 Copyright @copyright{} 1992--1996, 1998--2017, 2020--2021 Free Software
214 Foundation, Inc.
216 @quotation
217 Permission is granted to copy, distribute and/or modify this document
218 under the terms of the GNU Free Documentation License,
219 Version 1.3 or any later version published by the Free Software
220 Foundation; with no Invariant Sections, no Front-Cover texts, and
221 no Back-Cover Texts.  A copy of the license is included in the section
222 entitled ``GNU Free Documentation License.''
223 @end quotation
224 @end copying
228 @dircategory Software development
229 @direntry
230 * Autoconf: (autoconf).         Create source code configuration scripts.
231 @end direntry
233 @dircategory Individual utilities
234 @direntry
235 * autoscan: (autoconf)autoscan Invocation.
236                                 Semi-automatic @file{configure.ac} writing
237 * ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
238 * autoconf-invocation: (autoconf)autoconf Invocation.
239                                 How to create configuration scripts
240 * autoreconf: (autoconf)autoreconf Invocation.
241                                 Remaking multiple @command{configure} scripts
242 * autoheader: (autoconf)autoheader Invocation.
243                                 How to create configuration templates
244 * autom4te: (autoconf)autom4te Invocation.
245                                 The Autoconf executables backbone
246 * configure: (autoconf)configure Invocation.    Configuring a package.
247 * autoupdate: (autoconf)autoupdate Invocation.
248                                 Automatic update of @file{configure.ac}
249 * config.status: (autoconf)config.status Invocation. Recreating configurations.
250 * testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
251 @end direntry
253 @titlepage
254 @title Autoconf
255 @subtitle Creating Automatic Configuration Scripts
256 @subtitle for version @value{VERSION}, @value{UPDATED}
257 @author David MacKenzie
258 @author Ben Elliston
259 @author Akim Demaille
260 @page
261 @vskip 0pt plus 1filll
262 @insertcopying
263 @end titlepage
265 @contents
268 @ifnottex
269 @node Top
270 @top Autoconf
271 @insertcopying
272 @end ifnottex
274 @c The master menu, created with texinfo-master-menu, goes here.
276 @menu
277 * Introduction::                Autoconf's purpose, strengths, and weaknesses
278 * The GNU Build System::        A set of tools for portable software packages
279 * Making configure Scripts::    How to organize and produce Autoconf scripts
280 * Setup::                       Initialization and output
281 * Existing Tests::              Macros that check for particular features
282 * Writing Tests::               How to write new feature checks
283 * Results::                     What to do with results from feature checks
284 * Programming in M4::           Layers on top of which Autoconf is written
285 * Programming in M4sh::         Shell portability layer
286 * Writing Autoconf Macros::     Adding new macros to Autoconf
287 * Portable Shell::              Shell script portability pitfalls
288 * Portable Make::               Makefile portability pitfalls
289 * Portable C and C++::          C and C++ portability pitfalls
290 * Manual Configuration::        Selecting features that can't be guessed
291 * Site Configuration::          Local defaults for @command{configure}
292 * Running configure Scripts::   How to use the Autoconf output
293 * config.status Invocation::    Recreating a configuration
294 * Obsolete Constructs::         Kept for backward compatibility
295 * Using Autotest::              Creating portable test suites
296 * FAQ::                         Frequent Autoconf Questions, with answers
297 * History::                     History of Autoconf
298 * GNU Free Documentation License::  License for copying this manual
299 * Indices::                     Indices of symbols, concepts, etc.
301 @detailmenu
302  --- The Detailed Node Listing ---
304 The GNU Build System
306 * Automake::                    Escaping makefile hell
307 * Gnulib::                      The GNU portability library
308 * Libtool::                     Building libraries portably
309 * Pointers::                    More info on the GNU build system
311 Making @command{configure} Scripts
313 * Writing Autoconf Input::      What to put in an Autoconf input file
314 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
315 * ifnames Invocation::          Listing the conditionals in source code
316 * autoconf Invocation::         How to create configuration scripts
317 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
319 Writing @file{configure.ac}
321 * Shell Script Compiler::       Autoconf as solution of a problem
322 * Autoconf Language::           Programming in Autoconf
323 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
325 Initialization and Output Files
327 * Initializing configure::      Option processing etc.
328 * Versioning::                  Dealing with Autoconf versions
329 * Notices::                     Copyright, version numbers in @command{configure}
330 * Input::                       Where Autoconf should find files
331 * Output::                      Outputting results from the configuration
332 * Configuration Actions::       Preparing the output based on results
333 * Configuration Files::         Creating output files
334 * Makefile Substitutions::      Using output variables in makefiles
335 * Configuration Headers::       Creating a configuration header file
336 * Configuration Commands::      Running arbitrary instantiation commands
337 * Configuration Links::         Links depending on the configuration
338 * Subdirectories::              Configuring independent packages together
339 * Default Prefix::              Changing the default installation prefix
341 Substitutions in Makefiles
343 * Preset Output Variables::     Output variables that are always set
344 * Installation Directory Variables::  Other preset output variables
345 * Changed Directory Variables::  Warnings about @file{datarootdir}
346 * Build Directories::           Supporting multiple concurrent compiles
347 * Automatic Remaking::          Makefile rules for configuring
349 Configuration Header Files
351 * Header Templates::            Input for the configuration headers
352 * autoheader Invocation::       How to create configuration templates
353 * Autoheader Macros::           How to specify CPP templates
355 Existing Tests
357 * Common Behavior::             Macros' standard schemes
358 * Alternative Programs::        Selecting between alternative programs
359 * Files::                       Checking for the existence of files
360 * Libraries::                   Library archives that might be missing
361 * Library Functions::           C library functions that might be missing
362 * Header Files::                Header files that might be missing
363 * Declarations::                Declarations that may be missing
364 * Structures::                  Structures or members that might be missing
365 * Types::                       Types that might be missing
366 * Compilers and Preprocessors::  Checking for compiling programs
367 * System Services::             Operating system services
368 * C and Posix Variants::        Kludges for C and Posix variants
369 * Erlang Libraries::            Checking for the existence of Erlang libraries
371 Common Behavior
373 * Standard Symbols::            Symbols defined by the macros
374 * Default Includes::            Includes used by the generic macros
376 Alternative Programs
378 * Particular Programs::         Special handling to find certain programs
379 * Generic Programs::            How to find other programs
381 Library Functions
383 * Function Portability::        Pitfalls with usual functions
384 * Particular Functions::        Special handling to find certain functions
385 * Generic Functions::           How to find other functions
387 Header Files
389 * Header Portability::          Collected knowledge on common headers
390 * Particular Headers::          Special handling to find certain headers
391 * Generic Headers::             How to find other headers
393 Declarations
395 * Particular Declarations::     Macros to check for certain declarations
396 * Generic Declarations::        How to find other declarations
398 Structures
400 * Particular Structures::       Macros to check for certain structure members
401 * Generic Structures::          How to find other structure members
403 Types
405 * Particular Types::            Special handling to find certain types
406 * Generic Types::               How to find other types
408 Compilers and Preprocessors
410 * Specific Compiler Characteristics::  Some portability issues
411 * Generic Compiler Characteristics::  Language independent tests and features
412 * C Compiler::                  Checking its characteristics
413 * C++ Compiler::                Likewise
414 * Objective C Compiler::        Likewise
415 * Objective C++ Compiler::      Likewise
416 * Erlang Compiler and Interpreter::  Likewise
417 * Fortran Compiler::            Likewise
418 * Go Compiler::                 Likewise
420 Writing Tests
422 * Language Choice::             Selecting which language to use for testing
423 * Writing Test Programs::       Forging source files for compilers
424 * Running the Preprocessor::    Detecting preprocessor symbols
425 * Running the Compiler::        Detecting language or header features
426 * Running the Linker::          Detecting library features
427 * Runtime::                     Testing for runtime features
428 * Systemology::                 A zoology of operating systems
429 * Multiple Cases::              Tests for several possible values
431 Writing Test Programs
433 * Guidelines::                  General rules for writing test programs
434 * Test Functions::              Avoiding pitfalls in test programs
435 * Generating Sources::          Source program boilerplate
437 Results of Tests
439 * Defining Symbols::            Defining C preprocessor symbols
440 * Setting Output Variables::    Replacing variables in output files
441 * Special Chars in Variables::  Characters to beware of in variables
442 * Caching Results::             Speeding up subsequent @command{configure} runs
443 * Printing Messages::           Notifying @command{configure} users
445 Caching Results
447 * Cache Variable Names::        Shell variables used in caches
448 * Cache Files::                 Files @command{configure} uses for caching
449 * Cache Checkpointing::         Loading and saving the cache file
451 Programming in M4
453 * M4 Quotation::                Protecting macros from unwanted expansion
454 * Using autom4te::              The Autoconf executables backbone
455 * Programming in M4sugar::      Convenient pure M4 macros
456 * Debugging via autom4te::      Figuring out what M4 was doing
458 M4 Quotation
460 * Active Characters::           Characters that change the behavior of M4
461 * One Macro Call::              Quotation and one macro call
462 * Quoting and Parameters::      M4 vs. shell parameters
463 * Quotation and Nested Macros::  Macros calling macros
464 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
465 * Quadrigraphs::                Another way to escape special characters
466 * Balancing Parentheses::       Dealing with unbalanced parentheses
467 * Quotation Rule Of Thumb::     One parenthesis, one quote
469 Using @command{autom4te}
471 * autom4te Invocation::         A GNU M4 wrapper
472 * Customizing autom4te::        Customizing the Autoconf package
474 Programming in M4sugar
476 * Redefined M4 Macros::         M4 builtins changed in M4sugar
477 * Diagnostic Macros::           Diagnostic messages from M4sugar
478 * Diversion support::           Diversions in M4sugar
479 * Conditional constructs::      Conditions in M4
480 * Looping constructs::          Iteration in M4
481 * Evaluation Macros::           More quotation and evaluation control
482 * Text processing Macros::      String manipulation in M4
483 * Number processing Macros::    Arithmetic computation in M4
484 * Set manipulation Macros::     Set manipulation in M4
485 * Forbidden Patterns::          Catching unexpanded macros
487 Programming in M4sh
489 * Common Shell Constructs::     Portability layer for common shell constructs
490 * Polymorphic Variables::       Support for indirect variable names
491 * Initialization Macros::       Macros to establish a sane shell environment
492 * File Descriptor Macros::      File descriptor macros for input and output
494 Writing Autoconf Macros
496 * Macro Definitions::           Basic format of an Autoconf macro
497 * Macro Names::                 What to call your new macros
498 * Dependencies Between Macros::  What to do when macros depend on other macros
499 * Obsoleting Macros::           Warning about old ways of doing things
500 * Coding Style::                Writing Autoconf macros @`a la Autoconf
502 Dependencies Between Macros
504 * Prerequisite Macros::         Ensuring required information
505 * Suggested Ordering::          Warning about possible ordering problems
506 * One-Shot Macros::             Ensuring a macro is called only once
508 Portable Shell Programming
510 * Shellology::                  A zoology of shells
511 * Invoking the Shell::          Invoking the shell as a command
512 * Here-Documents::              Quirks and tricks
513 * File Descriptors::            FDs and redirections
514 * Signal Handling::             Shells, signals, and headaches
515 * File System Conventions::     File names
516 * Shell Pattern Matching::      Pattern matching
517 * Shell Substitutions::         Variable and command expansions
518 * Assignments::                 Varying side effects of assignments
519 * Parentheses::                 Parentheses in shell scripts
520 * Slashes::                     Slashes in shell scripts
521 * Special Shell Variables::     Variables you should not change
522 * Shell Functions::             What to look out for if you use them
523 * Limitations of Builtins::     Portable use of not so portable /bin/sh
524 * Limitations of Usual Tools::  Portable use of portable tools
526 Portable Make Programming
528 * $< in Ordinary Make Rules::   $< in ordinary rules
529 * Failure in Make Rules::       Failing portably in rules
530 * Special Chars in Names::      Special Characters in Macro Names
531 * Backslash-Newline-Empty::     Empty lines after backslash-newline
532 * Backslash-Newline Comments::  Spanning comments across line boundaries
533 * Long Lines in Makefiles::     Line length limitations
534 * Macros and Submakes::         @code{make macro=value} and submakes
535 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
536 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
537 * Parallel Make::               Parallel @command{make} quirks
538 * Comments in Make Rules::      Other problems with Make comments
539 * Newlines in Make Rules::      Using literal newlines in rules
540 * Comments in Make Macros::     Other problems with Make comments in macros
541 * Trailing whitespace in Make Macros::  Macro substitution problems
542 * Command-line Macros and whitespace::  Whitespace trimming of values
543 * obj/ and Make::               Don't name a subdirectory @file{obj}
544 * make -k Status::              Exit status of @samp{make -k}
545 * VPATH and Make::              @code{VPATH} woes
546 * Single Suffix Rules::         Single suffix rules and separated dependencies
547 * Timestamps and Make::         Sub-second timestamp resolution
549 @code{VPATH} and Make
551 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
552 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
553 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
554 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
555 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
556 * Make Target Lookup::          More details about @code{VPATH} lookup
558 Portable C and C++ Programming
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
569 Integer Overflow
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}
577 Manual Configuration
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
583 Site Configuration
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
594 Transforming Program Names When Installing
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
600 Running @command{configure} Scripts
602 * Basic Installation::          Instructions for typical cases
603 * Compilers and Options::       Selecting compilers and optimization
604 * Multiple Architectures::      Compiling for multiple architectures at once
605 * Installation Names::          Installing in different directories
606 * Optional Features::           Selecting optional features
607 * Particular Systems::          Particular systems
608 * System Type::                 Specifying the 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
613 Obsolete Constructs
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
622 Upgrading From Version 1
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
630 Upgrading From Version 2.13
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
638 Generating Test Suites with Autotest
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}
645 Using an Autotest Test Suite
647 * testsuite Scripts::           The concepts of Autotest
648 * Autotest Logs::               Their contents
650 Frequent Autoconf Questions, with answers
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
662 History of Autoconf
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
670 Indices
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
682 @end detailmenu
683 @end menu
685 @c ============================================================= Introduction.
687 @node Introduction
688 @chapter Introduction
689 @cindex Introduction
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?''
702 ---Anonymous
703 @end flushright
704 @c (via Franc,ois Pinard)
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.
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.
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.
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.
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.
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.
767 Autoconf imposes some restrictions on the names of macros used with
768 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
770 Autoconf requires GNU M4 version 1.4.6 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.14 or later, though this is not
774 required.
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.
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.
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}.
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}.
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.
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}.
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}.
819 @c ================================================= The GNU Build System
821 @node The GNU Build System
822 @chapter The GNU Build System
823 @cindex GNU build system
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.
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
842 @node Automake
843 @section Automake
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
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:
867 @example
868 bin_PROGRAMS = hello
869 hello_SOURCES = hello.c
870 @end example
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}).
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{}
884 @node Gnulib
885 @section Gnulib
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.
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.
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{stdalign} module implements a @file{stdalign.h} header that nearly
905 conforms to C11, even on old-fashioned hosts that lack @file{stdalign.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 old-fashioned systems.
910 For more information, consult the Gnulib website,
911 @uref{https://@/www.gnu.org/@/software/@/gnulib/}.
913 @node Libtool
914 @section Libtool
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
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.
939 @node Pointers
940 @section Pointers
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.)
951 There are a number of places that you can go to for more information on
952 the GNU build tools.
954 @itemize @minus
956 @item Web
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}.
964 @item Automake Manual
966 @xref{Top, , Automake, automake, GNU Automake}, for more
967 information on Automake.
969 @item Books
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}.
978 @end itemize
980 @c ================================================= Making configure Scripts.
982 @node Making configure Scripts
983 @chapter Making @command{configure} Scripts
984 @cindex @file{aclocal.m4}
985 @cindex @command{configure}
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:
992 @itemize @minus
993 @item
994 one or more @file{Makefile} files, usually one in each subdirectory of the
995 package (@pxref{Makefile Substitutions});
997 @item
998 optionally, a C header file, the name of which is configurable,
999 containing @code{#define} directives (@pxref{Configuration Headers});
1001 @item
1002 a shell script called @file{config.status} that, when run, recreates
1003 the files listed above (@pxref{config.status Invocation});
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});
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
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.
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}).
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
1037 @group
1038 configure.ac --.
1039                |   .------> autoconf* -----> configure
1040 [aclocal.m4] --+---+
1041                |   `-----> [autoheader*] --> [config.h.in]
1042 [acsite.m4] ---'
1043 @end group
1045 Makefile.in
1046 @end example
1048 @noindent
1049 Additionally, if you use Automake, the following additional productions
1050 come into play:
1052 @example
1053 @group
1054 [acinclude.m4] --.
1055                  |
1056 [local macros] --+--> aclocal* --> aclocal.m4
1057                  |
1058 configure.ac ----'
1059 @end group
1061 @group
1062 configure.ac --.
1063                +--> automake* --> Makefile.in
1064 Makefile.am ---'
1065 @end group
1066 @end example
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
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
1089 @node Writing Autoconf Input
1090 @section Writing @file{configure.ac}
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).
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}.
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
1120 @node Shell Script Compiler
1121 @subsection A Shell Script Compiler
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.
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.
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.
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}.
1146 How does @command{autoconf} perform this task?
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.
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.
1166 @node Autoconf Language
1167 @subsection The Autoconf Language
1168 @cindex quotation
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.
1177 When calling macros that take arguments, there must not be any white
1178 space between the macro name and the open parenthesis.
1180 @example
1181 AC_INIT ([oops], [1.0]) # incorrect
1182 AC_INIT([hello], [1.0]) # good
1183 @end example
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}.
1194 For instance:
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
1203 @noindent
1204 is quoted properly.  You may safely simplify its quotation to:
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
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:
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
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.
1239 The following example is wrong and dangerous, as it is underquoted:
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
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:
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
1267 @noindent
1268 which results in this text in @file{configure}:
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
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:
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
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}:
1294 @example
1295 echo "Hard rock was here!  --AC""_DC"
1296 AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1297 @end example
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:
1304 @example
1305 AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [],
1306  [AC_MSG_ERROR([you lose])])
1307 @end example
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:
1322 @example
1323 AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [],
1324   [AC_MSG_ERROR([you lose])])
1325 @end example
1327 @noindent
1328 Voil@`a, you actually produce @samp{char b[10];} this time!
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.
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:
1342 @example
1343 AC_CHECK_HEADERS([stdio.h], [], [], [])
1344 AC_CHECK_HEADERS([stdio.h],,,)
1345 AC_CHECK_HEADERS([stdio.h])
1346 @end example
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.
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:
1360 @example
1361 # Process this file with autoconf to produce a configure script.
1362 @end example
1364 @node Autoconf Input Layout
1365 @subsection Standard @file{configure.ac} Layout
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.
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.
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
1401 @node autoscan Invocation
1402 @section Using @command{autoscan} to Create @file{configure.ac}
1403 @cindex @command{autoscan}
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.
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).
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.
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.
1437 @command{autoscan} accepts the following options:
1439 @table @option
1440 @item --help
1441 @itemx -h
1442 Print a summary of the command line options and exit.
1444 @item --version
1445 @itemx -V
1446 Print the version number of Autoconf and exit.
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.
1453 @item --debug
1454 @itemx -d
1455 Don't remove temporary files.
1457 @item --include=@var{dir}
1458 @itemx -I @var{dir}
1459 Append @var{dir} to the include path.  Multiple invocations accumulate.
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
1466 @node ifnames Invocation
1467 @section Using @command{ifnames} to List Conditionals
1468 @cindex @command{ifnames}
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}).
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{#elif}, @code{#ifdef}, or @code{#ifndef}
1482 directives.  It prints each identifier on a line, followed by a
1483 space-separated list of the files in which that identifier occurs.
1485 @noindent
1486 @command{ifnames} accepts the following options:
1488 @table @option
1489 @item --help
1490 @itemx -h
1491 Print a summary of the command line options and exit.
1493 @item --version
1494 @itemx -V
1495 Print the version number of Autoconf and exit.
1496 @end table
1498 @node autoconf Invocation
1499 @section Using @command{autoconf} to Create @command{configure}
1500 @cindex @command{autoconf}
1502 To create @command{configure} from @file{configure.ac}, run the
1503 @command{autoconf} program with no arguments.  @command{autoconf} processes
1504 @file{configure.ac} with the M4 macro processor, using the
1505 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1506 file instead of @file{configure.ac} and writes the configuration script
1507 to the standard output instead of to @command{configure}.  If you give
1508 @command{autoconf} the argument @option{-}, it reads from the standard
1509 input instead of @file{configure.ac} and writes the configuration script
1510 to the standard output.
1512 The Autoconf macros are defined in several files.  Some of the files are
1513 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1514 looks for the optional file @file{acsite.m4} in the directory that
1515 contains the distributed Autoconf macro files, and for the optional file
1516 @file{aclocal.m4} in the current directory.  Those files can contain
1517 your site's or the package's own Autoconf macro definitions
1518 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1519 defined in more than one of the files that @command{autoconf} reads, the
1520 last definition it reads overrides the earlier ones.
1522 @command{autoconf} accepts the following options:
1524 @table @option
1525 @item --help
1526 @itemx -h
1527 Print a summary of the command line options and exit.
1529 @item --version
1530 @itemx -V
1531 Print the version number of Autoconf and exit.
1533 @item --verbose
1534 @itemx -v
1535 Report processing steps.
1537 @item --debug
1538 @itemx -d
1539 Don't remove the temporary files.
1541 @item --force
1542 @itemx -f
1543 Remake @file{configure} even if newer than its input files.
1545 @item --include=@var{dir}
1546 @itemx -I @var{dir}
1547 Append @var{dir} to the include path.  Multiple invocations accumulate.
1549 @item --prepend-include=@var{dir}
1550 @itemx -B @var{dir}
1551 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1553 @item --output=@var{file}
1554 @itemx -o @var{file}
1555 Save output (script or trace) to @var{file}.  The file @option{-} stands
1556 for the standard output.
1558 @item --warnings=@var{category}[,@var{category}...]
1559 @itemx -W@var{category}[,@var{category}...]
1560 @evindex WARNINGS
1561 Enable or disable warnings related to each @var{category}.
1562 @xref{m4_warn}, for a comprehensive list of categories.
1563 Special values include:
1565 @table @samp
1566 @item all
1567 Enable all categories of warnings.
1569 @item none
1570 Disable all categories of warnings.
1572 @item error
1573 Treat all warnings as errors.
1575 @item no-@var{category}
1576 Disable warnings falling into @var{category}.
1577 @end table
1579 The enviroment variable @env{WARNINGS} may also be set to a
1580 comma-separated list of warning categories to enable or disable.
1581 It is interpreted exactly the same way as the argument of
1582 @option{--warnings}, but unknown categories are silently ignored.
1583 The command line takes precedence; for instance, if @env{WARNINGS}
1584 is set to @code{obsolete}, but @option{-Wnone} is given on the
1585 command line, no warnings will be issued.
1587 Some categories of warnings are on by default.
1588 Again, for details see @ref{m4_warn}.
1590 @item --trace=@var{macro}[:@var{format}]
1591 @itemx -t @var{macro}[:@var{format}]
1592 Do not create the @command{configure} script, but list the calls to
1593 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1594 arguments can be used to list several macros.  Multiple @option{--trace}
1595 arguments for a single macro are not cumulative; instead, you should
1596 just make @var{format} as long as needed.
1598 The @var{format} is a regular string, with newlines if desired, and
1599 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1600 @ref{autom4te Invocation}, for details on the @var{format}.
1602 @item --initialization
1603 @itemx -i
1604 By default, @option{--trace} does not trace the initialization of the
1605 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1606 results in a noticeable speedup, but can be disabled by this option.
1607 @end table
1610 It is often necessary to check the content of a @file{configure.ac}
1611 file, but parsing it yourself is extremely fragile and error-prone.  It
1612 is suggested that you rely upon @option{--trace} to scan
1613 @file{configure.ac}.  For instance, to find the list of variables that
1614 are substituted, use:
1616 @example
1617 @group
1618 $ @kbd{autoconf -t AC_SUBST}
1619 configure.ac:2:AC_SUBST:ECHO_C
1620 configure.ac:2:AC_SUBST:ECHO_N
1621 configure.ac:2:AC_SUBST:ECHO_T
1622 @i{More traces deleted}
1623 @end group
1624 @end example
1626 @noindent
1627 The example below highlights the difference between @samp{$@@},
1628 @samp{$*}, and @samp{$%}.
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
1646 @noindent
1647 The @var{format} gives you a lot of freedom:
1649 @example
1650 @group
1651 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1652 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1653 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1654 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1655 @i{More traces deleted}
1656 @end group
1657 @end example
1659 @noindent
1660 A long @var{separator} can be used to improve the readability of complex
1661 structures, and to ease their parsing (for instance when no single
1662 character is suitable as a separator):
1664 @example
1665 @group
1666 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1667 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1668 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1669 AUTOMAKE|:::::|automake|:::::|$missing_dir
1670 @i{More traces deleted}
1671 @end group
1672 @end example
1674 @node autoreconf Invocation
1675 @section Using @command{autoreconf} to Update @command{configure} Scripts
1676 @cindex @command{autoreconf}
1678 Installing the various components of the GNU Build System can be
1679 tedious: running @command{autopoint} for Gettext, @command{automake} for
1680 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1681 because some tools such as @command{automake} have been updated on your
1682 system, or because some of the sources such as @file{configure.ac} have
1683 been updated, or finally, simply in order to install the GNU Build
1684 System in a fresh tree.
1686 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1687 @command{aclocal}, @command{automake}, @command{libtoolize}, @command{intltoolize},
1688 @command{gtkdocize}, and @command{autopoint} (when appropriate) repeatedly
1689 to update the GNU Build System in the specified directories and their
1690 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1691 those files that are older than their sources.  The environment variables
1692 @env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL},
1693 @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{INTLTOOLIZE}, @env{GTKDOCIZE}, @env{M4},
1694 and @env{MAKE} may be used to override the invocation of the respective tools.
1696 If you install a new version of some tool, you can make
1697 @command{autoreconf} remake @emph{all} of the files by giving it the
1698 @option{--force} option.
1700 @xref{Automatic Remaking}, for Make rules to automatically
1701 rebuild @command{configure} scripts when their source files change.  That
1702 method handles the timestamps of configuration header templates
1703 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1704 @option{--localdir=@var{dir}}.
1706 @cindex Gettext
1707 @cindex @command{autopoint}
1708 Gettext supplies the @command{autopoint} command to add translation
1709 infrastructure to a source package.  If you use @command{autopoint},
1710 your @file{configure.ac} should invoke @code{AM_GNU_GETTEXT} and
1711 one of @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})} or
1712 @code{AM_GNU_GETTEXT_REQUIRE_VERSION(@var{min-gettext-version})}.
1713 @xref{autopoint Invocation, , Invoking the @code{autopoint} Program,
1714 gettext, GNU @code{gettext} utilities}, for further details.
1716 @noindent
1717 @command{autoreconf} accepts the following options:
1719 @table @option
1720 @item --help
1721 @itemx -h
1722 Print a summary of the command line options and exit.
1724 @item --version
1725 @itemx -V
1726 Print the version number of Autoconf and exit.
1728 @item --verbose
1729 @itemx -v
1730 Print the name of each directory @command{autoreconf} examines and the
1731 commands it runs.  If given two or more times, pass @option{--verbose}
1732 to subordinate tools that support it.
1734 @item --debug
1735 @itemx -d
1736 Don't remove the temporary files.
1738 @item --force
1739 @itemx -f
1740 Consider all generated and standard auxiliary files to be obsolete.
1741 This remakes even @file{configure} scripts and configuration headers
1742 that are newer than their input files (@file{configure.ac} and, if
1743 present, @file{aclocal.m4}).
1745 If deemed appropriate, this option triggers calls to @samp{automake
1746 --force-missing}.  Passing both @option{--force} and @option{--install}
1747 to @command{autoreconf} will in turn undo any customizations to standard
1748 files.  Note that the macro @code{AM_INIT_AUTOMAKE} has some options
1749 which change the set of files considered to be standard.
1751 @item --install
1752 @itemx -i
1753 Install any missing standard auxiliary files in the package.  By
1754 default, files are copied; this can be changed with @option{--symlink}.
1756 If deemed appropriate, this option triggers calls to
1757 @samp{automake --add-missing},
1758 @samp{libtoolize}, @samp{autopoint}, etc.
1760 @item --no-recursive
1761 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1762 macro @code{AC_CONFIG_SUBDIRS}).
1764 @item --symlink
1765 @itemx -s
1766 When used with @option{--install}, install symbolic links to the missing
1767 auxiliary files instead of copying them.
1769 @item --make
1770 @itemx -m
1771 When the directories were configured, update the configuration by
1772 running @samp{./config.status --recheck && ./config.status}, and then
1773 run @samp{make}.
1775 @item --include=@var{dir}
1776 @itemx -I @var{dir}
1777 Append @var{dir} to the include path.  Multiple invocations accumulate.
1778 Passed on to @command{aclocal}, @command{autoconf} and
1779 @command{autoheader} internally.
1781 @item --prepend-include=@var{dir}
1782 @itemx -B @var{dir}
1783 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1784 Passed on to @command{autoconf} and @command{autoheader} internally.
1786 @item --warnings=@var{category}[,@var{category}...]
1787 @itemx -W@var{category}[,@var{category}...]
1788 @evindex WARNINGS
1789 Enable or disable warnings related to each @var{category}.
1790 @xref{m4_warn}, for a comprehensive list of categories.
1791 Special values include:
1793 @table @samp
1794 @item all
1795 Enable all categories of warnings.
1797 @item none
1798 Disable all categories of warnings.
1800 @item error
1801 Treat all warnings as errors.
1803 @item no-@var{category}
1804 Disable warnings falling into @var{category}.
1805 @end table
1807 The enviroment variable @env{WARNINGS} may also be set to a
1808 comma-separated list of warning categories to enable or disable.
1809 It is interpreted exactly the same way as the argument of
1810 @option{--warnings}, but unknown categories are silently ignored.
1811 The command line takes precedence; for instance, if @env{WARNINGS}
1812 is set to @code{obsolete}, but @option{-Wnone} is given on the
1813 command line, no warnings will be issued.
1815 Some categories of warnings are on by default.
1816 Again, for details see @ref{m4_warn}.
1817 @end table
1819 If you want @command{autoreconf} to pass flags that are not listed here
1820 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1821 Due to a limitation in the Autoconf implementation these flags currently
1822 must be set on a single line in @file{Makefile.am}, without any
1823 backslash-newlines.  Also, be aware that future Automake releases might
1824 start flagging @code{ACLOCAL_AMFLAGS} as obsolescent, or even remove
1825 support for it.
1827 @c ========================================= Initialization and Output Files.
1829 @node Setup
1830 @chapter Initialization and Output Files
1832 Autoconf-generated @command{configure} scripts need some information about
1833 how to initialize, such as how to find the package's source files and
1834 about the output files to produce.  The following sections describe the
1835 initialization and the creation of output files.
1837 @menu
1838 * Initializing configure::      Option processing etc.
1839 * Versioning::                  Dealing with Autoconf versions
1840 * Notices::                     Copyright, version numbers in @command{configure}
1841 * Input::                       Where Autoconf should find files
1842 * Output::                      Outputting results from the configuration
1843 * Configuration Actions::       Preparing the output based on results
1844 * Configuration Files::         Creating output files
1845 * Makefile Substitutions::      Using output variables in makefiles
1846 * Configuration Headers::       Creating a configuration header file
1847 * Configuration Commands::      Running arbitrary instantiation commands
1848 * Configuration Links::         Links depending on the configuration
1849 * Subdirectories::              Configuring independent packages together
1850 * Default Prefix::              Changing the default installation prefix
1851 @end menu
1853 @node Initializing configure
1854 @section Initializing @command{configure}
1856 Every @command{configure} script must call @code{AC_INIT} before doing
1857 anything else that produces output.  Calls to silent macros, such as
1858 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1859 are generally used via @file{aclocal.m4}, since that is implicitly
1860 included before the start of @file{configure.ac}.  The only other
1861 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1863 @anchor{AC_INIT}
1864 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1865   @ovar{tarname}, @ovar{url})
1866 @acindex{INIT}
1867 Process any command-line arguments and perform initialization
1868 and verification.
1870 Set the name of the @var{package} and its @var{version}.  These are
1871 typically used in @option{--version} support, including that of
1872 @command{configure}.  The optional argument @var{bug-report} should be
1873 the email to which users should send bug reports.  The package
1874 @var{tarname} differs from @var{package}: the latter designates the full
1875 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1876 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1877 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1878 other than alphanumerics and underscores are changed to @samp{-}.  If
1879 provided, @var{url} should be the home page for the package.
1881 Leading and trailing whitespace is stripped from all the arguments to
1882 @code{AC_INIT}, and interior whitespace is collapsed to a single space.
1883 This means that, for instance, if you want to put several email
1884 addresses in @var{bug-report}, you can put each one on its own line:
1886 @smallexample
1887 @group
1888 # We keep having problems with the mail hosting for
1889 # gnomovision.example, so give people an alternative.
1890 AC_INIT([Gnomovision], [17.0.1], [
1891     bugs@@gnomovision.example
1892     or gnomo-bugs@@reliable-email.example
1894 @end group
1895 @end smallexample
1897 The arguments to @code{AC_INIT} may be computed by M4, when
1898 @command{autoconf} is run.  For instance, if you want to include the
1899 package's version number in the @var{tarname}, but you don't want to
1900 repeat it, you can use a helper macro:
1902 @smallexample
1903 @group
1904 m4_define([gnomo_VERSION], [17.0.1])
1905 AC_INIT([Gnomovision],
1906         m4_defn([gnomo_VERSION]),
1907         [bugs@@gnomovision.example],
1908         [gnomo-]m4_defn([gnomo_VERSION]))
1909 @end group
1910 @end smallexample
1912 This uses @code{m4_defn} to produce the expansion of
1913 @code{gnomo_VERSION} @emph{as a quoted string}, so that if there happen
1914 to be any more M4 macro names in @code{gnomo_VERSION}, they will not be
1915 expanded. @xref{Defn,,Renaming Macros,m4,GNU m4 macro processor}.
1917 Continuing this example, if you don't want to embed the version number
1918 in @file{configure.ac} at all, you can use @code{m4_esyscmd} to look it
1919 up somewhere else when @command{autoconf} is run:
1921 @smallexample
1922 @group
1923 m4_define([gnomo_VERSION],
1924   m4_esyscmd([build-aux/git-version-gen .tarball-version]))
1925 AC_INIT([Gnomovision],
1926         m4_defn([gnomo_VERSION]),
1927         [bugs@@gnomovision.example],
1928         [gnomo-]m4_defn([gnomo_VERSION]))
1929 @end group
1930 @end smallexample
1932 This uses the utility script @command{git-version-gen} to look up
1933 the package's version in its version control metadata.  This script
1934 is part of Gnulib (@pxref{Gnulib}).
1936 The arguments to @code{AC_INIT} are written into @file{configure} in
1937 several different places.  Therefore, we strongly recommend that you
1938 write any M4 logic in @code{AC_INIT} arguments to be evaluated
1939 @emph{before} @code{AC_INIT} itself is evaluated.  For instance, in the
1940 above example, the second argument to @code{m4_define} is @emph{not}
1941 quoted, so the @code{m4_esyscmd} is evaluated only once, and
1942 @code{gnomo_VERSION} is defined to the output of the command.  If the
1943 second argument to @code{m4_define} were quoted, @code{m4_esyscmd} would
1944 be evaluated each time the @var{version} or @var{tarname} arguments were
1945 written to @file{configure}, and the command would be run repeatedly.
1947 In some of the places where the arguments to @code{AC_INIT} are used,
1948 within @file{configure}, shell evaluation cannot happen.  Therefore, the
1949 arguments to @code{AC_INIT} may @emph{not} be computed when
1950 @command{configure} is run.  If they contain any construct that isn't
1951 always treated as literal by the shell (e.g.@: variable expansions),
1952 @command{autoconf} will issue an error.
1954 The @var{tarname} argument is used to construct filenames.  It should
1955 not contain wildcard characters, white space, or anything else that
1956 could be troublesome as part of a file or directory name.
1958 Some of M4's active characters (notably parentheses, square brackets,
1959 @samp{,} and @samp{#}) commonly appear in URLs and lists of email
1960 addresses.  If any of these characters appear in an argument to AC_INIT,
1961 that argument will probably need to be double-quoted to avoid errors
1962 and mistranscriptions.  @xref{M4 Quotation}.
1964 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1965 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1966 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1968 @table @asis
1969 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1970 @acindex{PACKAGE_NAME}
1971 @ovindex PACKAGE_NAME
1972 @cvindex PACKAGE_NAME
1973 Exactly @var{package}.
1975 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1976 @acindex{PACKAGE_TARNAME}
1977 @ovindex PACKAGE_TARNAME
1978 @cvindex PACKAGE_TARNAME
1979 Exactly @var{tarname}, possibly generated from @var{package}.
1981 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1982 @acindex{PACKAGE_VERSION}
1983 @ovindex PACKAGE_VERSION
1984 @cvindex PACKAGE_VERSION
1985 Exactly @var{version}.
1987 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1988 @acindex{PACKAGE_STRING}
1989 @ovindex PACKAGE_STRING
1990 @cvindex PACKAGE_STRING
1991 Exactly @samp{@var{package} @var{version}}.
1993 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1994 @acindex{PACKAGE_BUGREPORT}
1995 @ovindex PACKAGE_BUGREPORT
1996 @cvindex PACKAGE_BUGREPORT
1997 Exactly @var{bug-report}, if one was provided.  Typically an email
1998 address, or URL to a bug management web page.
2000 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
2001 @acindex{PACKAGE_URL}
2002 @ovindex PACKAGE_URL
2003 @cvindex PACKAGE_URL
2004 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
2005 @var{package} begins with @samp{GNU }, then this defaults to
2006 @samp{https://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
2007 assumed.
2008 @end table
2009 @end defmac
2011 If your @command{configure} script does its own option processing, it
2012 should inspect @samp{$@@} or @samp{$*} immediately after calling
2013 @code{AC_INIT}, because other Autoconf macros liberally use the
2014 @command{set} command to process strings, and this has the side effect
2015 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
2016 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
2017 implement your own option processing.  @xref{Site Configuration}.
2019 @node Versioning
2020 @section Dealing with Autoconf versions
2021 @cindex Autoconf version
2022 @cindex version, Autoconf
2024 The following optional macros can be used to help choose the minimum
2025 version of Autoconf that can successfully compile a given
2026 @file{configure.ac}.
2028 @defmac AC_PREREQ (@var{version})
2029 @acindex{PREREQ}
2030 @cindex Version
2031 Ensure that a recent enough version of Autoconf is being used.  If the
2032 version of Autoconf being used to create @command{configure} is
2033 earlier than @var{version}, print an error message to the standard
2034 error output and exit with failure (exit status is 63).  For example:
2036 @example
2037 AC_PREREQ([@value{VERSION}])
2038 @end example
2040 This macro may be used before @code{AC_INIT}.
2041 @end defmac
2043 @defmac AC_AUTOCONF_VERSION
2044 @acindex{AUTOCONF_VERSION}
2045 This macro was introduced in Autoconf 2.62.  It identifies the version
2046 of Autoconf that is currently parsing the input file, in a format
2047 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
2048 other words, for this release of Autoconf, its value is
2049 @samp{@value{VERSION}}.  One potential use of this macro is for writing
2050 conditional fallbacks based on when a feature was added to Autoconf,
2051 rather than using @code{AC_PREREQ} to require the newer version of
2052 Autoconf.  However, remember that the Autoconf philosophy favors feature
2053 checks over version checks.
2055 You should not expand this macro directly; use
2056 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
2057 users might
2058 have a beta version of Autoconf installed, with arbitrary letters
2059 included in its version string.  This means it is possible for the
2060 version string to contain the name of a defined macro, such that
2061 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
2062 macro during rescanning, and change the version string to be different
2063 than what you intended to check.
2064 @end defmac
2066 @node Notices
2067 @section Notices in @command{configure}
2068 @cindex Notices in @command{configure}
2070 The following macros manage version numbers for @command{configure}
2071 scripts.  Using them is optional.
2073 @defmac AC_COPYRIGHT (@var{copyright-notice})
2074 @acindex{COPYRIGHT}
2075 @cindex Copyright Notice
2076 State that, in addition to the Free Software Foundation's copyright on
2077 the Autoconf macros, parts of your @command{configure} are covered by the
2078 @var{copyright-notice}.
2080 The @var{copyright-notice} shows up in both the head of
2081 @command{configure} and in @samp{configure --version}.
2082 @end defmac
2085 @defmac AC_REVISION (@var{revision-info})
2086 @acindex{REVISION}
2087 @cindex Revision
2088 Copy revision stamp @var{revision-info} into the @command{configure}
2089 script, with any dollar signs or double-quotes removed.  This macro lets
2090 you put a revision stamp from @file{configure.ac} into @command{configure}
2091 without RCS or CVS changing it when you check in
2092 @command{configure}.  That way, you can determine easily which revision of
2093 @file{configure.ac} a particular @command{configure} corresponds to.
2095 For example, this line in @file{configure.ac}:
2097 @c The @w prevents RCS from changing the example in the manual.
2098 @example
2099 AC_REVISION([@w{$}Revision: 1.30 $])
2100 @end example
2102 @noindent
2103 produces this in @command{configure}:
2105 @example
2106 #!/bin/sh
2107 # From configure.ac Revision: 1.30
2108 @end example
2109 @end defmac
2112 @node Input
2113 @section Configure Input: Source Code, Macros, and Auxiliary Files
2115 The following macros help you manage the contents of your source tree.
2117 @anchor{AC_CONFIG_SRCDIR}
2118 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2119 @acindex{CONFIG_SRCDIR}
2120 Distinguish this package's source directory from other source
2121 directories that might happen to exist in the file system.
2122 @var{unique-file-in-source-dir} should name a file that is unique to
2123 this package.  @command{configure} will verify that this file exists in
2124 @file{@var{srcdir}}, before it runs any other checks.
2126 Use of this macro is strongly recommended.  It protects against people
2127 accidentally specifying the wrong directory with @option{--srcdir}.
2128 @xref{configure Invocation}, for more information.
2129 @end defmac
2131 Packages that use @command{aclocal} to generate @file{aclocal.m4}
2132 should declare where local macros can be found using
2133 @code{AC_CONFIG_MACRO_DIRS}.
2135 @defmac AC_CONFIG_MACRO_DIRS (@var{dir1} [@var{dir2} ... @var{dirN}])
2136 @defmacx AC_CONFIG_MACRO_DIR (@var{dir})
2137 @acindex{CONFIG_MACRO_DIRS}
2138 @acindex{CONFIG_MACRO_DIR}
2139 @acindex{CONFIG_MACRO_DIR_TRACE}
2140 Specify the given directories as the location of additional local Autoconf
2141 macros.  These macros are intended for use by commands like
2142 @command{autoreconf} or @command{aclocal} that trace macro calls; they should
2143 be called directly from @file{configure.ac} so that tools that install
2144 macros for @command{aclocal} can find the macros' declarations.  Tools
2145 that want to learn which directories have been selected should trace
2146 @code{AC_CONFIG_MACRO_DIR_TRACE}, which will be called once per directory.
2148 AC_CONFIG_MACRO_DIRS is the preferred form, and can be called multiple
2149 times and with multiple arguments; in such cases, directories in earlier
2150 calls are expected to be searched before directories in later calls, and
2151 directories appearing in the same call are expected to be searched in
2152 the order in which they appear in the call.  For historical reasons, the
2153 macro AC_CONFIG_MACRO_DIR can also be used once, if it appears first,
2154 for tools such as older @command{libtool} that weren't prepared to
2155 handle multiple directories.  For example, a usage like
2157 @smallexample
2158 AC_CONFIG_MACRO_DIR([dir1])
2159 AC_CONFIG_MACRO_DIRS([dir2])
2160 AC_CONFIG_MACRO_DIRS([dir3 dir4])
2161 @end smallexample
2163 will cause the trace of AC_CONFIG_MACRO_DIR_TRACE to appear four times,
2164 and should cause the directories to be searched in this order:
2165 @samp{dir1 dir2 dir3 dir4}.
2167 Note that if you use @command{aclocal} from an Automake release prior to
2168 1.13 to generate @file{aclocal.m4}, you must also set
2169 @code{ACLOCAL_AMFLAGS = -I @var{dir1} [-I @var{dir2} ... -I @var{dirN}]}
2170 in your top-level @file{Makefile.am}.  Due to a limitation in
2171 the Autoconf implementation of @command{autoreconf}, these include
2172 directives currently must be set on a single line in @file{Makefile.am},
2173 without any backslash-newlines.
2174 @end defmac
2176 @prindex @command{config.guess}
2177 @prindex @command{config.sub}
2178 @prindex @command{install-sh}
2180 Some Autoconf macros require auxiliary scripts.  @code{AC_PROG_INSTALL}
2181 and @code{AC_PROG_@w{MKDIR_P}} (@pxref{Particular Programs}) require a
2182 fallback implementation of @command{install} called @file{install-sh},
2183 and the @code{AC_CANONICAL} macros (@pxref{Manual Configuration})
2184 require the system-identification scripts @file{config.sub} and
2185 @file{config.guess}.  Third-party tools, such as Automake and Libtool,
2186 may require additional auxiliary scripts.
2188 By default, @command{configure} looks for these scripts next to itself,
2189 in @file{@var{srcdir}}.  For convenience when working with subdirectories
2190 with their own configure scripts (@pxref{Subdirectories}), if the
2191 scripts are not in @file{@var{srcdir}} it will also look in
2192 @file{@var{srcdir}/..} and @file{@var{srcdir}/../..}.  All of the
2193 scripts must be found in the same directory.
2195 If these default locations are not adequate, or simply to reduce clutter
2196 at the top level of the source tree, packages can use
2197 @code{AC_CONFIG_AUX_DIR} to declare where to look for auxiliary scripts.
2199 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2200 @acindex{CONFIG_AUX_DIR}
2201 Look for auxiliary scripts in @var{dir}.  Normally, @var{dir} should be a
2202 relative path, which is taken as relative to @file{@var{srcdir}}.
2203 If @var{dir} is an absolute path or contains shell variables, however,
2204 it is used as-is.
2206 When the goal of using @code{AC_CONFIG_AUX_DIR} is to reduce clutter at
2207 the top level of the source tree, the conventional name for @var{dir} is
2208 @file{build-aux}.  If you need portability to DOS variants, do not name
2209 the auxiliary directory @file{aux}.  @xref{File System Conventions}.
2210 @end defmac
2212 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2213 @acindex{REQUIRE_AUX_FILE}
2214 @vrindex ac_aux_dir
2215 Declare that @var{file} is an auxiliary script needed by this configure
2216 script, and set the shell variable @code{ac_aux_dir} to the directory
2217 where it can be found.  The value of @code{ac_aux_dir} is guaranteed to
2218 end with a @samp{/}.
2220 Macros that need auxiliary scripts must use this macro to register each
2221 script they need.
2222 @end defmac
2224 @command{configure} checks for all the auxiliary scripts it needs on
2225 startup, and exits with an error if any are missing.
2227 @command{autoreconf} also detects missing auxiliary scripts.  When used
2228 with the @option{--install} option, @command{autoreconf} will try to add
2229 missing scripts to the directory specified by @code{AC_CONFIG_AUX_DIR},
2230 or to the top level of the source tree if @code{AC_CONFIG_AUX_DIR} was
2231 not used.  It can always do this for the scripts needed by Autoconf core
2232 macros: @file{install-sh}, @file{config.sub}, and @file{config.guess}.
2233 Many other commonly-needed scripts are installed by the third-party
2234 tools that @command{autoreconf} knows how to run, such as @file{missing}
2235 for Automake and @file{ltmain.sh} for Libtool.
2237 If you are using Automake, auxiliary scripts will automatically be
2238 included in the tarball created by @command{make dist}.  If you are
2239 not using Automake you will need to arrange for auxiliary scripts to
2240 be included in tarballs yourself.  Auxiliary scripts should normally
2241 @emph{not} be checked into a version control system, for the same
2242 reasons that @command{configure} shouldn't be.
2244 The scripts needed by Autoconf core macros can be found in
2245 @file{$(datadir)/autoconf/build-aux} of the Autoconf installation
2246 (@pxref{Installation Directory Variables}).
2247 @file{install-sh} can be downloaded from
2248 @url{https://git.savannah.gnu.org/cgit/automake.git/plain/lib/install-sh}.
2249 @file{config.sub} and @file{config.guess} can be downloaded from
2250 @url{https://git.savannah.gnu.org/cgit/config.git/tree/}.
2252 @node Output
2253 @section Outputting Files
2254 @cindex Outputting files
2256 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2257 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2258 @file{config.status}, which in turn creates the makefiles and any
2259 other files resulting from configuration.  This is the only required
2260 macro besides @code{AC_INIT} (@pxref{Input}).
2262 @anchor{AC_OUTPUT}
2263 @defmac AC_OUTPUT
2264 @acindex{OUTPUT}
2265 @cindex Instantiation
2266 Generate @file{config.status} and launch it.  Call this macro once, at
2267 the end of @file{configure.ac}.
2269 @file{config.status} performs all the configuration actions: all the
2270 output files (see @ref{Configuration Files}, macro
2271 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2272 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2273 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2274 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2275 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2276 are honored.
2278 The location of your @code{AC_OUTPUT} invocation is the exact point
2279 where configuration actions are taken: any code afterwards is
2280 executed by @command{configure} once @command{config.status} was run.  If
2281 you want to bind actions to @command{config.status} itself
2282 (independently of whether @command{configure} is being run), see
2283 @ref{Configuration Commands, , Running Arbitrary Configuration
2284 Commands}.
2285 @end defmac
2287 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2288 @xref{Obsolete Macros}, for a description of the arguments that
2289 @code{AC_OUTPUT} used to support.
2292 If you run @command{make} in subdirectories, you should run it using the
2293 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2294 @code{MAKE} to the name of the @command{make} program plus any options it
2295 was given.  (But many do not include in it the values of any variables
2296 set on the command line, so those are not passed on automatically.)
2297 Some old versions of @command{make} do not set this variable.  The
2298 following macro allows you to use it even with those versions.
2300 @anchor{AC_PROG_MAKE_SET}
2301 @defmac AC_PROG_MAKE_SET
2302 @acindex{PROG_MAKE_SET}
2303 @ovindex SET_MAKE
2304 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2305 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2306 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2307 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2308 @code{SET_MAKE}.
2309 @end defmac
2311 If you use this macro, place a line like this in each @file{Makefile.in}
2312 that runs @command{MAKE} on other directories:
2314 @example
2315 @@SET_MAKE@@
2316 @end example
2320 @node Configuration Actions
2321 @section Performing Configuration Actions
2322 @cindex Configuration actions
2324 @file{configure} is designed so that it appears to do everything itself,
2325 but there is actually a hidden slave: @file{config.status}.
2326 @file{configure} is in charge of examining your system, but it is
2327 @file{config.status} that actually takes the proper actions based on the
2328 results of @file{configure}.  The most typical task of
2329 @file{config.status} is to @emph{instantiate} files.
2331 @acindex{CONFIG_@var{ITEMS}}
2332 This section describes the common behavior of the four standard
2333 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2334 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2335 have this prototype:
2337 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2338 @c awful.
2339 @example
2340 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2341 @end example
2343 @noindent
2344 where the arguments are:
2346 @table @var
2347 @item tag@dots{}
2348 A blank-or-newline-separated list of tags, which are typically the names of
2349 the files to instantiate.
2351 You are encouraged to use literals as @var{tags}.  In particular, you
2352 should avoid
2354 @example
2355 @dots{} && my_foos="$my_foos fooo"
2356 @dots{} && my_foos="$my_foos foooo"
2357 AC_CONFIG_@var{ITEMS}([$my_foos])
2358 @end example
2360 @noindent
2361 and use this instead:
2363 @example
2364 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2365 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2366 @end example
2368 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2369 special @var{tag} values: they may have the form @samp{@var{output}} or
2370 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2371 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2373 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2374 for example, asks for
2375 the creation of the file @file{Makefile} that contains the expansion of the
2376 output variables in the concatenation of @file{boiler/top.mk} and
2377 @file{boiler/bot.mk}.
2379 The special value @samp{-} might be used to denote the standard output
2380 when used in @var{output}, or the standard input when used in the
2381 @var{inputs}.  You most probably don't need to use this in
2382 @file{configure.ac}, but it is convenient when using the command line
2383 interface of @file{./config.status}, see @ref{config.status Invocation},
2384 for more details.
2386 The @var{inputs} may be absolute or relative file names.  In the latter
2387 case they are first looked for in the build tree, and then in the source
2388 tree.  Input files should be text files, and a line length below 2000
2389 bytes should be safe.
2391 @item commands
2392 Shell commands output literally into @file{config.status}, and
2393 associated with a tag that the user can use to tell @file{config.status}
2394 which commands to run.  The commands are run each time a @var{tag}
2395 request is given to @file{config.status}, typically each time the file
2396 @file{@var{tag}} is created.
2398 The variables set during the execution of @command{configure} are
2399 @emph{not} available here: you first need to set them via the
2400 @var{init-cmds}.  Nonetheless the following variables are pre-computed:
2402 @table @code
2403 @item srcdir
2404 @vrindex srcdir
2405 The name of the top source directory, assuming that the working
2406 directory is the top build directory.  This
2407 is what @command{configure}'s @option{--srcdir} option sets.
2409 @item ac_top_srcdir
2410 @vrindex ac_top_srcdir
2411 The name of the top source directory, assuming that the working
2412 directory is the current build directory.
2414 @item ac_top_build_prefix
2415 @vrindex ac_top_build_prefix
2416 The name of the top build directory, assuming that the working
2417 directory is the current build directory.
2418 It can be empty, or else ends with a slash, so that you may concatenate
2421 @item ac_srcdir
2422 @vrindex ac_srcdir
2423 The name of the corresponding source directory, assuming that the
2424 working directory is the current build directory.
2426 @item tmp
2427 @vrindex tmp
2428 The name of a temporary directory within the build tree, which you
2429 can use if you need to create additional temporary files.  The
2430 directory is cleaned up when @command{config.status} is done or
2431 interrupted.  Please use package-specific file name prefixes to
2432 avoid clashing with files that @command{config.status} may use
2433 internally.
2434 @end table
2436 @noindent
2437 The @dfn{current} directory refers to the directory (or
2438 pseudo-directory) containing the input part of @var{tags}.  For
2439 instance, running
2441 @example
2442 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2443 @end example
2445 @noindent
2446  with @option{--srcdir=../package} produces the following values:
2448 @example
2449 # Argument of --srcdir
2450 srcdir='../package'
2451 # Reversing deep/dir
2452 ac_top_build_prefix='../../'
2453 # Concatenation of $ac_top_build_prefix and srcdir
2454 ac_top_srcdir='../../../package'
2455 # Concatenation of $ac_top_srcdir and deep/dir
2456 ac_srcdir='../../../package/deep/dir'
2457 @end example
2459 @noindent
2460 independently of @samp{in/in.in}.
2462 @item init-cmds
2463 Shell commands output @emph{unquoted} near the beginning of
2464 @file{config.status}, and executed each time @file{config.status} runs
2465 (regardless of the tag).  Because they are unquoted, for example,
2466 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2467 is typically used by @file{configure} to give @file{config.status} some
2468 variables it needs to run the @var{commands}.
2470 You should be extremely cautious in your variable names: all the
2471 @var{init-cmds} share the same name space and may overwrite each other
2472 in unpredictable ways.  Sorry@enddots{}
2473 @end table
2475 All these macros can be called multiple times, with different
2476 @var{tag} values, of course!
2479 @node Configuration Files
2480 @section Creating Configuration Files
2481 @cindex Creating configuration files
2482 @cindex Configuration file creation
2484 Be sure to read the previous section, @ref{Configuration Actions}.
2486 @anchor{AC_CONFIG_FILES}
2487 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2488 @acindex{CONFIG_FILES}
2489 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2490 file (by default @file{@var{file}.in}), substituting the output variable
2491 values.
2492 @c Before we used to have this feature, which was later rejected
2493 @c because it complicates the writing of makefiles:
2494 @c If the file would be unchanged, it is left untouched, to preserve
2495 @c timestamp.
2496 This macro is one of the instantiating macros; see @ref{Configuration
2497 Actions}.  @xref{Makefile Substitutions}, for more information on using
2498 output variables.  @xref{Setting Output Variables}, for more information
2499 on creating them.  This macro creates the directory that the file is in
2500 if it doesn't exist.  Usually, makefiles are created this way,
2501 but other files, such as @file{.gdbinit}, can be specified as well.
2503 Typical calls to @code{AC_CONFIG_FILES} look like this:
2505 @example
2506 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2507 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2508 @end example
2510 You can override an input file name by appending to @var{file} a
2511 colon-separated list of input files.  Examples:
2513 @example
2514 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2515                 [lib/Makefile:boiler/lib.mk])
2516 @end example
2518 @noindent
2519 Doing this allows you to keep your file names acceptable to
2520 DOS variants, or
2521 to prepend and/or append boilerplate to the file.
2523 The @var{file} names should not contain shell metacharacters.
2524 @xref{Special Chars in Variables}.
2525 @end defmac
2529 @node Makefile Substitutions
2530 @section Substitutions in Makefiles
2531 @cindex Substitutions in makefiles
2532 @cindex Makefile substitutions
2534 Each subdirectory in a distribution that contains something to be
2535 compiled or installed should come with a file @file{Makefile.in}, from
2536 which @command{configure} creates a file @file{Makefile} in that directory.
2537 To create @file{Makefile}, @command{configure} performs a simple variable
2538 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2539 @file{Makefile.in} with the value that @command{configure} has determined
2540 for that variable.  Variables that are substituted into output files in
2541 this way are called @dfn{output variables}.  They are ordinary shell
2542 variables that are set in @command{configure}.  To make @command{configure}
2543 substitute a particular variable into the output files, the macro
2544 @code{AC_SUBST} must be called with that variable name as an argument.
2545 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2546 left unchanged.  @xref{Setting Output Variables}, for more information
2547 on creating output variables with @code{AC_SUBST}.
2549 A software package that uses a @command{configure} script should be
2550 distributed with a file @file{Makefile.in}, but no makefile; that
2551 way, the user has to properly configure the package for the local system
2552 before compiling it.
2554 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2555 GNU Coding Standards}, for more information on what to put in
2556 makefiles.
2558 @menu
2559 * Preset Output Variables::     Output variables that are always set
2560 * Installation Directory Variables::  Other preset output variables
2561 * Changed Directory Variables::  Warnings about @file{datarootdir}
2562 * Build Directories::           Supporting multiple concurrent compiles
2563 * Automatic Remaking::          Makefile rules for configuring
2564 @end menu
2566 @node Preset Output Variables
2567 @subsection Preset Output Variables
2568 @cindex Output variables
2570 Some output variables are preset by the Autoconf macros.  Some of the
2571 Autoconf macros set additional output variables, which are mentioned in
2572 the descriptions for those macros.  @xref{Output Variable Index}, for a
2573 complete list of output variables.  @xref{Installation Directory
2574 Variables}, for the list of the preset ones related to installation
2575 directories.  Below are listed the other preset ones, many of which are
2576 precious variables (@pxref{Setting Output Variables},
2577 @code{AC_ARG_VAR}).
2579 The preset variables which are available during @file{config.status}
2580 (@pxref{Configuration Actions}) may also be used during
2581 @command{configure} tests.  For example, it is permissible to reference
2582 @samp{$srcdir} when constructing a list of directories to pass via
2583 the @option{-I} option during a compiler feature check.  When used in this
2584 manner, coupled with the fact that @command{configure} is always run
2585 from the top build directory, it is sufficient to use just
2586 @samp{$srcdir} instead of @samp{$top_srcdir}.
2588 @c Just say no to ASCII sorting!  We're humans, not computers.
2589 @c These variables are listed as they would be in a dictionary:
2590 @c actor
2591 @c Actress
2592 @c actress
2594 @defvar CFLAGS
2595 @evindex CFLAGS
2596 @ovindex CFLAGS
2597 Debugging and optimization options for the C compiler.  If it is not set
2598 in the environment when @command{configure} runs, the default value is set
2599 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2600 uses this variable when compiling or linking programs to test for C features.
2602 If a compiler option affects only the behavior of the preprocessor
2603 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2604 instead.  If it affects only the linker (e.g., @option{-L@var{directory}}),
2605 it should be put into @code{LDFLAGS} instead.  If it
2606 affects only the compiler proper, @code{CFLAGS} is the natural home for
2607 it.  If an option affects multiple phases of the compiler, though,
2608 matters get tricky:
2610 @itemize @bullet
2611 @item
2612 If an option selects a 32-bit or 64-bit build on a bi-arch system, it
2613 must be put direcly into @code{CC}, e.g., @code{CC='gcc -m64'}.  This is
2614 necessary for @code{config.guess} to work right.
2615 @item
2616 Otherwise one approach is to put the option into @code{CC}.  Another is
2617 to put it into both @code{CPPFLAGS} and @code{LDFLAGS}, but not into
2618 @code{CFLAGS}.
2619 @end itemize
2621 However, remember that some @file{Makefile} variables are reserved by
2622 the GNU Coding Standards for the use of the ``user''---the person
2623 building the package.  For instance, @code{CFLAGS} is one such variable.
2625 Sometimes package developers are tempted to set user variables such as
2626 @code{CFLAGS} because it appears to make their job easier.  However, the
2627 package itself should never set a user variable, particularly not to
2628 include switches that are required for proper compilation of the
2629 package.  Since these variables are documented as being for the package
2630 builder, that person rightfully expects to be able to override any of
2631 these variables at build time.  If the package developer needs to add
2632 switches without interfering with the user, the proper way to do that is
2633 to introduce an additional variable.  Automake makes this easy by
2634 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2635 automake, GNU Automake}), but the concept is the same even if
2636 Automake is not used.
2637 @end defvar
2639 @defvar configure_input
2640 @ovindex configure_input
2641 A comment saying that the file was generated automatically by
2642 @command{configure} and giving the name of the input file.
2643 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2644 of every makefile it creates.  For other files, you should
2645 reference this variable in a comment at the top of each input file.  For
2646 example, an input shell script should begin like this:
2648 @example
2649 #!/bin/sh
2650 # @@configure_input@@
2651 @end example
2653 @noindent
2654 The presence of that line also reminds people editing the file that it
2655 needs to be processed by @command{configure} in order to be used.
2656 @end defvar
2658 @defvar CPPFLAGS
2659 @evindex CPPFLAGS
2660 @ovindex CPPFLAGS
2661 Preprocessor options for the C, C++, Objective C, and Objective C++
2662 preprocessors and compilers.  If
2663 it is not set in the environment when @command{configure} runs, the default
2664 value is empty.  @command{configure} uses this variable when preprocessing
2665 or compiling programs to test for C, C++, Objective C, and Objective C++
2666 features.
2668 This variable's contents should contain options like @option{-I},
2669 @option{-D}, and @option{-U} that affect only the behavior of the
2670 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2671 can do if an option affects other phases of the compiler as well.
2673 Currently, @command{configure} always links as part of a single
2674 invocation of the compiler that also preprocesses and compiles, so it
2675 uses this variable also when linking programs.  However, it is unwise to
2676 depend on this behavior because the GNU Coding Standards do
2677 not require it and many packages do not use @code{CPPFLAGS} when linking
2678 programs.
2680 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2681 might run into.
2682 @end defvar
2684 @defvar CXXFLAGS
2685 @evindex CXXFLAGS
2686 @ovindex CXXFLAGS
2687 Debugging and optimization options for the C++ compiler.  It acts like
2688 @code{CFLAGS}, but for C++ instead of C.
2689 @end defvar
2691 @defvar DEFS
2692 @ovindex DEFS
2693 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2694 is called, @command{configure} replaces @samp{@@DEFS@@} with
2695 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2696 variable is not defined while @command{configure} is performing its tests,
2697 only when creating the output files.  @xref{Setting Output Variables}, for
2698 how to check the results of previous tests.
2699 @end defvar
2701 @defvar ECHO_C
2702 @defvarx ECHO_N
2703 @defvarx ECHO_T
2704 @ovindex ECHO_C
2705 @ovindex ECHO_N
2706 @ovindex ECHO_T
2707 How does one suppress the trailing newline from @command{echo} for
2708 question-answer message pairs?  These variables provide a way:
2710 @example
2711 echo $ECHO_N "And the winner is... $ECHO_C"
2712 sleep 100000000000
2713 echo "$@{ECHO_T@}dead."
2714 @end example
2716 @noindent
2717 Some old and uncommon @command{echo} implementations offer no means to
2718 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2719 want to use it.
2720 @end defvar
2722 @defvar ERLCFLAGS
2723 @evindex ERLCFLAGS
2724 @ovindex ERLCFLAGS
2725 Debugging and optimization options for the Erlang compiler.  If it is not set
2726 in the environment when @command{configure} runs, the default value is empty.
2727 @command{configure} uses this variable when compiling
2728 programs to test for Erlang features.
2729 @end defvar
2731 @defvar FCFLAGS
2732 @evindex FCFLAGS
2733 @ovindex FCFLAGS
2734 Debugging and optimization options for the Fortran compiler.  If it
2735 is not set in the environment when @command{configure} runs, the default
2736 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2737 @command{configure} uses this variable when compiling or linking
2738 programs to test for Fortran features.
2739 @end defvar
2741 @defvar FFLAGS
2742 @evindex FFLAGS
2743 @ovindex FFLAGS
2744 Debugging and optimization options for the Fortran 77 compiler.  If it
2745 is not set in the environment when @command{configure} runs, the default
2746 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2747 @command{configure} uses this variable when compiling or linking
2748 programs to test for Fortran 77 features.
2749 @end defvar
2751 @defvar LDFLAGS
2752 @evindex LDFLAGS
2753 @ovindex LDFLAGS
2754 Options for the linker.  If it is not set
2755 in the environment when @command{configure} runs, the default value is empty.
2756 @command{configure} uses this variable when linking programs to test for
2757 C, C++, Objective C, Objective C++, Fortran, and Go features.
2759 This variable's contents should contain options like @option{-s} and
2760 @option{-L} that affect only the behavior of the linker.  Please see the
2761 explanation of @code{CFLAGS} for what you can do if an option also
2762 affects other phases of the compiler.
2764 Don't use this variable to pass library names
2765 (@option{-l}) to the linker; use @code{LIBS} instead.
2766 @end defvar
2768 @defvar LIBS
2769 @evindex LIBS
2770 @ovindex LIBS
2771 @option{-l} options to pass to the linker.  The default value is empty,
2772 but some Autoconf macros may prepend extra libraries to this variable if
2773 those libraries are found and provide necessary functions, see
2774 @ref{Libraries}.  @command{configure} uses this variable when linking
2775 programs to test for C, C++, Objective C, Objective C++, Fortran, and Go
2776 features.
2777 @end defvar
2779 @defvar OBJCFLAGS
2780 @evindex OBJCFLAGS
2781 @ovindex OBJCFLAGS
2782 Debugging and optimization options for the Objective C compiler.  It
2783 acts like @code{CFLAGS}, but for Objective C instead of C.
2784 @end defvar
2786 @defvar OBJCXXFLAGS
2787 @evindex OBJCXXFLAGS
2788 @ovindex OBJCXXFLAGS
2789 Debugging and optimization options for the Objective C++ compiler.  It
2790 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2791 @end defvar
2793 @defvar GOFLAGS
2794 @evindex GOFLAGS
2795 @ovindex GOFLAGS
2796 Debugging and optimization options for the Go compiler.  It acts like
2797 @code{CFLAGS}, but for Go instead of C.
2798 @end defvar
2800 @defvar builddir
2801 @ovindex builddir
2802 Rigorously equal to @samp{.}.  Added for symmetry only.
2803 @end defvar
2805 @defvar abs_builddir
2806 @ovindex abs_builddir
2807 Absolute name of @code{builddir}.
2808 @end defvar
2810 @defvar top_builddir
2811 @ovindex top_builddir
2812 The relative name of the top level of the current build tree.  In the
2813 top-level directory, this is the same as @code{builddir}.
2814 @end defvar
2816 @defvar top_build_prefix
2817 @ovindex top_build_prefix
2818 The relative name of the top level of the current build tree with final
2819 slash if nonempty.  This is the same as @code{top_builddir}, except that
2820 it contains zero or more runs of @code{../}, so it should not be
2821 appended with a slash for concatenation.  This helps for @command{make}
2822 implementations that otherwise do not treat @file{./file} and @file{file}
2823 as equal in the top-level build directory.
2824 @end defvar
2826 @defvar abs_top_builddir
2827 @ovindex abs_top_builddir
2828 Absolute name of @code{top_builddir}.
2829 @end defvar
2831 @defvar srcdir
2832 @ovindex srcdir
2833 The name of the directory that contains the source code for
2834 that makefile.
2835 @end defvar
2837 @defvar abs_srcdir
2838 @ovindex abs_srcdir
2839 Absolute name of @code{srcdir}.
2840 @end defvar
2842 @defvar top_srcdir
2843 @ovindex top_srcdir
2844 The name of the top-level source code directory for the
2845 package.  In the top-level directory, this is the same as @code{srcdir}.
2846 @end defvar
2848 @defvar abs_top_srcdir
2849 @ovindex abs_top_srcdir
2850 Absolute name of @code{top_srcdir}.
2851 @end defvar
2853 @node Installation Directory Variables
2854 @subsection Installation Directory Variables
2855 @cindex Installation directories
2856 @cindex Directories, installation
2858 The following variables specify the directories for
2859 package installation, see @ref{Directory Variables, , Variables for
2860 Installation Directories, standards, The GNU Coding
2861 Standards}, for more information.  Each variable corresponds to an
2862 argument of @command{configure}; trailing slashes are stripped so that
2863 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2864 between directory names.  See the end of this section for
2865 details on when and how to use these variables.
2867 @defvar bindir
2868 @ovindex bindir
2869 The directory for installing executables that users run.
2870 @end defvar
2872 @defvar datadir
2873 @ovindex datadir
2874 The directory for installing idiosyncratic read-only
2875 architecture-independent data.
2876 @end defvar
2878 @defvar datarootdir
2879 @ovindex datarootdir
2880 The root of the directory tree for read-only architecture-independent
2881 data files.
2882 @end defvar
2884 @defvar docdir
2885 @ovindex docdir
2886 The directory for installing documentation files (other than Info and
2887 man).
2888 @end defvar
2890 @defvar dvidir
2891 @ovindex dvidir
2892 The directory for installing documentation files in DVI format.
2893 @end defvar
2895 @defvar exec_prefix
2896 @ovindex exec_prefix
2897 The installation prefix for architecture-dependent files.  By default
2898 it's the same as @code{prefix}.  You should avoid installing anything
2899 directly to @code{exec_prefix}.  However, the default value for
2900 directories containing architecture-dependent files should be relative
2901 to @code{exec_prefix}.
2902 @end defvar
2904 @defvar htmldir
2905 @ovindex htmldir
2906 The directory for installing HTML documentation.
2907 @end defvar
2909 @defvar includedir
2910 @ovindex includedir
2911 The directory for installing C header files.
2912 @end defvar
2914 @defvar infodir
2915 @ovindex infodir
2916 The directory for installing documentation in Info format.
2917 @end defvar
2919 @defvar libdir
2920 @ovindex libdir
2921 The directory for installing object code libraries.
2922 @end defvar
2924 @defvar libexecdir
2925 @ovindex libexecdir
2926 The directory for installing executables that other programs run.
2927 @end defvar
2929 @defvar localedir
2930 @ovindex localedir
2931 The directory for installing locale-dependent but
2932 architecture-independent data, such as message catalogs.  This directory
2933 usually has a subdirectory per locale.
2934 @end defvar
2936 @defvar localstatedir
2937 @ovindex localstatedir
2938 The directory for installing modifiable single-machine data.  Content in
2939 this directory typically survives a reboot.
2940 @end defvar
2942 @defvar runstatedir
2943 @ovindex runstatedir
2944 The directory for installing temporary modifiable single-machine data.
2945 Content in this directory survives as long as the process is running
2946 (such as pid files), as contrasted with @file{/tmp} that may be
2947 periodically cleaned.  Conversely, this directory is typically cleaned
2948 on a reboot.  By default, this is a subdirectory of
2949 @code{localstatedir}.
2950 @end defvar
2952 @defvar mandir
2953 @ovindex mandir
2954 The top-level directory for installing documentation in man format.
2955 @end defvar
2957 @defvar oldincludedir
2958 @ovindex oldincludedir
2959 The directory for installing C header files for non-GCC compilers.
2960 @end defvar
2962 @defvar pdfdir
2963 @ovindex pdfdir
2964 The directory for installing PDF documentation.
2965 @end defvar
2967 @defvar prefix
2968 @ovindex prefix
2969 The common installation prefix for all files.  If @code{exec_prefix}
2970 is defined to a different value, @code{prefix} is used only for
2971 architecture-independent files.
2972 @end defvar
2974 @defvar psdir
2975 @ovindex psdir
2976 The directory for installing PostScript documentation.
2977 @end defvar
2979 @defvar sbindir
2980 @ovindex sbindir
2981 The directory for installing executables that system
2982 administrators run.
2983 @end defvar
2985 @defvar sharedstatedir
2986 @ovindex sharedstatedir
2987 The directory for installing modifiable architecture-independent data.
2988 @end defvar
2990 @defvar sysconfdir
2991 @ovindex sysconfdir
2992 The directory for installing read-only single-machine data.
2993 @end defvar
2996 Most of these variables have values that rely on @code{prefix} or
2997 @code{exec_prefix}.  It is deliberate that the directory output
2998 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2999 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
3000 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
3002 This behavior is mandated by the GNU Coding Standards, so that when
3003 the user runs:
3005 @table @samp
3006 @item make
3007 she can still specify a different prefix from the one specified to
3008 @command{configure}, in which case, if needed, the package should hard
3009 code dependencies corresponding to the make-specified prefix.
3011 @item make install
3012 she can specify a different installation location, in which case the
3013 package @emph{must} still depend on the location which was compiled in
3014 (i.e., never recompile when @samp{make install} is run).  This is an
3015 extremely important feature, as many people may decide to install all
3016 the files of a package grouped together, and then install links from
3017 the final locations to there.
3018 @end table
3020 In order to support these features, it is essential that
3021 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
3022 so that its value can be expanded based
3023 on the current value of @code{prefix}.
3025 A corollary is that you should not use these variables except in
3026 makefiles.  For instance, instead of trying to evaluate @code{datadir}
3027 in @file{configure} and hard-coding it in makefiles using
3028 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
3029 you should add
3030 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
3031 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
3033 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
3034 @code{bindir} and friends in your shell scripts and other files; instead,
3035 let @command{make} manage their replacement.  For instance Autoconf
3036 ships templates of its shell scripts ending with @samp{.in}, and uses a
3037 makefile snippet similar to the following to build scripts like
3038 @command{autoheader} and @command{autom4te}:
3040 @example
3041 @group
3042 edit = sed \
3043         -e 's|@@bindir[@@]|$(bindir)|g' \
3044         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
3045         -e 's|@@prefix[@@]|$(prefix)|g'
3046 @end group
3048 @group
3049 autoheader autom4te: Makefile
3050         rm -f $@@ $@@.tmp
3051         srcdir=''; \
3052           test -f ./$@@.in || srcdir=$(srcdir)/; \
3053           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
3054 @c $$ restore font-lock
3055         chmod +x $@@.tmp
3056         chmod a-w $@@.tmp
3057         mv $@@.tmp $@@
3058 @end group
3060 @group
3061 autoheader: $(srcdir)/autoheader.in
3062 autom4te: $(srcdir)/autom4te.in
3063 @end group
3064 @end example
3066 Some details are noteworthy:
3068 @table @asis
3069 @item @samp{@@bindir[@@]}
3070 The brackets prevent @command{configure} from replacing
3071 @samp{@@bindir@@} in the Sed expression itself.
3072 Brackets are preferable to a backslash here, since
3073 Posix says @samp{\@@} is not portable.
3075 @item @samp{$(bindir)}
3076 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
3077 instead.
3079 @item @samp{$(pkgdatadir)}
3080 The example takes advantage of the variable @samp{$(pkgdatadir)}
3081 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
3083 @item @samp{/}
3084 Don't use @samp{/} in the Sed expressions that replace file names since
3085 most likely the
3086 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
3087 Use a shell metacharacter instead, such as @samp{|}.
3089 @item special characters
3090 File names, file name components, and the value of @code{VPATH} should
3091 not contain shell metacharacters or white
3092 space.  @xref{Special Chars in Variables}.
3094 @item dependency on @file{Makefile}
3095 Since @code{edit} uses values that depend on the configuration specific
3096 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
3097 the output depends on @file{Makefile}, not @file{configure.ac}.
3099 @item @samp{$@@}
3100 The main rule is generic, and uses @samp{$@@} extensively to
3101 avoid the need for multiple copies of the rule.
3103 @item Separated dependencies and single suffix rules
3104 You can't use them!  The above snippet cannot be (portably) rewritten
3107 @example
3108 autoconf autoheader: Makefile
3109 @group
3110 .in:
3111         rm -f $@@ $@@.tmp
3112         $(edit) $< >$@@.tmp
3113         chmod +x $@@.tmp
3114         mv $@@.tmp $@@
3115 @end group
3116 @end example
3118 @xref{Single Suffix Rules}, for details.
3120 @item @samp{$(srcdir)}
3121 Be sure to specify the name of the source directory,
3122 otherwise the package won't support separated builds.
3123 @end table
3125 For the more specific installation of Erlang libraries, the following variables
3126 are defined:
3128 @defvar ERLANG_INSTALL_LIB_DIR
3129 @ovindex ERLANG_INSTALL_LIB_DIR
3130 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
3131 The common parent directory of Erlang library installation directories.
3132 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
3133 macro in @file{configure.ac}.
3134 @end defvar
3136 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
3137 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
3138 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3139 The installation directory for Erlang library @var{library}.
3140 This variable is set by using the
3141 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3142 macro in @file{configure.ac}.
3143 @end defvar
3145 @xref{Erlang Libraries}, for details.
3148 @node Changed Directory Variables
3149 @subsection Changed Directory Variables
3150 @cindex @file{datarootdir}
3152 In Autoconf 2.60, the set of directory variables has changed, and the
3153 defaults of some variables have been adjusted
3154 (@pxref{Installation Directory Variables}) to changes in the
3155 GNU Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
3156 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
3157 upgrading from an earlier Autoconf version, you may need to adjust your files
3158 to ensure that the directory variables are substituted correctly
3159 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
3160 in place.  For example, in a @file{Makefile.in}, adding
3162 @example
3163 datarootdir = @@datarootdir@@
3164 @end example
3166 @noindent
3167 is usually sufficient.  If you use Automake to create @file{Makefile.in},
3168 it will add this for you.
3170 To help with the transition, Autoconf warns about files that seem to use
3171 @code{datarootdir} without defining it.  In some cases, it then expands
3172 the value of @code{$datarootdir} in substitutions of the directory
3173 variables.  The following example shows such a warning:
3175 @example
3176 $ @kbd{cat configure.ac}
3177 AC_INIT
3178 AC_CONFIG_FILES([Makefile])
3179 AC_OUTPUT
3180 $ @kbd{cat Makefile.in}
3181 prefix = @@prefix@@
3182 datadir = @@datadir@@
3183 $ @kbd{autoconf}
3184 $ @kbd{configure}
3185 configure: creating ./config.status
3186 config.status: creating Makefile
3187 config.status: WARNING:
3188                Makefile.in seems to ignore the --datarootdir setting
3189 $ @kbd{cat Makefile}
3190 prefix = /usr/local
3191 datadir = $@{prefix@}/share
3192 @end example
3194 Usually one can easily change the file to accommodate both older and newer
3195 Autoconf releases:
3197 @example
3198 $ @kbd{cat Makefile.in}
3199 prefix = @@prefix@@
3200 datarootdir = @@datarootdir@@
3201 datadir = @@datadir@@
3202 $ @kbd{configure}
3203 configure: creating ./config.status
3204 config.status: creating Makefile
3205 $ @kbd{cat Makefile}
3206 prefix = /usr/local
3207 datarootdir = $@{prefix@}/share
3208 datadir = $@{datarootdir@}
3209 @end example
3211 @acindex{DATAROOTDIR_CHECKED}
3212 In some cases, however, the checks may not be able to detect that a suitable
3213 initialization of @code{datarootdir} is in place, or they may fail to detect
3214 that such an initialization is necessary in the output file.  If, after
3215 auditing your package, there are still spurious @file{configure} warnings about
3216 @code{datarootdir}, you may add the line
3218 @example
3219 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3220 @end example
3222 @noindent
3223 to your @file{configure.ac} to disable the warnings.  This is an exception
3224 to the usual rule that you should not define a macro whose name begins with
3225 @code{AC_} (@pxref{Macro Names}).
3229 @node Build Directories
3230 @subsection Build Directories
3231 @cindex Build directories
3232 @cindex Directories, build
3234 You can support compiling a software package for several architectures
3235 simultaneously from the same copy of the source code.  The object files
3236 for each architecture are kept in their own directory.
3238 To support doing this, @command{make} uses the @code{VPATH} variable to
3239 find the files that are in the source directory.  GNU Make
3240 can do this.  Most other recent @command{make} programs can do this as
3241 well, though they may have difficulties and it is often simpler to
3242 recommend GNU @command{make} (@pxref{VPATH and Make}).  Older
3243 @command{make} programs do not support @code{VPATH}; when using them, the
3244 source code must be in the same directory as the object files.
3246 If you are using GNU Automake, the remaining details in this
3247 section are already covered for you, based on the contents of your
3248 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
3249 supporting @code{VPATH} requires the following in your
3250 @file{Makefile.in}:
3252 @example
3253 srcdir = @@srcdir@@
3254 VPATH = @@srcdir@@
3255 @end example
3257 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3258 listed in VPATH}.
3260 @command{configure} substitutes the correct value for @code{srcdir} when
3261 it produces @file{Makefile}.
3263 Do not use the @command{make} variable @code{$<}, which expands to the
3264 file name of the file in the source directory (found with @code{VPATH}),
3265 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3266 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3267 versions of @command{make} do not set @code{$<} in explicit rules; they
3268 expand it to an empty value.
3270 Instead, Make command lines should always refer to source
3271 files by prefixing them with @samp{$(srcdir)/}.  It's safer
3272 to quote the source directory name, in case it contains characters that
3273 are special to the shell.  Because @samp{$(srcdir)} is expanded by Make,
3274 single-quoting works and is safer than double-quoting.  For example:
3276 @example
3277 time.info: time.texinfo
3278         $(MAKEINFO) '$(srcdir)/time.texinfo'
3279 @end example
3281 @node Automatic Remaking
3282 @subsection Automatic Remaking
3283 @cindex Automatic remaking
3284 @cindex Remaking automatically
3286 You can put rules like the following in the top-level @file{Makefile.in}
3287 for a package to automatically update the configuration information when
3288 you change the configuration files.  This example includes all of the
3289 optional files, such as @file{aclocal.m4} and those related to
3290 configuration header files.  Omit from the @file{Makefile.in} rules for
3291 any of these files that your package does not use.
3293 The @samp{$(srcdir)/} prefix is included because of limitations in the
3294 @code{VPATH} mechanism.
3296 The @file{stamp-} files are necessary because the timestamps of
3297 @file{config.h.in} and @file{config.h} are not changed if remaking
3298 them does not change their contents.  This feature avoids unnecessary
3299 recompilation.  You should include the file @file{stamp-h.in} in your
3300 package's distribution, so that @command{make} considers
3301 @file{config.h.in} up to date.  Don't use @command{touch}
3302 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3303 @command{echo} (using
3304 @command{date} would cause needless differences, hence CVS
3305 conflicts, etc.).
3307 @example
3308 @group
3309 $(srcdir)/configure: configure.ac aclocal.m4
3310         cd '$(srcdir)' && autoconf
3312 # autoheader might not change config.h.in, so touch a stamp file.
3313 $(srcdir)/config.h.in: stamp-h.in ;
3314 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3315         cd '$(srcdir)' && autoheader
3316         echo timestamp > '$(srcdir)/stamp-h.in'
3318 config.h: stamp-h ;
3319 stamp-h: config.h.in config.status
3320         ./config.status
3322 Makefile: Makefile.in config.status
3323         ./config.status
3325 config.status: configure
3326         ./config.status --recheck
3327 @end group
3328 @end example
3330 @noindent
3331 (Be careful if you copy these lines directly into your makefile, as you
3332 need to convert the indented lines to start with the tab character.)
3334 In addition, you should use
3336 @example
3337 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3338 @end example
3340 @noindent
3341 so @file{config.status} ensures that @file{config.h} is considered up to
3342 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3344 @xref{config.status Invocation}, for more examples of handling
3345 configuration-related dependencies.
3347 @node Configuration Headers
3348 @section Configuration Header Files
3349 @cindex Configuration Header
3350 @cindex @file{config.h}
3352 When a package contains more than a few tests that define C preprocessor
3353 symbols, the command lines to pass @option{-D} options to the compiler
3354 can get quite long.  This causes two problems.  One is that the
3355 @command{make} output is hard to visually scan for errors.  More
3356 seriously, the command lines can exceed the length limits of some
3357 operating systems.  As an alternative to passing @option{-D} options to
3358 the compiler, @command{configure} scripts can create a C header file
3359 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3360 macro selects this kind of output.  Though it can be called anywhere
3361 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3362 it right after @code{AC_INIT}.
3364 The package should @samp{#include} the configuration header file before
3365 any other header files, to prevent inconsistencies in declarations (for
3366 example, if it redefines @code{const}, or if it defines a macro like
3367 @code{_FILE_OFFSET_BITS} that affects the behavior of system
3368 headers). Note that it is okay to only include @file{config.h} from
3369 @file{.c} files; the project's @file{.h} files can rely on
3370 @file{config.h} already being included first by the corresponding
3371 @file{.c} file.
3373 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3374 option (or @option{-I..}; whichever directory contains @file{config.h}).
3375 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3376 the directory of the currently read file, i.e., the source directory, not
3377 the build directory.
3379 With the appropriate @option{-I} option, you can use
3380 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3381 because in the rare case when the source directory contains another
3382 @file{config.h}, the build directory should be searched first.
3385 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3386 @acindex{CONFIG_HEADERS}
3387 @cvindex HAVE_CONFIG_H
3388 This macro is one of the instantiating macros; see @ref{Configuration
3389 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3390 blank-or-newline-separated list @var{header} containing C preprocessor
3391 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3392 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3393 The usual name for @var{header} is @file{config.h};
3394 @var{header} should not contain shell metacharacters.
3395 @xref{Special Chars in Variables}.
3397 If @var{header} already exists and its contents are identical to what
3398 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3399 making some changes in the configuration without needlessly causing
3400 object files that depend on the header file to be recompiled.
3402 Usually the input file is named @file{@var{header}.in}; however, you can
3403 override the input file name by appending to @var{header} a
3404 colon-separated list of input files.  For example, you might need to make
3405 the input file name acceptable to DOS variants:
3407 @example
3408 AC_CONFIG_HEADERS([config.h:config.hin])
3409 @end example
3411 @end defmac
3413 @defmac AH_HEADER
3414 @ahindex{HEADER}
3415 This macro is defined as the name of the first declared config header
3416 and undefined if no config headers have been declared up to this point.
3417 A third-party macro may, for example, require use of a config header
3418 without invoking AC_CONFIG_HEADERS twice, like this:
3420 @example
3421 AC_CONFIG_COMMANDS_PRE(
3422         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3423 @end example
3425 @end defmac
3427 @xref{Configuration Actions}, for more details on @var{header}.
3429 @menu
3430 * Header Templates::            Input for the configuration headers
3431 * autoheader Invocation::       How to create configuration templates
3432 * Autoheader Macros::           How to specify CPP templates
3433 @end menu
3435 @node Header Templates
3436 @subsection Configuration Header Templates
3437 @cindex Configuration Header Template
3438 @cindex Header templates
3439 @cindex @file{config.h.in}
3441 Your distribution should contain a template file that looks as you want
3442 the final header file to look, including comments, with @code{#undef}
3443 statements which are used as hooks.  For example, suppose your
3444 @file{configure.ac} makes these calls:
3446 @example
3447 AC_CONFIG_HEADERS([conf.h])
3448 AC_CHECK_HEADERS([unistd.h])
3449 @end example
3451 @noindent
3452 Then you could have code like the following in @file{conf.h.in}.
3453 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3454 to 1, if and only if the system has @file{unistd.h}.
3456 @example
3457 @group
3458 /* Define as 1 if you have unistd.h.  */
3459 #undef HAVE_UNISTD_H
3460 @end group
3461 @end example
3463 The format of the template file is stricter than what the C preprocessor
3464 is required to accept.  A directive line should contain only whitespace,
3465 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3466 instead of @samp{#undef}, or of comments on the same line as
3467 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3468 once.  Other preprocessor lines, such as @samp{#ifdef} or
3469 @samp{#include}, are copied verbatim from the template into the
3470 generated header.
3472 Since it is a tedious task to keep a template header up to date, you may
3473 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3475 During the instantiation of the header, each @samp{#undef} line in the
3476 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3477 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3478 been executed during the @command{configure} run, the @samp{#undef} line is
3479 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3480 on many systems, it can be implicitly defined by the compiler, and
3481 undefining it in the header would then break compilation of subsequent
3482 headers.)
3484 Currently, @emph{all} remaining @samp{#undef} lines in the header
3485 template are commented out, whether or not there was a corresponding
3486 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3487 for future releases of Autoconf.
3489 Generally speaking, since you should not use @samp{#define}, and you
3490 cannot guarantee whether a @samp{#undef} directive in the header
3491 template will be converted to a @samp{#define} or commented out in the
3492 generated header file, the template file cannot be used for conditional
3493 definition effects.  Consequently, if you need to use the construct
3495 @example
3496 @group
3497 #ifdef THIS
3498 # define THAT
3499 #endif
3500 @end group
3501 @end example
3503 @noindent
3504 you must place it outside of the template.
3505 If you absolutely need to hook it to the config header itself, please put
3506 the directives to a separate file, and @samp{#include} that file from the
3507 config header template.  If you are using @command{autoheader}, you would
3508 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3511 @node autoheader Invocation
3512 @subsection Using @command{autoheader} to Create @file{config.h.in}
3513 @cindex @command{autoheader}
3515 The @command{autoheader} program can create a template file of C
3516 @samp{#define} statements for @command{configure} to use.
3517 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3518 @file{configure} sources to determine the name of the template.
3519 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3520 input file name, @command{autoheader} uses the first one.)
3522 It is recommended that only one input file is used.  If you want to append
3523 a boilerplate code, it is preferable to use
3524 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3525 File @file{conf_post.h} is not processed during the configuration then,
3526 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3527 prepend a boilerplate code.
3529 In order to do its job, @command{autoheader} needs you to document all
3530 of the symbols that you might use.  Typically this is done via an
3531 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3532 is a literal symbol and whose third argument describes the symbol
3533 (@pxref{Defining Symbols}).  Alternatively, you can use
3534 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3535 suitable input file for a subsequent configuration header file.
3536 Symbols defined by Autoconf's builtin tests are already documented properly;
3537 you need to document only those that you
3538 define yourself.
3540 You might wonder why @command{autoheader} is needed: after all, why
3541 would @command{configure} need to ``patch'' a @file{config.h.in} to
3542 produce a @file{config.h} instead of just creating @file{config.h} from
3543 scratch?  Well, when everything rocks, the answer is just that we are
3544 wasting our time maintaining @command{autoheader}: generating
3545 @file{config.h} directly is all that is needed.  When things go wrong,
3546 however, you'll be thankful for the existence of @command{autoheader}.
3548 The fact that the symbols are documented is important in order to
3549 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3550 well-defined list of symbols that should be defined (or not) is
3551 also important for people who are porting packages to environments where
3552 @command{configure} cannot be run: they just have to @emph{fill in the
3553 blanks}.
3555 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3557 If you give @command{autoheader} an argument, it uses that file instead
3558 of @file{configure.ac} and writes the header file to the standard output
3559 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3560 argument of @option{-}, it reads the standard input instead of
3561 @file{configure.ac} and writes the header file to the standard output.
3563 @command{autoheader} accepts the following options:
3565 @table @option
3566 @item --help
3567 @itemx -h
3568 Print a summary of the command line options and exit.
3570 @item --version
3571 @itemx -V
3572 Print the version number of Autoconf and exit.
3574 @item --verbose
3575 @itemx -v
3576 Report processing steps.
3578 @item --debug
3579 @itemx -d
3580 Don't remove the temporary files.
3582 @item --force
3583 @itemx -f
3584 Remake the template file even if newer than its input files.
3586 @item --include=@var{dir}
3587 @itemx -I @var{dir}
3588 Append @var{dir} to the include path.  Multiple invocations accumulate.
3590 @item --prepend-include=@var{dir}
3591 @itemx -B @var{dir}
3592 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3594 @item --warnings=@var{category}[,@var{category}...]
3595 @itemx -W@var{category}[,@var{category}...]
3596 @evindex WARNINGS
3597 Enable or disable warnings related to each @var{category}.
3598 @xref{m4_warn}, for a comprehensive list of categories.
3599 Special values include:
3601 @table @samp
3602 @item all
3603 Enable all categories of warnings.
3605 @item none
3606 Disable all categories of warnings.
3608 @item error
3609 Treat all warnings as errors.
3611 @item no-@var{category}
3612 Disable warnings falling into @var{category}.
3613 @end table
3615 The enviroment variable @env{WARNINGS} may also be set to a
3616 comma-separated list of warning categories to enable or disable.
3617 It is interpreted exactly the same way as the argument of
3618 @option{--warnings}, but unknown categories are silently ignored.
3619 The command line takes precedence; for instance, if @env{WARNINGS}
3620 is set to @code{obsolete}, but @option{-Wnone} is given on the
3621 command line, no warnings will be issued.
3623 Some categories of warnings are on by default.
3624 Again, for details see @ref{m4_warn}.
3625 @end table
3629 @node Autoheader Macros
3630 @subsection Autoheader Macros
3631 @cindex Autoheader macros
3633 @command{autoheader} scans @file{configure.ac} and figures out which C
3634 preprocessor symbols it might define.  It knows how to generate
3635 templates for symbols defined by @code{AC_CHECK_HEADERS},
3636 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3637 symbol, you must define a template for it.  If there are missing
3638 templates, @command{autoheader} fails with an error message.
3640 The template for a @var{symbol} is created
3641 by @command{autoheader} from
3642 the @var{description} argument to an @code{AC_DEFINE};
3643 see @ref{Defining Symbols}.
3645 For special needs, you can use the following macros.
3648 @defmac AH_TEMPLATE (@var{key}, @var{description})
3649 @ahindex{TEMPLATE}
3650 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3651 generates standard templates just like @code{AC_DEFINE} when a
3652 @var{description} is given.
3654 For example:
3656 @example
3657 AH_TEMPLATE([NULL_DEVICE],
3658   [Name of the file to open to get
3659    a null file, or a data sink.])
3660 @end example
3662 @noindent
3663 generates the following template, with the description properly
3664 justified.
3666 @example
3667 /* Name of the file to open to get a null file, or a data sink. */
3668 #undef NULL_DEVICE
3669 @end example
3670 @end defmac
3673 @defmac AH_VERBATIM (@var{key}, @var{template})
3674 @ahindex{VERBATIM}
3675 Tell @command{autoheader} to include the @var{template} as-is in the header
3676 template file.  This @var{template} is associated with the @var{key},
3677 which is used to sort all the different templates and guarantee their
3678 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3679 @end defmac
3682 @defmac AH_TOP (@var{text})
3683 @ahindex{TOP}
3684 Include @var{text} at the top of the header template file.
3685 @end defmac
3688 @defmac AH_BOTTOM (@var{text})
3689 @ahindex{BOTTOM}
3690 Include @var{text} at the bottom of the header template file.
3691 @end defmac
3694 Please note that @var{text} gets included ``verbatim'' to the template file,
3695 not to the resulting config header, so it can easily get mangled when the
3696 template is processed.  There is rarely a need for something other than
3698 @example
3699 AH_BOTTOM([#include <custom.h>])
3700 @end example
3704 @node Configuration Commands
3705 @section Running Arbitrary Configuration Commands
3706 @cindex Configuration commands
3707 @cindex Commands for configuration
3709 You can execute arbitrary commands before, during, and after
3710 @file{config.status} is run.  The three following macros accumulate the
3711 commands to run when they are called multiple times.
3712 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3713 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3715 @anchor{AC_CONFIG_COMMANDS}
3716 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3717 @acindex{CONFIG_COMMANDS}
3718 Specify additional shell commands to run at the end of
3719 @file{config.status}, and shell commands to initialize any variables
3720 from @command{configure}.  Associate the commands with @var{tag}.
3721 Since typically the @var{cmds} create a file, @var{tag} should
3722 naturally be the name of that file.  If needed, the directory hosting
3723 @var{tag} is created.  The @var{tag} should not contain shell
3724 metacharacters.  @xref{Special Chars in Variables}.
3725 This macro is one of the instantiating macros;
3726 see @ref{Configuration Actions}.
3728 Here is an unrealistic example:
3729 @example
3730 fubar=42
3731 AC_CONFIG_COMMANDS([fubar],
3732                    [echo this is extra $fubar, and so on.],
3733                    [fubar=$fubar])
3734 @end example
3736 Here is a better one:
3737 @example
3738 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3739 @end example
3740 @end defmac
3742 The following two macros look similar, but in fact they are not of the same
3743 breed: they are executed directly by @file{configure}, so you cannot use
3744 @file{config.status} to rerun them.
3746 @c Yet it is good to leave them here.  The user sees them together and
3747 @c decides which best fits their needs.
3749 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3750 @acindex{CONFIG_COMMANDS_PRE}
3751 Execute the @var{cmds} right before creating @file{config.status}.
3753 This macro presents the last opportunity to call @code{AC_SUBST},
3754 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3755 @end defmac
3757 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3758 @acindex{CONFIG_COMMANDS_POST}
3759 Execute the @var{cmds} right after creating @file{config.status}.
3760 @end defmac
3765 @node Configuration Links
3766 @section Creating Configuration Links
3767 @cindex Configuration links
3768 @cindex Links for configuration
3770 You may find it convenient to create links whose destinations depend upon
3771 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3772 creation of relative symbolic links can be delicate when the package is
3773 built in a directory different from the source directory.
3775 @anchor{AC_CONFIG_LINKS}
3776 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3777   @ovar{init-cmds})
3778 @acindex{CONFIG_LINKS}
3779 @cindex Links
3780 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3781 the corresponding link name @var{dest}.  Makes a symbolic link if
3782 possible, otherwise a hard link if possible, otherwise a copy.  The
3783 @var{dest} and @var{source} names should be relative to the top level
3784 source or build directory, and should not contain shell metacharacters.
3785 @xref{Special Chars in Variables}.
3787 This macro is one of the instantiating
3788 macros; see @ref{Configuration Actions}.
3790 For example, this call:
3792 @example
3793 AC_CONFIG_LINKS([host.h:config/$machine.h
3794                 object.h:config/$obj_format.h])
3795 @end example
3797 @noindent
3798 creates in the current directory @file{host.h} as a link to
3799 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3800 link to @file{@var{srcdir}/config/$obj_format.h}.
3802 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3803 impossible for @samp{config.status} to guess the links to establish.
3805 One can then run:
3806 @example
3807 ./config.status host.h object.h
3808 @end example
3809 @noindent
3810 to create the links.
3811 @end defmac
3815 @node Subdirectories
3816 @section Configuring Other Packages in Subdirectories
3817 @cindex Configure subdirectories
3818 @cindex Subdirectory configure
3820 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3821 makefiles in subdirectories.  However, @command{configure} scripts
3822 that control more than one independent package can use
3823 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3824 packages in subdirectories.
3826 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3827 @acindex{CONFIG_SUBDIRS}
3828 @ovindex subdirs
3829 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3830 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3831 be a literal, i.e., please do not use:
3833 @example
3834 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3835 if test "x$package_foo_enabled" = xyes; then
3836   my_subdirs="$my_subdirs foo"
3838 AC_CONFIG_SUBDIRS([$my_subdirs])
3839 @end example
3841 @noindent
3842 because this prevents @samp{./configure --help=recursive} from
3843 displaying the options of the package @code{foo}.  Instead, you should
3844 write:
3846 @example
3847 if test "x$package_foo_enabled" = xyes; then
3848   AC_CONFIG_SUBDIRS([foo])
3850 @end example
3852 If a given @var{dir} is not found at @command{configure} run time, a
3853 warning is reported; if the subdirectory is optional, write:
3855 @example
3856 if test -d "$srcdir/foo"; then
3857   AC_CONFIG_SUBDIRS([foo])
3859 @end example
3861 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3862 of @command{configure}.  This is for packages that might use a
3863 non-Autoconf script @command{Configure}, which can't be called through a
3864 wrapper @command{configure} since it would be the same file on
3865 case-insensitive file systems.
3867 The subdirectory @command{configure} scripts are given the same command
3868 line options that were given to this @command{configure} script, with minor
3869 changes if needed, which include:
3871 @itemize @minus
3872 @item
3873 adjusting a relative name for the cache file;
3875 @item
3876 adjusting a relative name for the source directory;
3878 @item
3879 propagating the current value of @code{$prefix}, including if it was
3880 defaulted, and if the default values of the top level and of the subdirectory
3881 @file{configure} differ.
3882 @end itemize
3884 This macro also sets the output variable @code{subdirs} to the list of
3885 directories @samp{@var{dir} @dots{}}.  Make rules can use
3886 this variable to determine which subdirectories to recurse into.
3888 This macro may be called multiple times.
3889 @end defmac
3891 @node Default Prefix
3892 @section Default Prefix
3893 @cindex Install prefix
3894 @cindex Prefix for install
3896 By default, @command{configure} sets the prefix for files it installs to
3897 @file{/usr/local}.  The user of @command{configure} can select a different
3898 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3899 There are two ways to change the default: when creating
3900 @command{configure}, and when running it.
3902 Some software packages might want to install in a directory other than
3903 @file{/usr/local} by default.  To accomplish that, use the
3904 @code{AC_PREFIX_DEFAULT} macro.
3906 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3907 @acindex{PREFIX_DEFAULT}
3908 Set the default installation prefix to @var{prefix} instead of
3909 @file{/usr/local}.
3910 @end defmac
3912 It may be convenient for users to have @command{configure} guess the
3913 installation prefix from the location of a related program that they
3914 have already installed.  If you wish to do that, you can call
3915 @code{AC_PREFIX_PROGRAM}.
3917 @anchor{AC_PREFIX_PROGRAM}
3918 @defmac AC_PREFIX_PROGRAM (@var{program})
3919 @acindex{PREFIX_PROGRAM}
3920 If the user did not specify an installation prefix (using the
3921 @option{--prefix} option), guess a value for it by looking for
3922 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3923 is found, set the prefix to the parent of the directory containing
3924 @var{program}, else default the prefix as described above
3925 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3926 @var{program} is @code{gcc} and the @env{PATH} contains
3927 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3928 @end defmac
3932 @c ======================================================== Existing tests
3934 @node Existing Tests
3935 @chapter Existing Tests
3937 These macros test for particular system features that packages might
3938 need or want to use.  If you need to test for a kind of feature that
3939 none of these macros check for, you can probably do it by calling
3940 primitive test macros with appropriate arguments (@pxref{Writing
3941 Tests}).
3943 These tests print messages telling the user which feature they're
3944 checking for, and what they find.  They cache their results for future
3945 @command{configure} runs (@pxref{Caching Results}).
3947 Some of these macros set output variables.  @xref{Makefile
3948 Substitutions}, for how to get their values.  The phrase ``define
3949 @var{name}'' is used below as a shorthand to mean ``define the C
3950 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3951 Symbols}, for how to get those symbol definitions into your program.
3953 @menu
3954 * Common Behavior::             Macros' standard schemes
3955 * Alternative Programs::        Selecting between alternative programs
3956 * Files::                       Checking for the existence of files
3957 * Libraries::                   Library archives that might be missing
3958 * Library Functions::           C library functions that might be missing
3959 * Header Files::                Header files that might be missing
3960 * Declarations::                Declarations that may be missing
3961 * Structures::                  Structures or members that might be missing
3962 * Types::                       Types that might be missing
3963 * Compilers and Preprocessors::  Checking for compiling programs
3964 * System Services::             Operating system services
3965 * C and Posix Variants::        Kludges for C and Posix variants
3966 * Erlang Libraries::            Checking for the existence of Erlang libraries
3967 @end menu
3969 @node Common Behavior
3970 @section Common Behavior
3971 @cindex Common autoconf behavior
3973 Much effort has been expended to make Autoconf easy to learn.  The most
3974 obvious way to reach this goal is simply to enforce standard interfaces
3975 and behaviors, avoiding exceptions as much as possible.  Because of
3976 history and inertia, unfortunately, there are still too many exceptions
3977 in Autoconf; nevertheless, this section describes some of the common
3978 rules.
3980 @menu
3981 * Standard Symbols::            Symbols defined by the macros
3982 * Default Includes::            Includes used by the generic macros
3983 @end menu
3985 @node Standard Symbols
3986 @subsection Standard Symbols
3987 @cindex Standard symbols
3989 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3990 their test transform their @var{argument} values to a standard alphabet.
3991 First, @var{argument} is converted to upper case and any asterisks
3992 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3993 that are not alphanumeric are converted to underscores.
3995 For instance,
3997 @example
3998 AC_CHECK_TYPES([struct $Expensive*])
3999 @end example
4001 @noindent
4002 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
4003 succeeds.
4006 @node Default Includes
4007 @subsection Default Includes
4008 @cindex Default includes
4009 @cindex Includes, default
4010 @hdrindex{assert.h}
4011 @hdrindex{ctype.h}
4012 @hdrindex{errno.h}
4013 @hdrindex{float.h}
4014 @hdrindex{iso646.h}
4015 @hdrindex{limits.h}
4016 @hdrindex{locale.h}
4017 @hdrindex{math.h}
4018 @hdrindex{setjmp.h}
4019 @hdrindex{signal.h}
4020 @hdrindex{stdarg.h}
4021 @hdrindex{stddef.h}
4022 @hdrindex{stdio.h}
4023 @hdrindex{stdlib.h}
4024 @hdrindex{string.h}
4025 @hdrindex{time.h}
4026 @hdrindex{wchar.h}
4027 @hdrindex{wctype.h}
4029 Test programs frequently need to include headers that may or may not be
4030 available on the system whose features are being tested.  Each test can
4031 use all the preprocessor macros that have been @code{AC_DEFINE}d by
4032 previous tests, so for example one may write
4034 @example
4035 @group
4036 #include <time.h>
4037 #ifdef HAVE_SYS_TIME_H
4038 # include <sys/time.h>
4039 #endif
4040 @end group
4041 @end example
4043 @noindent
4044 if @file{sys/time.h} has already been tested for.
4046 All hosted environments that are still of interest for portable code
4047 provide all of the headers specified in ISO C90 (as amended in 1995):
4048 @file{assert.h}, @file{ctype.h}, @file{errno.h}, @file{float.h},
4049 @file{iso646.h}, @file{limits.h}, @file{locale.h}, @file{math.h},
4050 @file{setjmp.h}, @file{signal.h}, @file{stdarg.h}, @file{stddef.h},
4051 @file{stdio.h}, @file{stdlib.h}, @file{string.h}, @file{time.h},
4052 @file{wchar.h}, and @file{wctype.h}.  Most programs can safely include
4053 these headers unconditionally.  All other headers, including all headers
4054 from later revisions of the C standard, need to be tested for
4055 (@pxref{Header Files}).
4057 If your program needs to be portable to a @emph{freestanding}
4058 environment, such as an embedded OS that doesn't provide all of the
4059 facilities of the C90 standard library, you may need to test for some of
4060 the above headers as well.  Note that many Autoconf macros internally
4061 assume that the complete set of C90 headers are available.
4063 Most generic macros use the following macro to provide a default set
4064 of includes:
4066 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
4067 @acindex{INCLUDES_DEFAULT}
4068 Expand to @var{include-directives} if present and nonempty, otherwise to:
4070 @example
4071 @group
4072 #include <stddef.h>
4073 #ifdef HAVE_STDIO_H
4074 # include <stdio.h>
4075 #endif
4076 #ifdef HAVE_STDLIB_H
4077 # include <stdlib.h>
4078 #endif
4079 #ifdef HAVE_STRING_H
4080 # include <string.h>
4081 #endif
4082 #ifdef HAVE_INTTYPES_H
4083 # include <inttypes.h>
4084 #endif
4085 #ifdef HAVE_STDINT_H
4086 # include <stdint.h>
4087 #endif
4088 #ifdef HAVE_STRINGS_H
4089 # include <strings.h>
4090 #endif
4091 #ifdef HAVE_SYS_TYPES_H
4092 # include <sys/types.h>
4093 #endif
4094 #ifdef HAVE_SYS_STAT_H
4095 # include <sys/stat.h>
4096 #endif
4097 #ifdef HAVE_UNISTD_H
4098 # include <unistd.h>
4099 #endif
4100 @end group
4101 @end example
4103 Using this macro without @var{include-directives} has the side effect of
4104 checking for @file{stdio.h}, @file{stdlib.h}, @file{string.h},
4105 @file{inttypes.h}, @file{stdint.h}, @file{strings.h},
4106 @file{sys/types.h}, @file{sys/stat.h}, and @file{unistd.h}, as if by
4107 @code{AC_CHECK_HEADERS_ONCE}.  For backward compatibility, the macro
4108 @code{STDC_HEADERS} will be defined when both @file{stdlib.h} and
4109 @file{string.h} are available.
4111 @strong{Portability Note:} It is safe for most programs to assume the
4112 presence of all of the headers required by the original 1990 C standard.
4113 @code{AC_INCLUDES_DEFAULT} checks for @file{stdio.h}, @file{stdlib.h},
4114 and @file{string.h}, even though they are in that list, because they
4115 might not be available when compiling for a ``freestanding environment''
4116 (in which most of the features of the C library are optional).  You
4117 probably do not need to write @samp{#ifdef HAVE_STDIO_H} in your own
4118 code.
4120 @file{inttypes.h} and @file{stdint.h} were added to C in the 1999
4121 revision of the standard, and @file{strings.h}, @file{sys/types.h},
4122 @file{sys/stat.h}, and @file{unistd.h} are POSIX extensions.  You
4123 @emph{should} guard uses of these headers with appropriate conditionals.
4124 @end defmac
4126 @defmac AC_CHECK_INCLUDES_DEFAULT
4127 @acindex{CHECK_INCLUDES_DEFAULT}
4128 Check for all the headers that @code{AC_INCLUDES_DEFAULT} would check
4129 for as a side-effect, if this has not already happened.
4131 This macro mainly exists so that @code{autoupdate} can replace certain
4132 obsolete constructs with it. You should not need to use it yourself; in
4133 fact, it is likely to be safe to delete it from any script in which it
4134 appears.  (@code{autoupdate} does not know whether preprocessor macros
4135 such as @code{HAVE_STDINT_H} are used in the program, nor whether they
4136 would get defined as a side-effect of other checks.)
4137 @end defmac
4139 @node Alternative Programs
4140 @section Alternative Programs
4141 @cindex Programs, checking
4143 These macros check for the presence or behavior of particular programs.
4144 They are used to choose between several alternative programs and to
4145 decide what to do once one has been chosen.  If there is no macro
4146 specifically defined to check for a program you need, and you don't need
4147 to check for any special properties of it, then you can use one of the
4148 general program-check macros.
4150 @menu
4151 * Particular Programs::         Special handling to find certain programs
4152 * Generic Programs::            How to find other programs
4153 @end menu
4155 @node Particular Programs
4156 @subsection Particular Program Checks
4158 These macros check for particular programs---whether they exist, and
4159 in some cases whether they support certain features.
4161 @defmac AC_PROG_AR
4162 @acindex{PROG_AR}
4163 @ovindex AR
4164 @c @caindex prog_AR
4165 @c @caindex prog_ac_ct_AR
4166 Set output variable @code{AR} to @samp{ar} if @code{ar} is found, and
4167 otherwise to @samp{:} (do nothing).
4168 @end defmac
4170 @defmac AC_PROG_AWK
4171 @acindex{PROG_AWK}
4172 @ovindex AWK
4173 @caindex prog_AWK
4174 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
4175 order, and set output variable @code{AWK} to the first one that is found.
4176 It tries @code{gawk} first because that is reported to be the
4177 best implementation.  The result can be overridden by setting the
4178 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
4180 Using this macro is sufficient to avoid the pitfalls of traditional
4181 @command{awk} (@pxref{awk, , Limitations of Usual Tools}).
4182 @end defmac
4184 @defmac AC_PROG_GREP
4185 @acindex{PROG_GREP}
4186 @ovindex GREP
4187 @caindex prog_GREP
4188 Look for the best available @code{grep} or @code{ggrep} that accepts the
4189 longest input lines possible, and that supports multiple @option{-e} options.
4190 Set the output variable @code{GREP} to whatever is chosen.
4191 @xref{grep, , Limitations of Usual Tools}, for more information about
4192 portability problems with the @command{grep} command family.  The result
4193 can be overridden by setting the @code{GREP} variable and is cached in the
4194 @code{ac_cv_path_GREP} variable.
4195 @end defmac
4197 @defmac AC_PROG_EGREP
4198 @acindex{PROG_EGREP}
4199 @ovindex EGREP
4200 @caindex prog_EGREP
4201 Check whether @code{$GREP -E} works, or else look for the best available
4202 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
4203 Set the output variable @code{EGREP} to whatever is chosen.  The result
4204 can be overridden by setting the @code{EGREP} variable and is cached in the
4205 @code{ac_cv_path_EGREP} variable.
4206 @end defmac
4208 @defmac AC_PROG_FGREP
4209 @acindex{PROG_FGREP}
4210 @ovindex FGREP
4211 @caindex prog_FGREP
4212 Check whether @code{$GREP -F} works, or else look for the best available
4213 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
4214 Set the output variable @code{FGREP} to whatever is chosen.  The result
4215 can be overridden by setting the @code{FGREP} variable and is cached in the
4216 @code{ac_cv_path_FGREP} variable.
4217 @end defmac
4219 @defmac AC_PROG_INSTALL
4220 @acindex{PROG_INSTALL}
4221 @ovindex INSTALL
4222 @ovindex INSTALL_PROGRAM
4223 @ovindex INSTALL_DATA
4224 @ovindex INSTALL_SCRIPT
4225 @caindex path_install
4226 @prindex @command{install-sh}
4227 Set output variable @code{INSTALL} to the name of a BSD-compatible
4228 @command{install} program, if one is found in the current @env{PATH}.
4229 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
4230 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
4231 default directories) to determine @var{dir} (@pxref{Output}).  Also set
4232 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
4233 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
4235 @samp{@@INSTALL@@} is special, as its value may vary for different
4236 configuration files.
4238 This macro screens out various instances of @command{install} known not to
4239 work.  It prefers to find a C program rather than a shell script, for
4240 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
4241 but that name is obsolete because some @command{make} programs have a rule
4242 that creates @file{install} from it if there is no makefile.  Further, this
4243 macro requires @command{install} to be able to install multiple files into a
4244 target directory in a single invocation.
4246 Autoconf comes with a copy of @file{install-sh} that you can use.
4247 If you use @code{AC_PROG_INSTALL}, you must include @file{install-sh} in
4248 your distribution; otherwise @command{autoreconf} and @command{configure}
4249 will produce an error message saying they can't find it---even if the
4250 system you're on has a good @command{install} program.  This check is a
4251 safety measure to prevent you from accidentally leaving that file out,
4252 which would prevent your package from installing on systems that don't
4253 have a BSD-compatible @command{install} program.
4255 If you need to use your own installation program because it has features
4256 not found in standard @command{install} programs, there is no reason to use
4257 @code{AC_PROG_INSTALL}; just put the file name of your program into your
4258 @file{Makefile.in} files.
4260 The result of the test can be overridden by setting the variable
4261 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4262 @end defmac
4264 @defmac AC_PROG_MKDIR_P
4265 @acindex{PROG_MKDIR_P}
4266 @ovindex MKDIR_P
4267 @caindex path_mkdir
4268 @prindex @command{install-sh}
4269 Set output variable @code{MKDIR_P} to a program that ensures that for
4270 each argument, a directory named by this argument exists, creating it
4271 and its parent directories if needed, and without race conditions when
4272 two instances of the program attempt to make the same directory at
4273 nearly the same time.
4275 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
4276 falls back on invoking @command{install-sh} with the @option{-d} option,
4277 so your package should
4278 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4279 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4280 is vulnerable to race conditions, so if you want to support parallel
4281 installs from
4282 different packages into the same directory you need to make sure you
4283 have an up-to-date @file{install-sh}.  In particular, be careful about
4284 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4286 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4287 in M4sh}), but it sets an output variable intended for use in other
4288 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4289 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
4290 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4291 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4292 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4293 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4294 Finally, @code{AS_MKDIR_P} does not check for race condition
4295 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4297 @samp{@@MKDIR_P@@} is special, as its value may vary for different
4298 configuration files.
4300 The result of the test can be overridden by setting the variable
4301 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4302 @end defmac
4304 @anchor{AC_PROG_LEX}
4305 @defmac AC_PROG_LEX (@var{options})
4306 @acindex{PROG_LEX}
4307 @ovindex LEX
4308 @ovindex LEXLIB
4309 @cvindex YYTEXT_POINTER
4310 @ovindex LEX_OUTPUT_ROOT
4311 @caindex prog_LEX
4312 Search for a lexical analyzer generator, preferring @code{flex}
4313 to plain @code{lex}.  Output variable @code{LEX} is set to whichever
4314 program is available.  If neither program is available, @code{LEX}
4315 is set to @samp{:};
4316 for packages that ship the generated @file{file.yy.c}
4317 alongside the source @file{file.l}, this default allows users without a
4318 lexer generator to still build the package even if the timestamp for
4319 @file{file.l} is inadvertently changed.
4321 The name of the program to use can be overridden by setting the
4322 output variable @code{LEX} or the cache variable @code{ac_cv_prog_LEX}
4323 when running @command{configure}.
4325 If a lexical analyzer generator is found, this macro performs additional
4326 checks for common portability pitfalls.  If these additional checks
4327 fail, @code{LEX} is reset to @samp{:}; otherwise the following
4328 additional macros and variables are provided.
4330 Preprocessor macro @code{YYTEXT_POINTER} is defined if the lexer
4331 skeleton, by default, declares @code{yytext} as a @samp{@w{char *}}
4332 rather than a @samp{@w{char []}}.
4334 Output variable @code{LEX_OUTPUT_ROOT} is set to the base of the file
4335 name that the lexer generates; this is usually either @file{lex.yy} or
4336 @file{lexyy}.
4338 If generated lexers need a library to work, output variable
4339 @code{LEXLIB} is set to a link option for that library (e.g.,
4340 @option{-ll}), otherwise it is set to empty.
4342 The @var{options} argument modifies the behavior of @code{AC_PROG_LEX}.
4343 It should be a whitespace-separated list of options.  Currently there
4344 are only two options, and they are mutually exclusive:
4346 @table @code
4347 @item yywrap
4348 Indicate that the library in @code{LEXLIB} needs to define the function
4349 @code{yywrap}.  If a library that defines this function cannot be found,
4350 @code{LEX} will be reset to @samp{:}.
4352 @item noyywrap
4353 Indicate that the library in @code{LEXLIB} does not need to define the
4354 function @code{yywrap}.  @command{configure} will not search for it at
4355 all.
4356 @end table
4358 Prior to Autoconf 2.70, @code{AC_PROG_LEX} did not take any arguments,
4359 and its behavior was different from either of the above possibilities:
4360 it would search for a library that defines @code{yywrap}, and would set
4361 @code{LEXLIB} to that library if it finds one.  However, if a library
4362 that defines this function could not be found, @code{LEXLIB} would be
4363 left empty and @code{LEX} would @emph{not} be reset.  This behavior was
4364 due to a bug, but several packages came to depend on it, so
4365 @code{AC_PROG_LEX} still does this if neither the @code{yywrap} nor the
4366 @code{noyywrap} option is given.
4368 Usage of @code{AC_PROG_LEX} without choosing one of the @code{yywrap}
4369 or @code{noyywrap} options is deprecated.  It is usually better to
4370 use @code{noyywrap} and define the @code{yywrap} function yourself,
4371 as this almost always renders the @code{LEXLIB} unnecessary.
4373 @strong{Caution:} As a side-effect of the test, this macro may delete
4374 any file in the configure script's current working directory named
4375 @file{lex.yy.c} or @file{lexyy.c}.
4377 @strong{Caution:} Packages that ship a generated @file{lex.yy.c}
4378 cannot assume that the definition of @code{YYTEXT_POINTER} matches
4379 the code in that file.  They also cannot assume that @code{LEXLIB}
4380 provides the library routines required by the code in that file.
4382 If you use Flex to generate @file{lex.yy.c}, you can work around these
4383 limitations by defining @code{yywrap} and @code{main} yourself
4384 (rendering @code{-lfl} unnecessary), and by using either the
4385 @option{--array} or @option{--pointer} options to control how
4386 @code{yytext} is declared.  The code generated by Flex is also more
4387 portable than the code generated by historical versions of Lex.
4389 If you have used Flex to generate @file{lex.yy.c}, and especially if
4390 your scanner depends on Flex features, we recommend you use this
4391 Autoconf snippet to prevent the scanner being regenerated with
4392 historical Lex:
4394 @example
4395 AC_PROG_LEX
4396 if test "x$LEX" != xflex; then
4397   LEX="$SHELL $missing_dir/missing flex"
4398   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4399   AC_SUBST([LEXLIB], [''])
4401 @end example
4403 The shell script @command{missing} can be found in the Automake
4404 distribution.
4406 Remember that the user may have supplied an alternate location in
4407 @env{LEX}, so if Flex is required, it is better to check that the user
4408 provided something sufficient by parsing the output of @samp{$LEX
4409 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4410 @end defmac
4412 @anchor{AC_PROG_LN_S}
4413 @defmac AC_PROG_LN_S
4414 @acindex{PROG_LN_S}
4415 @ovindex LN_S
4416 If @samp{ln -s} works on the current file system (the operating system
4417 and file system support symbolic links), set the output variable
4418 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4419 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -pR}.
4421 If you make a link in a directory other than the current directory, its
4422 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4423 create links using @samp{$(LN_S)}, either find out which form is used
4424 and adjust the arguments, or always invoke @code{ln} in the directory
4425 where the link is to be created.
4427 In other words, it does not work to do:
4428 @example
4429 $(LN_S) foo /x/bar
4430 @end example
4432 Instead, do:
4434 @example
4435 (cd /x && $(LN_S) foo bar)
4436 @end example
4437 @end defmac
4439 @defmac AC_PROG_RANLIB
4440 @acindex{PROG_RANLIB}
4441 @ovindex RANLIB
4442 @c @caindex prog_RANLIB
4443 @c @caindex prog_ac_ct_RANLIB
4444 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4445 is found, and otherwise to @samp{:} (do nothing).
4446 @end defmac
4448 @defmac AC_PROG_SED
4449 @acindex{PROG_SED}
4450 @ovindex SED
4451 @caindex path_SED
4452 Set output variable @code{SED} to a Sed implementation that conforms to
4453 Posix and does not have arbitrary length limits.  Report an error if no
4454 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4455 information about portability problems with Sed.
4457 The result of this test can be overridden by setting the @code{SED} variable
4458 and is cached in the @code{ac_cv_path_SED} variable.
4459 @end defmac
4461 @defmac AC_PROG_YACC
4462 @acindex{PROG_YACC}
4463 @evindex YACC
4464 @evindex YFLAGS
4465 @ovindex YACC
4466 @caindex prog_YACC
4467 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4468 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4469 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4470 The result of this test can be influenced by setting the variable
4471 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4472 @end defmac
4474 @node Generic Programs
4475 @subsection Generic Program and File Checks
4477 These macros are used to find programs not covered by the ``particular''
4478 test macros.  If you need to check the behavior of a program as well as
4479 find out whether it is present, you have to write your own test for it
4480 (@pxref{Writing Tests}).  By default, these macros use the environment
4481 variable @env{PATH}.  If you need to check for a program that might not
4482 be in the user's @env{PATH}, you can pass a modified path to use
4483 instead, like this:
4485 @example
4486 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4487              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4488 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4489 @end example
4491 You are strongly encouraged to declare the @var{variable} passed to
4492 @code{AC_CHECK_PROG} etc.@: as precious.  @xref{Setting Output Variables},
4493 @code{AC_ARG_VAR}, for more details.
4495 @anchor{AC_CHECK_PROG}
4496 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4497   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4498   @ovar{reject})
4499 @acindex{CHECK_PROG}
4500 @caindex prog_@var{variable}
4501 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4502 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4503 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4504 absolute file name) even if it is the first found in the search path; in
4505 that case, set @var{variable} using the absolute file name of the
4506 @var{prog-to-check-for} found that is not @var{reject}.  If
4507 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4508 @var{variable}.  The result of this test can be overridden by setting the
4509 @var{variable} variable or the cache variable
4510 @code{ac_cv_prog_@var{variable}}.
4511 @end defmac
4513 @anchor{AC_CHECK_PROGS}
4514 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4515   @ovar{value-if-not-found}, @dvar{path, $PATH})
4516 @acindex{CHECK_PROGS}
4517 @caindex prog_@var{variable}
4518 Check for each program in the blank-separated list
4519 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4520 @var{variable} to the name of that program.  Otherwise, continue
4521 checking the next program in the list.  If none of the programs in the
4522 list are found, set @var{variable} to @var{value-if-not-found}; if
4523 @var{value-if-not-found} is not specified, the value of @var{variable}
4524 is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4525 this test can be overridden by setting the @var{variable} variable or the
4526 cache variable @code{ac_cv_prog_@var{variable}}.
4527 @end defmac
4529 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4530   @ovar{value-if-not-found}, @dvar{path, $PATH})
4531 @acindex{CHECK_TARGET_TOOL}
4532 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4533 with a prefix of the target type as determined by
4534 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4535 If the tool cannot be found with a prefix, and if the build and target
4536 types are equal, then it is also searched for without a prefix.
4538 As noted in @ref{Specifying Target Triplets}, the
4539 target is rarely specified, because most of the time it is the same
4540 as the host: it is the type of system for which any compiler tool in
4541 the package produces code.  What this macro looks for is,
4542 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4543 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4544 uses to produce objects, archives or executables}.
4545 @end defmac
4547 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4548   @ovar{value-if-not-found}, @dvar{path, $PATH})
4549 @acindex{CHECK_TOOL}
4550 @c @caindex prog_@var{VARIABLE}
4551 @c @caindex prog_ac_ct_@var{VARIABLE}
4552 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4553 with a prefix of the host type as specified by @option{--host}, followed by a
4554 dash.  For example, if the user runs
4555 @samp{configure --build=x86_64-gnu --host=aarch64-linux-gnu}, then this call:
4556 @example
4557 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4558 @end example
4559 @noindent
4560 sets @code{RANLIB} to @file{aarch64-linux-gnu-ranlib} if that program exists in
4561 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4562 @var{path}, or to @samp{:} if neither program exists.
4564 When cross-compiling, this macro will issue a warning if no program
4565 prefixed with the host type could be found.
4566 For more information, see @ref{Specifying Target Triplets}.
4567 @end defmac
4569 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4570   @ovar{value-if-not-found}, @dvar{path, $PATH})
4571 @acindex{CHECK_TARGET_TOOLS}
4572 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4573 @var{progs-to-check-for} are checked with a prefix of the target type as
4574 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4575 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4576 prefix, and if the build and target types are equal, then the first one
4577 without a prefix is used.  If a tool is found, set @var{variable} to
4578 the name of that program.  If none of the tools in the list are found,
4579 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4580 is not specified, the value of @var{variable} is not changed.  Calls
4581 @code{AC_SUBST} for @var{variable}.
4582 @end defmac
4584 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4585   @ovar{value-if-not-found}, @dvar{path, $PATH})
4586 @acindex{CHECK_TOOLS}
4587 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4588 @var{progs-to-check-for} are checked with a prefix of the host type as
4589 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4590 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4591 prefix, then the first one without a prefix is used.  If a tool is found,
4592 set @var{variable} to the name of that program.  If none of the tools in
4593 the list are found, set @var{variable} to @var{value-if-not-found}; if
4594 @var{value-if-not-found} is not specified, the value of @var{variable}
4595 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4597 When cross-compiling, this macro will issue a warning if no program
4598 prefixed with the host type could be found.
4599 For more information, see @ref{Specifying Target Triplets}.
4600 @end defmac
4602 @anchor{AC_PATH_PROG}
4603 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4604   @ovar{value-if-not-found}, @dvar{path, $PATH})
4605 @acindex{PATH_PROG}
4606 @caindex path_@var{variable}
4607 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4608 name of @var{prog-to-check-for} if found.  The result of this test
4609 can be overridden by setting the @var{variable} variable.  A positive
4610 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4611 variable.
4612 @end defmac
4614 @anchor{AC_PATH_PROGS}
4615 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4616   @ovar{value-if-not-found}, @dvar{path, $PATH})
4617 @acindex{PATH_PROGS}
4618 @caindex path_@var{variable}
4619 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4620 are found, set @var{variable} to the absolute name of the program
4621 found.  The result of this test can be overridden by setting the
4622 @var{variable} variable.  A positive result of this test is cached in
4623 the @code{ac_cv_path_@var{variable}} variable.
4624 @end defmac
4626 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4627   @var{progs-to-check-for}, @var{feature-test}, @
4628   @ovar{action-if-not-found}, @dvar{path, $PATH})
4629 @acindex{PATH_PROGS_FEATURE_CHECK}
4630 @caindex path_@var{variable}
4631 @vrindex ac_path_@var{variable}
4632 @vrindex ac_path_@var{variable}_found
4633 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4634 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4635 its value.  Otherwise, check for each program in the blank-separated
4636 list @var{progs-to-check-for} existing in @var{path}.  For each program
4637 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4638 set to the absolute name of the candidate program.  If no invocation of
4639 @var{feature-test} sets the shell variable
4640 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4641 executed.  @var{feature-test} will be run even when
4642 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4643 choose a better candidate found later in @var{path}; to accept the
4644 current setting and bypass all further checks, @var{feature-test} can
4645 execute @code{ac_path_@var{variable}_found=:}.
4647 Note that this macro has some subtle differences from
4648 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4649 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4650 particular, @var{variable} is not set to the final value of
4651 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4652 run.  Also, on failure, any action can be performed, whereas
4653 @code{AC_CHECK_PROGS} only performs
4654 @code{@var{variable}=@var{value-if-not-found}}.
4656 Here is an example, similar to what Autoconf uses in its own configure
4657 script.  It will search for an implementation of @command{m4} that
4658 supports the @code{indir} builtin, even if it goes by the name
4659 @command{gm4} or is not the first implementation on @env{PATH}.
4661 @example
4662 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4663   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4664     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4665       test "x$m4out" = x0 \
4666       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4667     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4668 AC_SUBST([M4], [$ac_cv_path_M4])
4669 @end example
4670 @end defmac
4672 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4673   @ovar{value-if-not-found}, @dvar{path, $PATH})
4674 @acindex{PATH_TARGET_TOOL}
4675 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4676 name of the program if it is found.
4677 @end defmac
4679 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4680   @ovar{value-if-not-found}, @dvar{path, $PATH})
4681 @acindex{PATH_TOOL}
4682 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4683 name of the program if it is found.
4685 When cross-compiling, this macro will issue a warning if no program
4686 prefixed with the host type could be found.
4687 For more information, see @ref{Specifying Target Triplets}.
4688 @end defmac
4691 @node Files
4692 @section Files
4693 @cindex File, checking
4695 You might also need to check for the existence of files.  Before using
4696 these macros, ask yourself whether a runtime test might not be a better
4697 solution.  Be aware that, like most Autoconf macros, they test a feature
4698 of the host machine, and therefore, they die when cross-compiling.
4700 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4701   @ovar{action-if-not-found})
4702 @acindex{CHECK_FILE}
4703 @caindex file_@var{file}
4704 Check whether file @var{file} exists on the native system.  If it is
4705 found, execute @var{action-if-found}, otherwise do
4706 @var{action-if-not-found}, if given.  Cache the result of this test
4707 in the @code{ac_cv_file_@var{file}} variable, with characters not
4708 suitable for a variable name mapped to underscores.
4709 @end defmac
4711 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4712   @ovar{action-if-not-found})
4713 @acindex{CHECK_FILES}
4714 @caindex file_@var{file}
4715 For each file listed in @var{files}, execute @code{AC_CHECK_FILE}
4716 and perform either @var{action-if-found} or @var{action-if-not-found}.
4717 Like @code{AC_CHECK_FILE}, this defines @samp{HAVE_@var{file}}
4718 (@pxref{Standard Symbols}) for each file found and caches the results of
4719 each test in the @code{ac_cv_file_@var{file}} variable, with characters
4720 not suitable for a variable name mapped to underscores.
4721 @end defmac
4724 @node Libraries
4725 @section Library Files
4726 @cindex Library, checking
4728 The following macros check for the presence of certain C, C++, Fortran,
4729 or Go library archive files.
4731 @anchor{AC_CHECK_LIB}
4732 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4733   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4734 @acindex{CHECK_LIB}
4735 @caindex lib_@var{library}_@var{function}
4736 Test whether the library @var{library} is available by trying to link
4737 a test program that calls function @var{function} with the library.
4738 @var{function} should be a function provided by the library.
4739 Use the base
4740 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4741 the @var{library} argument.
4743 @var{action-if-found} is a list of shell commands to run if the link
4744 with the library succeeds; @var{action-if-not-found} is a list of shell
4745 commands to run if the link fails.  If @var{action-if-found} is not
4746 specified, the default action prepends @option{-l@var{library}} to
4747 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4748 capitals).  This macro is intended to support building @code{LIBS} in
4749 a right-to-left (least-dependent to most-dependent) fashion such that
4750 library dependencies are satisfied as a natural side effect of
4751 consecutive tests.  Linkers are sensitive to library ordering
4752 so the order in which @code{LIBS} is generated is important to reliable
4753 detection of libraries.
4755 If linking with @var{library} results in unresolved symbols that would
4756 be resolved by linking with additional libraries, give those libraries
4757 as the @var{other-libraries} argument, separated by spaces:
4758 e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4759 that @var{library} is present, because linking the test program can
4760 fail with unresolved symbols.  The @var{other-libraries} argument
4761 should be limited to cases where it is desirable to test for one library
4762 in the presence of another that is not already in @code{LIBS}.
4764 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4765 in some common cases.  Many standard functions like @code{gethostbyname}
4766 appear in the standard C library on some hosts, and in special libraries
4767 like @code{nsl} on other hosts.  On some hosts the special libraries
4768 contain variant implementations that you may not want to use.  These
4769 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4770 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4772 The result of this test is cached in the
4773 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4774 @end defmac
4776 @anchor{AC_SEARCH_LIBS}
4777 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4778   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4779 @acindex{SEARCH_LIBS}
4780 @caindex search_@var{function}
4781 Search for a library defining @var{function} if it's not already
4782 available.  This equates to calling
4783 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4784 no libraries, then for each library listed in @var{search-libs}.
4786 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4787 to contain @var{function}, and run @var{action-if-found}.  If the
4788 function is not found, run @var{action-if-not-found}.
4790 If linking with @var{library} results in unresolved symbols that would
4791 be resolved by linking with additional libraries, give those libraries
4792 as the @var{other-libraries} argument, separated by spaces:
4793 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4794 that @var{function} is present, because linking the test program
4795 always fails with unresolved symbols.
4797 The result of this test is cached in the
4798 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4799 @var{function} is already available, as @samp{no} if no library
4800 containing @var{function} was found, otherwise as the
4801 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4802 @end defmac
4806 @node Library Functions
4807 @section Library Functions
4809 The following macros check for particular C library functions.
4810 If there is no macro specifically defined to check for a function you need,
4811 and you don't need to check for any special properties of
4812 it, then you can use one of the general function-check macros.
4814 @menu
4815 * Function Portability::        Pitfalls with usual functions
4816 * Particular Functions::        Special handling to find certain functions
4817 * Generic Functions::           How to find other functions
4818 @end menu
4820 @node Function Portability
4821 @subsection Portability of C Functions
4822 @cindex Portability of C functions
4823 @cindex C function portability
4825 Most usual functions can either be missing, or be buggy, or be limited
4826 on some architectures.  This section tries to make an inventory of these
4827 portability issues.  By definition, this list always requires
4828 additions.  A much more complete list is maintained by the Gnulib
4829 project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4830 Current Posix Functions, gnulib, Gnulib}, @ref{Legacy Function
4831 Substitutes, , Legacy Functions, gnulib, Gnulib}, and @ref{Glibc
4832 Function Substitutes, , Glibc Functions, gnulib, Gnulib}.  Please
4833 help us keep the Gnulib list as complete as possible.
4835 @table @asis
4836 @item @code{exit}
4837 @c @fuindex exit
4838 @prindex @code{exit}
4839 On ancient hosts, @code{exit} returned @code{int}.
4840 This is because @code{exit} predates @code{void}, and there was a long
4841 tradition of it returning @code{int}.
4843 On current hosts, the problem more likely is that @code{exit} is not
4844 declared, due to C++ problems of some sort or another.  For this reason
4845 we suggest that test programs not invoke @code{exit}, but return from
4846 @code{main} instead.
4848 @item @code{free}
4849 @c @fuindex free
4850 @prindex @code{free}
4851 The C standard says a call @code{free (NULL)} does nothing, but
4852 some old systems don't support this (e.g., NextStep).
4854 @item @code{isinf}
4855 @itemx @code{isnan}
4856 @c @fuindex isinf
4857 @c @fuindex isnan
4858 @prindex @code{isinf}
4859 @prindex @code{isnan}
4860 In C99 and later, @code{isinf} and @code{isnan} are
4861 macros.  On some systems just macros are available
4862 (e.g., HP-UX and Solaris 10), on
4863 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4864 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4865 these functions are declared in nonstandard headers like
4866 @code{<sunmath.h>} and defined in non-default libraries like
4867 @option{-lm} or @option{-lsunmath}.
4869 In C99 and later, @code{isinf} and @code{isnan} macros work correctly with
4870 @code{long double} arguments, but pre-C99 systems that use functions
4871 typically assume @code{double} arguments.  On such a system,
4872 @code{isinf} incorrectly returns true for a finite @code{long double}
4873 argument that is outside the range of @code{double}.
4875 The best workaround for these issues is to use Gnulib modules
4876 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4877 solution involves code like the following.
4879 @smallexample
4880 #include <math.h>
4882 #ifndef isnan
4883 # define isnan(x) \
4884     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4885      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4886      : isnan_f (x))
4887 static int isnan_f  (float       x) @{ return x != x; @}
4888 static int isnan_d  (double      x) @{ return x != x; @}
4889 static int isnan_ld (long double x) @{ return x != x; @}
4890 #endif
4892 #ifndef isinf
4893 # define isinf(x) \
4894     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4895      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4896      : isinf_f (x))
4897 static int isinf_f  (float       x)
4898 @{ return !isnan (x) && isnan (x - x); @}
4899 static int isinf_d  (double      x)
4900 @{ return !isnan (x) && isnan (x - x); @}
4901 static int isinf_ld (long double x)
4902 @{ return !isnan (x) && isnan (x - x); @}
4903 #endif
4904 @end smallexample
4906 Some optimizing compilers mishandle these definitions, but systems with that bug
4907 typically have many other floating point corner-case compliance problems
4908 anyway, so it's probably not worth worrying about.
4910 @item @code{malloc}
4911 @c @fuindex malloc
4912 @prindex @code{malloc}
4913 The C standard says a call @code{malloc (0)} is implementation
4914 dependent.  It can return either @code{NULL} or a new non-null pointer.
4915 The latter is more common (e.g., the GNU C Library) but is by
4916 no means universal.  @code{AC_FUNC_MALLOC}
4917 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4919 @item @code{putenv}
4920 @c @fuindex putenv
4921 @prindex @code{putenv}
4922 Posix prefers @code{setenv} to @code{putenv}; among other things,
4923 @code{putenv} is not required of all Posix implementations, but
4924 @code{setenv} is.
4926 Posix specifies that @code{putenv} puts the given string directly in
4927 @code{environ}, but some systems make a copy of it instead (e.g.,
4928 glibc 2.0, or BSD).  And when a copy is made, @code{unsetenv} might
4929 not free it, causing a memory leak (e.g., FreeBSD 4).
4931 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4932 environment, but this is not standard usage and it dumps core
4933 on some systems (e.g., AIX).
4935 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4936 environment, rather than inserting it with an empty value.
4938 @item @code{realloc}
4939 @c @fuindex realloc
4940 @prindex @code{realloc}
4941 The C standard says a call @code{realloc (NULL, size)} is equivalent
4942 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4943 NextStep).
4945 @item @code{signal} handler
4946 @c @fuindex signal
4947 @prindex @code{signal}
4948 @prindex @code{sigaction}
4949 Normally @code{signal} takes a handler function with a return type of
4950 @code{void}, but some old systems required @code{int} instead.  Any
4951 actual @code{int} value returned is not used; this is only a
4952 difference in the function prototype demanded.
4954 All systems we know of in current use return @code{void}.  The
4955 @code{int} was to support K&R C, where of course @code{void} is not
4956 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4957 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4958 all cases.
4960 In most cases, it is more robust to use @code{sigaction} when it is
4961 available, rather than @code{signal}.
4963 @item @code{snprintf}
4964 @c @fuindex snprintf
4965 @prindex @code{snprintf}
4966 @c @fuindex vsnprintf
4967 @prindex @code{vsnprintf}
4968 In C99 and later, if the output array isn't big enough
4969 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4970 truncate the output and return the number of bytes that ought to have
4971 been produced.  Some older systems return the truncated length (e.g.,
4972 GNU C Library 2.0.x or IRIX 6.5), some a negative value
4973 (e.g., earlier GNU C Library versions), and some the buffer
4974 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4975 older systems ignore the length and overrun the buffer (e.g., 64-bit
4976 Solaris 7).
4978 @item @code{sprintf}
4979 @c @fuindex sprintf
4980 @prindex @code{sprintf}
4981 @c @fuindex vsprintf
4982 @prindex @code{vsprintf}
4983 The C standard says @code{sprintf} and @code{vsprintf} return the
4984 number of bytes written.  On some ancient systems (SunOS 4 for
4985 instance) they return the buffer pointer instead, but these no
4986 longer need to be worried about.
4988 @item @code{sscanf}
4989 @c @fuindex sscanf
4990 @prindex @code{sscanf}
4991 On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4992 that its
4993 input string be writable (though it doesn't actually change it).  This
4994 can be a problem when using @command{gcc} since it normally puts
4995 constant strings in read-only memory (@pxref{Incompatibilities,
4996 Incompatibilities of GCC, , gcc, Using and
4997 Porting the GNU Compiler Collection}).  Apparently in some cases even
4998 having format strings read-only can be a problem.
5000 @item @code{strerror_r}
5001 @c @fuindex strerror_r
5002 @prindex @code{strerror_r}
5003 Posix specifies that @code{strerror_r} returns an @code{int}, but many
5004 systems (e.g., GNU C Library version 2.2.4) provide a
5005 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
5006 can detect which is in use (@pxref{Particular Functions}).
5008 @item @code{strnlen}
5009 @c @fuindex strnlen
5010 @prindex @code{strnlen}
5011 AIX 4.3 provides a broken version which produces the
5012 following results:
5014 @example
5015 strnlen ("foobar", 0) = 0
5016 strnlen ("foobar", 1) = 3
5017 strnlen ("foobar", 2) = 2
5018 strnlen ("foobar", 3) = 1
5019 strnlen ("foobar", 4) = 0
5020 strnlen ("foobar", 5) = 6
5021 strnlen ("foobar", 6) = 6
5022 strnlen ("foobar", 7) = 6
5023 strnlen ("foobar", 8) = 6
5024 strnlen ("foobar", 9) = 6
5025 @end example
5027 @item @code{sysconf}
5028 @c @fuindex sysconf
5029 @prindex @code{sysconf}
5030 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
5031 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
5032 @code{#ifdef}.
5034 @item @code{unlink}
5035 @c @fuindex unlink
5036 @prindex @code{unlink}
5037 The Posix spec says that @code{unlink} causes the given file to be
5038 removed only after there are no more open file handles for it.  Some
5039 non-Posix hosts have trouble with this requirement, though,
5040 and some DOS variants even corrupt the file system.
5042 @item @code{unsetenv}
5043 @c @fuindex unsetenv
5044 @prindex @code{unsetenv}
5045 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
5046 can be removed with a call @code{putenv ("FOO=")}, as described under
5047 @code{putenv} above.
5049 @item @code{va_copy}
5050 @c @fuindex va_copy
5051 @prindex @code{va_copy}
5052 C99 and later provide @code{va_copy} for copying
5053 @code{va_list} variables.  It may be available in older environments
5054 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
5055 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
5056 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
5057 portability.
5059 @item @code{va_list}
5060 @c @fuindex va_list
5061 @prindex @code{va_list}
5062 @code{va_list} is not necessarily just a pointer.  It can be a
5063 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
5064 not portable.  Or it can be an array (e.g., @command{gcc} in some
5065 PowerPC configurations), which means as a function parameter it can be
5066 effectively call-by-reference and library routines might modify the
5067 value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
5068 2.1).
5070 @item Signed @code{>>}
5071 Normally the C @code{>>} right shift of a signed type replicates the
5072 high bit, giving a so-called ``arithmetic'' shift.  But care should be
5073 taken since Standard C doesn't require that behavior.  On those
5074 few processors without a native arithmetic shift (for instance Cray
5075 vector systems) zero bits may be shifted in, the same as a shift of an
5076 unsigned type.
5078 @item Integer @code{/}
5079 C divides signed integers by truncating their quotient toward zero,
5080 yielding the same result as Fortran.  However, before C99 the standard
5081 allowed C implementations to take the floor or ceiling of the quotient
5082 in some cases.  Hardly any implementations took advantage of this
5083 freedom, though, and it's probably not worth worrying about this issue
5084 nowadays.
5085 @end table
5088 @node Particular Functions
5089 @subsection Particular Function Checks
5090 @cindex Function, checking
5092 These macros check for particular C functions---whether they exist, and
5093 in some cases how they respond when given certain arguments.
5095 @anchor{AC_FUNC_ALLOCA}
5096 @defmac AC_FUNC_ALLOCA
5097 @acindex{FUNC_ALLOCA}
5098 @cvindex C_ALLOCA
5099 @cvindex HAVE_ALLOCA_H
5100 @ovindex ALLOCA
5101 @c @fuindex alloca
5102 @prindex @code{alloca}
5103 @hdrindex{alloca.h}
5104 @c @caindex working_alloca_h
5105 Check for the @code{alloca} function.  Define @code{HAVE_ALLOCA_H} if
5106 @file{alloca.h} defines a working @code{alloca}.  If not, look for a
5107 builtin alternative.  If either method succeeds, define
5108 @code{HAVE_ALLOCA}.  Otherwise, set the output variable @code{ALLOCA} to
5109 @samp{$@{LIBOBJDIR@}alloca.o} and define
5110 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
5111 garbage collect).  This variable is separate from @code{LIBOBJS} so
5112 multiple programs can share the value of @code{ALLOCA} without needing
5113 to create an actual library, in case only some of them use the code in
5114 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
5115 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
5117 Source files that use @code{alloca} should start with a piece of code
5118 like the following, to declare it properly.
5120 @example
5121 @group
5122 #include <stdlib.h>
5123 #include <stddef.h>
5124 #ifdef HAVE_ALLOCA_H
5125 # include <alloca.h>
5126 #elif !defined alloca
5127 # ifdef __GNUC__
5128 #  define alloca __builtin_alloca
5129 # elif defined _MSC_VER
5130 #  include <malloc.h>
5131 #  define alloca _alloca
5132 # elif !defined HAVE_ALLOCA
5133 #  ifdef  __cplusplus
5134 extern "C"
5135 #  endif
5136 void *alloca (size_t);
5137 # endif
5138 #endif
5139 @end group
5140 @end example
5142 If you don't want to maintain this piece of code in your package manually,
5143 you can instead use the Gnulib module @code{alloca-opt} or @code{alloca}.
5144 @xref{Gnulib}.
5145 @end defmac
5147 @defmac AC_FUNC_CHOWN
5148 @acindex{FUNC_CHOWN}
5149 @cvindex HAVE_CHOWN
5150 @c @fuindex chown
5151 @prindex @code{chown}
5152 @caindex func_chown_works
5153 If the @code{chown} function is available and works (in particular, it
5154 should accept @option{-1} for @code{uid} and @code{gid}), define
5155 @code{HAVE_CHOWN}.  The result of this macro is cached in the
5156 @code{ac_cv_func_chown_works} variable.
5158 If you want a workaround, that is, a @code{chown} function that is
5159 available and works, you can use the Gnulib module @code{chown}.
5160 @xref{Gnulib}.
5161 @end defmac
5163 @anchor{AC_FUNC_CLOSEDIR_VOID}
5164 @defmac AC_FUNC_CLOSEDIR_VOID
5165 @acindex{FUNC_CLOSEDIR_VOID}
5166 @cvindex CLOSEDIR_VOID
5167 @c @fuindex closedir
5168 @prindex @code{closedir}
5169 @caindex func_closedir_void
5170 If the @code{closedir} function does not return a meaningful value,
5171 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
5172 return value for an error indicator.
5174 Currently this test is implemented by running a test program.  When
5175 cross compiling the pessimistic assumption that @code{closedir} does not
5176 return a meaningful value is made.
5178 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
5179 variable.
5181 This macro is obsolescent, as @code{closedir} returns a meaningful value
5182 on current systems.  New programs need not use this macro.
5183 @end defmac
5185 @defmac AC_FUNC_ERROR_AT_LINE
5186 @acindex{FUNC_ERROR_AT_LINE}
5187 @c @fuindex error_at_line
5188 @prindex @code{error_at_line}
5189 @caindex lib_error_at_line
5190 If the @code{error_at_line} function is not found, require an
5191 @code{AC_LIBOBJ} replacement of @samp{error}.
5193 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
5194 variable.
5196 The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent.  New programs
5197 should use Gnulib's @code{error} module.  @xref{Gnulib}.
5198 @end defmac
5200 @defmac AC_FUNC_FNMATCH
5201 @acindex{FUNC_FNMATCH}
5202 @c @fuindex fnmatch
5203 @prindex @code{fnmatch}
5204 @caindex func_fnmatch_works
5205 If the @code{fnmatch} function conforms to Posix, define
5206 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
5207 the bugs in Solaris 2.4.
5209 Unlike the other specific
5210 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
5211 broken/missing @code{fnmatch}.  This is for historical reasons.
5212 See @code{AC_REPLACE_FNMATCH} below.
5214 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
5215 variable.
5217 This macro is obsolescent.  New programs should use Gnulib's
5218 @code{fnmatch-posix} module.  @xref{Gnulib}.
5219 @end defmac
5221 @defmac AC_FUNC_FNMATCH_GNU
5222 @acindex{FUNC_FNMATCH_GNU}
5223 @c @fuindex fnmatch
5224 @prindex @code{fnmatch}
5225 @caindex func_fnmatch_gnu
5226 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
5227 whether @code{fnmatch} supports GNU extensions.  Detect common
5228 implementation bugs, for example, the bugs in the GNU C
5229 Library 2.1.
5231 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
5232 variable.
5234 This macro is obsolescent.  New programs should use Gnulib's
5235 @code{fnmatch-gnu} module.  @xref{Gnulib}.
5236 @end defmac
5238 @anchor{AC_FUNC_FORK}
5239 @defmac AC_FUNC_FORK
5240 @acindex{FUNC_FORK}
5241 @cvindex HAVE_VFORK_H
5242 @cvindex HAVE_WORKING_FORK
5243 @cvindex HAVE_WORKING_VFORK
5244 @cvindex vfork
5245 @c @fuindex fork
5246 @prindex @code{fork}
5247 @c @fuindex vfork
5248 @prindex @code{vfork}
5249 @hdrindex{vfork.h}
5250 @c @caindex func_fork
5251 @c @caindex func_fork_works
5252 This macro checks for the @code{fork} and @code{vfork} functions.  If a
5253 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
5254 checks whether @code{fork} is just a stub by trying to run it.
5256 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
5257 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
5258 define @code{vfork} to be @code{fork} for backward compatibility with
5259 previous versions of @command{autoconf}.  This macro checks for several known
5260 errors in implementations of @code{vfork} and considers the system to not
5261 have a working @code{vfork} if it detects any of them.
5263 Since this macro defines @code{vfork} only for backward compatibility with
5264 previous versions of @command{autoconf} you're encouraged to define it
5265 yourself in new code:
5266 @example
5267 @group
5268 #ifndef HAVE_WORKING_VFORK
5269 # define vfork fork
5270 #endif
5271 @end group
5272 @end example
5274 The results of this macro are cached in the @code{ac_cv_func_fork_works}
5275 and @code{ac_cv_func_vfork_works} variables.  In order to override the
5276 test, you also need to set the @code{ac_cv_func_fork} and
5277 @code{ac_cv_func_vfork} variables.
5278 @end defmac
5280 @defmac AC_FUNC_FSEEKO
5281 @acindex{FUNC_FSEEKO}
5282 @cvindex _LARGEFILE_SOURCE
5283 @cvindex HAVE_FSEEKO
5284 @c @fuindex fseeko
5285 @prindex @code{fseeko}
5286 @c @fuindex ftello
5287 @prindex @code{ftello}
5288 @c @caindex sys_largefile_source
5289 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
5290 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
5291 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
5292 may occur when compiling with @code{AC_SYS_LARGEFILE} on
5293 largefile-sensitive systems where @code{off_t} does not default to a
5294 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
5296 The Gnulib module @code{fseeko} invokes @code{AC_FUNC_FSEEKO}
5297 and also contains workarounds for other portability problems of
5298 @code{fseeko}.  @xref{Gnulib}.
5299 @end defmac
5301 @defmac AC_FUNC_GETGROUPS
5302 @acindex{FUNC_GETGROUPS}
5303 @cvindex HAVE_GETGROUPS
5304 @ovindex GETGROUPS_LIBS
5305 @c @fuindex getgroups
5306 @prindex @code{getgroups}
5307 @caindex func_getgroups_works
5308 If the @code{getgroups} function is available and works (unlike on
5309 Ultrix 4.3 and NeXTstep 3.2, where @samp{getgroups (0, 0)} always fails),
5310 define @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
5311 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
5313 This macro is obsolescent. New programs need not use this macro.  But
5314 they may want to use the Gnulib module @code{getgroups}, which provides
5315 workarounds to other portability problems of this function.
5316 @end defmac
5318 @anchor{AC_FUNC_GETLOADAVG}
5319 @defmac AC_FUNC_GETLOADAVG
5320 @acindex{FUNC_GETLOADAVG}
5321 @cvindex SVR4
5322 @cvindex DGUX
5323 @cvindex UMAX
5324 @cvindex UMAX4_3
5325 @cvindex HAVE_NLIST_H
5326 @cvindex NLIST_NAME_UNION
5327 @cvindex GETLOADAVG_PRIVILEGED
5328 @cvindex NEED_SETGID
5329 @cvindex C_GETLOADAVG
5330 @ovindex LIBOBJS
5331 @ovindex NEED_SETGID
5332 @ovindex KMEM_GROUP
5333 @ovindex GETLOADAVG_LIBS
5334 @c @fuindex getloadavg
5335 @prindex @code{getloadavg}
5336 Check how to get the system load averages.  To perform its tests
5337 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5338 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5339 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5341 If the system has the @code{getloadavg} function, define
5342 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5343 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
5344 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
5345 @samp{getloadavg} and possibly define several other C preprocessor
5346 macros and output variables:
5348 @enumerate
5349 @item
5350 Define @code{C_GETLOADAVG}.
5352 @item
5353 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5354 those systems.
5356 @item
5357 @hdrindex{nlist.h}
5358 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5360 @item
5361 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5362 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
5363 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5365 @item
5366 Programs may need to be installed set-group-ID (or set-user-ID) for
5367 @code{getloadavg} to work.  In this case, define
5368 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5369 to @samp{true} (and otherwise to @samp{false}), and set
5370 @code{KMEM_GROUP} to the name of the group that should own the installed
5371 program.
5372 @end enumerate
5374 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5375 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5376 @end defmac
5378 @anchor{AC_FUNC_GETMNTENT}
5379 @defmac AC_FUNC_GETMNTENT
5380 @acindex{FUNC_GETMNTENT}
5381 @cvindex HAVE_GETMNTENT
5382 @c @fuindex getmntent
5383 @prindex @code{getmntent}
5384 @caindex search_getmntent
5385 Check for @code{getmntent} in the standard C library, and then in the
5386 @file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5387 IRIX 4, PTX, and UnixWare, respectively.  Then, if
5388 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5389 @code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5390 @code{ac_cv_func_getmntent} to @code{no}.
5392 The result of this macro can be overridden by setting the cache variable
5393 @code{ac_cv_search_getmntent}.
5395 The @code{AC_FUNC_GETMNTENT} macro is obsolescent.  New programs should
5396 use Gnulib's @code{mountlist} module.  @xref{Gnulib}.
5397 @end defmac
5399 @defmac AC_FUNC_GETPGRP
5400 @acindex{FUNC_GETPGRP}
5401 @cvindex GETPGRP_VOID
5402 @c @fuindex getpgid
5403 @c @fuindex getpgrp
5404 @prindex @code{getpgid}
5405 @prindex @code{getpgrp}
5406 @caindex func_getpgrp_void
5407 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5408 @code{getpgrp}; this is the Posix behavior.  On older BSD
5409 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5410 behaves like Posix's @code{getpgid}.
5412 @example
5413 #ifdef GETPGRP_VOID
5414   pid = getpgrp ();
5415 #else
5416   pid = getpgrp (0);
5417 #endif
5418 @end example
5420 This macro does not check whether
5421 @code{getpgrp} exists at all; if you need to work in that situation,
5422 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5424 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5425 variable.
5427 This macro is obsolescent, as current systems have a @code{getpgrp}
5428 whose signature conforms to Posix.  New programs need not use this macro.
5429 @end defmac
5431 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5432 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5433 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5434 @c @fuindex lstat
5435 @prindex @code{lstat}
5436 @caindex func_lstat_dereferences_slashed_symlink
5437 If @file{link} is a symbolic link, then @code{lstat} should treat
5438 @file{link/} the same as @file{link/.}.  However, many older
5439 @code{lstat} implementations incorrectly ignore trailing slashes.
5441 It is safe to assume that if @code{lstat} incorrectly ignores
5442 trailing slashes, then other symbolic-link-aware functions like
5443 @code{unlink} also incorrectly ignore trailing slashes.
5445 If @code{lstat} behaves properly, define
5446 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5447 @code{AC_LIBOBJ} replacement of @code{lstat}.
5449 The result of this macro is cached in the
5450 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5452 The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5453 New programs should use Gnulib's @code{lstat} module.  @xref{Gnulib}.
5454 @end defmac
5456 @defmac AC_FUNC_MALLOC
5457 @acindex{FUNC_MALLOC}
5458 @cvindex HAVE_MALLOC
5459 @cvindex malloc
5460 @c @fuindex malloc
5461 @prindex @code{malloc}
5462 @caindex func_malloc_0_nonnull
5463 If the @code{malloc} function is compatible with the GNU C
5464 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5465 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5466 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5467 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5468 native @code{malloc} is not used in the main project.
5470 Typically, the replacement file @file{malloc.c} should look like (note
5471 the @samp{#undef malloc}):
5473 @verbatim
5474 #include <config.h>
5475 #undef malloc
5477 #include <sys/types.h>
5479 void *malloc ();
5481 /* Allocate an N-byte block of memory from the heap.
5482    If N is zero, allocate a 1-byte block.  */
5484 void *
5485 rpl_malloc (size_t n)
5487   if (n == 0)
5488     n = 1;
5489   return malloc (n);
5491 @end verbatim
5493 The result of this macro is cached in the
5494 @code{ac_cv_func_malloc_0_nonnull} variable.
5496 If you don't want to maintain a @code{malloc.c} file in your package
5497 manually, you can instead use the Gnulib module @code{malloc-gnu}.
5498 @end defmac
5500 @defmac AC_FUNC_MBRTOWC
5501 @acindex{FUNC_MBRTOWC}
5502 @cvindex HAVE_MBRTOWC
5503 @c @fuindex mbrtowc
5504 @prindex @code{mbrtowc}
5505 @caindex func_mbrtowc
5506 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5507 type @code{mbstate_t} are properly declared.
5509 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5510 variable.
5512 The Gnulib module @code{mbrtowc} not only ensures that the
5513 function is declared, but also works around other portability
5514 problems of this function.
5515 @end defmac
5517 @defmac AC_FUNC_MEMCMP
5518 @acindex{FUNC_MEMCMP}
5519 @ovindex LIBOBJS
5520 @c @fuindex memcmp
5521 @prindex @code{memcmp}
5522 @caindex func_memcmp_working
5523 If the @code{memcmp} function is not available, or does not work on
5524 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5525 bytes or more and with at least one buffer not starting on a 4-byte
5526 boundary (such as the one on NeXT x86 OpenStep), require an
5527 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5529 The result of this macro is cached in the
5530 @code{ac_cv_func_memcmp_working} variable.
5532 This macro is obsolescent, as current systems have a working
5533 @code{memcmp}.  New programs need not use this macro.
5534 @end defmac
5536 @defmac AC_FUNC_MKTIME
5537 @acindex{FUNC_MKTIME}
5538 @ovindex LIBOBJS
5539 @c @fuindex mktime
5540 @prindex @code{mktime}
5541 @caindex func_working_mktime
5542 If the @code{mktime} function is not available, or does not work
5543 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5544 For the purposes of this test, @code{mktime} should conform to the
5545 Posix standard and should be the inverse of
5546 @code{localtime}.
5548 The result of this macro is cached in the
5549 @code{ac_cv_func_working_mktime} variable.
5551 The @code{AC_FUNC_MKTIME} macro is obsolescent.  New programs should
5552 use Gnulib's @code{mktime} module.  @xref{Gnulib}.
5553 @end defmac
5555 @anchor{AC_FUNC_MMAP}
5556 @defmac AC_FUNC_MMAP
5557 @acindex{FUNC_MMAP}
5558 @cvindex HAVE_MMAP
5559 @c @fuindex mmap
5560 @prindex @code{mmap}
5561 @caindex func_mmap_fixed_mapped
5562 If the @code{mmap} function exists and works correctly, define
5563 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5564 memory.
5566 The result of this macro is cached in the
5567 @code{ac_cv_func_mmap_fixed_mapped} variable.
5569 Note: This macro asks for more than what an average program needs from
5570 @code{mmap}.  In particular, the use of @code{MAP_FIXED} fails on
5571 HP-UX 11, whereas @code{mmap} otherwise works fine on this platform.
5572 @end defmac
5574 @defmac AC_FUNC_OBSTACK
5575 @acindex{FUNC_OBSTACK}
5576 @cvindex HAVE_OBSTACK
5577 @cindex obstack
5578 @caindex func_obstack
5579 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5580 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5582 The result of this macro is cached in the @code{ac_cv_func_obstack}
5583 variable.
5585 The @code{AC_FUNC_OBSTACK} macro is obsolescent.  New programs should use
5586 Gnulib's @code{obstack} module.  @xref{Gnulib}.
5587 @end defmac
5589 @defmac AC_FUNC_REALLOC
5590 @acindex{FUNC_REALLOC}
5591 @cvindex HAVE_REALLOC
5592 @cvindex realloc
5593 @c @fuindex realloc
5594 @prindex @code{realloc}
5595 @caindex func_realloc_0_nonnull
5596 If the @code{realloc} function is compatible with the GNU C
5597 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5598 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5599 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5600 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5601 the native @code{realloc} is not used in the main project.  See
5602 @code{AC_FUNC_MALLOC} for details.
5604 The result of this macro is cached in the
5605 @code{ac_cv_func_realloc_0_nonnull} variable.
5607 If you don't want to maintain a @code{realloc.c} file in your package
5608 manually, you can instead use the Gnulib module @code{realloc-gnu}.
5609 @end defmac
5611 @defmac AC_FUNC_SELECT_ARGTYPES
5612 @acindex{FUNC_SELECT_ARGTYPES}
5613 @cvindex SELECT_TYPE_ARG1
5614 @cvindex SELECT_TYPE_ARG234
5615 @cvindex SELECT_TYPE_ARG5
5616 @c @fuindex select
5617 @prindex @code{select}
5618 @c @caindex func_select_args
5619 Determines the correct type to be passed for each of the
5620 @code{select} function's arguments, and defines those types
5621 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5622 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5623 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5624 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5626 This macro is obsolescent, as current systems have a @code{select} whose
5627 signature conforms to Posix.  New programs need not use this macro.
5628 @end defmac
5630 @defmac AC_FUNC_SETPGRP
5631 @acindex{FUNC_SETPGRP}
5632 @cvindex SETPGRP_VOID
5633 @c @fuindex setpgrp
5634 @prindex @code{setpgrp}
5635 @caindex func_setpgrp_void
5636 If @code{setpgrp} takes no argument (the Posix version), define
5637 @code{SETPGRP_VOID}.  Otherwise, it is the BSD version, which takes
5638 two process IDs as arguments.  This macro does not check whether
5639 @code{setpgrp} exists at all; if you need to work in that situation,
5640 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.  This macro also
5641 does not check for the Solaris variant of @code{setpgrp}, which returns
5642 a @code{pid_t} instead of an @code{int}; portable code should only use
5643 the return value by comparing it against @code{-1} to check for errors.
5645 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5646 variable.
5648 This macro is obsolescent, as all forms of @code{setpgrp} are also
5649 obsolescent.  New programs should use the Posix function @code{setpgid},
5650 which takes two process IDs as arguments (like the BSD @code{setpgrp}).
5651 @end defmac
5653 @defmac AC_FUNC_STAT
5654 @defmacx AC_FUNC_LSTAT
5655 @acindex{FUNC_STAT}
5656 @acindex{FUNC_LSTAT}
5657 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5658 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5659 @c @fuindex stat
5660 @prindex @code{stat}
5661 @c @fuindex lstat
5662 @prindex @code{lstat}
5663 @caindex func_stat_empty_string_bug
5664 @caindex func_lstat_empty_string_bug
5665 Determine whether @code{stat} or @code{lstat} have the bug that it
5666 succeeds when given the zero-length file name as argument.  The @code{stat}
5667 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5668 this.
5670 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5671 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5672 replacement of it.
5674 The results of these macros are cached in the
5675 @code{ac_cv_func_stat_empty_string_bug} and the
5676 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5678 These macros are obsolescent, as no current systems have the bug.
5679 New programs need not use these macros.
5680 @end defmac
5682 @anchor{AC_FUNC_STRCOLL}
5683 @defmac AC_FUNC_STRCOLL
5684 @acindex{FUNC_STRCOLL}
5685 @cvindex HAVE_STRCOLL
5686 @c @fuindex strcoll
5687 @prindex @code{strcoll}
5688 @caindex func_strcoll_works
5689 If the @code{strcoll} function exists and works correctly, define
5690 @code{HAVE_STRCOLL}.  This does a bit more than
5691 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5692 definitions of @code{strcoll} that should not be used.  But it does
5693 not check against a known bug of this function on Solaris 10.
5695 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5696 variable.
5697 @end defmac
5699 @defmac AC_FUNC_STRERROR_R
5700 @acindex{FUNC_STRERROR_R}
5701 @cvindex HAVE_STRERROR_R
5702 @cvindex HAVE_DECL_STRERROR_R
5703 @cvindex STRERROR_R_CHAR_P
5704 @c @fuindex strerror_r
5705 @caindex func_strerror_r_char_p
5706 @prindex @code{strerror_r}
5707 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5708 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5709 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5710 returns an @code{int} error number.  The Thread-Safe Functions option of
5711 Posix requires @code{strerror_r} to return @code{int}, but
5712 many systems (including, for example, version 2.2.4 of the GNU C
5713 Library) return a @code{char *} value that is not necessarily equal to
5714 the buffer argument.
5716 The result of this macro is cached in the
5717 @code{ac_cv_func_strerror_r_char_p} variable.
5719 The Gnulib module @code{strerror_r} not only ensures that the function
5720 has the return type specified by Posix, but also works around other
5721 portability problems of this function.
5722 @end defmac
5724 @anchor{AC_FUNC_STRFTIME}
5725 @defmac AC_FUNC_STRFTIME
5726 @acindex{FUNC_STRFTIME}
5727 @cvindex HAVE_STRFTIME
5728 @c @fuindex strftime
5729 @prindex @code{strftime}
5730 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5731 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5733 This macro is obsolescent, as no current systems require the @file{intl}
5734 library for @code{strftime}.  New programs need not use this macro.
5735 @end defmac
5737 @defmac AC_FUNC_STRTOD
5738 @acindex{FUNC_STRTOD}
5739 @ovindex POW_LIB
5740 @c @fuindex strtod
5741 @prindex @code{strtod}
5742 @caindex func_strtod
5743 @caindex func_pow
5744 If the @code{strtod} function does not exist or doesn't work correctly,
5745 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5746 because @file{strtod.c} is likely to need @samp{pow}, set the output
5747 variable @code{POW_LIB} to the extra library needed.
5749 This macro caches its result in the @code{ac_cv_func_strtod} variable
5750 and depends upon the result in the @code{ac_cv_func_pow} variable.
5752 The @code{AC_FUNC_STRTOD} macro is obsolescent.  New programs should
5753 use Gnulib's @code{strtod} module.  @xref{Gnulib}.
5754 @end defmac
5756 @defmac AC_FUNC_STRTOLD
5757 @acindex{FUNC_STRTOLD}
5758 @cvindex HAVE_STRTOLD
5759 @prindex @code{strtold}
5760 @caindex func_strtold
5761 If the @code{strtold} function exists and conforms to C99 or later, define
5762 @code{HAVE_STRTOLD}.
5764 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5766 The Gnulib module @code{strtold} not only ensures that the
5767 function exists, but also works around other portability
5768 problems of this function.
5769 @end defmac
5771 @defmac AC_FUNC_STRNLEN
5772 @acindex{FUNC_STRNLEN}
5773 @cvindex HAVE_STRNLEN
5774 @c @fuindex strnlen
5775 @prindex @code{strnlen}
5776 @caindex func_strnlen_working
5777 If the @code{strnlen} function is not available, or is buggy (like the one
5778 from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5780 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5781 variable.
5783 The @code{AC_FUNC_STRNLEN} macro is obsolescent.  New programs should
5784 use Gnulib's @code{strnlen} module.  @xref{Gnulib}.
5785 @end defmac
5787 @anchor{AC_FUNC_UTIME_NULL}
5788 @defmac AC_FUNC_UTIME_NULL
5789 @acindex{FUNC_UTIME_NULL}
5790 @cvindex HAVE_UTIME_NULL
5791 @c @fuindex utime
5792 @prindex @code{utime}
5793 @caindex func_utime_null
5794 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5795 the present, define @code{HAVE_UTIME_NULL}.
5797 This macro caches its result in the @code{ac_cv_func_utime_null}
5798 variable.
5800 This macro is obsolescent, as all current systems have a @code{utime}
5801 that behaves this way.  New programs need not use this macro.
5802 @end defmac
5804 @anchor{AC_FUNC_VPRINTF}
5805 @defmac AC_FUNC_VPRINTF
5806 @acindex{FUNC_VPRINTF}
5807 @cvindex HAVE_VPRINTF
5808 @cvindex HAVE_DOPRNT
5809 @c @fuindex vprintf
5810 @prindex @code{vprintf}
5811 @c @fuindex vsprintf
5812 @prindex @code{vsprintf}
5813 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5814 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5815 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5816 are also available.)
5818 This macro is obsolescent, as all current systems have @code{vprintf}.
5819 New programs need not use this macro.
5820 @end defmac
5822 @defmac AC_REPLACE_FNMATCH
5823 @acindex{REPLACE_FNMATCH}
5824 @c @fuindex fnmatch
5825 @prindex @code{fnmatch}
5826 @hdrindex{fnmatch.h}
5827 @caindex func_fnmatch_works
5828 If the @code{fnmatch} function does not conform to Posix (see
5829 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5831 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5832 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5833 copy of the source code of GNU @code{fnmatch}.  If necessary,
5834 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5835 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5836 included in place of the system @code{<fnmatch.h>}.
5838 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5839 variable.
5841 This macro is obsolescent, as it assumes the use of particular source
5842 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5843 which provides this macro along with the source files.  @xref{Gnulib}.
5844 @end defmac
5848 @node Generic Functions
5849 @subsection Generic Function Checks
5851 These macros are used to find functions not covered by the ``particular''
5852 test macros.  If the functions might be in libraries other than the
5853 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5854 If you need to check the behavior of a function as well as find out
5855 whether it is present, you have to write your own test for
5856 it (@pxref{Writing Tests}).
5858 @anchor{AC_CHECK_FUNC}
5859 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5860   @ovar{action-if-not-found})
5861 @acindex{CHECK_FUNC}
5862 @caindex func_@var{function}
5863 If C function @var{function} is available, run shell commands
5864 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5865 want to define a symbol if the function is available, consider using
5866 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5867 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5868 standardized than C++.  (@pxref{Language Choice}, for more information
5869 about selecting the language for checks.)
5871 This macro caches its result in the @code{ac_cv_func_@var{function}}
5872 variable.
5873 @end defmac
5875 @anchor{AC_CHECK_FUNCS}
5876 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5877   @ovar{action-if-not-found})
5878 @acindex{CHECK_FUNCS}
5879 @cvindex HAVE_@var{function}
5880 For each @var{function} enumerated in the blank-or-newline-separated argument
5881 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5882 If @var{action-if-found} is given, it is additional shell code to
5883 execute when one of the functions is found.  You can give it a value of
5884 @samp{break} to break out of the loop on the first match.  If
5885 @var{action-if-not-found} is given, it is executed when one of the
5886 functions is not found.
5888 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5889 @end defmac
5891 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5892 @acindex{CHECK_FUNCS_ONCE}
5893 @cvindex HAVE_@var{function}
5894 For each @var{function} enumerated in the blank-or-newline-separated argument
5895 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5896 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5897 checking code at most once, so that @command{configure} is smaller and
5898 faster; but the checks cannot be conditionalized and are always done once,
5899 early during the @command{configure} run.
5900 @end defmac
5902 @sp 1
5904 Autoconf follows a philosophy that was formed over the years by those
5905 who have struggled for portability: isolate the portability issues in
5906 specific files, and then program as if you were in a Posix
5907 environment.  Some functions may be missing or unfixable, and your
5908 package must be ready to replace them.
5910 Suitable replacements for many such problem functions are available from
5911 Gnulib (@pxref{Gnulib}).
5913 @defmac AC_LIBOBJ (@var{function})
5914 @acindex{LIBOBJ}
5915 @ovindex LIBOBJS
5916 Specify that @samp{@var{function}.c} must be included in the executables
5917 to replace a missing or broken implementation of @var{function}.
5919 @vrindex ac_objext
5920 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5921 variable @code{LIBOBJS} if it is not already in, and calls
5922 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5923 directly change @code{LIBOBJS}, since this is not traceable.
5924 @end defmac
5926 @defmac AC_LIBSOURCE (@var{file})
5927 @acindex{LIBSOURCE}
5928 Specify that @var{file} might be needed to compile the project.  If you
5929 need to know what files might be needed by a @file{configure.ac}, you
5930 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5932 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5933 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5934 that case, since shell variables cannot be traced statically, you must
5935 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5936 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5937 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5938 @code{"foo"} or @code{"bar"}, you should do:
5940 @example
5941 AC_LIBSOURCE([foo.c])
5942 AC_LIBSOURCE([bar.c])
5943 AC_LIBOBJ([$foo_or_bar])
5944 @end example
5946 @noindent
5947 There is usually a way to avoid this, however, and you are encouraged to
5948 simply call @code{AC_LIBOBJ} with literal arguments.
5950 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5951 slightly different semantics: the old macro took the function name,
5952 e.g., @code{foo}, as its argument rather than the file name.
5953 @end defmac
5955 @defmac AC_LIBSOURCES (@var{files})
5956 @acindex{LIBSOURCES}
5957 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5958 comma-separated M4 list.  Thus, the above example might be rewritten:
5960 @example
5961 AC_LIBSOURCES([foo.c, bar.c])
5962 AC_LIBOBJ([$foo_or_bar])
5963 @end example
5964 @end defmac
5966 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5967 @acindex{CONFIG_LIBOBJ_DIR}
5968 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5969 @var{directory}, a name relative to the top level of the
5970 source tree.  The replacement directory defaults to @file{.}, the top
5971 level directory, and the most typical value is @file{lib}, corresponding
5972 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5974 @command{configure} might need to know the replacement directory for the
5975 following reasons: (i) some checks use the replacement files, (ii) some
5976 macros bypass broken system headers by installing links to the
5977 replacement headers (iii) when used in conjunction with Automake,
5978 within each makefile, @var{directory} is used as a relative path
5979 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5980 @code{LTLIBOBJS}, etc.
5981 @end defmac
5983 @sp 1
5985 It is common to merely check for the existence of a function, and ask
5986 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5987 a convenient shorthand.
5989 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5990 @acindex{REPLACE_FUNCS}
5991 @cvindex HAVE_@var{function}
5992 @ovindex LIBOBJS
5993 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5994 @var{action-if-not-found}.  You can declare your replacement function by
5995 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5996 system has the function, it probably declares it in a header file you
5997 should be including, so you shouldn't redeclare it lest your declaration
5998 conflict.
5999 @end defmac
6001 @node Header Files
6002 @section Header Files
6003 @cindex Header, checking
6005 The following macros check for the presence of certain C header files.
6006 If there is no macro specifically defined to check for a header file you need,
6007 and you don't need to check for any special properties of
6008 it, then you can use one of the general header-file check macros.
6010 @menu
6011 * Header Portability::          Collected knowledge on common headers
6012 * Particular Headers::          Special handling to find certain headers
6013 * Generic Headers::             How to find other headers
6014 @end menu
6016 @node Header Portability
6017 @subsection Portability of Headers
6018 @cindex Portability of headers
6019 @cindex Header portability
6021 This section documents some collected knowledge about common headers,
6022 and the problems they cause.  By definition, this list always requires
6023 additions.  A much more complete list is maintained by the Gnulib
6024 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
6025 Posix Headers, gnulib, Gnulib} and @ref{Glibc Header File
6026 Substitutes, , Glibc Headers, gnulib, Gnulib}.  Please help us keep
6027 the Gnulib list as complete as possible.
6029 When we say that a header ``may require'' some set of other headers, we
6030 mean that it may be necessary for you to manually include those other
6031 headers first, or the contents of the header under test will fail to
6032 compile.  When checking for these headers, you must provide the
6033 potentially-required headers in the @var{includes} argument to
6034 @code{AC_CHECK_HEADER} or @code{AC_CHECK_HEADERS}, or the check will
6035 fail spuriously.  @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes})
6036 arranges to include a number of common requirements and should normally
6037 come first in your @var{includes}.  For example, @file{net/if.h} may
6038 require @file{sys/types.h}, @file{sys/socket.h}, or both, and
6039 @code{AC_INCLUDES_DEFAULT} handles @file{sys/types.h} but not
6040 @file{sys/socket.h}, so you should check for it like this:
6042 @example
6043 AC_CHECK_HEADERS([sys/socket.h])
6044 AC_CHECK_HEADERS([net/if.h], [], [],
6045 [AC_INCLUDES_DEFAULT[
6046 #ifdef HAVE_SYS_SOCKET_H
6047 # include <sys/socket.h>
6048 #endif
6050 @end example
6052 Note that the example mixes single quoting (for@code{AC_INCLUDES_DEFAULT},
6053 so that it gets expanded) and double quoting (to ensure that each
6054 preprocessor @code{#} gets treated as a literal string rather than a
6055 comment).
6057 @table @asis
6059 @item @file{limits.h}
6060 In C99 and later, @file{limits.h} defines @code{LLONG_MIN},
6061 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
6062 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
6063 define them.
6065 @item @file{memory.h}
6066 @hdrindex{memory.h}
6067 This header file is obsolete; use @file{string.h} instead.
6069 @item @file{strings.h}
6070 @hdrindex{strings.h}
6071 On some systems, this is the only header that declares
6072 @code{strcasecmp}, @code{strncasecmp}, and @code{ffs}.
6074 This header may or may not include @file{string.h} for you.  However, on
6075 all recent systems it is safe to include both @file{string.h} and
6076 @file{strings.h}, in either order, in the same source file.
6078 @item @file{inttypes.h} vs.@: @file{stdint.h}
6079 @hdrindex{inttypes.h}
6080 @hdrindex{stdint.h}
6081 C99 specifies that @file{inttypes.h} includes @file{stdint.h}, so there's
6082 no need to include @file{stdint.h} separately in a standard environment.
6083 However, some implementations have @file{inttypes.h} but not @file{stdint.h}
6084 (e.g., Solaris 7), and some have @file{stdint.h} but not @file{inttypes.h}
6085 (e.g. MSVC 2012).  Therefore, it is necessary to check for each and include
6086 each only if available.
6088 @item @file{linux/irda.h}
6089 @hdrindex{linux/irda.h}
6090 This header may require @file{linux/types.h} and/or @file{sys/socket.h}.
6092 @item @file{linux/random.h}
6093 @hdrindex{linux/random.h}
6094 This header may require @file{linux/types.h}.
6096 @item @file{net/if.h}
6097 @hdrindex{net/if.h}
6098 This header may require @file{sys/types.h} and/or @file{sys/socket.h}.
6100 @item @file{netinet/if_ether.h}
6101 @hdrindex{netinet/if_ether.h}
6102 This header may require some combination of @file{sys/types.h},
6103 @file{sys/socket.h}, @file{netinet/in.h}, and @file{net/if.h}.
6105 @item @file{sys/mount.h}
6106 @hdrindex{sys/mount.h}
6107 This header may require @file{sys/params.h}.
6109 @item @file{sys/ptem.h}
6110 @hdrindex{sys/ptem.h}
6111 This header may require @file{sys/stream.h}.
6113 @item @file{sys/socket.h}
6114 @hdrindex{sys/socket.h}
6115 This header may require @file{sys/types.h}.
6117 @item @file{sys/ucred.h}
6118 @hdrindex{sys/ucred.h}
6119 This header may require @file{sys/types.h}.
6121 @item @file{X11/extensions/scrnsaver.h}
6122 @hdrindex{X11/extensions/scrnsaver.h}
6123 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
6124 so required that you might not even consider looking for it.
6126 @end table
6129 @node Particular Headers
6130 @subsection Particular Header Checks
6132 These macros check for particular system header files---whether they
6133 exist, and in some cases whether they declare certain symbols.
6135 @defmac AC_CHECK_HEADER_STDBOOL
6136 @acindex{CHECK_HEADER_STDBOOL}
6137 @cvindex HAVE__BOOL
6138 @hdrindex{stdbool.h}
6139 @caindex header_stdbool_h
6140 Check whether @file{stdbool.h} exists and conforms to C99 or later,
6141 and cache the result in the @code{ac_cv_header_stdbool_h} variable.
6142 If the type @code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
6144 This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
6145 packages that supply a substitute @file{stdbool.h} on platforms lacking
6146 a conforming one.  The @code{AC_HEADER_STDBOOL} macro is better for code
6147 that explicitly checks for @file{stdbool.h}.
6148 @end defmac
6150 @defmac AC_HEADER_ASSERT
6151 @acindex{HEADER_ASSERT}
6152 @cvindex NDEBUG
6153 @hdrindex{assert.h}
6154 Check whether to enable assertions in the style of @file{assert.h}.
6155 Assertions are enabled by default, but the user can override this by
6156 invoking @command{configure} with the @option{--disable-assert} option.
6157 @end defmac
6159 @anchor{AC_HEADER_DIRENT}
6160 @defmac AC_HEADER_DIRENT
6161 @acindex{HEADER_DIRENT}
6162 @cvindex HAVE_DIRENT_H
6163 @cvindex HAVE_NDIR_H
6164 @cvindex HAVE_SYS_DIR_H
6165 @cvindex HAVE_SYS_NDIR_H
6166 @hdrindex{dirent.h}
6167 @hdrindex{sys/ndir.h}
6168 @hdrindex{sys/dir.h}
6169 @hdrindex{ndir.h}
6170 Check for the following header files.  For the first one that is
6171 found and defines @samp{DIR}, define the listed C preprocessor macro:
6173 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
6174 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
6175 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
6176 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
6177 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
6178 @end multitable
6180 The directory-library declarations in your source code should look
6181 something like the following:
6183 @example
6184 @group
6185 #include <sys/types.h>
6186 #ifdef HAVE_DIRENT_H
6187 # include <dirent.h>
6188 # define NAMLEN(dirent) strlen ((dirent)->d_name)
6189 #else
6190 # define dirent direct
6191 # define NAMLEN(dirent) ((dirent)->d_namlen)
6192 # ifdef HAVE_SYS_NDIR_H
6193 #  include <sys/ndir.h>
6194 # endif
6195 # ifdef HAVE_SYS_DIR_H
6196 #  include <sys/dir.h>
6197 # endif
6198 # ifdef HAVE_NDIR_H
6199 #  include <ndir.h>
6200 # endif
6201 #endif
6202 @end group
6203 @end example
6205 Using the above declarations, the program would declare variables to be
6206 of type @code{struct dirent}, not @code{struct direct}, and would access
6207 the length of a directory entry name by passing a pointer to a
6208 @code{struct dirent} to the @code{NAMLEN} macro.
6210 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
6212 This macro is obsolescent, as all current systems with directory
6213 libraries have @code{<dirent.h>}.  New programs need not use this macro.
6215 Also see @code{AC_STRUCT_DIRENT_D_INO} and
6216 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
6217 @end defmac
6219 @anchor{AC_HEADER_MAJOR}
6220 @defmac AC_HEADER_MAJOR
6221 @acindex{HEADER_MAJOR}
6222 @cvindex MAJOR_IN_MKDEV
6223 @cvindex MAJOR_IN_SYSMACROS
6224 @hdrindex{sys/mkdev.h}
6225 @hdrindex{sys/sysmacros.h}
6226 Detect the headers required to use @code{makedev}, @code{major}, and
6227 @code{minor}.  These functions may be defined by @file{sys/mkdev.h},
6228 @code{sys/sysmacros.h}, or @file{sys/types.h}.
6230 @code{AC_HEADER_MAJOR} defines @code{MAJOR_IN_MKDEV} if they are in
6231 @file{sys/mkdev.h}, or @code{MAJOR_IN_SYSMACROS} if they are in
6232 @file{sys/sysmacros.h}.  If neither macro is defined, they are either in
6233 @file{sys/types.h} or unavailable.
6235 To properly use these functions, your code should contain something
6236 like:
6238 @verbatim
6239 #include <sys/types.h>
6240 #ifdef MAJOR_IN_MKDEV
6241 # include <sys/mkdev.h>
6242 #elif defined MAJOR_IN_SYSMACROS
6243 # include <sys/sysmacros.h>
6244 #endif
6245 @end verbatim
6247 Note: Configure scripts built with Autoconf 2.69 or earlier will not
6248 detect a problem if @file{sys/types.h} contains definitions of
6249 @code{major}, @code{minor}, and/or @code{makedev} that trigger compiler
6250 warnings upon use.  This is known to occur with GNU libc 2.25, where
6251 those definitions are being deprecated to reduce namespace pollution.
6252 If it is not practical to use Autoconf 2.70 to regenerate the configure
6253 script of affected software, you can work around the problem by setting
6254 @samp{ac_cv_header_sys_types_h_makedev=no}, as an argument to
6255 @command{configure} or as part of a @file{config.site} site default file
6256 (@pxref{Site Defaults}).
6257 @end defmac
6259 @defmac AC_HEADER_RESOLV
6260 @acindex{HEADER_RESOLV}
6261 @cvindex HAVE_RESOLV_H
6262 @hdrindex{resolv.h}
6263 Checks for header @file{resolv.h}, checking for prerequisites first.
6264 To properly use @file{resolv.h}, your code should contain something like
6265 the following:
6267 @verbatim
6268 #ifdef HAVE_SYS_TYPES_H
6269 #  include <sys/types.h>
6270 #endif
6271 #ifdef HAVE_NETINET_IN_H
6272 #  include <netinet/in.h>   /* inet_ functions / structs */
6273 #endif
6274 #ifdef HAVE_ARPA_NAMESER_H
6275 #  include <arpa/nameser.h> /* DNS HEADER struct */
6276 #endif
6277 #ifdef HAVE_NETDB_H
6278 #  include <netdb.h>
6279 #endif
6280 #include <resolv.h>
6281 @end verbatim
6282 @end defmac
6284 @anchor{AC_HEADER_STAT}
6285 @defmac AC_HEADER_STAT
6286 @acindex{HEADER_STAT}
6287 @cvindex STAT_MACROS_BROKEN
6288 @hdrindex{sys/stat.h}
6289 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
6290 @file{sys/stat.h} do not work properly (returning false positives),
6291 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
6292 Amdahl UTS and Motorola System V/88.
6294 This macro is obsolescent, as no current systems have the bug.
6295 New programs need not use this macro.
6296 @end defmac
6298 @defmac AC_HEADER_STDBOOL
6299 @acindex{HEADER_STDBOOL}
6300 @cvindex HAVE_STDBOOL_H
6301 @cvindex HAVE__BOOL
6302 @hdrindex{stdbool.h}
6303 @caindex header_stdbool_h
6304 If @file{stdbool.h} exists and conforms to C99 or later, define
6305 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
6306 @code{HAVE__BOOL} to 1.  To fulfill the standard's requirements, your
6307 program could contain the following code:
6309 @example
6310 @group
6311 #ifdef HAVE_STDBOOL_H
6312 # include <stdbool.h>
6313 #else
6314 # ifndef HAVE__BOOL
6315 #  ifdef __cplusplus
6316 typedef bool _Bool;
6317 #  else
6318 #   define _Bool signed char
6319 #  endif
6320 # endif
6321 # define bool _Bool
6322 # define false 0
6323 # define true 1
6324 # define __bool_true_false_are_defined 1
6325 #endif
6326 @end group
6327 @end example
6329 Alternatively you can use the @samp{stdbool} package of Gnulib
6330 (@pxref{Gnulib}).  It simplifies your code so that it can say just
6331 @code{#include <stdbool.h>}, and it adds support for less-common
6332 platforms.
6334 This macro caches its result in the @code{ac_cv_header_stdbool_h}
6335 variable.
6337 This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
6338 defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
6339 does not.
6340 @end defmac
6342 @anchor{AC_HEADER_STDC}
6343 @defmac AC_HEADER_STDC
6344 @acindex{HEADER_STDC}
6345 @cvindex STDC_HEADERS
6346 @caindex header_stdc
6348 This macro is obsolescent.  Its sole effect is to make sure that all the
6349 headers that are included by @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6350 Includes}), but not part of ISO C90, have been checked for.
6352 All hosted environments that are still of interest for portable code
6353 provide all of the headers specified in ISO C90 (as amended in 1995).
6354 @end defmac
6356 @defmac AC_HEADER_SYS_WAIT
6357 @acindex{HEADER_SYS_WAIT}
6358 @cvindex HAVE_SYS_WAIT_H
6359 @hdrindex{sys/wait.h}
6360 @caindex header_sys_wait_h
6361 If @file{sys/wait.h} exists and is compatible with Posix, define
6362 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
6363 does not exist, or if it uses the old BSD @code{union wait} instead
6364 of @code{int} to store a status value.  If @file{sys/wait.h} is not
6365 Posix compatible, then instead of including it, define the
6366 Posix macros with their usual interpretations.  Here is an
6367 example:
6369 @example
6370 @group
6371 #include <sys/types.h>
6372 #ifdef HAVE_SYS_WAIT_H
6373 # include <sys/wait.h>
6374 #endif
6375 #ifndef WEXITSTATUS
6376 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6377 #endif
6378 #ifndef WIFEXITED
6379 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6380 #endif
6381 @end group
6382 @end example
6384 @noindent
6385 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6386 variable.
6388 This macro is obsolescent, as current systems are compatible with Posix.
6389 New programs need not use this macro.
6390 @end defmac
6392 @cvindex _POSIX_VERSION
6393 @hdrindex{unistd.h}
6394 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6395 Posix systems.  If there is no @file{unistd.h}, it is definitely
6396 not a Posix system.  However, some non-Posix systems do
6397 have @file{unistd.h}.
6399 The way to check whether the system supports Posix is:
6401 @example
6402 @group
6403 #ifdef HAVE_UNISTD_H
6404 # include <sys/types.h>
6405 # include <unistd.h>
6406 #endif
6408 #ifdef _POSIX_VERSION
6409 /* Code for Posix systems.  */
6410 #endif
6411 @end group
6412 @end example
6414 @defmac AC_HEADER_TIOCGWINSZ
6415 @acindex{HEADER_TIOCGWINSZ}
6416 @cvindex GWINSZ_IN_SYS_IOCTL
6417 @hdrindex{sys/ioctl.h}
6418 @hdrindex{termios.h}
6419 @c FIXME: I need clarifications from Jim.
6420 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6421 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6422 found in @file{<termios.h>}.
6424 Use:
6426 @example
6427 @group
6428 #ifdef HAVE_TERMIOS_H
6429 # include <termios.h>
6430 #endif
6432 #ifdef GWINSZ_IN_SYS_IOCTL
6433 # include <sys/ioctl.h>
6434 #endif
6435 @end group
6436 @end example
6437 @end defmac
6439 @node Generic Headers
6440 @subsection Generic Header Checks
6442 These macros are used to find system header files not covered by the
6443 ``particular'' test macros.  If you need to check the contents of a header
6444 as well as find out whether it is present, you have to write your own
6445 test for it (@pxref{Writing Tests}).
6447 @anchor{AC_CHECK_HEADER}
6448 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6449   @ovar{action-if-not-found}, @ovar{includes})
6450 @acindex{CHECK_HEADER}
6451 @caindex header_@var{header-file}
6452 If the system header file @var{header-file} is compilable, execute shell
6453 commands @var{action-if-found}, otherwise execute
6454 @var{action-if-not-found}.  If you just want to define a symbol if the
6455 header file is available, consider using @code{AC_CHECK_HEADERS}
6456 instead.
6458 @var{includes} should be the appropriate @dfn{prerequisite} code, i.e.@:
6459 whatever might be required to appear above
6460 @samp{#include <@var{header-file}>} for it to compile without error.
6461 This can be anything, but will normally be additional @samp{#include}
6462 directives. If @var{includes} is omitted or empty, @file{configure} will
6463 use the contents of the macro @code{AC_INCLUDES_DEFAULT}.
6464 @xref{Default Includes}.
6466 This macro used to check only for the @emph{presence} of a header, not
6467 whether its contents were acceptable to the compiler.  Some older
6468 @command{configure} scripts rely on this behavior, so it is still
6469 available by specifying @samp{-} as @var{includes}.  This mechanism is
6470 deprecated as of Autoconf 2.70; situations where a preprocessor-only
6471 check is required should use @code{AC_PREPROC_IFELSE}.
6472 @xref{Running the Preprocessor}.
6474 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6475 variable, with characters not suitable for a variable name mapped to
6476 underscores.
6477 @end defmac
6479 @anchor{AC_CHECK_HEADERS}
6480 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6481   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6482   @ovar{includes})
6483 @acindex{CHECK_HEADERS}
6484 @cvindex HAVE_@var{header}
6485 @caindex header_@var{header-file}
6486 For each given system header file @var{header-file} in the
6487 blank-separated argument list that exists, define
6488 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6489 is given, it is additional shell code to execute when one of the header
6490 files is found.  You can give it a value of @samp{break} to break out of
6491 the loop on the first match.  If @var{action-if-not-found} is given, it
6492 is executed when one of the header files is not found.
6494 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6495 choose the set of preprocessor directives supplied before the header
6496 under test.
6498 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6499 variable, with characters not suitable for a variable name mapped to
6500 underscores.
6501 @end defmac
6503 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6504 @acindex{CHECK_HEADERS_ONCE}
6505 @cvindex HAVE_@var{header}
6506 For each given system header file @var{header-file} in the
6507 blank-separated argument list that exists, define
6508 @code{HAVE_@var{header-file}} (in all capitals).
6510 If you do not need the full power of @code{AC_CHECK_HEADERS}, this
6511 variant generates smaller, faster @command{configure} files.  All
6512 headers passed to @code{AC_CHECK_HEADERS_ONCE} are checked for in one
6513 pass, early during the @command{configure} run.  The checks cannot be
6514 conditionalized, you cannot specify an @var{action-if-found} or
6515 @var{action-if-not-found}, and @code{AC_INCLUDES_DEFAULT} is always used
6516 for the prerequisites.
6517 @end defmac
6519 In previous versions of Autoconf, these macros merely checked whether
6520 the header was accepted by the preprocessor.  This was changed because
6521 the old test was inappropriate for typical uses.  Headers are typically
6522 used to compile, not merely to preprocess, and the old behavior
6523 sometimes accepted headers that clashed at compile-time
6524 (@pxref{Present But Cannot Be Compiled}).  If for some reason it is
6525 inappropriate to check whether a header is compilable, you should use
6526 @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}) instead of
6527 these macros.
6529 Requiring each header to compile improves the robustness of the test,
6530 but it also requires you to make sure that the @var{includes} are
6531 correct.  Most system headers nowadays make sure to @code{#include}
6532 whatever they require, or else have their dependencies satisfied by
6533 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), but
6534 @pxref{Header Portability}, for known exceptions.  In general, if you
6535 are looking for @file{bar.h}, which requires that @file{foo.h} be
6536 included first if it exists, you should do something like this:
6538 @example
6539 AC_CHECK_HEADERS([foo.h])
6540 AC_CHECK_HEADERS([bar.h], [], [],
6541 [#ifdef HAVE_FOO_H
6542 # include <foo.h>
6543 #endif
6545 @end example
6547 @node Declarations
6548 @section Declarations
6549 @cindex Declaration, checking
6551 The following macros check for the declaration of variables and
6552 functions.  If there is no macro specifically defined to check for a
6553 symbol you need, then you can use the general macros (@pxref{Generic
6554 Declarations}) or, for more complex tests, you may use
6555 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6557 @menu
6558 * Particular Declarations::     Macros to check for certain declarations
6559 * Generic Declarations::        How to find other declarations
6560 @end menu
6562 @node Particular Declarations
6563 @subsection Particular Declaration Checks
6565 There are no specific macros for declarations.
6567 @node Generic Declarations
6568 @subsection Generic Declaration Checks
6570 These macros are used to find declarations not covered by the ``particular''
6571 test macros.
6573 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6574   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6575 @acindex{CHECK_DECL}
6576 @caindex have_decl_@var{symbol}
6577 If @var{symbol} (a function, variable, or constant) is not declared in
6578 @var{includes} and a declaration is needed, run the shell commands
6579 @var{action-if-not-found}, otherwise @var{action-if-found}.
6580 @var{includes} is a series of include directives, defaulting to
6581 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6582 prior to the declaration under test.
6584 This macro actually tests whether @var{symbol} is defined as a macro or
6585 can be used as an r-value, not whether it is really declared, because it
6586 is much safer to avoid introducing extra declarations when they are not
6587 needed.  In order to facilitate use of C++ and overloaded function
6588 declarations, it is possible to specify function argument types in
6589 parentheses for types which can be zero-initialized:
6591 @example
6592 AC_CHECK_DECL([basename(char *)])
6593 @end example
6595 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6596 variable, with characters not suitable for a variable name mapped to
6597 underscores.
6598 @end defmac
6600 @anchor{AC_CHECK_DECLS}
6601 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6602   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6603 @acindex{CHECK_DECLS}
6604 @cvindex HAVE_DECL_@var{symbol}
6605 @caindex have_decl_@var{symbol}
6606 For each of the @var{symbols} (@emph{comma}-separated list with optional
6607 function argument types for C++ overloads), define
6608 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6609 @var{symbol} is declared, otherwise to @samp{0}.  If
6610 @var{action-if-not-found} is given, it is additional shell code to
6611 execute when one of the function declarations is needed, otherwise
6612 @var{action-if-found} is executed.
6614 @var{includes} is a series of include directives, defaulting to
6615 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6616 prior to the declarations under test.
6618 This macro uses an M4 list as first argument:
6619 @example
6620 AC_CHECK_DECLS([strdup])
6621 AC_CHECK_DECLS([strlen])
6622 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6623 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6624 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6625 @end example
6627 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6628 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6629 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6630 @emph{sure} that the check was performed, use
6631 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6633 @example
6634 #if !HAVE_DECL_SYMBOL
6635 extern char *symbol;
6636 #endif
6637 @end example
6639 @noindent
6640 If the test may have not been performed, however, because it is safer
6641 @emph{not} to declare a symbol than to use a declaration that conflicts
6642 with the system's one, you should use:
6644 @example
6645 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6646 void *malloc (size_t *s);
6647 #endif
6648 @end example
6650 @noindent
6651 You fall into the second category only in extreme situations: either
6652 your files may be used without being configured, or they are used during
6653 the configuration.  In most cases the traditional approach is enough.
6655 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6656 variables, with characters not suitable for a variable name mapped to
6657 underscores.
6658 @end defmac
6660 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6661 @acindex{CHECK_DECLS_ONCE}
6662 @cvindex HAVE_DECL_@var{symbol}
6663 For each of the @var{symbols} (@emph{comma}-separated list), define
6664 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6665 @var{symbol} is declared in the default include files, otherwise to
6666 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6667 generates the checking code at most once, so that @command{configure} is
6668 smaller and faster; but the checks cannot be conditionalized and are
6669 always done once, early during the @command{configure} run.
6670 @end defmac
6673 @node Structures
6674 @section Structures
6675 @cindex Structure, checking
6677 The following macros check for the presence of certain members in C
6678 structures.  If there is no macro specifically defined to check for a
6679 member you need, then you can use the general structure-member macros
6680 (@pxref{Generic Structures}) or, for more complex tests, you may use
6681 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6683 @menu
6684 * Particular Structures::       Macros to check for certain structure members
6685 * Generic Structures::          How to find other structure members
6686 @end menu
6688 @node Particular Structures
6689 @subsection Particular Structure Checks
6691 The following macros check for certain structures or structure members.
6693 @defmac AC_STRUCT_DIRENT_D_INO
6694 @acindex{STRUCT_DIRENT_D_INO}
6695 @cvindex HAVE_STRUCT_DIRENT_D_INO
6696 @c @caindex header_dirent_dirent_h
6697 @c @caindex member_struct_dirent_d_ino
6698 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6699 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6700 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6702 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6703 @code{d_ino}, not whether its contents are always reliable.
6704 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6705 though current systems hide this detail from the user and never return
6706 zero @code{d_ino} values.
6707 Many current systems report an incorrect @code{d_ino} for a directory
6708 entry that is a mount point.
6709 @end defmac
6711 @defmac AC_STRUCT_DIRENT_D_TYPE
6712 @acindex{STRUCT_DIRENT_D_TYPE}
6713 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6714 @c @caindex header_dirent_dirent_h
6715 @c @caindex member_struct_dirent_d_type
6716 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6717 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6718 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6719 @end defmac
6721 @anchor{AC_STRUCT_ST_BLOCKS}
6722 @defmac AC_STRUCT_ST_BLOCKS
6723 @acindex{STRUCT_ST_BLOCKS}
6724 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6725 @cvindex HAVE_ST_BLOCKS
6726 @ovindex LIBOBJS
6727 @caindex member_struct_stat_st_blocks
6728 If @code{struct stat} contains an @code{st_blocks} member, define
6729 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6730 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6731 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6732 future.
6734 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6735 variable.
6736 @end defmac
6738 @defmac AC_STRUCT_TM
6739 @acindex{STRUCT_TM}
6740 @cvindex TM_IN_SYS_TIME
6741 @hdrindex{time.h}
6742 @hdrindex{sys/time.h}
6743 If @file{time.h} does not define @code{struct tm}, define
6744 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6745 had better define @code{struct tm}.
6747 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6748 current systems.  New programs need not use this macro.
6749 @end defmac
6751 @anchor{AC_STRUCT_TIMEZONE}
6752 @defmac AC_STRUCT_TIMEZONE
6753 @acindex{STRUCT_TIMEZONE}
6754 @cvindex HAVE_DECL_TZNAME
6755 @cvindex HAVE_STRUCT_TM_TM_ZONE
6756 @cvindex HAVE_TM_ZONE
6757 @cvindex HAVE_TZNAME
6758 @c @caindex member_struct_tm_tm_zone
6759 @c @caindex struct_tm
6760 Figure out how to get the current timezone.  If @code{struct tm} has a
6761 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6762 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6763 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6764 define @code{HAVE_DECL_TZNAME}.
6765 @end defmac
6767 @node Generic Structures
6768 @subsection Generic Structure Checks
6770 These macros are used to find structure members not covered by the
6771 ``particular'' test macros.
6773 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6774   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6775   @dvar{includes, AC_INCLUDES_DEFAULT})
6776 @acindex{CHECK_MEMBER}
6777 @caindex member_@var{aggregate}_@var{member}
6778 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6779 If no @var{includes} are specified, the default includes are used
6780 (@pxref{Default Includes}).
6782 @example
6783 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6784                 [AC_MSG_ERROR([we need 'passwd.pw_gecos'])],
6785                 [[#include <pwd.h>]])
6786 @end example
6788 You can use this macro for submembers:
6790 @example
6791 AC_CHECK_MEMBER(struct top.middle.bot)
6792 @end example
6794 This macro caches its result in the
6795 @code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6796 characters not suitable for a variable name mapped to underscores.
6797 @end defmac
6799 @anchor{AC_CHECK_MEMBERS}
6800 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6801   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6802 @acindex{CHECK_MEMBERS}
6803 @cvindex HAVE_@var{aggregate}_@var{member}
6804 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6805 @var{members} using the previous macro.  When @var{member} belongs to
6806 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6807 capitals, with spaces and dots replaced by underscores).  If
6808 @var{action-if-found} is given, it is executed for each of the found
6809 members.  If @var{action-if-not-found} is given, it is executed for each
6810 of the members that could not be found.
6812 @var{includes} is a series of include directives, defaulting to
6813 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6814 prior to the members under test.
6816 This macro uses M4 lists:
6817 @example
6818 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6819 @end example
6820 @end defmac
6823 @node Types
6824 @section Types
6825 @cindex Types
6826 @cindex C types
6828 The following macros check for C types, either builtin or typedefs.  If
6829 there is no macro specifically defined to check for a type you need, and
6830 you don't need to check for any special properties of it, then you can
6831 use a general type-check macro.
6833 @menu
6834 * Particular Types::            Special handling to find certain types
6835 * Generic Types::               How to find other types
6836 @end menu
6838 @node Particular Types
6839 @subsection Particular Type Checks
6841 @hdrindex{sys/types.h}
6842 @hdrindex{stdlib.h}
6843 @hdrindex{stdint.h}
6844 @hdrindex{inttypes.h}
6845 These macros check for particular C types in @file{sys/types.h},
6846 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6847 exist.
6849 The Gnulib @code{stdint} module is an alternate way to define many of
6850 these symbols; it is useful if you prefer your code to assume a
6851 C99-or-better environment.  @xref{Gnulib}.
6853 @anchor{AC_TYPE_GETGROUPS}
6854 @defmac AC_TYPE_GETGROUPS
6855 @acindex{TYPE_GETGROUPS}
6856 @cvindex GETGROUPS_T
6857 @caindex type_getgroups
6858 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6859 is the base type of the array argument to @code{getgroups}.
6861 This macro caches the base type in the @code{ac_cv_type_getgroups}
6862 variable.
6863 @end defmac
6865 @defmac AC_TYPE_INT8_T
6866 @acindex{TYPE_INT8_T}
6867 @cvindex HAVE_INT8_T
6868 @cvindex int8_t
6869 @caindex c_int8_t
6870 If @file{stdint.h} or @file{inttypes.h} does not define the type
6871 @code{int8_t}, define @code{int8_t} to a signed
6872 integer type that is exactly 8 bits wide and that uses two's complement
6873 representation, if such a type exists.
6874 If you are worried about porting to hosts that lack such a type, you can
6875 use the results of this macro in C89-or-later code as follows:
6877 @example
6878 #if HAVE_STDINT_H
6879 # include <stdint.h>
6880 #endif
6881 #if defined INT8_MAX || defined int8_t
6882  @emph{code using int8_t}
6883 #else
6884  @emph{complicated alternative using >8-bit 'signed char'}
6885 #endif
6886 @end example
6888 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6889 @end defmac
6891 @defmac AC_TYPE_INT16_T
6892 @acindex{TYPE_INT16_T}
6893 @cvindex HAVE_INT16_T
6894 @cvindex int16_t
6895 @caindex c_int16_t
6896 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6897 @end defmac
6899 @defmac AC_TYPE_INT32_T
6900 @acindex{TYPE_INT32_T}
6901 @cvindex HAVE_INT32_T
6902 @cvindex int32_t
6903 @caindex c_int32_t
6904 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6905 @end defmac
6907 @defmac AC_TYPE_INT64_T
6908 @acindex{TYPE_INT64_T}
6909 @cvindex HAVE_INT64_T
6910 @cvindex int64_t
6911 @caindex c_int64_t
6912 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6913 @end defmac
6915 @defmac AC_TYPE_INTMAX_T
6916 @acindex{TYPE_INTMAX_T}
6917 @cvindex HAVE_INTMAX_T
6918 @cvindex intmax_t
6919 @c @caindex type_intmax_t
6920 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6921 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6922 widest signed integer type.
6923 @end defmac
6925 @defmac AC_TYPE_INTPTR_T
6926 @acindex{TYPE_INTPTR_T}
6927 @cvindex HAVE_INTPTR_T
6928 @cvindex intptr_t
6929 @c @caindex type_intptr_t
6930 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6931 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6932 signed integer type wide enough to hold a pointer, if such a type
6933 exists.
6934 @end defmac
6936 @defmac AC_TYPE_LONG_DOUBLE
6937 @acindex{TYPE_LONG_DOUBLE}
6938 @cvindex HAVE_LONG_DOUBLE
6939 @caindex type_long_double
6940 If the C compiler supports a working @code{long double} type, define
6941 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6942 same range and precision as @code{double}.
6944 This macro caches its result in the @code{ac_cv_type_long_double}
6945 variable.
6947 This macro is obsolescent, as current C compilers support @code{long
6948 double}.  New programs need not use this macro.
6949 @end defmac
6951 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6952 @acindex{TYPE_LONG_DOUBLE_WIDER}
6953 @cvindex HAVE_LONG_DOUBLE_WIDER
6954 @caindex type_long_double_wider
6955 If the C compiler supports a working @code{long double} type with more
6956 range or precision than the @code{double} type, define
6957 @code{HAVE_LONG_DOUBLE_WIDER}.
6959 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6960 variable.
6961 @end defmac
6963 @defmac AC_TYPE_LONG_LONG_INT
6964 @acindex{TYPE_LONG_LONG_INT}
6965 @cvindex HAVE_LONG_LONG_INT
6966 @caindex type_long_long_int
6967 If the C compiler supports a working @code{long long int} type, define
6968 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6969 @code{long long int} values in preprocessor @code{#if} expressions,
6970 because too many compilers mishandle such expressions.
6971 @xref{Preprocessor Arithmetic}.
6973 This macro caches its result in the @code{ac_cv_type_long_long_int}
6974 variable.
6975 @end defmac
6977 @defmac AC_TYPE_MBSTATE_T
6978 @acindex{TYPE_MBSTATE_T}
6979 @cvindex mbstate_t
6980 @hdrindex{wchar.h}
6981 @caindex type_mbstate_t
6982 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6983 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6984 @code{<wchar.h>} does not declare it.
6986 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6987 variable.
6988 @end defmac
6990 @anchor{AC_TYPE_MODE_T}
6991 @defmac AC_TYPE_MODE_T
6992 @acindex{TYPE_MODE_T}
6993 @cvindex mode_t
6994 @caindex type_mode_t
6995 Define @code{mode_t} to a suitable type, if standard headers do not
6996 define it.
6998 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6999 @end defmac
7001 @anchor{AC_TYPE_OFF_T}
7002 @defmac AC_TYPE_OFF_T
7003 @acindex{TYPE_OFF_T}
7004 @cvindex off_t
7005 @caindex type_off_t
7006 Define @code{off_t} to a suitable type, if standard headers do not
7007 define it.
7009 This macro caches its result in the @code{ac_cv_type_off_t} variable.
7010 @end defmac
7012 @anchor{AC_TYPE_PID_T}
7013 @defmac AC_TYPE_PID_T
7014 @acindex{TYPE_PID_T}
7015 @cvindex pid_t
7016 @caindex type_pid_t
7017 Define @code{pid_t} to a suitable type, if standard headers do not
7018 define it.
7020 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
7021 @end defmac
7023 @anchor{AC_TYPE_SIZE_T}
7024 @defmac AC_TYPE_SIZE_T
7025 @acindex{TYPE_SIZE_T}
7026 @cvindex size_t
7027 @caindex type_size_t
7028 Define @code{size_t} to a suitable type, if standard headers do not
7029 define it.
7031 This macro caches its result in the @code{ac_cv_type_size_t} variable.
7032 @end defmac
7034 @defmac AC_TYPE_SSIZE_T
7035 @acindex{TYPE_SSIZE_T}
7036 @cvindex ssize_t
7037 @caindex type_ssize_t
7038 Define @code{ssize_t} to a suitable type, if standard headers do not
7039 define it.
7041 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
7042 @end defmac
7044 @anchor{AC_TYPE_UID_T}
7045 @defmac AC_TYPE_UID_T
7046 @acindex{TYPE_UID_T}
7047 @cvindex uid_t
7048 @cvindex gid_t
7049 @caindex type_uid_t
7050 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
7051 headers do not define them.
7053 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
7054 @end defmac
7056 @defmac AC_TYPE_UINT8_T
7057 @acindex{TYPE_UINT8_T}
7058 @cvindex HAVE_UINT8_T
7059 @cvindex uint8_t
7060 @caindex c_uint8_t
7061 If @file{stdint.h} or @file{inttypes.h} does not define the type
7062 @code{uint8_t}, define @code{uint8_t} to an
7063 unsigned integer type that is exactly 8 bits wide, if such a type
7064 exists.
7065 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
7066 @end defmac
7068 @defmac AC_TYPE_UINT16_T
7069 @acindex{TYPE_UINT16_T}
7070 @cvindex HAVE_UINT16_T
7071 @cvindex uint16_t
7072 @caindex c_uint16_t
7073 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
7074 @end defmac
7076 @defmac AC_TYPE_UINT32_T
7077 @acindex{TYPE_UINT32_T}
7078 @cvindex HAVE_UINT32_T
7079 @cvindex uint32_t
7080 @caindex c_uint32_t
7081 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
7082 @end defmac
7084 @defmac AC_TYPE_UINT64_T
7085 @acindex{TYPE_UINT64_T}
7086 @cvindex HAVE_UINT64_T
7087 @cvindex uint64_t
7088 @caindex c_uint64_t
7089 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
7090 @end defmac
7092 @defmac AC_TYPE_UINTMAX_T
7093 @acindex{TYPE_UINTMAX_T}
7094 @cvindex HAVE_UINTMAX_T
7095 @cvindex uintmax_t
7096 @c @caindex type_uintmax_t
7097 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
7098 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
7099 widest unsigned integer type.
7100 @end defmac
7102 @defmac AC_TYPE_UINTPTR_T
7103 @acindex{TYPE_UINTPTR_T}
7104 @cvindex HAVE_UINTPTR_T
7105 @cvindex uintptr_t
7106 @c @caindex type_uintptr_t
7107 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
7108 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
7109 unsigned integer type wide enough to hold a pointer, if such a type
7110 exists.
7111 @end defmac
7113 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
7114 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
7115 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
7116 @caindex type_unsigned_long_long_int
7117 If the C compiler supports a working @code{unsigned long long int} type,
7118 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
7119 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
7120 because too many compilers mishandle such expressions.
7121 @xref{Preprocessor Arithmetic}.
7123 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
7124 variable.
7125 @end defmac
7127 @node Generic Types
7128 @subsection Generic Type Checks
7130 These macros are used to check for types not covered by the ``particular''
7131 test macros.
7133 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
7134   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
7135 @acindex{CHECK_TYPE}
7136 @caindex type_@var{type}
7137 Check whether @var{type} is defined.  It may be a compiler builtin type
7138 or defined by the @var{includes}.  @var{includes} is a series of include
7139 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
7140 Includes}), which are used prior to the type under test.
7142 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
7143 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
7144 same test is applied when compiling for C++, which means that in C++
7145 @var{type} should be a type-id and should not be an anonymous
7146 @samp{struct} or @samp{union}.
7148 This macro caches its result in the @code{ac_cv_type_@var{type}}
7149 variable, with @samp{*} mapped to @samp{p} and other characters not
7150 suitable for a variable name mapped to underscores.
7151 @end defmac
7154 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
7155   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
7156 @acindex{CHECK_TYPES}
7157 @cvindex HAVE_@var{type}
7158 For each @var{type} of the @var{types} that is defined, define
7159 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
7160 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
7161 specified, the default includes are used (@pxref{Default Includes}).  If
7162 @var{action-if-found} is given, it is additional shell code to execute
7163 when one of the types is found.  If @var{action-if-not-found} is given,
7164 it is executed when one of the types is not found.
7166 This macro uses M4 lists:
7167 @example
7168 AC_CHECK_TYPES([ptrdiff_t])
7169 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
7170 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
7171 @end example
7173 @end defmac
7175 Autoconf, up to 2.13, used to provide to another version of
7176 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
7177 compatibility, a simple heuristic, quite safe but not totally, is
7178 implemented.  In case of doubt, read the documentation of the former
7179 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
7182 @node Compilers and Preprocessors
7183 @section Compilers and Preprocessors
7184 @cindex Compilers
7185 @cindex Preprocessors
7187 @ovindex EXEEXT
7188 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
7189 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
7190 the output of the compiler, typically to the empty string if
7191 Posix and @samp{.exe} if a DOS variant.
7193 @ovindex OBJEXT
7194 They also define the output variable @code{OBJEXT} based on the
7195 output of the compiler, after @file{.c} files have been excluded, typically
7196 to @samp{o} if Posix, @samp{obj} if a DOS variant.
7198 If the compiler being used does not produce executables, the tests fail.  If
7199 the executables can't be run, and cross-compilation is not enabled, they
7200 fail too.  @xref{Manual Configuration}, for more on support for cross
7201 compiling.
7203 @menu
7204 * Specific Compiler Characteristics::  Some portability issues
7205 * Generic Compiler Characteristics::  Language independent tests and features
7206 * C Compiler::                  Checking its characteristics
7207 * C++ Compiler::                Likewise
7208 * Objective C Compiler::        Likewise
7209 * Objective C++ Compiler::      Likewise
7210 * Erlang Compiler and Interpreter::  Likewise
7211 * Fortran Compiler::            Likewise
7212 * Go Compiler::                 Likewise
7213 @end menu
7215 @node Specific Compiler Characteristics
7216 @subsection Specific Compiler Characteristics
7218 Some compilers exhibit different behaviors.
7220 @table @asis
7221 @item Static/Dynamic Expressions
7222 Autoconf relies on a trick to extract one bit of information from the C
7223 compiler: using negative array sizes.  For instance the following
7224 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
7225 bytes wide:
7227 @example
7228 static int test_array[sizeof (int) == 4 ? 1 : -1];
7229 @end example
7231 @noindent
7232 To our knowledge, there is a single compiler that does not support this
7233 trick: the HP C compilers (the real ones, not only the
7234 ``bundled'') on HP-UX 11.00.
7235 They incorrectly reject the above program with the diagnostic
7236 ``Variable-length arrays cannot have static storage.''
7237 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
7238 not from the @code{? 1 : -1}, and
7239 Autoconf works around this problem by casting @code{sizeof (int)} to
7240 @code{long int} before comparing it.
7241 @end table
7243 @node Generic Compiler Characteristics
7244 @subsection Generic Compiler Characteristics
7246 @anchor{AC_CHECK_SIZEOF}
7247 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7248   @dvar{includes, AC_INCLUDES_DEFAULT})
7249 @acindex{CHECK_SIZEOF}
7250 @cvindex SIZEOF_@var{type-or-expr}
7251 @caindex sizeof_@var{type-or-expr}
7252 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7253 the size in bytes of @var{type-or-expr}, which may be either a type or
7254 an expression returning a value that has a size.  If the expression
7255 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7256 @var{includes} is a series of include directives, defaulting to
7257 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7258 prior to the expression under test.
7260 This macro now works even when cross-compiling.  The @var{unused}
7261 argument was used when cross-compiling.
7263 For example, the call
7265 @example
7266 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7267 AC_CHECK_SIZEOF([int *])
7268 @end example
7270 @noindent
7271 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
7273 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7274 variable, with @samp{*} mapped to @samp{p} and other characters not
7275 suitable for a variable name mapped to underscores.
7276 @end defmac
7278 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7279 @acindex{CHECK_ALIGNOF}
7280 @cvindex ALIGNOF_@var{type}
7281 @caindex alignof_@var{type-or-expr}
7282 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7283 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
7284 a structure member declaration.  If @samp{type} is unknown, the result
7285 is 0.  If no @var{includes} are specified, the default includes are used
7286 (@pxref{Default Includes}).
7288 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7289 variable, with @samp{*} mapped to @samp{p} and other characters not
7290 suitable for a variable name mapped to underscores.
7291 @end defmac
7293 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7294   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7295 @acindex{COMPUTE_INT}
7296 Store into the shell variable @var{var} the value of the integer
7297 @var{expression}.  The
7298 value should fit in an initializer in a C variable of type @code{signed
7299 long}.  To support cross compilation (in which case, the macro only works on
7300 hosts that use twos-complement arithmetic), it should be possible to evaluate
7301 the expression at compile-time.  If no @var{includes} are specified, the
7302 default includes are used (@pxref{Default Includes}).
7304 Execute @var{action-if-fails} if the value cannot be determined correctly.
7305 @end defmac
7307 @defmac AC_LANG_WERROR
7308 @acindex{LANG_WERROR}
7309 Normally Autoconf ignores warnings generated by the compiler, linker, and
7310 preprocessor.  If this macro is used, warnings count as fatal
7311 errors for the current language.  This macro is useful when the
7312 results of configuration are used where warnings are unacceptable; for
7313 instance, if parts of a program are built with the GCC
7314 @option{-Werror}
7315 option.  If the whole program is built using @option{-Werror} it is
7316 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7317 etc.).
7318 @end defmac
7320 @defmac AC_OPENMP
7321 @acindex{OPENMP}
7322 @cvindex _OPENMP
7323 @ovindex OPENMP_CFLAGS
7324 @ovindex OPENMP_CXXFLAGS
7325 @ovindex OPENMP_FFLAGS
7326 @ovindex OPENMP_FCFLAGS
7327 @caindex prog_c_openmp
7328 @caindex prog_cxx_openmp
7329 @caindex prog_f77_openmp
7330 @caindex prog_fc_openmp
7331 @uref{http://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7332 and Fortran that simplify optimization of shared memory parallelism,
7333 which is a common problem on multi-core CPUs.
7335 If the current language is C, the macro @code{AC_OPENMP} sets the
7336 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7337 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
7338 compiler already supports OpenMP, if it has no way to activate OpenMP
7339 support, or if the user rejects OpenMP support by invoking
7340 @samp{configure} with the @samp{--disable-openmp} option.
7342 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7343 preprocessing program source, and when linking programs.  Therefore you
7344 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7345 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
7346 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
7347 OpenMP support is revealed at compile time by the preprocessor macro
7348 @code{_OPENMP}.
7350 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7351 shared library to the program's dependencies, so its use is recommended
7352 only on programs that actually require OpenMP.
7354 If the current language is C++, @code{AC_OPENMP} sets the variable
7355 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7356 hold as for C.
7358 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7359 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7360 respectively.  Similar remarks as for C hold, except that
7361 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7362 signals OpenMP support.
7364 For portability, it is best to avoid spaces between @samp{#} and
7365 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7366 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7367 latter.
7369 This macro caches its result in the @code{ac_cv_prog_c_openmp},
7370 @code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7371 @code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7373 @strong{Caution:} Some of the compiler options that @code{AC_OPENMP}
7374 tests, mean ``enable OpenMP'' to one compiler, but ``write output to a
7375 file named @file{mp} or @file{penmp}'' to other compilers.  We cannot
7376 guarantee that the implementation of @code{AC_OPENMP} will not overwrite
7377 an existing file with either of these names.
7379 Therefore, as a defensive measure, a @command{configure} script that
7380 uses @code{AC_OPENMP} will issue an error and stop (before doing any of
7381 the operations that might overwrite these files) upon encountering
7382 either of these files in its working directory.
7383 @command{autoconf} will also issue an error if it finds either of
7384 these files in the same directory as a @file{configure.ac} that
7385 uses @code{AC_OPENMP}.
7387 If you have files with either of these names at the top level of your
7388 source tree, and you need to use @code{AC_OPENMP}, we recommend you
7389 either change their names or move them into a subdirectory.
7390 @end defmac
7392 @node C Compiler
7393 @subsection C Compiler Characteristics
7395 The following macros provide ways to find and exercise a C Compiler.
7396 There are a few constructs that ought to be avoided, but do not deserve
7397 being checked for, since they can easily be worked around.
7399 @table @asis
7400 @item Don't use lines containing solitary backslashes
7401 They tickle a bug in the HP-UX C compiler (checked on
7402 HP-UX 10.20,
7403 11.00, and 11i).  When given the following source:
7405 @example
7406 #ifdef __STDC__
7408 * A comment with backslash-newlines in it.  %@{ %@} *\
7411 char str[] = "\\
7412 " A string with backslash-newlines in it %@{ %@} \\
7414 char apostrophe = '\\
7418 #endif
7419 @end example
7421 @noindent
7422 the compiler incorrectly fails with the diagnostics ``Non-terminating
7423 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7424 Removing the lines with solitary backslashes solves the problem.
7426 @item Don't compile several files at once if output matters to you
7427 Some compilers, such as HP's, report names of files being
7428 compiled when given more than one file operand.  For instance:
7430 @example
7431 $ @kbd{cc a.c b.c}
7432 a.c:
7433 b.c:
7434 @end example
7436 @noindent
7437 This can cause problems if you observe the output of the compiler to
7438 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7439 b.o} solves the issue.
7441 @item Don't rely on @code{#error} failing
7442 The IRIX C compiler does not fail when #error is preprocessed; it
7443 simply emits a diagnostic and continues, exiting successfully.  So,
7444 instead of an error directive like @code{#error "Unsupported word size"}
7445 it is more portable to use an invalid directive like @code{#Unsupported
7446 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7447 OK, since installers with inadequate compilers like IRIX can simply
7448 examine these compilers' diagnostic output.
7450 @item Don't rely on correct @code{#line} support
7451 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7452 diagnoses @code{#line} directives whose line
7453 numbers are greater than 32767.  Nothing in Posix
7454 makes this invalid.  That is why Autoconf stopped issuing
7455 @code{#line} directives.
7456 @end table
7458 @anchor{AC_PROG_CC}
7459 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7460 @acindex{PROG_CC}
7461 @evindex CC
7462 @evindex CFLAGS
7463 @ovindex CC
7464 @ovindex CFLAGS
7465 Determine a C compiler to use.
7467 If the environment variable @code{CC} is set, its value will be taken as
7468 the name of the C compiler to use.  Otherwise, search for a C compiler
7469 under a series of likely names, trying @code{gcc} and @code{cc} first.
7470 Regardless, the output variable @code{CC} is set to the chosen compiler.
7472 If the optional first argument to the macro is used, it must be a
7473 whitespace-separated list of potential names for a C compiler,
7474 which overrides the built-in list.
7476 If no C compiler can be found, @command{configure} will error out.
7478 If the selected C compiler is found to be GNU C (regardless of
7479 its name), the shell variable @code{GCC} will be set to @samp{yes}.
7480 If the shell variable @code{CFLAGS} was not already set, it is set
7481 to @option{-g -O2} for the GNU C compiler (@option{-O2} on systems
7482 where GCC does not accept @option{-g}), or @option{-g} for other
7483 compilers.  @code{CFLAGS} is then made an output variable.
7484 You can override the default for @code{CFLAGS} by inserting a shell
7485 default assignment between @code{AC_INIT} and @code{AC_PROG_CC}:
7487 @example
7488 : $@{CFLAGS="@var{options}"@}
7489 @end example
7491 where @var{options} are the appropriate set of options to use by
7492 default.  (It is important to use this construct rather than a normal
7493 assignment, so that @code{CFLAGS} can still be overridden by the
7494 person building the package.  @xref{Preset Output Variables}.)
7496 If necessary, options are added to @code{CC} to enable support for
7497 ISO Standard C features with extensions, preferring the newest edition
7498 of the C standard that is supported.  Currently the newest edition
7499 Autoconf knows how to detect support for is ISO C 2011.  After calling
7500 this macro you can check whether the C compiler has been set to accept
7501 standard C by inspecting the shell variable @code{ac_prog_cc_stdc}.
7502 Its value will be @samp{c11}, @samp{c99}, or @samp{c89}, respectively,
7503 if the C compiler has been set to use the 2011, 1999, or 1990 edition of
7504 the C standard, and @samp{no} if the compiler does not support compiling
7505 standard C at all.
7507 The tests for standard conformance are not comprehensive.  They test the
7508 values of @code{__STDC__} and @code{__STDC_VERSION__}, and a
7509 representative sample of the language features added in each version of
7510 the C standard.  They do not test the C standard library, because the C
7511 compiler might be generating code for a ``freestanding environment''
7512 (in which most of the standard library is optional).  If you need to know
7513 whether a particular C standard header exists, use @code{AC_CHECK_HEADER}.
7515 None of the options that may be added to @code{CC} by this macro
7516 enable @emph{strict} conformance to the C standard.  In particular,
7517 system-specific extensions are not disabled.  (For example, for GNU C,
7518 the @option{-std=gnu@var{nn}} options may be used, but not the
7519 @option{-std=c@var{nn}} options.)
7521 Many Autoconf macros use a compiler, and thus call
7522 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7523 determined before the body of the outermost @code{AC_DEFUN} macro.
7524 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7525 performs certain checks (such as the proper value of @env{EXEEXT}) only
7526 on the first invocation.  Therefore, care must be used when invoking
7527 this macro from within another macro rather than at the top level
7528 (@pxref{Expanded Before Required}).
7529 @end defmac
7531 @anchor{AC_PROG_CC_C_O}
7532 @defmac AC_PROG_CC_C_O
7533 @acindex{PROG_CC_C_O}
7534 @cvindex NO_MINUS_C_MINUS_O
7535 @caindex prog_cc_@var{compiler}_c_o
7536 If the C compiler does not accept the @option{-c} and @option{-o} options
7537 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7538 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7539 the first @code{cc} in the path.  The test fails if one fails.  This
7540 macro was created for GNU Make to choose the default C compilation
7541 rule.
7543 For the compiler @var{compiler}, this macro caches its result in the
7544 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7545 @end defmac
7548 @defmac AC_PROG_CPP
7549 @acindex{PROG_CPP}
7550 @evindex CPP
7551 @ovindex CPP
7552 Set output variable @code{CPP} to a command that runs the
7553 C preprocessor.  If @samp{$CC -E} doesn't work, tries @code{cpp} and
7554 @file{/lib/cpp}, in that order.
7556 It is only portable to run @code{CPP} on files with a @file{.c}
7557 extension.
7559 Some preprocessors don't indicate missing include files by the error
7560 status.  For such preprocessors an internal variable is set that causes
7561 other macros to check the standard error from the preprocessor and
7562 consider the test failed if any warnings have been reported.
7563 For most preprocessors, though, warnings do not cause include-file
7564 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7565 @end defmac
7567 @defmac AC_PROG_CPP_WERROR
7568 @acindex{PROG_CPP_WERROR}
7569 @ovindex CPP
7570 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7571 preprocessor as errors even if the preprocessor exit status indicates
7572 success.  This is useful for avoiding headers that generate mandatory
7573 warnings, such as deprecation notices.
7574 @end defmac
7577 The following macros check for C compiler or machine architecture
7578 features.  To check for characteristics not listed here, use
7579 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7580 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7582 @defmac AC_C_BACKSLASH_A
7583 @acindex{C_BACKSLASH_A}
7584 @cvindex HAVE_C_BACKSLASH_A
7585 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7586 @samp{\a}.
7588 This macro is obsolescent, as current C compilers understand @samp{\a}.
7589 New programs need not use this macro.
7590 @end defmac
7592 @anchor{AC_C_BIGENDIAN}
7593 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7594   @ovar{action-if-unknown}, @ovar{action-if-universal})
7595 @acindex{C_BIGENDIAN}
7596 @cvindex WORDS_BIGENDIAN
7597 @cindex Endianness
7598 If words are stored with the most significant byte first (like Motorola
7599 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7600 the least significant byte first (like Intel and VAX CPUs), execute
7601 @var{action-if-false}.
7603 This macro runs a test-case if endianness cannot be determined from the
7604 system header files.  When cross-compiling, the test-case is not run but
7605 grep'ed for some magic values.  @var{action-if-unknown} is executed if
7606 the latter case fails to determine the byte sex of the host system.
7608 In some cases a single run of a compiler can generate code for multiple
7609 architectures.  This can happen, for example, when generating Mac OS X
7610 universal binary files, which work on both PowerPC and Intel
7611 architectures.  In this case, the different variants might be for
7612 architectures with differing endianness.  If
7613 @command{configure} detects this, it executes @var{action-if-universal}
7614 instead of @var{action-if-unknown}.
7616 The default for @var{action-if-true} is to define
7617 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7618 nothing.  The default for @var{action-if-unknown} is to
7619 abort configure and tell the installer how to bypass this test.
7620 And finally, the default for @var{action-if-universal} is to ensure that
7621 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7622 detected and the current code is big-endian; this default works only if
7623 @command{autoheader} is used (@pxref{autoheader Invocation}).
7625 If you use this macro without specifying @var{action-if-universal}, you
7626 should also use @code{AC_CONFIG_HEADERS}; otherwise
7627 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7628 binary files.
7629 @end defmac
7631 @anchor{AC_C_CONST}
7632 @defmac AC_C_CONST
7633 @acindex{C_CONST}
7634 @cvindex const
7635 @caindex c_const
7636 If the C compiler does not fully support the @code{const} keyword,
7637 define @code{const} to be empty.  Some C compilers that do
7638 not define @code{__STDC__} do support @code{const}; some compilers that
7639 define @code{__STDC__} do not completely support @code{const}.  Programs
7640 can simply use @code{const} as if every C compiler supported it; for
7641 those that don't, the makefile or configuration header file
7642 defines it as empty.
7644 Occasionally installers use a C++ compiler to compile C code, typically
7645 because they lack a C compiler.  This causes problems with @code{const},
7646 because C and C++ treat @code{const} differently.  For example:
7648 @example
7649 const int foo;
7650 @end example
7652 @noindent
7653 is valid in C but not in C++.  These differences unfortunately cannot be
7654 papered over by defining @code{const} to be empty.
7656 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7657 as this generally yields better results in practice.  However, using a
7658 C++ compiler to compile C code is not recommended or supported, and
7659 installers who run into trouble in this area should get a C compiler
7660 like GCC to compile their C code.
7662 This macro caches its result in the @code{ac_cv_c_const} variable.
7664 This macro is obsolescent, as current C compilers support @code{const}.
7665 New programs need not use this macro.
7666 @end defmac
7668 @defmac AC_C__GENERIC
7669 @acindex{C__GENERIC}
7670 @cvindex _Generic
7671 If the C compiler supports C11-style generic selection using the
7672 @code{_Generic} keyword, define @code{HAVE_C__GENERIC}.
7673 @end defmac
7675 @defmac AC_C_RESTRICT
7676 @acindex{C_RESTRICT}
7677 @cvindex restrict
7678 @caindex c_restrict
7679 If the C compiler recognizes a variant spelling for the @code{restrict}
7680 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7681 then define @code{restrict} to that; this is more likely to do the right
7682 thing with compilers that support language variants where plain
7683 @code{restrict} is not a keyword.  Otherwise, if the C compiler
7684 recognizes the @code{restrict} keyword, don't do anything.
7685 Otherwise, define @code{restrict} to be empty.
7686 Thus, programs may simply use @code{restrict} as if every C compiler
7687 supported it; for those that do not, the makefile
7688 or configuration header defines it away.
7690 Although support in C++ for the @code{restrict} keyword is not
7691 required, several C++ compilers do accept the keyword.
7692 This macro works for them, too.
7694 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7695 if @code{restrict} is not supported, and a supported spelling otherwise.
7696 @end defmac
7698 @defmac AC_C_VOLATILE
7699 @acindex{C_VOLATILE}
7700 @cvindex volatile
7701 If the C compiler does not understand the keyword @code{volatile},
7702 define @code{volatile} to be empty.  Programs can simply use
7703 @code{volatile} as if every C compiler supported it; for those that do
7704 not, the makefile or configuration header defines it as
7705 empty.
7707 If the correctness of your program depends on the semantics of
7708 @code{volatile}, simply defining it to be empty does, in a sense, break
7709 your code.  However, given that the compiler does not support
7710 @code{volatile}, you are at its mercy anyway.  At least your
7711 program compiles, when it wouldn't before.
7712 @xref{Volatile Objects}, for more about @code{volatile}.
7714 In general, the @code{volatile} keyword is a standard C feature, so
7715 you might expect that @code{volatile} is available only when
7716 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7717 support volatile, but does not define @code{__STDC__}.
7719 This macro is obsolescent, as current C compilers support @code{volatile}.
7720 New programs need not use this macro.
7721 @end defmac
7723 @anchor{AC_C_INLINE}
7724 @defmac AC_C_INLINE
7725 @acindex{C_INLINE}
7726 @cvindex inline
7727 If the C compiler supports the keyword @code{inline}, do nothing.
7728 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7729 if it accepts one of those, otherwise define @code{inline} to be empty.
7730 @end defmac
7732 @anchor{AC_C_CHAR_UNSIGNED}
7733 @defmac AC_C_CHAR_UNSIGNED
7734 @acindex{C_CHAR_UNSIGNED}
7735 @cvindex __CHAR_UNSIGNED__
7736 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7737 unless the C compiler predefines it.
7739 These days, using this macro is not necessary.  The same information can
7740 be determined by this portable alternative, thus avoiding the use of
7741 preprocessor macros in the namespace reserved for the implementation.
7743 @example
7744 #include <limits.h>
7745 #if CHAR_MIN == 0
7746 # define CHAR_UNSIGNED 1
7747 #endif
7748 @end example
7749 @end defmac
7751 @defmac AC_C_STRINGIZE
7752 @acindex{C_STRINGIZE}
7753 @cvindex HAVE_STRINGIZE
7754 If the C preprocessor supports the stringizing operator, define
7755 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7756 found in macros such as this:
7758 @example
7759 #define x(y) #y
7760 @end example
7762 This macro is obsolescent, as current C compilers support the
7763 stringizing operator.  New programs need not use this macro.
7764 @end defmac
7766 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7767 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7768 @cvindex FLEXIBLE_ARRAY_MEMBER
7769 If the C compiler supports flexible array members, define
7770 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7771 That way, a declaration like this:
7773 @example
7774 struct s
7775   @{
7776     size_t n_vals;
7777     double val[FLEXIBLE_ARRAY_MEMBER];
7778   @};
7779 @end example
7781 @noindent
7782 will let applications use the ``struct hack'' even with compilers that
7783 do not support flexible array members.  To allocate and use such an
7784 object, you can use code like this:
7786 @example
7787 size_t i;
7788 size_t n = compute_value_count ();
7789 struct s *p =
7790    malloc (offsetof (struct s, val)
7791            + n * sizeof (double));
7792 p->n_vals = n;
7793 for (i = 0; i < n; i++)
7794   p->val[i] = compute_value (i);
7795 @end example
7796 @end defmac
7798 @defmac AC_C_VARARRAYS
7799 @acindex{C_VARARRAYS}
7800 @cvindex __STDC_NO_VLA__
7801 @cvindex HAVE_C_VARARRAYS
7802 If the C compiler does not support variable-length arrays, define the
7803 macro @code{__STDC_NO_VLA__} to be 1 if it is not already defined.  A
7804 variable-length array is an array of automatic storage duration whose
7805 length is determined at run time, when the array is declared.  For
7806 backward compatibility this macro also defines @code{HAVE_C_VARARRAYS}
7807 if the C compiler supports variable-length arrays, but this usage is
7808 obsolescent and new programs should use @code{__STDC_NO_VLA__}.
7809 @end defmac
7811 @defmac AC_C_TYPEOF
7812 @acindex{C_TYPEOF}
7813 @cvindex HAVE_TYPEOF
7814 @cvindex typeof
7815 If the C compiler supports GNU C's @code{typeof} syntax either
7816 directly or
7817 through a different spelling of the keyword (e.g., @code{__typeof__}),
7818 define @code{HAVE_TYPEOF}.  If the support is available only through a
7819 different spelling, define @code{typeof} to that spelling.
7820 @end defmac
7822 @defmac AC_C_PROTOTYPES
7823 @acindex{C_PROTOTYPES}
7824 @cvindex PROTOTYPES
7825 @cvindex __PROTOTYPES
7826 @cvindex PARAMS
7827 If function prototypes are understood by the compiler (as determined by
7828 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7829 Defining @code{__PROTOTYPES} is for the benefit of
7830 header files that cannot use macros that infringe on user name space.
7832 This macro is obsolescent, as current C compilers support prototypes.
7833 New programs need not use this macro.
7834 @end defmac
7836 @anchor{AC_PROG_GCC_TRADITIONAL}
7837 @defmac AC_PROG_GCC_TRADITIONAL
7838 @acindex{PROG_GCC_TRADITIONAL}
7839 @ovindex CC
7840 Add @option{-traditional} to output variable @code{CC} if using a
7841 GNU C compiler and @code{ioctl} does not work properly without
7842 @option{-traditional}.  That usually happens when the fixed header files
7843 have not been installed on an old system.
7845 This macro is obsolescent, since current versions of the GNU C
7846 compiler fix the header files automatically when installed.
7847 @end defmac
7850 @node C++ Compiler
7851 @subsection C++ Compiler Characteristics
7854 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7855 @acindex{PROG_CXX}
7856 @evindex CXX
7857 @evindex CXXFLAGS
7858 @ovindex CXX
7859 @ovindex CXXFLAGS
7860 Determine a C++ compiler to use.
7862 If either the environment variable @code{CXX} or the environment
7863 variable @code{CCC} is set, its value will be taken as the name of a
7864 C++ compiler.  If both are set, @code{CXX} is preferred.  If neither
7865 are set, search for a C++ compiler under a series of likely names,
7866 trying @code{g++} and @code{c++} first.  Regardless, the output
7867 variable @code{CXX} is set to the chosen compiler.
7869 If the optional first argument to the macro is used, it must be a
7870 whitespace-separated list of potential names for a C++ compiler,
7871 which overrides the built-in list.
7873 If no C++ compiler can be found, as a last resort @code{CXX} is set to
7874 @code{g++} (and subsequent tests will probably fail).
7876 If the selected C++ compiler is found to be GNU C++ (regardless of
7877 its name), the shell variable @code{GXX} will be set to @samp{yes}.
7878 If the shell variable @code{CXXFLAGS} was not already set, it is set
7879 to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on systems
7880 where G++ does not accept @option{-g}), or @option{-g} for other
7881 compilers.  @code{CXXFLAGS} is then made an output variable.
7882 You can override the default for @code{CXXFLAGS} by inserting a shell
7883 default assignment between @code{AC_INIT} and @code{AC_PROG_CXX}:
7885 @example
7886 : $@{CXXFLAGS="@var{options}"@}
7887 @end example
7889 where @var{options} are the appropriate set of options to use by
7890 default.  (It is important to use this construct rather than a normal
7891 assignment, so that @code{CXXFLAGS} can still be overridden by the
7892 person building the package.  @xref{Preset Output Variables}.)
7894 If necessary, options are added to @code{CXX} to enable support for
7895 ISO Standard C++ features with extensions, preferring the newest edition
7896 of the C++ standard that is supported.  Currently the newest edition
7897 Autoconf knows how to detect support for is ISO C++ 2011.  After calling
7898 this macro, you can check whether the C++ compiler has been set to
7899 accept standard C++ by inspecting the shell variable @code{ac_prog_cxx_stdcxx}.
7900 Its value will be @samp{cxx11} or @samp{cxx98}, respectively,
7901 if the C++ compiler has been set to use the 2011 or 1990 edition of the
7902 C++ standard, and @samp{no} if the compiler does not support compiling
7903 standard C++ at all.
7905 The tests for standard conformance are not comprehensive.  They test
7906 the value of @code{__cplusplus} and a representative sample of the
7907 language features added in each version of the C++ standard.  They
7908 do not test the C++ standard library, because this can be extremely
7909 slow, and because the C++ compiler might be generating code for a
7910 ``freestanding environment'' (in which most of the C++ standard library
7911 is optional).  If you need to know whether a particular C++ standard
7912 header exists, use @code{AC_CHECK_HEADER}.
7914 None of the options that may be added to @code{CXX} by this macro
7915 enable @emph{strict} conformance to the C++ standard.  In particular,
7916 system-specific extensions are not disabled.  (For example, for GNU
7917 C++, the @option{-std=gnu++@var{nn}} options may be used, but not the
7918 @option{-std=c++@var{nn}} options.)
7919 @end defmac
7921 @defmac AC_PROG_CXXCPP
7922 @acindex{PROG_CXXCPP}
7923 @evindex CXXCPP
7924 @ovindex CXXCPP
7925 Set output variable @code{CXXCPP} to a command that runs the C++
7926 preprocessor.  If @samp{$CXX -E} doesn't work, tries @code{cpp} and
7927 @file{/lib/cpp}, in that order.  Because of this fallback, @code{CXXCPP}
7928 may or may not set C++-specific predefined macros (such as @code{__cplusplus}).
7930 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7931 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7933 Some preprocessors don't indicate missing include files by the error
7934 status.  For such preprocessors an internal variable is set that causes
7935 other macros to check the standard error from the preprocessor and
7936 consider the test failed if any warnings have been reported.  However,
7937 it is not known whether such broken preprocessors exist for C++.
7938 @end defmac
7940 @defmac AC_PROG_CXX_C_O
7941 @acindex{PROG_CXX_C_O}
7942 @cvindex CXX_NO_MINUS_C_MINUS_O
7943 Test whether the C++ compiler accepts the options @option{-c} and
7944 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7945 if it does not.
7946 @end defmac
7949 @node Objective C Compiler
7950 @subsection Objective C Compiler Characteristics
7953 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7954 @acindex{PROG_OBJC}
7955 @evindex OBJC
7956 @evindex OBJCFLAGS
7957 @ovindex OBJC
7958 @ovindex OBJCFLAGS
7959 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7960 set in the environment, check for Objective C compilers.  Set output
7961 variable @code{OBJC} to the name of the compiler found.
7963 This macro may, however, be invoked with an optional first argument
7964 which, if specified, must be a blank-separated list of Objective C compilers to
7965 search for.  This just gives the user an opportunity to specify an
7966 alternative search list for the Objective C compiler.  For example, if you
7967 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7968 like this:
7970 @example
7971 AC_PROG_OBJC([gcc objcc objc])
7972 @end example
7974 If using a compiler that supports GNU Objective C, set shell variable
7975 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7976 already set, set it to @option{-g -O2} for a GNU Objective C
7977 compiler (@option{-O2} on systems where the compiler does not accept
7978 @option{-g}), or @option{-g} for other compilers.
7979 @end defmac
7981 @defmac AC_PROG_OBJCPP
7982 @acindex{PROG_OBJCPP}
7983 @evindex OBJCPP
7984 @ovindex OBJCPP
7985 Set output variable @code{OBJCPP} to a command that runs the Objective C
7986 preprocessor.  If @samp{$OBJC -E} doesn't work, tries @code{cpp} and
7987 @file{/lib/cpp}, in that order.  Because of this fallback, @code{CXXCPP}
7988 may or may not set Objective-C-specific predefined macros (such as
7989 @code{__OBJC__}).
7990 @end defmac
7993 @node Objective C++ Compiler
7994 @subsection Objective C++ Compiler Characteristics
7997 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7998 @acindex{PROG_OBJCXX}
7999 @evindex OBJCXX
8000 @evindex OBJCXXFLAGS
8001 @ovindex OBJCXX
8002 @ovindex OBJCXXFLAGS
8003 Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
8004 set in the environment, check for Objective C++ compilers.  Set output
8005 variable @code{OBJCXX} to the name of the compiler found.
8007 This macro may, however, be invoked with an optional first argument
8008 which, if specified, must be a blank-separated list of Objective C++ compilers
8009 to search for.  This just gives the user an opportunity to specify an
8010 alternative search list for the Objective C++ compiler.  For example, if you
8011 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
8012 like this:
8014 @example
8015 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
8016 @end example
8018 If using a compiler that supports GNU Objective C++, set shell variable
8019 @code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
8020 already set, set it to @option{-g -O2} for a GNU Objective C++
8021 compiler (@option{-O2} on systems where the compiler does not accept
8022 @option{-g}), or @option{-g} for other compilers.
8023 @end defmac
8025 @defmac AC_PROG_OBJCXXCPP
8026 @acindex{PROG_OBJCXXCPP}
8027 @evindex OBJCXXCPP
8028 @ovindex OBJCXXCPP
8029 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
8030 preprocessor.  If @samp{$OBJCXX -E} doesn't work, tries @code{cpp} and
8031 @file{/lib/cpp}, in that order.  Because of this fallback, @code{CXXCPP}
8032 may or may not set Objective-C++-specific predefined macros (such as
8033 @code{__cplusplus} and @code{__OBJC__}).
8034 @end defmac
8037 @node Erlang Compiler and Interpreter
8038 @subsection Erlang Compiler and Interpreter Characteristics
8039 @cindex Erlang
8041 Autoconf defines the following macros for determining paths to the essential
8042 Erlang/OTP programs:
8044 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
8045 @acindex{ERLANG_PATH_ERLC}
8046 @evindex ERLC
8047 @evindex ERLCFLAGS
8048 @ovindex ERLC
8049 @ovindex ERLCFLAGS
8050 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
8051 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
8052 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
8053 is not set in the environment, set it to an empty value.
8055 The two optional arguments have the same meaning as the two last arguments of
8056 macro @code{AC_PATH_PROG} for looking for the @command{erlc} program.  For
8057 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
8058 directory:
8060 @example
8061 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
8062 @end example
8063 @end defmac
8065 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
8066 @acindex{ERLANG_NEED_ERLC}
8067 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
8068 error message and exits the @command{configure} script if the @command{erlc}
8069 program is not found.
8070 @end defmac
8072 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
8073 @acindex{ERLANG_PATH_ERL}
8074 @evindex ERL
8075 @ovindex ERL
8076 Determine an Erlang interpreter to use.  If @code{ERL} is not already
8077 set in the
8078 environment, check for @command{erl}.  Set output variable @code{ERL} to the
8079 complete path of the interpreter command found.
8081 The two optional arguments have the same meaning as the two last arguments of
8082 macro @code{AC_PATH_PROG} for looking for the @command{erl} program.  For
8083 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
8084 directory:
8086 @example
8087 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
8088 @end example
8089 @end defmac
8091 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
8092 @acindex{ERLANG_NEED_ERL}
8093 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
8094 error message and exits the @command{configure} script if the @command{erl}
8095 program is not found.
8096 @end defmac
8099 @node Fortran Compiler
8100 @subsection Fortran Compiler Characteristics
8101 @cindex Fortran
8102 @cindex F77
8104 The Autoconf Fortran support is divided into two categories: legacy
8105 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
8106 The former are intended for traditional Fortran 77 code, and have output
8107 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
8108 are for newer programs that can (or must) compile under the newer
8109 Fortran standards, and have output variables like @code{FC},
8110 @code{FCFLAGS}, and @code{FCLIBS}.
8112 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
8113 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
8114 @code{FC} and @code{F77} macros behave almost identically, and so they
8115 are documented together in this section.
8118 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
8119 @acindex{PROG_F77}
8120 @evindex F77
8121 @evindex FFLAGS
8122 @ovindex F77
8123 @ovindex FFLAGS
8124 @caindex f77_compiler_gnu
8125 @caindex prog_f77_g
8126 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
8127 set in the environment, then check for @code{g77} and @code{f77}, and
8128 then some other names.  Set the output variable @code{F77} to the name
8129 of the compiler found.
8131 This macro may, however, be invoked with an optional first argument
8132 which, if specified, must be a blank-separated list of Fortran 77
8133 compilers to search for.  This just gives the user an opportunity to
8134 specify an alternative search list for the Fortran 77 compiler.  For
8135 example, if you didn't like the default order, then you could invoke
8136 @code{AC_PROG_F77} like this:
8138 @example
8139 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
8140 @end example
8142 If using a compiler that supports GNU Fortran 77,
8143 set the shell variable @code{G77} to @samp{yes}.
8144 If the output variable @code{FFLAGS} was not already set in the
8145 environment, set it to @option{-g -02} for @code{g77} (or @option{-O2}
8146 where the GNU Fortran 77 compiler does not accept @option{-g}), or
8147 @option{-g} for other compilers.
8149 The result of the GNU test is cached in the
8150 @code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
8151 @code{ac_cv_prog_f77_g} variable.
8152 @end defmac
8154 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
8155 @acindex{PROG_FC}
8156 @evindex FC
8157 @evindex FCFLAGS
8158 @ovindex FC
8159 @ovindex FCFLAGS
8160 @caindex fc_compiler_gnu
8161 @caindex prog_fc_g
8162 Determine a Fortran compiler to use.  If @code{FC} is not already set in
8163 the environment, then @code{dialect} is a hint to indicate what Fortran
8164 dialect to search for; the default is to search for the newest available
8165 dialect.  Set the output variable @code{FC} to the name of the compiler
8166 found.
8168 By default, newer dialects are preferred over older dialects, but if
8169 @code{dialect} is specified then older dialects are preferred starting
8170 with the specified dialect.  @code{dialect} can currently be one of
8171 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
8172 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
8173 and no attempt is made to guarantee that a particular language standard
8174 is actually supported.  Thus, it is preferable that you avoid the
8175 @code{dialect} option, and use AC_PROG_FC only for code compatible with
8176 the latest Fortran standard.
8178 This macro may, alternatively, be invoked with an optional first argument
8179 which, if specified, must be a blank-separated list of Fortran
8180 compilers to search for, just as in @code{AC_PROG_F77}.
8182 If using a compiler that supports GNU Fortran,
8183 set the shell variable @code{GFC} to @samp{yes}.
8184 If the output variable @code{FCFLAGS} was not already set in the
8185 environment, then set it to @option{-g -02} for a GNU Fortran compiler (or
8186 @option{-O2} where the compiler does not accept @option{-g}), or
8187 @option{-g} for other compilers.
8189 The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
8190 variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
8191 variable.
8192 @end defmac
8194 @defmac AC_PROG_F77_C_O
8195 @defmacx AC_PROG_FC_C_O
8196 @acindex{PROG_F77_C_O}
8197 @acindex{PROG_FC_C_O}
8198 @cvindex F77_NO_MINUS_C_MINUS_O
8199 @cvindex FC_NO_MINUS_C_MINUS_O
8200 @caindex prog_f77_c_o
8201 @caindex prog_fc_c_o
8202 Test whether the Fortran compiler accepts the options @option{-c} and
8203 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
8204 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
8206 The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
8207 @code{ac_cv_prog_fc_c_o} variable, respectively.
8208 @end defmac
8210 The following macros check for Fortran compiler characteristics.
8211 To check for characteristics not listed here, use
8212 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
8213 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
8214 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
8215 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
8218 @defmac AC_F77_LIBRARY_LDFLAGS
8219 @defmacx AC_FC_LIBRARY_LDFLAGS
8220 @acindex{F77_LIBRARY_LDFLAGS}
8221 @ovindex FLIBS
8222 @acindex{FC_LIBRARY_LDFLAGS}
8223 @ovindex FCLIBS
8224 @caindex prog_f77_v
8225 @caindex prog_fc_v
8226 @caindex f77_libs
8227 @caindex fc_libs
8228 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
8229 @dfn{Fortran intrinsic and runtime libraries} that are required to
8230 successfully link a Fortran program or shared library.  The output
8231 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
8232 should be included after @code{LIBS} when linking).
8234 This macro is intended to be used in those situations when it is
8235 necessary to mix, e.g., C++ and Fortran source code in a single
8236 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
8237 automake, GNU Automake}).
8239 For example, if object files from a C++ and Fortran compiler must be
8240 linked together, then the C++ compiler/linker must be used for linking
8241 (since special C++-ish things need to happen at link time like calling
8242 global constructors, instantiating templates, enabling exception
8243 support, etc.).
8245 However, the Fortran intrinsic and runtime libraries must be linked in
8246 as well, but the C++ compiler/linker doesn't know by default how to add
8247 these Fortran 77 libraries.  Hence, this macro was created to determine
8248 these Fortran libraries.
8250 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8251 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
8252 link C/C++ with Fortran; see below.  Further, it is highly recommended
8253 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
8254 because the complex defines that the function wrapper macros create
8255 may not work with C/C++ compiler drivers.
8257 These macros internally compute the flag needed to verbose linking
8258 output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
8259 variables, respectively.  The computed linker flags are cached in
8260 @code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
8261 @end defmac
8263 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @
8264   @dvar{action-if-not-found, AC_MSG_FAILURE})
8265 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @
8266   @dvar{action-if-not-found, AC_MSG_FAILURE})
8267 @acindex{F77_DUMMY_MAIN}
8268 @cvindex F77_DUMMY_MAIN
8269 @acindex{FC_DUMMY_MAIN}
8270 @cvindex FC_DUMMY_MAIN
8271 @caindex f77_dummy_main
8272 @caindex fc_dummy_main
8273 With many compilers, the Fortran libraries detected by
8274 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
8275 their own @code{main} entry function that initializes things like
8276 Fortran I/O, and which then calls a user-provided entry function named
8277 (say) @code{MAIN__} to run the user's program.  The
8278 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8279 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
8280 this interaction.
8282 When using Fortran for purely numerical functions (no I/O, etc.)@: often
8283 one prefers to provide one's own @code{main} and skip the Fortran
8284 library initializations.  In this case, however, one may still need to
8285 provide a dummy @code{MAIN__} routine in order to prevent linking errors
8286 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8287 detects whether any such routine is @emph{required} for linking, and
8288 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8289 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8290 was found, and @code{none} when no such dummy main is needed.
8292 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8293 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8294 @emph{if} it is required.  @var{action-if-not-found} defaults to
8295 exiting with an error.
8297 In order to link with Fortran routines, the user's C/C++ program should
8298 then include the following code to define the dummy main if it is
8299 needed:
8301 @example
8302 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8303 #ifdef F77_DUMMY_MAIN
8304 #  ifdef __cplusplus
8305      extern "C"
8306 #  endif
8307    int F77_DUMMY_MAIN () @{ return 1; @}
8308 #endif
8309 @end example
8311 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8313 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8314 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8315 explicitly unless one wants to change the default actions.
8317 The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8318 @code{ac_cv_fc_dummy_main} variable, respectively.
8319 @end defmac
8321 @defmac AC_F77_MAIN
8322 @defmacx AC_FC_MAIN
8323 @acindex{F77_MAIN}
8324 @cvindex F77_MAIN
8325 @acindex{FC_MAIN}
8326 @cvindex FC_MAIN
8327 @caindex f77_main
8328 @caindex fc_main
8329 As discussed above, many Fortran libraries allow you to provide an entry
8330 point called (say) @code{MAIN__} instead of the usual @code{main}, which
8331 is then called by a @code{main} function in the Fortran libraries that
8332 initializes things like Fortran I/O@.  The
8333 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8334 @emph{possible} to utilize such an alternate main function, and defines
8335 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
8336 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8337 simply defined to @code{main}.)
8339 Thus, when calling Fortran routines from C that perform things like I/O,
8340 one should use this macro and declare the "main" function like so:
8342 @example
8343 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8344 #ifdef __cplusplus
8345   extern "C"
8346 #endif
8347 int F77_MAIN (int argc, char *argv[]);
8348 @end example
8350 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8352 The result of this macro is cached in the @code{ac_cv_f77_main} or
8353 @code{ac_cv_fc_main} variable, respectively.
8354 @end defmac
8356 @defmac AC_F77_WRAPPERS
8357 @defmacx AC_FC_WRAPPERS
8358 @acindex{F77_WRAPPERS}
8359 @cvindex F77_FUNC
8360 @cvindex F77_FUNC_
8361 @acindex{FC_WRAPPERS}
8362 @cvindex FC_FUNC
8363 @cvindex FC_FUNC_
8364 @caindex f77_mangling
8365 @caindex fc_mangling
8366 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8367 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8368 mangle the names of C/C++ identifiers, and identifiers with underscores,
8369 respectively, so that they match the name-mangling scheme used by the
8370 Fortran compiler.
8372 Fortran is case-insensitive, and in order to achieve this the Fortran
8373 compiler converts all identifiers into a canonical case and format.  To
8374 call a Fortran subroutine from C or to write a C function that is
8375 callable from Fortran, the C program must explicitly use identifiers in
8376 the format expected by the Fortran compiler.  In order to do this, one
8377 simply wraps all C identifiers in one of the macros provided by
8378 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
8379 you have the following Fortran 77 subroutine:
8381 @example
8382 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8383       subroutine foobar (x, y)
8384       double precision x, y
8385       y = 3.14159 * x
8386       return
8387       end
8388 @end example
8390 You would then declare its prototype in C or C++ as:
8392 @example
8393 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8394 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8395 #ifdef __cplusplus
8396 extern "C"  /* prevent C++ name mangling */
8397 #endif
8398 void FOOBAR_F77 (double *x, double *y);
8399 @end example
8401 Note that we pass both the lowercase and uppercase versions of the
8402 function name to @code{F77_FUNC} so that it can select the right one.
8403 Note also that all parameters to Fortran 77 routines are passed as
8404 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8405 Automake}).
8407 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8409 Although Autoconf tries to be intelligent about detecting the
8410 name-mangling scheme of the Fortran compiler, there may be Fortran
8411 compilers that it doesn't support yet.  In this case, the above code
8412 generates a compile-time error, but some other behavior
8413 (e.g., disabling Fortran-related features) can be induced by checking
8414 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8416 Now, to call that routine from a C program, we would do something like:
8418 @example
8419 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8421     double x = 2.7183, y;
8422     FOOBAR_F77 (&x, &y);
8424 @end example
8426 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8427 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8428 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
8429 because some Fortran compilers mangle names differently if they contain
8430 an underscore.
8432 The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8433 @code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8434 the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8435 @end defmac
8437 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8438 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8439 @acindex{F77_FUNC}
8440 @acindex{FC_FUNC}
8441 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8442 hold the mangled version @var{name} according to the rules of the
8443 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8444 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
8445 supplied, the shell variable is simply @var{name}.  The purpose of
8446 this macro is to give the caller a way to access the name-mangling
8447 information other than through the C preprocessor as above, for example,
8448 to call Fortran routines from some language other than C/C++.
8449 @end defmac
8451 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8452   @dvar{action-if-failure, AC_MSG_FAILURE})
8453 @defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8454   @dvar{action-if-failure, AC_MSG_FAILURE})
8455 @acindex{FC_SRCEXT}
8456 @acindex{FC_PP_SRCEXT}
8457 @caindex fc_srcext_@var{ext}
8458 @caindex fc_pp_srcext_@var{ext}
8459 By default, the @code{FC} macros perform their tests using a @file{.f}
8460 extension for source-code files.  Some compilers, however, only enable
8461 newer language features for appropriately named files, e.g., Fortran 90
8462 features only for @file{.f90} files, or preprocessing only with
8463 @file{.F} files or maybe other upper-case extensions.  On the other
8464 hand, some other compilers expect all source files to end in @file{.f}
8465 and require special flags to support other file name extensions.  The
8466 @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8467 issues.
8469 The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8470 accept files ending with the extension @file{.@var{ext}} (i.e.,
8471 @var{ext} does @emph{not} contain the dot).  If any special compiler
8472 flags are needed for this, it stores them in the output variable
8473 @code{FCFLAGS_@var{ext}}.  This extension and these flags are then used
8474 for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8475 @code{AC_FC_PP_SRCEXT} is called another time).
8477 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8478 @file{.f90} extension in future tests, and it would set the
8479 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8480 to compile such files.
8482 Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8483 compiler to preprocess and compile files with the extension
8484 @file{.@var{ext}}.  When both @command{fpp} and @command{cpp} style
8485 preprocessing are provided, the former is preferred, as the latter may
8486 treat continuation lines, @code{//} tokens, and white space differently
8487 from what some Fortran dialects expect.  Conversely, if you do not want
8488 files to be preprocessed, use only lower-case characters in the file
8489 name extension.  Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8490 are stored in the @code{FCFLAGS_@var{ext}} variable.
8492 The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8493 into @code{FCFLAGS}, for two reasons based on the limitations of some
8494 compilers.  First, only one @code{FCFLAGS_@var{ext}} can be used at a
8495 time, so files with different extensions must be compiled separately.
8496 Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8497 the source-code file name when compiling.  So, continuing the example
8498 above, you might compile a @file{foo.f90} file in your makefile with the
8499 command:
8501 @example
8502 foo.o: foo.f90
8503        $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8504 @end example
8506 If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8507 files with the @var{ext} extension, it calls @var{action-if-success}
8508 (defaults to nothing).  If it fails, and cannot find a way to make the
8509 @code{FC} compiler accept such files, it calls @var{action-if-failure}
8510 (defaults to exiting with an error message).
8512 The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8513 results in @code{ac_cv_fc_srcext_@var{ext}} and
8514 @code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8515 @end defmac
8517 @defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @
8518   @dvar{action-if-failure, AC_MSG_FAILURE})
8519 @acindex{FC_PP_DEFINE}
8520 @caindex fc_pp_define
8522 Find a flag to specify defines for preprocessed Fortran.  Not all
8523 Fortran compilers use @option{-D}.  Substitute @code{FC_DEFINE} with
8524 the result and call @var{action-if-success} (defaults to nothing) if
8525 successful, and @var{action-if-failure} (defaults to failing with an
8526 error message) if not.
8528 This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8529 preprocess a @file{conftest.F} file, but restores a previously used
8530 Fortran source file extension afterwards again.
8532 The result of this test is cached in the @code{ac_cv_fc_pp_define}
8533 variable.
8534 @end defmac
8536 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @
8537   @dvar{action-if-failure, AC_MSG_FAILURE})
8538 @acindex{FC_FREEFORM}
8539 @caindex fc_freeform
8541 Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8542 source code (as opposed to the older fixed-format style from Fortran
8543 77).  If necessary, it may add some additional flags to @code{FCFLAGS}.
8545 This macro is most important if you are using the default @file{.f}
8546 extension, since many compilers interpret this extension as indicating
8547 fixed-format source unless an additional flag is supplied.  If you
8548 specify a different extension with @code{AC_FC_SRCEXT}, such as
8549 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8550 modifying @code{FCFLAGS}.  For extensions which the compiler does not
8551 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8552 the compiler assume Fortran 77 by default, however.
8554 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8555 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8556 calls @var{action-if-failure} (defaults to exiting with an error
8557 message).
8559 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8560 the @code{ac_cv_fc_freeform} variable.
8561 @end defmac
8563 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @
8564   @dvar{action-if-failure, AC_MSG_FAILURE})
8565 @acindex{FC_FIXEDFORM}
8566 @caindex fc_fixedform
8568 Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8569 fixed-format source code (as opposed to free-format style).  If
8570 necessary, it may add some additional flags to @code{FCFLAGS}.
8572 This macro is needed for some compilers alias names like @command{xlf95}
8573 which assume free-form source code by default, and in case you want to
8574 use fixed-form source with an extension like @file{.f90} which many
8575 compilers interpret as free-form by default.  If you specify a different
8576 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8577 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8578 @code{FCFLAGS}.
8580 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8581 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8582 calls @var{action-if-failure} (defaults to exiting with an error
8583 message).
8585 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8586 the @code{ac_cv_fc_fixedform} variable.
8587 @end defmac
8589 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8590   @dvar{action-if-failure, AC_MSG_FAILURE})
8591 @acindex{FC_LINE_LENGTH}
8592 @caindex fc_line_length
8594 Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8595 code lines.  The @var{length} argument may be given as 80, 132, or
8596 unlimited, and defaults to 132.  Note that line lengths above 250
8597 columns are not portable, and some compilers do not accept more than 132
8598 columns at least for fixed format source.  If necessary, it may add some
8599 additional flags to @code{FCFLAGS}.
8601 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8602 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8603 calls @var{action-if-failure} (defaults to exiting with an error
8604 message).
8606 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8607 the @code{ac_cv_fc_line_length} variable.
8608 @end defmac
8610 @defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8611   @dvar{action-if-failure, AC_MSG_FAILURE})
8612 @acindex{FC_CHECK_BOUNDS}
8613 @caindex fc_check_bounds
8615 The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8616 in the Fortran compiler.  If successful, the @var{action-if-success}
8617 is called and any needed flags are added to @code{FCFLAGS}.  Otherwise,
8618 @var{action-if-failure} is called, which defaults to failing with an error
8619 message.  The macro currently requires Fortran 90 or a newer dialect.
8621 The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8622 variable.
8623 @end defmac
8625 @defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8626   @dvar{action-if-failure, AC_MSG_FAILURE})
8627 @defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8628   @dvar{action-if-failure, AC_MSG_FAILURE})
8629 @acindex{F77_IMPLICIT_NONE}
8630 @acindex{FC_IMPLICIT_NONE}
8631 @caindex f77_implicit_none
8632 @caindex fc_implicit_none
8634 Try to disallow implicit declarations in the Fortran compiler.  If
8635 successful, @var{action-if-success} is called and any needed flags
8636 are added to @code{FFLAGS} or @code{FCFLAGS}, respectively.  Otherwise,
8637 @var{action-if-failure} is called, which defaults to failing with an error
8638 message.
8640 The result of these macros are cached in the
8641 @code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8642 variables, respectively.
8643 @end defmac
8645 @defmac AC_FC_MODULE_EXTENSION
8646 @acindex{FC_MODULE_EXTENSION}
8647 @caindex fc_module_ext
8648 @ovindex FC_MODEXT
8650 Find the Fortran 90 module file name extension.  Most Fortran 90
8651 compilers store module information in files separate from the object
8652 files.  The module files are usually named after the name of the module
8653 rather than the source file name, with characters possibly turned to
8654 upper case, plus an extension, often @file{.mod}.
8656 Not all compilers use module files at all, or by default.  The Cray
8657 Fortran compiler requires @option{-e m} in order to store and search
8658 module information in @file{.mod} files rather than in object files.
8659 Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8660 indicate how module information is stored.
8662 The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8663 without the leading dot, and stores that in the @code{FC_MODEXT}
8664 variable.  If the compiler does not produce module files, or the
8665 extension cannot be determined, @code{FC_MODEXT} is empty.  Typically,
8666 the result of this macro may be used in cleanup @command{make} rules as
8667 follows:
8669 @example
8670 clean-modules:
8671         -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8672 @end example
8674 The extension, or @samp{unknown}, is cached in the
8675 @code{ac_cv_fc_module_ext} variable.
8676 @end defmac
8678 @defmac AC_FC_MODULE_FLAG (@ovar{action-if-success}, @
8679   @dvar{action-if-failure, AC_MSG_FAILURE})
8680 @acindex{FC_MODULE_FLAG}
8681 @caindex fc_module_flag
8682 @ovindex FC_MODINC
8683 @ovindex ac_empty
8685 Find the compiler flag to include Fortran 90 module information from
8686 another directory, and store that in the @code{FC_MODINC} variable.
8687 Call @var{action-if-success} (defaults to nothing) if successful, and
8688 set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8689 to exiting with an error message) if not.
8691 Most Fortran 90 compilers provide a way to specify module directories.
8692 Some have separate flags for the directory to write module files to,
8693 and directories to search them in, whereas others only allow writing to
8694 the current directory or to the first directory specified in the include
8695 path.  Further, with some compilers, the module search path and the
8696 preprocessor search path can only be modified with the same flag.  Thus,
8697 for portability, write module files to the current directory only and
8698 list that as first directory in the search path.
8700 There may be no whitespace between @code{FC_MODINC} and the following
8701 directory name, but @code{FC_MODINC} may contain trailing white space.
8702 For example, if you use Automake and would like to search @file{../lib}
8703 for module files, you can use the following:
8705 @example
8706 AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8707 @end example
8709 Inside @command{configure} tests, you can use:
8711 @example
8712 if test -n "$FC_MODINC"; then
8713   FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8715 @end example
8717 The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8718 The substituted value of @code{FC_MODINC} may refer to the
8719 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8720 the significant trailing whitespace in a @file{Makefile}.
8721 @end defmac
8723 @defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-success}, @
8724   @dvar{action-if-failure, AC_MSG_FAILURE})
8725 @acindex{FC_MODULE_OUTPUT_FLAG}
8726 @caindex fc_module_output_flag
8727 @ovindex FC_MODOUT
8729 Find the compiler flag to write Fortran 90 module information to
8730 another directory, and store that in the @code{FC_MODOUT} variable.
8731 Call @var{action-if-success} (defaults to nothing) if successful, and
8732 set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8733 to exiting with an error message) if not.
8735 Not all Fortran 90 compilers write module files, and of those that do,
8736 not all allow writing to a directory other than the current one, nor
8737 do all have separate flags for writing and reading; see the description
8738 of @code{AC_FC_MODULE_FLAG} above.  If you need to be able to write to
8739 another directory, for maximum portability use @code{FC_MODOUT} before
8740 any @code{FC_MODINC} and include both the current directory and the one
8741 you write to in the search path:
8743 @example
8744 AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8745 @end example
8747 The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8748 The substituted value of @code{FC_MODOUT} may refer to the
8749 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8750 the significant trailing whitespace in a @file{Makefile}.
8751 @end defmac
8753 @defmac AC_F77_CRAY_POINTERS (@ovar{action-if-success}, @
8754   @dvar{action-if-failure, AC_MSG_FAILURE})
8755 @defmacx AC_FC_CRAY_POINTERS (@ovar{action-if-success}, @
8756   @dvar{action-if-failure, AC_MSG_FAILURE})
8757 @acindex{F77_CRAY_POINTERS}
8758 @acindex{FC_CRAY_POINTERS}
8759 @caindex fc_cray_pointer
8761 Try to ensure that the Fortran compiler (@code{$F77} or @code{$FC})
8762 accepts Cray pointers.  If successful, the @var{action-if-success} is
8763 called and any needed flags are added to @code{FFLAGS} or
8764 @code{FCFLAGS}.  Otherwise, @var{action-if-failure} is called, which
8765 defaults to failing with an error message.
8767 Cray pointers are a non-standard extension supported by many Fortran
8768 compilers which allow an integer to be declared as C-like pointer to
8769 a target variable.
8771 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8772 the @code{ac_cv_f77_cray_ptr} or @code{ac_cv_fc_cray_ptr} variable.
8773 @end defmac
8776 @node Go Compiler
8777 @subsection Go Compiler Characteristics
8778 @cindex Go
8780 Autoconf provides basic support for the Go programming language when
8781 using the @code{gccgo} compiler (there is currently no support for the
8782 @code{6g} and @code{8g} compilers).
8784 @defmac AC_PROG_GO (@ovar{compiler-search-list})
8785 Find the Go compiler to use.  Check whether the environment variable
8786 @code{GOC} is set; if so, then set output variable @code{GOC} to its
8787 value.
8789 Otherwise, if the macro is invoked without an argument, then search for
8790 a Go compiler named @code{gccgo}.  If it is not found, then as a last
8791 resort set @code{GOC} to @code{gccgo}.
8793 This macro may be invoked with an optional first argument which, if
8794 specified, must be a blank-separated list of Go compilers to search for.
8796 If output variable @code{GOFLAGS} was not already set, set it to
8797 @option{-g -O2}.  If your package does not like this default,
8798 @code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8799 @end defmac
8802 @node System Services
8803 @section System Services
8805 The following macros check for operating system services or capabilities.
8807 @anchor{AC_PATH_X}
8808 @defmac AC_PATH_X
8809 @acindex{PATH_X}
8810 @evindex XMKMF
8811 @cindex X Window System
8812 Try to locate the X Window System include files and libraries.  If the
8813 user gave the command line options @option{--x-includes=@var{dir}} and
8814 @option{--x-libraries=@var{dir}}, use those directories.
8816 If either or both were not given, get the missing values by running
8817 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8818 environment variable) on a trivial @file{Imakefile} and examining the
8819 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8820 disables this method.
8822 If this method fails to find the X Window System, @command{configure}
8823 looks for the files in several directories where they often reside.
8824 If either method is successful, set the shell variables
8825 @code{x_includes} and @code{x_libraries} to their locations, unless they
8826 are in directories the compiler searches by default.
8828 If both methods fail, or the user gave the command line option
8829 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8830 otherwise set it to the empty string.
8831 @end defmac
8833 @anchor{AC_PATH_XTRA}
8834 @defmac AC_PATH_XTRA
8835 @acindex{PATH_XTRA}
8836 @ovindex X_CFLAGS
8837 @ovindex X_LIBS
8838 @ovindex X_EXTRA_LIBS
8839 @ovindex X_PRE_LIBS
8840 @cvindex X_DISPLAY_MISSING
8841 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8842 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8843 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8844 available.
8846 This macro also checks for special libraries that some systems need in
8847 order to compile X programs.  It adds any that the system needs to
8848 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8849 libraries that need to be linked with before @option{-lX11}, and adds
8850 any found to the output variable @code{X_PRE_LIBS}.
8852 @c This is an incomplete kludge.  Make a real way to do it.
8853 @c If you need to check for other X functions or libraries yourself, then
8854 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8855 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8856 @end defmac
8858 @anchor{AC_SYS_INTERPRETER}
8859 @defmac AC_SYS_INTERPRETER
8860 @acindex{SYS_INTERPRETER}
8861 Check whether the system supports starting scripts with a line of the
8862 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8863 After running this macro, shell code in @file{configure.ac} can check
8864 the shell variable @code{interpval}; it is set to @samp{yes}
8865 if the system supports @samp{#!}, @samp{no} if not.
8866 @end defmac
8868 @defmac AC_SYS_LARGEFILE
8869 @acindex{SYS_LARGEFILE}
8870 @cvindex _FILE_OFFSET_BITS
8871 @cvindex _LARGE_FILES
8872 @ovindex CC
8873 @cindex Large file support
8874 @cindex LFS
8875 Arrange for 64-bit file offsets, known as
8876 @uref{http://@/www.unix.org/@/version2/@/whatsnew/@/lfs20mar.html,
8877 large-file support}.  On some hosts, one must use special compiler
8878 options to build programs that can access large files.  Append any such
8879 options to the output variable @code{CC}.  Define
8880 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8882 Large-file support can be disabled by configuring with the
8883 @option{--disable-largefile} option.
8885 If you use this macro, check that your program works even when
8886 @code{off_t} is wider than @code{long int}, since this is common when
8887 large-file support is enabled.  For example, it is not correct to print
8888 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8889 (long int) X)}.  Also, when using this macro in concert with
8890 @code{AC_CONFIG_HEADERS}, be sure that @file{config.h} is included
8891 before any system header.
8893 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8894 replace their C counterparts @code{fseek} and @code{ftell} that do not
8895 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8896 prototypes available when using them and large-file support is
8897 enabled.
8898 @end defmac
8900 @anchor{AC_SYS_LONG_FILE_NAMES}
8901 @defmac AC_SYS_LONG_FILE_NAMES
8902 @acindex{SYS_LONG_FILE_NAMES}
8903 @cvindex HAVE_LONG_FILE_NAMES
8904 If the system supports file names longer than 14 characters, define
8905 @code{HAVE_LONG_FILE_NAMES}.
8906 @end defmac
8908 @defmac AC_SYS_POSIX_TERMIOS
8909 @acindex{SYS_POSIX_TERMIOS}
8910 @cindex Posix termios headers
8911 @cindex termios Posix headers
8912 @caindex sys_posix_termios
8913 Check to see if the Posix termios headers and functions are available on the
8914 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8915 @samp{yes}.  If not, set the variable to @samp{no}.
8916 @end defmac
8918 @node C and Posix Variants
8919 @section C and Posix Variants
8921 The following macro makes it possible to use C language and library
8922 extensions defined by the C standards committee, features of Posix that
8923 are extensions to C, and platform extensions not defined by Posix.
8925 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8926 @defmac AC_USE_SYSTEM_EXTENSIONS
8927 @acindex{USE_SYSTEM_EXTENSIONS}
8928 If possible, enable extensions to C or Posix on hosts that normally
8929 disable the extensions, typically due to standards-conformance namespace
8930 issues.  This should be called before any macros that run the C
8931 compiler.  Also, when using this macro in concert with
8932 @code{AC_CONFIG_HEADERS}, be sure that @file{config.h} is included
8933 before any system header.
8935 The following preprocessor macros are defined unconditionally:
8937 @table @code
8938 @item _ALL_SOURCE
8939 @cvindex _ALL_SOURCE
8940 Enable extensions on AIX 3 and Interix.
8941 @item _DARWIN_C_SOURCE
8942 @cvindex _DARWIN_C_SOURCE
8943 Enable extensions on macOS.
8944 @item _GNU_SOURCE
8945 @cvindex _GNU_SOURCE
8946 Enable extensions on GNU systems.
8947 @item _NETBSD_SOURCE
8948 @cvindex _NETBSD_SOURCE
8949 Enable general extensions on NetBSD.
8950 Enable NetBSD compatibility extensions on Minix.
8951 @item _OPENBSD_SOURCE
8952 @cvindex _OPENBSD_SOURCE
8953 Enable OpenBSD compatibility extensions on NetBSD.
8954 Oddly enough, this does nothing on OpenBSD.
8955 @item _POSIX_PTHREAD_SEMANTICS
8956 @cvindex _POSIX_PTHREAD_SEMANTICS
8957 Enable Posix-compatible threading on Solaris.
8958 @item __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8959 @cvindex __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8960 Enable extensions specified by ISO/IEC TS 18661-5:2014.
8961 @item __STDC_WANT_IEC_60559_BFP_EXT__
8962 @cvindex __STDC_WANT_IEC_60559_BFP_EXT__
8963 Enable extensions specified by ISO/IEC TS 18661-1:2014.
8964 @item __STDC_WANT_IEC_60559_DFP_EXT__
8965 @cvindex __STDC_WANT_IEC_60559_DFP_EXT__
8966 Enable extensions specified by ISO/IEC TS 18661-2:2015.
8967 @item __STDC_WANT_IEC_60559_FUNCS_EXT__
8968 @cvindex __STDC_WANT_IEC_60559_FUNCS_EXT__
8969 Enable extensions specified by ISO/IEC TS 18661-4:2015.
8970 @item __STDC_WANT_IEC_60559_TYPES_EXT__
8971 @cvindex __STDC_WANT_IEC_60559_TYPES_EXT__
8972 Enable extensions specified by ISO/IEC TS 18661-3:2015.
8973 @item __STDC_WANT_LIB_EXT2__
8974 @cvindex __STDC_WANT_LIB_EXT2__
8975 Enable extensions specified by ISO/IEC TR 24731-2:2010.
8976 @item __STDC_WANT_MATH_SPEC_FUNCS__
8977 @cvindex __STDC_WANT_MATH_SPEC_FUNCS__
8978 Enable extensions specified by ISO/IEC 24747:2009.
8979 @item _TANDEM_SOURCE
8980 @cvindex _TANDEM_SOURCE
8981 Enable extensions on HP NonStop systems.
8982 @end table
8984 The following preprocessor macros are defined only when necessary;
8985 they enable access to extensions on some operating systems but
8986 @emph{disable} extensions on other operating systems.
8988 @table @code
8989 @item __EXTENSIONS__
8990 @cvindex __EXTENSIONS__
8991 Enable general extensions on Solaris.  This macro is defined only if
8992 the headers included by @code{AC_INCLUDES_DEFAULT}
8993 (@pxref{Default Includes}) work correctly with it defined.
8995 @item _MINIX
8996 @itemx _POSIX_SOURCE
8997 @itemx _POSIX_1_SOURCE
8998 @cvindex _MINIX
8999 @cvindex _POSIX_SOURCE
9000 @cvindex _POSIX_1_SOURCE
9001 Defined only on MINIX.  @code{_POSIX_SOURCE} and @code{_POSIX_1_SOURCE}
9002 are needed to enable a number of POSIX features on this OS.
9003 @code{_MINIX} does not affect the system headers' behavior;
9004 future versions of Autoconf may stop defining it.
9005 Programs that need to recognize Minix should use @code{AC_CANONICAL_HOST}.
9007 @item _XOPEN_SOURCE
9008 @cvindex _XOPEN_SOURCE
9009 Defined (with value 500) only if needed to make @file{wchar.h} declare
9010 @code{mbstate_t}.  This is known to be necessary on some versions of HP/UX.
9011 @end table
9013 @cvindex __STDC_WANT_DEC_FP__
9014 The C preprocessor macro @code{__STDC_WANT_DEC_FP__} is not defined.
9015 ISO/IEC TR 24732:2009 was superseded by ISO/IEC TS 18661-2:2015.
9017 @cvindex __STDC_WANT_LIB_EXT1__
9018 The C preprocessor macro @code{__STDC_WANT_LIB_EXT1__} is not defined,
9019 as C11 Annex K is problematic.  See: O'Donell C, Sebor M.
9020 @uref{http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm, Field
9021 Experience With Annex K---Bounds Checking Interfaces}.
9023 The Autoconf macro @code{AC_USE_SYSTEM_EXTENSIONS} was introduced in
9024 Autoconf 2.60.
9025 @end defmac
9028 @node Erlang Libraries
9029 @section Erlang Libraries
9030 @cindex Erlang, Library, checking
9032 The following macros check for an installation of Erlang/OTP, and for the
9033 presence of certain Erlang libraries.  All those macros require the
9034 configuration of an Erlang interpreter and an Erlang compiler
9035 (@pxref{Erlang Compiler and Interpreter}).
9037 @defmac AC_ERLANG_SUBST_ERTS_VER
9038 @acindex{ERLANG_SUBST_ERTS_VER}
9039 @ovindex ERLANG_ERTS_VER
9040 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
9041 Erlang runtime system (as returned by Erlang's
9042 @code{erlang:system_info(version)} function).  The result of this test
9043 is cached if caching is enabled when running @command{configure}.  The
9044 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
9045 for features of specific ERTS versions, but to be used for substituting
9046 the ERTS version in Erlang/OTP release resource files (@code{.rel}
9047 files), as shown below.
9048 @end defmac
9050 @defmac AC_ERLANG_SUBST_ROOT_DIR
9051 @acindex{ERLANG_SUBST_ROOT_DIR}
9052 @ovindex ERLANG_ROOT_DIR
9053 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
9054 directory in which Erlang/OTP is installed (as returned by Erlang's
9055 @code{code:root_dir/0} function).  The result of this test is cached if
9056 caching is enabled when running @command{configure}.
9057 @end defmac
9059 @defmac AC_ERLANG_SUBST_LIB_DIR
9060 @acindex{ERLANG_SUBST_LIB_DIR}
9061 @ovindex ERLANG_LIB_DIR
9062 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
9063 directory of Erlang/OTP (as returned by Erlang's
9064 @code{code:lib_dir/0} function), which subdirectories each contain an installed
9065 Erlang/OTP library.  The result of this test is cached if caching is enabled
9066 when running @command{configure}.
9067 @end defmac
9069 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
9070   @ovar{action-if-not-found})
9071 @acindex{ERLANG_CHECK_LIB}
9072 @ovindex ERLANG_LIB_DIR_@var{library}
9073 @ovindex ERLANG_LIB_VER_@var{library}
9074 Test whether the Erlang/OTP library @var{library} is installed by
9075 calling Erlang's @code{code:lib_dir/1} function.  The result of this
9076 test is cached if caching is enabled when running @command{configure}.
9077 @var{action-if-found} is a list of shell commands to run if the library
9078 is installed; @var{action-if-not-found} is a list of shell commands to
9079 run if it is not.  Additionally, if the library is installed, the output
9080 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
9081 library installation directory, and the output variable
9082 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
9083 part of the subdirectory name, if it is in the standard form
9084 (@code{@var{library}-@var{version}}).  If the directory name does not
9085 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
9086 empty string.  If the library is not installed,
9087 @samp{ERLANG_LIB_DIR_@var{library}} and
9088 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
9089 example, to check if library @code{stdlib} is installed:
9091 @example
9092 AC_ERLANG_CHECK_LIB([stdlib],
9093   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
9094    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
9095   [AC_MSG_ERROR([stdlib was not found!])])
9096 @end example
9098 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
9099 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
9100 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
9101 testing for features of specific versions of libraries or of the Erlang
9102 runtime system.  Those variables are intended to be substituted in
9103 Erlang release resource files (@code{.rel} files).  For instance, to
9104 generate a @file{example.rel} file for an application depending on the
9105 @code{stdlib} library, @file{configure.ac} could contain:
9107 @example
9108 AC_ERLANG_SUBST_ERTS_VER
9109 AC_ERLANG_CHECK_LIB([stdlib],
9110   [],
9111   [AC_MSG_ERROR([stdlib was not found!])])
9112 AC_CONFIG_FILES([example.rel])
9113 @end example
9115 @noindent
9116 The @file{example.rel.in} file used to generate @file{example.rel}
9117 should contain:
9119 @example
9120 @{release,
9121     @{"@@PACKAGE@@", "@@VERSION@@"@},
9122     @{erts, "@@ERLANG_ERTS_VER@@"@},
9123     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
9124      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
9125 @end example
9126 @end defmac
9128 In addition to the above macros, which test installed Erlang libraries, the
9129 following macros determine the paths to the directories into which newly built
9130 Erlang libraries are to be installed:
9132 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
9133 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
9134 @ovindex ERLANG_INSTALL_LIB_DIR
9136 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
9137 which every built Erlang library should be installed in a separate
9138 subdirectory.
9139 If this variable is not set in the environment when @command{configure} runs,
9140 its default value is @code{$@{libdir@}/erlang/lib}.
9141 @end defmac
9143 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
9144 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
9145 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
9147 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
9148 directory into which the built Erlang library @var{library} version
9149 @var{version} should be installed.  If this variable is not set in the
9150 environment when @command{configure} runs, its default value is
9151 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
9152 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
9153 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
9154 @end defmac
9160 @c ========================================================= Writing Tests
9162 @node Writing Tests
9163 @chapter Writing Tests
9165 If the existing feature tests don't do something you need, you have to
9166 write new ones.  These macros are the building blocks.  They provide
9167 ways for other macros to check whether various kinds of features are
9168 available and report the results.
9170 This chapter contains some suggestions and some of the reasons why the
9171 existing tests are written the way they are.  You can also learn a lot
9172 about how to write Autoconf tests by looking at the existing ones.  If
9173 something goes wrong in one or more of the Autoconf tests, this
9174 information can help you understand the assumptions behind them, which
9175 might help you figure out how to best solve the problem.
9177 These macros check the output of the compiler system of the current
9178 language (@pxref{Language Choice}).  They do not cache the results of
9179 their tests for future use (@pxref{Caching Results}), because they don't
9180 know enough about the information they are checking for to generate a
9181 cache variable name.  They also do not print any messages, for the same
9182 reason.  The checks for particular kinds of features call these macros
9183 and do cache their results and print messages about what they're
9184 checking for.
9186 When you write a feature test that could be applicable to more than one
9187 software package, the best thing to do is encapsulate it in a new macro.
9188 @xref{Writing Autoconf Macros}, for how to do that.
9190 @menu
9191 * Language Choice::             Selecting which language to use for testing
9192 * Writing Test Programs::       Forging source files for compilers
9193 * Running the Preprocessor::    Detecting preprocessor symbols
9194 * Running the Compiler::        Detecting language or header features
9195 * Running the Linker::          Detecting library features
9196 * Runtime::                     Testing for runtime features
9197 * Systemology::                 A zoology of operating systems
9198 * Multiple Cases::              Tests for several possible values
9199 @end menu
9201 @node Language Choice
9202 @section Language Choice
9203 @cindex Language
9205 Autoconf-generated @command{configure} scripts check for the C compiler and
9206 its features by default.  Packages that use other programming languages
9207 (maybe more than one, e.g., C and C++) need to test features of the
9208 compilers for the respective languages.  The following macros determine
9209 which programming language is used in the subsequent tests in
9210 @file{configure.ac}.
9212 @anchor{AC_LANG}
9213 @defmac AC_LANG (@var{language})
9214 @acindex{LANG}
9215 Do compilation tests using the compiler, preprocessor, and file
9216 extensions for the specified @var{language}.
9218 Supported languages are:
9220 @table @samp
9221 @item C
9222 Do compilation tests using @code{CC} and @code{CPP} and use extension
9223 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
9224 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
9226 @item C++
9227 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
9228 extension @file{.C} for test programs.  Use compilation flags:
9229 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
9230 @code{CXXFLAGS} with @code{CXX}.
9232 @item Fortran 77
9233 Do compilation tests using @code{F77} and use extension @file{.f} for
9234 test programs.  Use compilation flags: @code{FFLAGS}.
9236 @item Fortran
9237 Do compilation tests using @code{FC} and use extension @file{.f} (or
9238 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
9239 compilation flags: @code{FCFLAGS}.
9241 @item Erlang
9242 @ovindex ERLC
9243 @ovindex ERL
9244 @ovindex ERLCFLAGS
9245 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
9246 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
9248 @item Objective C
9249 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
9250 extension @file{.m} for test programs.  Use compilation flags:
9251 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
9252 @code{OBJCFLAGS} with @code{OBJC}.
9254 @item Objective C++
9255 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
9256 extension @file{.mm} for test programs.  Use compilation flags:
9257 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
9258 @code{OBJCXXFLAGS} with @code{OBJCXX}.
9260 @item Go
9261 Do compilation tests using @code{GOC} and use extension @file{.go} for
9262 test programs.  Use compilation flags @code{GOFLAGS}.
9263 @end table
9264 @end defmac
9266 @anchor{AC_LANG_PUSH}
9267 @defmac AC_LANG_PUSH (@var{language})
9268 @acindex{LANG_PUSH}
9269 Remember the current language (as set by @code{AC_LANG}) on a stack, and
9270 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
9271 in macros that need to temporarily switch to a particular language.
9272 @end defmac
9274 @defmac AC_LANG_POP (@ovar{language})
9275 @acindex{LANG_POP}
9276 Select the language that is saved on the top of the stack, as set by
9277 @code{AC_LANG_PUSH}, and remove it from the stack.
9279 If given, @var{language} specifies the language we just @emph{quit}.  It
9280 is a good idea to specify it when it's known (which should be the
9281 case@dots{}), since Autoconf detects inconsistencies.
9283 @example
9284 AC_LANG_PUSH([Fortran 77])
9285 # Perform some tests on Fortran 77.
9286 # @dots{}
9287 AC_LANG_POP([Fortran 77])
9288 @end example
9289 @end defmac
9291 @defmac AC_LANG_ASSERT (@var{language})
9292 @acindex{LANG_ASSERT}
9293 Check statically that the current language is @var{language}.
9294 You should use this in your language specific macros
9295 to avoid that they be called with an inappropriate language.
9297 This macro runs only at @command{autoconf} time, and incurs no cost at
9298 @command{configure} time.  Sadly enough and because Autoconf is a two
9299 layer language @footnote{Because M4 is not aware of Sh code,
9300 especially conditionals, some optimizations that look nice statically
9301 may produce incorrect results at runtime.}, the macros
9302 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
9303 therefore as much as possible you ought to avoid using them to wrap
9304 your code, rather, require from the user to run the macro with a
9305 correct current language, and check it with @code{AC_LANG_ASSERT}.
9306 And anyway, that may help the user understand she is running a Fortran
9307 macro while expecting a result about her Fortran 77 compiler@enddots{}
9308 @end defmac
9311 @defmac AC_REQUIRE_CPP
9312 @acindex{REQUIRE_CPP}
9313 Ensure that whichever preprocessor would currently be used for tests has
9314 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
9315 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
9316 depending on which language is current.
9317 @end defmac
9320 @node Writing Test Programs
9321 @section Writing Test Programs
9323 Autoconf tests follow a common scheme: feed some program with some
9324 input, and most of the time, feed a compiler with some source file.
9325 This section is dedicated to these source samples.
9327 @menu
9328 * Guidelines::                  General rules for writing test programs
9329 * Test Functions::              Avoiding pitfalls in test programs
9330 * Generating Sources::          Source program boilerplate
9331 @end menu
9333 @node Guidelines
9334 @subsection Guidelines for Test Programs
9336 The most important rule to follow when writing testing samples is:
9338 @center @emph{Look for realism.}
9340 This motto means that testing samples must be written with the same
9341 strictness as real programs are written.  In particular, you should
9342 avoid ``shortcuts'' and simplifications.
9344 Don't just play with the preprocessor if you want to prepare a
9345 compilation.  For instance, using @command{cpp} to check whether a header is
9346 functional might let your @command{configure} accept a header which
9347 causes some @emph{compiler} error.  Do not hesitate to check a header with
9348 other headers included before, especially required headers.
9350 Make sure the symbols you use are properly defined, i.e., refrain from
9351 simply declaring a function yourself instead of including the proper
9352 header.
9354 Test programs should not write to standard output.  They
9355 should exit with status 0 if the test succeeds, and with status 1
9356 otherwise, so that success
9357 can be distinguished easily from a core dump or other failure;
9358 segmentation violations and other failures produce a nonzero exit
9359 status.  Unless you arrange for @code{exit} to be declared, test
9360 programs should @code{return}, not @code{exit}, from @code{main},
9361 because on many systems @code{exit} is not declared by default.
9363 Test programs can use @code{#if} or @code{#ifdef} to check the values of
9364 preprocessor macros defined by tests that have already run.  For
9365 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9366 @file{configure.ac} you can have a test program that includes
9367 @file{stdbool.h} conditionally:
9369 @example
9370 @group
9371 #ifdef HAVE_STDBOOL_H
9372 # include <stdbool.h>
9373 #endif
9374 @end group
9375 @end example
9377 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9378 work with any standard C compiler.  Some developers prefer @code{#if}
9379 because it is easier to read, while others prefer @code{#ifdef} because
9380 it avoids diagnostics with picky compilers like GCC with the
9381 @option{-Wundef} option.
9383 If a test program needs to use or create a data file, give it a name
9384 that starts with @file{conftest}, such as @file{conftest.data}.  The
9385 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
9386 after running test programs and if the script is interrupted.
9388 @node Test Functions
9389 @subsection Test Functions
9391 These days it's safe to assume support for function prototypes
9392 (introduced in C89).
9394 Functions that test programs declare should also be conditionalized for
9395 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
9396 include any header files containing clashing prototypes.
9398 @example
9399 #ifdef __cplusplus
9400 extern "C"
9401 #endif
9402 void *valloc (size_t);
9403 @end example
9405 If a test program calls a function with invalid parameters (just to see
9406 whether it exists), organize the program to ensure that it never invokes
9407 that function.  You can do this by calling it in another function that is
9408 never invoked.  You can't do it by putting it after a call to
9409 @code{exit}, because GCC version 2 knows that @code{exit}
9410 never returns
9411 and optimizes out any code that follows it in the same block.
9413 If you include any header files, be sure to call the functions
9414 relevant to them with the correct number of arguments, even if they are
9415 just 0, to avoid compilation errors due to prototypes.  GCC
9416 version 2
9417 has internal prototypes for several functions that it automatically
9418 inlines; for example, @code{memcpy}.  To avoid errors when checking for
9419 them, either pass them the correct number of arguments or redeclare them
9420 with a different return type (such as @code{char}).
9423 @node Generating Sources
9424 @subsection Generating Sources
9426 Autoconf provides a set of macros that can be used to generate test
9427 source files.  They are written to be language generic, i.e., they
9428 actually depend on the current language (@pxref{Language Choice}) to
9429 ``format'' the output properly.
9432 @defmac AC_LANG_CONFTEST (@var{source})
9433 @acindex{LANG_CONFTEST}
9434 Save the @var{source} text in the current test source file:
9435 @file{conftest.@var{extension}} where the @var{extension} depends on the
9436 current language.  As of Autoconf 2.63b, the source file also contains
9437 the results of all of the @code{AC_DEFINE} performed so far.
9439 Note that the @var{source} is evaluated exactly once, like regular
9440 Autoconf macro arguments, and therefore (i) you may pass a macro
9441 invocation, (ii) if not, be sure to double quote if needed.
9443 The @var{source} text is expanded as an unquoted here-document, so
9444 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9445 @xref{Here-Documents}.
9447 This macro issues a warning during @command{autoconf} processing if
9448 @var{source} does not include an expansion of the macro
9449 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9450 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9452 This macro is seldom called directly, but is used under the hood by more
9453 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9454 @end defmac
9456 @defmac AC_LANG_DEFINES_PROVIDED
9457 @acindex{LANG_DEFINES_PROVIDED}
9458 This macro is called as a witness that the file
9459 @file{conftest.@var{extension}} appropriate for the current language is
9460 complete, including all previously determined results from
9461 @code{AC_DEFINE}.  This macro is seldom called directly, but exists if
9462 you have a compelling reason to write a conftest file without using
9463 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9464 @code{AC_LANG_CONFTEST}.
9465 @end defmac
9467 @defmac AC_LANG_SOURCE (@var{source})
9468 @acindex{LANG_SOURCE}
9469 Expands into the @var{source}, with the definition of
9470 all the @code{AC_DEFINE} performed so far.  This macro includes an
9471 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9473 In many cases, you may find it more convenient to use the wrapper
9474 @code{AC_LANG_PROGRAM}.
9475 @end defmac
9477 For instance, executing (observe the double quotation!):
9479 @example
9480 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9481 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9482         [https://www.example.org/])
9483 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9484   [Greetings string.])
9485 AC_LANG([C])
9486 AC_LANG_CONFTEST(
9487    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9488 gcc -E -dD conftest.c
9489 @end example
9491 @noindent
9492 on a system with @command{gcc} installed, results in:
9494 @example
9495 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9496 @dots{}
9497 @asis{#} 1 "conftest.c"
9499 #define PACKAGE_NAME "Hello"
9500 #define PACKAGE_TARNAME "hello"
9501 #define PACKAGE_VERSION "1.0"
9502 #define PACKAGE_STRING "Hello 1.0"
9503 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9504 #define PACKAGE_URL "https://www.example.org/"
9505 #define HELLO_WORLD "Hello, World\n"
9507 const char hw[] = "Hello, World\n";
9508 @end example
9510 When the test language is Fortran, Erlang, or Go, the @code{AC_DEFINE}
9511 definitions are not automatically translated into constants in the
9512 source code by this macro.
9514 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
9515 @acindex{LANG_PROGRAM}
9516 Expands into a source file which consists of the @var{prologue}, and
9517 then @var{body} as body of the main function (e.g., @code{main} in
9518 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9519 available.
9520 @end defmac
9522 For instance:
9524 @example
9525 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9526 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9527         [https://www.example.org/])
9528 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9529   [Greetings string.])
9530 AC_LANG_CONFTEST(
9531 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9532                  [[fputs (hw, stdout);]])])
9533 gcc -E -dD conftest.c
9534 @end example
9536 @noindent
9537 on a system with @command{gcc} installed, results in:
9539 @example
9540 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9541 @dots{}
9542 @asis{#} 1 "conftest.c"
9544 #define PACKAGE_NAME "Hello"
9545 #define PACKAGE_TARNAME "hello"
9546 #define PACKAGE_VERSION "1.0"
9547 #define PACKAGE_STRING "Hello 1.0"
9548 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9549 #define PACKAGE_URL "https://www.example.org/"
9550 #define HELLO_WORLD "Hello, World\n"
9552 const char hw[] = "Hello, World\n";
9554 main (void)
9556 fputs (hw, stdout);
9557   ;
9558   return 0;
9560 @end example
9562 In Erlang tests, the created source file is that of an Erlang module called
9563 @code{conftest} (@file{conftest.erl}).  This module defines and exports
9564 at least
9565 one @code{start/0} function, which is called to perform the test.  The
9566 @var{prologue} is optional code that is inserted between the module header and
9567 the @code{start/0} function definition.  @var{body} is the body of the
9568 @code{start/0} function without the final period (@pxref{Runtime}, about
9569 constraints on this function's behavior).
9571 For instance:
9573 @example
9574 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9575 AC_LANG(Erlang)
9576 AC_LANG_CONFTEST(
9577 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9578                  [[io:format("~s~n", [?HELLO_WORLD])]])])
9579 cat conftest.erl
9580 @end example
9582 @noindent
9583 results in:
9585 @example
9586 -module(conftest).
9587 -export([start/0]).
9588 -define(HELLO_WORLD, "Hello, world!").
9589 start() ->
9590 io:format("~s~n", [?HELLO_WORLD])
9592 @end example
9594 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
9595 @acindex{LANG_CALL}
9596 Expands into a source file which consists of the @var{prologue}, and
9597 then a call to the @var{function} as body of the main function (e.g.,
9598 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
9599 of the latter are available.
9601 This function will probably be replaced in the future by a version
9602 which would enable specifying the arguments.  The use of this macro is
9603 not encouraged, as it violates strongly the typing system.
9605 This macro cannot be used for Erlang tests.
9606 @end defmac
9608 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9609 @acindex{LANG_FUNC_LINK_TRY}
9610 Expands into a source file which uses the @var{function} in the body of
9611 the main function (e.g., @code{main} in C).  Since it uses
9612 @code{AC_LANG_PROGRAM}, the features of the latter are available.
9614 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9615 It is considered to be severely broken, and in the future will be
9616 removed in favor of actual function calls (with properly typed
9617 arguments).
9619 This macro cannot be used for Erlang tests.
9620 @end defmac
9622 @node Running the Preprocessor
9623 @section Running the Preprocessor
9625 Sometimes one might need to run the preprocessor on some source file.
9626 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9627 your project, not merely run the preprocessor on it; therefore you
9628 certainly want to run the compiler, not the preprocessor.  Resist the
9629 temptation of following the easiest path.
9631 Nevertheless, if you need to run the preprocessor, then use
9632 @code{AC_PREPROC_IFELSE}.
9634 The macros described in this section cannot be used for tests in Erlang,
9635 Fortran, or Go, since those languages require no preprocessor.
9637 @anchor{AC_PREPROC_IFELSE}
9638 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9639   @ovar{action-if-false})
9640 @acindex{PREPROC_IFELSE}
9641 Run the preprocessor of the current language (@pxref{Language Choice})
9642 on the @var{input}, run the shell commands @var{action-if-true} on
9643 success, @var{action-if-false} otherwise.
9645 If @var{input} is nonempty use the equivalent of
9646 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9647 file; otherwise reuse the already-existing test source file.
9648 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9649 The @var{input} text is expanded as an unquoted here-document, so
9650 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9651 @xref{Here-Documents}.
9653 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9654 @option{-g}, @option{-O}, etc.@: are not valid options to many C
9655 preprocessors.
9657 It is customary to report unexpected failures with
9658 @code{AC_MSG_FAILURE}.  If needed, @var{action-if-true} can further access
9659 the preprocessed output in the file @file{conftest.i}.
9660 @end defmac
9662 For instance:
9664 @example
9665 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9666 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9667   [Greetings string.])
9668 AC_PREPROC_IFELSE(
9669    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9670                     [[fputs (hw, stdout);]])],
9671    [AC_MSG_RESULT([OK])],
9672    [AC_MSG_FAILURE([unexpected preprocessor failure])])
9673 @end example
9675 @noindent
9676 might result in:
9678 @example
9679 checking for gcc... gcc
9680 checking whether the C compiler works... yes
9681 checking for C compiler default output file name... a.out
9682 checking for suffix of executables...
9683 checking whether we are cross compiling... no
9684 checking for suffix of object files... o
9685 checking whether the compiler supports GNU C... yes
9686 checking whether gcc accepts -g... yes
9687 checking for gcc option to enable C11 features... -std=gnu11
9688 checking how to run the C preprocessor... gcc -std=gnu11 -E
9690 @end example
9692 @sp 1
9694 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9695 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9696 it impossible to use it to elaborate sources.  You are encouraged to
9697 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9698 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9699 to run the @emph{preprocessor} and not the compiler?
9701 @anchor{AC_EGREP_HEADER}
9702 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9703   @var{action-if-found}, @ovar{action-if-not-found})
9704 @acindex{EGREP_HEADER}
9705 If the output of running the preprocessor on the system header file
9706 @var{header-file} matches the extended regular expression
9707 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9708 execute @var{action-if-not-found}.
9710 See below for some problems involving this macro.
9711 @end defmac
9713 @anchor{AC_EGREP_CPP}
9714 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9715   @ovar{action-if-found}, @ovar{action-if-not-found})
9716 @acindex{EGREP_CPP}
9717 @var{program} is the text of a C or C++ program, which is expanded as an
9718 unquoted here-document (@pxref{Here-Documents}).  If the
9719 output of running the preprocessor on @var{program} matches the
9720 extended regular expression @var{pattern}, execute shell commands
9721 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9723 See below for some problems involving this macro.
9724 @end defmac
9726 @code{AC_EGREP_CPP} and @code{AC_EGREP_HEADER} should be used with care,
9727 as preprocessors can insert line breaks between output tokens.  For
9728 example, the preprocessor might transform this:
9730 @example
9731 #define MAJOR 2
9732 #define MINOR 23
9733 Version MAJOR . MINOR
9734 @end example
9736 @noindent
9737 into this:
9739 @example
9740 Version
9741        2
9742                  .
9743                    23
9744 @end example
9746 @noindent
9747 Because preprocessors are allowed to insert white space, change escapes
9748 in string contants, insert backlash-newline pairs, or do any of a number
9749 of things that do not change the meaning of the preprocessed program, it
9750 is better to rely on @code{AC_PREPROC_IFELSE} than to resort to
9751 @code{AC_EGREP_CPP} or @code{AC_EGREP_HEADER}.
9754 @node Running the Compiler
9755 @section Running the Compiler
9757 To check for a syntax feature of the current language's (@pxref{Language
9758 Choice}) compiler, such as whether it recognizes a certain keyword, or
9759 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9760 to compile a small program that uses that feature.
9762 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9763   @ovar{action-if-false})
9764 @acindex{COMPILE_IFELSE}
9765 Run the compiler and compilation flags of the current language
9766 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9767 @var{action-if-true} on success, @var{action-if-false} otherwise.
9769 If @var{input} is nonempty use the equivalent of
9770 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9771 file; otherwise reuse the already-existing test source file.
9772 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9773 The @var{input} text is expanded as an unquoted here-document, so
9774 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9775 @xref{Here-Documents}.
9777 It is customary to report unexpected failures with
9778 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
9779 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9780 Linker}).  If needed, @var{action-if-true} can further access the
9781 just-compiled object file @file{conftest.$OBJEXT}.
9783 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9784 current language, which means that if the compiler has not yet been
9785 determined, the compiler determination will be made prior to the body of
9786 the outermost @code{AC_DEFUN} macro that triggered this macro to
9787 expand (@pxref{Expanded Before Required}).
9788 @end defmac
9790 @ovindex ERL
9791 For tests in Erlang, the @var{input} must be the source code of a module named
9792 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9793 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
9794 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9795 to ensure that the Erlang module has the right name.
9797 @node Running the Linker
9798 @section Running the Linker
9800 To check for a library, a function, or a global variable, Autoconf
9801 @command{configure} scripts try to compile and link a small program that
9802 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
9803 @code{ar} on the C library to try to figure out which functions are
9804 available.  Trying to link with the function is usually a more reliable
9805 approach because it avoids dealing with the variations in the options
9806 and output formats of @code{nm} and @code{ar} and in the location of the
9807 standard libraries.  It also allows configuring for cross-compilation or
9808 checking a function's runtime behavior if needed.  On the other hand,
9809 it can be slower than scanning the libraries once, but accuracy is more
9810 important than speed.
9812 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9813 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
9814 to check for libraries (@pxref{Libraries}), by adding the library being
9815 checked for to @code{LIBS} temporarily and trying to link a small
9816 program.
9818 @anchor{AC_LINK_IFELSE}
9819 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9820   @ovar{action-if-false})
9821 @acindex{LINK_IFELSE}
9822 Run the compiler (and compilation flags) and the linker of the current
9823 language (@pxref{Language Choice}) on the @var{input}, run the shell
9824 commands @var{action-if-true} on success, @var{action-if-false}
9825 otherwise.  If needed, @var{action-if-true} can further access the
9826 just-linked program file @file{conftest$EXEEXT}.
9828 If @var{input} is nonempty use the equivalent of
9829 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9830 file; otherwise reuse the already-existing test source file.
9831 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9832 The @var{input} text is expanded as an unquoted here-document, so
9833 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9834 @xref{Here-Documents}.
9836 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9837 current compilation flags.
9839 It is customary to report unexpected failures with
9840 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
9841 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9842 @end defmac
9844 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9845 programs are interpreted and do not require linking.
9849 @node Runtime
9850 @section Checking Runtime Behavior
9852 Sometimes you need to find out how a system performs at runtime, such
9853 as whether a given function has a certain capability or bug.  If you
9854 can, make such checks when your program runs instead of when it is
9855 configured.  You can check for things like the machine's endianness when
9856 your program initializes itself.
9858 If you really need to test for a runtime behavior while configuring,
9859 you can write a test program to determine the result, and compile and
9860 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
9861 possible, because this prevents people from configuring your package for
9862 cross-compiling.
9864 @anchor{AC_RUN_IFELSE}
9865 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9866   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9867 @acindex{RUN_IFELSE}
9868 Run the compiler (and compilation flags) and the linker of the current
9869 language (@pxref{Language Choice}) on the @var{input}, then execute the
9870 resulting program.  If the program returns an exit
9871 status of 0 when executed, run shell commands @var{action-if-true}.
9872 Otherwise, run shell commands @var{action-if-false}.
9874 If @var{input} is nonempty use the equivalent of
9875 @code{AC_LANG_CONFTEST(@var{input})} to generate the current test source
9876 file; otherwise reuse the already-existing test source file.
9877 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9878 The @var{input} text is expanded as an unquoted here-document, so
9879 @samp{$}, @samp{`} and some @samp{\}s should be backslash-escaped.
9880 @xref{Here-Documents}.
9882 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9883 compilation flags of the current language (@pxref{Language Choice}).
9884 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9885 for further testing.
9887 In the @var{action-if-false} section, the failing exit status is
9888 available in the shell variable @samp{$?}.  This exit status might be
9889 that of a failed compilation, or it might be that of a failed program
9890 execution.
9892 If cross-compilation mode is enabled (this is the case if either the
9893 compiler being used does not produce executables that run on the system
9894 where @command{configure} is being run, or if the options @code{--build}
9895 and @code{--host} were both specified and their values are different),
9896 then the test program is
9897 not run.  If the optional shell commands @var{action-if-cross-compiling}
9898 are given, those commands are run instead; typically these commands
9899 provide pessimistic defaults that allow cross-compilation to work even
9900 if the guess was wrong.  If the fourth argument is empty or omitted, but
9901 cross-compilation is detected, then @command{configure} prints an error
9902 message and exits.  If you want your package to be useful in a
9903 cross-compilation scenario, you @emph{should} provide a non-empty
9904 @var{action-if-cross-compiling} clause, as well as wrap the
9905 @code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9906 (@pxref{Caching Results}) which allows the user to override the
9907 pessimistic default if needed.
9909 It is customary to report unexpected failures with
9910 @code{AC_MSG_FAILURE}.
9911 @end defmac
9913 @command{autoconf} prints a warning message when creating
9914 @command{configure} each time it encounters a call to
9915 @code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9916 given.  If you are not concerned about users configuring your package
9917 for cross-compilation, you may ignore the warning.  A few of the macros
9918 distributed with Autoconf produce this warning message; but if this is a
9919 problem for you, please report it as a bug, along with an appropriate
9920 pessimistic guess to use instead.
9922 To configure for cross-compiling you can also choose a value for those
9923 parameters based on the canonical system name (@pxref{Manual
9924 Configuration}).  Alternatively, set up a test results cache file with
9925 the correct values for the host system (@pxref{Caching Results}).
9927 @ovindex cross_compiling
9928 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9929 in other macros, including a few of the ones that come with Autoconf,
9930 you can test whether the shell variable @code{cross_compiling} is set to
9931 @samp{yes}, and then use an alternate method to get the results instead
9932 of calling the macros.
9934 It is also permissible to temporarily assign to @code{cross_compiling}
9935 in order to force tests to behave as though they are in a
9936 cross-compilation environment, particularly since this provides a way to
9937 test your @var{action-if-cross-compiling} even when you are not using a
9938 cross-compiler.
9940 @example
9941 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9942 # to use the slow link-only method
9943 save_cross_compiling=$cross_compiling
9944 cross_compiling=yes
9945 AC_COMPUTE_INT([@dots{}])
9946 cross_compiling=$save_cross_compiling
9947 @end example
9949 A C or C++ runtime test should be portable.
9950 @xref{Portable C and C++}.
9952 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9953 function: the given status code is used to determine the success of the test
9954 (status is @code{0}) or its failure (status is different than @code{0}), as
9955 explained above.  It must be noted that data output through the standard output
9956 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9957 Therefore, if a test must output configuration information, it is recommended
9958 to create and to output data into the temporary file named @file{conftest.out},
9959 using the functions of module @code{file}.  The @code{conftest.out} file is
9960 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9961 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9962 macro is:
9964 @example
9965 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9966 AC_ERLANG_NEED_ERL
9967 AC_LANG(Erlang)
9968 AC_RUN_IFELSE(
9969   [AC_LANG_PROGRAM([], [dnl
9970     file:write_file("conftest.out", code:lib_dir()),
9971     halt(0)])],
9972   [echo "code:lib_dir() returned: `cat conftest.out`"],
9973   [AC_MSG_FAILURE([test Erlang program execution failed])])
9974 @end example
9977 @node Systemology
9978 @section Systemology
9979 @cindex Systemology
9981 This section aims at presenting some systems and pointers to
9982 documentation.  It may help you addressing particular problems reported
9983 by users.
9985 @uref{https://@/en.wikipedia.org/@/wiki/@/POSIX, Posix-conforming
9986 systems} are derived from the
9987 @uref{https://@/en.wikipedia.org/@/wiki/@/Unix, Unix operating system}.
9989 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9990 contains a table correlating the features of various Posix-conforming
9991 systems.  @uref{https://@/www.levenez.com/@/unix/, Unix History} is a
9992 simplified diagram of how many Unix systems were derived from each
9993 other.
9995 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9996 provides some variants of traditional implementations of Unix utilities.
9998 @table @asis
9999 @item Darwin
10000 @cindex Darwin
10001 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
10002 case-preserving, but case insensitive.  This can cause nasty problems,
10003 since for instance the installation attempt for a package having an
10004 @file{INSTALL} file can result in @samp{make install} report that
10005 nothing was to be done!
10007 That's all dependent on whether the file system is a UFS (case
10008 sensitive) or HFS+ (case preserving).  By default Apple wants you to
10009 install the OS on HFS+.  Unfortunately, there are some pieces of
10010 software which really need to be built on UFS@.  We may want to rebuild
10011 Darwin to have both UFS and HFS+ available (and put the /local/build
10012 tree on the UFS).
10014 @item QNX 4.25
10015 @cindex QNX 4.25
10016 @c FIXME: Please, if you feel like writing something more precise,
10017 @c it'd be great.  In particular, I can't understand the difference with
10018 @c QNX Neutrino.
10019 QNX is a realtime operating system running on Intel architecture
10020 meant to be scalable from the small embedded systems to the hundred
10021 processor super-computer.  It claims to be Posix certified.  More
10022 information is available on the
10023 @uref{https://@/blackberry.qnx.com/@/en, QNX home page}.
10025 @item Unix version 7
10026 @cindex Unix version 7
10027 @cindex V7
10028 Officially this was called the ``Seventh Edition'' of ``the UNIX
10029 time-sharing system'' but we use the more-common name ``Unix version 7''.
10030 Documentation is available in the
10031 @uref{https://@/s3.amazonaws.com/@/plan9-bell-labs/@/7thEdMan/@/index.html,
10032 Unix Seventh Edition Manual}.
10033 Previous versions of Unix are called ``Unix version 6'', etc., but
10034 they were not as widely used.
10035 @end table
10038 @node Multiple Cases
10039 @section Multiple Cases
10041 Some operations are accomplished in several possible ways, depending on
10042 the OS variant.  Checking for them essentially requires a ``case
10043 statement''.  Autoconf does not directly provide one; however, it is
10044 easy to simulate by using a shell variable to keep track of whether a
10045 way to perform the operation has been found yet.
10047 Here is an example that uses the shell variable @code{fstype} to keep
10048 track of whether the remaining cases need to be checked.  Note that
10049 since the value of @code{fstype} is under our control, we don't have to
10050 use the longer @samp{test "x$fstype" = xno}.
10052 @example
10053 @group
10054 AC_MSG_CHECKING([how to get file system type])
10055 fstype=no
10056 # The order of these tests is important.
10057 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
10058 #include <sys/fstyp.h>]])],
10059                   [AC_DEFINE([FSTYPE_STATVFS], [1],
10060                      [Define if statvfs exists.])
10061                    fstype=SVR4])
10062 if test $fstype = no; then
10063   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
10064 #include <sys/fstyp.h>]])],
10065                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
10066                      [Define if USG statfs.])
10067                    fstype=SVR3])
10069 if test $fstype = no; then
10070   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
10071 #include <sys/vmount.h>]])]),
10072                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
10073                      [Define if AIX statfs.])
10074                    fstype=AIX])
10076 # (more cases omitted here)
10077 AC_MSG_RESULT([$fstype])
10078 @end group
10079 @end example
10081 @c ====================================================== Results of Tests.
10083 @node Results
10084 @chapter Results of Tests
10086 Once @command{configure} has determined whether a feature exists, what can
10087 it do to record that information?  There are four sorts of things it can
10088 do: define a C preprocessor symbol, set a variable in the output files,
10089 save the result in a cache file for future @command{configure} runs, and
10090 print a message letting the user know the result of the test.
10092 @menu
10093 * Defining Symbols::            Defining C preprocessor symbols
10094 * Setting Output Variables::    Replacing variables in output files
10095 * Special Chars in Variables::  Characters to beware of in variables
10096 * Caching Results::             Speeding up subsequent @command{configure} runs
10097 * Printing Messages::           Notifying @command{configure} users
10098 @end menu
10100 @node Defining Symbols
10101 @section Defining C Preprocessor Symbols
10103 A common action to take in response to a feature test is to define a C
10104 preprocessor symbol indicating the results of the test.  That is done by
10105 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
10107 By default, @code{AC_OUTPUT} places the symbols defined by these macros
10108 into the output variable @code{DEFS}, which contains an option
10109 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
10110 Autoconf version 1, there is no variable @code{DEFS} defined while
10111 @command{configure} is running.  To check whether Autoconf macros have
10112 already defined a certain C preprocessor symbol, test the value of the
10113 appropriate cache variable, as in this example:
10115 @example
10116 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
10117                           [Define if vprintf exists.])])
10118 if test "x$ac_cv_func_vprintf" != xyes; then
10119   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
10120                             [Define if _doprnt exists.])])
10122 @end example
10124 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
10125 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
10126 correct values into @code{#define} statements in a template file.
10127 @xref{Configuration Headers}, for more information about this kind of
10128 output.
10130 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
10131 @defmacx AC_DEFINE (@var{variable})
10132 @cvindex @var{variable}
10133 @acindex{DEFINE}
10134 Define @var{variable} to @var{value} (verbatim), by defining a C
10135 preprocessor macro for @var{variable}.  @var{variable} should be a C
10136 identifier, optionally suffixed by a parenthesized argument list to
10137 define a C preprocessor macro with arguments.  The macro argument list,
10138 if present, should be a comma-separated list of C identifiers, possibly
10139 terminated by an ellipsis @samp{...} if C99-or-later syntax is employed.
10140 @var{variable} should not contain comments, white space, trigraphs,
10141 backslash-newlines, universal character names, or non-ASCII
10142 characters.
10144 @var{value} may contain backslash-escaped newlines, which will be
10145 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
10146 via @code{@@DEFS@@} (with no effect on the compilation, since the
10147 preprocessor sees only one line in the first place).  @var{value} should
10148 not contain raw newlines.  If you are not using
10149 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
10150 characters, as @command{make} tends to eat them.  To use a shell
10151 variable, use @code{AC_DEFINE_UNQUOTED} instead.
10153 @var{description} is only useful if you are using
10154 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
10155 the generated @file{config.h.in} as the comment before the macro define.
10156 The following example defines the C preprocessor variable
10157 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
10159 @example
10160 AC_DEFINE([EQUATION], ["$a > $b"],
10161   [Equation string.])
10162 @end example
10164 If neither @var{value} nor @var{description} are given, then
10165 @var{value} defaults to 1 instead of to the empty string.  This is for
10166 backwards compatibility with older versions of Autoconf, but this usage
10167 is obsolescent and may be withdrawn in future versions of Autoconf.
10169 If the @var{variable} is a literal string, it is passed to
10170 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
10172 If multiple @code{AC_DEFINE} statements are executed for the same
10173 @var{variable} name (not counting any parenthesized argument list),
10174 the last one wins.
10175 @end defmac
10177 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
10178 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
10179 @acindex{DEFINE_UNQUOTED}
10180 @cvindex @var{variable}
10181 Like @code{AC_DEFINE}, but three shell expansions are
10182 performed---once---on @var{variable} and @var{value}: variable expansion
10183 (@samp{$}), command substitution (@samp{`}), and backslash escaping
10184 (@samp{\}), as if in an unquoted here-document.  Single and double quote
10185 characters in the value have no
10186 special meaning.  Use this macro instead of @code{AC_DEFINE} when
10187 @var{variable} or @var{value} is a shell variable.  Examples:
10189 @example
10190 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
10191   [Configuration machine file.])
10192 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
10193   [getgroups return type.])
10194 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
10195   [Translated header name.])
10196 @end example
10197 @end defmac
10199 Due to a syntactical oddity of the Bourne shell, do not use
10200 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
10201 calls from other macro calls or shell code; that can cause syntax errors
10202 in the resulting @command{configure} script.  Use either blanks or
10203 newlines.  That is, do this:
10205 @example
10206 AC_CHECK_HEADER([elf.h],
10207   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
10208 @end example
10210 @noindent
10211 or this:
10213 @example
10214 AC_CHECK_HEADER([elf.h],
10215   [AC_DEFINE([SVR4], [1], [System V Release 4])
10216    LIBS="-lelf $LIBS"])
10217 @end example
10219 @noindent
10220 instead of this:
10222 @example
10223 AC_CHECK_HEADER([elf.h],
10224   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
10225 @end example
10227 @node Setting Output Variables
10228 @section Setting Output Variables
10229 @cindex Output variables
10231 Another way to record the results of tests is to set @dfn{output
10232 variables}, which are shell variables whose values are substituted into
10233 files that @command{configure} outputs.  The two macros below create new
10234 output variables.  @xref{Preset Output Variables}, for a list of output
10235 variables that are always available.
10237 @defmac AC_SUBST (@var{variable}, @ovar{value})
10238 @acindex{SUBST}
10239 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
10240 substitute the variable @var{variable} into output files (typically one
10241 or more makefiles).  This means that @code{AC_OUTPUT}
10242 replaces instances of @samp{@@@var{variable}@@} in input files with the
10243 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
10244 is called.  The value can contain any non-@code{NUL} character, including
10245 newline.  If you are using Automake 1.11 or newer, for newlines in values
10246 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
10247 @command{automake} from adding a line @code{@var{variable} =
10248 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
10249 Automake, automake, Other things Automake recognizes}).
10251 Variable occurrences should not overlap: e.g., an input file should
10252 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
10253 are variable names.
10254 The substituted value is not rescanned for more output variables;
10255 occurrences of @samp{@@@var{variable}@@} in the value are inserted
10256 literally into the output file.  (The algorithm uses the special marker
10257 @code{|#_!!_#|} internally, so neither the substituted value nor the
10258 output file may contain @code{|#_!!_#|}.)
10260 If @var{value} is given, in addition assign it to @var{variable}.
10262 The string @var{variable} is passed to @code{m4_pattern_allow}
10263 (@pxref{Forbidden Patterns}).  @var{variable} is not further expanded,
10264 even if there is another macro by the same name.
10265 @end defmac
10267 @defmac AC_SUBST_FILE (@var{variable})
10268 @acindex{SUBST_FILE}
10269 Another way to create an output variable from a shell variable.  Make
10270 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
10271 named by shell variable @var{variable} into output files.  This means
10272 that @code{AC_OUTPUT} replaces instances of
10273 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
10274 with the contents of the file that the shell variable @var{variable}
10275 names when @code{AC_OUTPUT} is called.  Set the variable to
10276 @file{/dev/null} for cases that do not have a file to insert.
10277 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
10278 line by itself, optionally surrounded by spaces and tabs.  The
10279 substitution replaces the whole line, including the spaces, tabs, and
10280 the terminating newline.
10282 This macro is useful for inserting makefile fragments containing
10283 special dependencies or other @command{make} directives for particular host
10284 or target types into makefiles.  For example, @file{configure.ac}
10285 could contain:
10287 @example
10288 AC_SUBST_FILE([host_frag])
10289 host_frag=$srcdir/conf/sun4.mh
10290 @end example
10292 @noindent
10293 and then a @file{Makefile.in} could contain:
10295 @example
10296 @@host_frag@@
10297 @end example
10299 The string @var{variable} is passed to @code{m4_pattern_allow}
10300 (@pxref{Forbidden Patterns}).
10301 @end defmac
10303 @cindex Precious Variable
10304 @cindex Variable, Precious
10305 Running @command{configure} in varying environments can be extremely
10306 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
10307 ./configure}, then the cache, @file{config.h}, and many other output
10308 files depend upon @command{bizarre-cc} being the C compiler.  If
10309 for some reason the user runs @command{./configure} again, or if it is
10310 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
10311 and @pxref{config.status Invocation}), then the configuration can be
10312 inconsistent, composed of results depending upon two different
10313 compilers.
10315 Environment variables that affect this situation, such as @samp{CC}
10316 above, are called @dfn{precious variables}, and can be declared as such
10317 by @code{AC_ARG_VAR}.
10319 @defmac AC_ARG_VAR (@var{variable}, @var{description})
10320 @acindex{ARG_VAR}
10321 Declare @var{variable} is a precious variable, and include its
10322 @var{description} in the variable section of @samp{./configure --help}.
10324 Being precious means that
10325 @itemize @minus
10326 @item
10327 @var{variable} is substituted via @code{AC_SUBST}.
10329 @item
10330 The value of @var{variable} when @command{configure} was launched is
10331 saved in the cache, including if it was not specified on the command
10332 line but via the environment.  Indeed, while @command{configure} can
10333 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
10334 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
10335 which, unfortunately, is what most users do.
10337 We emphasize that it is the @emph{initial} value of @var{variable} which
10338 is saved, not that found during the execution of @command{configure}.
10339 Indeed, specifying @samp{./configure FOO=foo} and letting
10340 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
10341 different things.
10343 @item
10344 @var{variable} is checked for consistency between two
10345 @command{configure} runs.  For instance:
10347 @example
10348 $ @kbd{./configure --silent --config-cache}
10349 $ @kbd{CC=cc ./configure --silent --config-cache}
10350 configure: error: 'CC' was not set in the previous run
10351 configure: error: changes in the environment can compromise \
10352 the build
10353 configure: error: run 'make distclean' and/or \
10354 'rm config.cache' and start over
10355 @end example
10357 @noindent
10358 and similarly if the variable is unset, or if its content is changed.
10359 If the content has white space changes only, then the error is degraded
10360 to a warning only, but the old value is reused.
10362 @item
10363 @var{variable} is kept during automatic reconfiguration
10364 (@pxref{config.status Invocation}) as if it had been passed as a command
10365 line argument, including when no cache is used:
10367 @example
10368 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
10369 $ @kbd{./config.status --recheck}
10370 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
10371   CC=/usr/bin/cc  --no-create --no-recursion
10372 @end example
10373 @end itemize
10374 @end defmac
10376 @node Special Chars in Variables
10377 @section Special Characters in Output Variables
10378 @cindex Output variables, special characters in
10380 Many output variables are intended to be evaluated both by
10381 @command{make} and by the shell.  Some characters are expanded
10382 differently in these two contexts, so to avoid confusion these
10383 variables' values should not contain any of the following characters:
10385 @example
10386 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
10387 @end example
10389 Also, these variables' values should neither contain newlines, nor start
10390 with @samp{~}, nor contain white space or @samp{:} immediately followed
10391 by @samp{~}.  The values can contain nonempty sequences of white space
10392 characters like tabs and spaces, but each such sequence might
10393 arbitrarily be replaced by a single space during substitution.
10395 These restrictions apply both to the values that @command{configure}
10396 computes, and to the values set directly by the user.  For example, the
10397 following invocations of @command{configure} are problematic, since they
10398 attempt to use special characters within @code{CPPFLAGS} and white space
10399 within @code{$(srcdir)}:
10401 @example
10402 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
10404 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
10405 @end example
10407 @node Caching Results
10408 @section Caching Results
10409 @cindex Cache
10411 To avoid checking for the same features repeatedly in various
10412 @command{configure} scripts (or in repeated runs of one script),
10413 @command{configure} can optionally save the results of many checks in a
10414 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
10415 runs with caching enabled and finds a cache file, it reads the results
10416 of previous runs from the cache and avoids rerunning those checks.  As a
10417 result, @command{configure} can then run much faster than if it had to
10418 perform all of the checks every time.
10420 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10421 @acindex{CACHE_VAL}
10422 Ensure that the results of the check identified by @var{cache-id} are
10423 available.  If the results of the check were in the cache file that was
10424 read, and @command{configure} was not given the @option{--quiet} or
10425 @option{--silent} option, print a message saying that the result was
10426 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
10427 the shell commands are run to determine the value, the value is
10428 saved in the cache file just before @command{configure} creates its output
10429 files.  @xref{Cache Variable Names}, for how to choose the name of the
10430 @var{cache-id} variable.
10432 The @var{commands-to-set-it} @emph{must have no side effects} except for
10433 setting the variable @var{cache-id}, see below.
10434 @end defmac
10436 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10437   @var{commands-to-set-it})
10438 @acindex{CACHE_CHECK}
10439 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10440 messages.  This macro provides a convenient shorthand for the most
10441 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
10442 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10443 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10445 The @var{commands-to-set-it} @emph{must have no side effects} except for
10446 setting the variable @var{cache-id}, see below.
10447 @end defmac
10449 It is common to find buggy macros using @code{AC_CACHE_VAL} or
10450 @code{AC_CACHE_CHECK}, because people are tempted to call
10451 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
10452 @emph{follows} the call to @code{AC_CACHE_VAL} should call
10453 @code{AC_DEFINE}, by examining the value of the cache variable.  For
10454 instance, the following macro is broken:
10456 @example
10457 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10458 @group
10459 AC_DEFUN([AC_SHELL_TRUE],
10460 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10461                 [my_cv_shell_true_works=no
10462                  (true) 2>/dev/null && my_cv_shell_true_works=yes
10463                  if test "x$my_cv_shell_true_works" = xyes; then
10464                    AC_DEFINE([TRUE_WORKS], [1],
10465                              [Define if 'true(1)' works properly.])
10466                  fi])
10468 @end group
10469 @end example
10471 @noindent
10472 This fails if the cache is enabled: the second time this macro is run,
10473 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
10476 @example
10477 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10478 @group
10479 AC_DEFUN([AC_SHELL_TRUE],
10480 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10481                 [my_cv_shell_true_works=no
10482                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
10483  if test "x$my_cv_shell_true_works" = xyes; then
10484    AC_DEFINE([TRUE_WORKS], [1],
10485              [Define if 'true(1)' works properly.])
10486  fi
10488 @end group
10489 @end example
10491 Also, @var{commands-to-set-it} should not print any messages, for
10492 example with @code{AC_MSG_CHECKING}; do that before calling
10493 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10494 the results of the check are retrieved from the cache or determined by
10495 running the shell commands.
10497 @menu
10498 * Cache Variable Names::        Shell variables used in caches
10499 * Cache Files::                 Files @command{configure} uses for caching
10500 * Cache Checkpointing::         Loading and saving the cache file
10501 @end menu
10503 @node Cache Variable Names
10504 @subsection Cache Variable Names
10505 @cindex Cache variable
10507 The names of cache variables should have the following format:
10509 @example
10510 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10511 @end example
10513 @noindent
10514 for example, @samp{ac_cv_header_stat_broken} or
10515 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
10517 @table @asis
10518 @item @var{package-prefix}
10519 An abbreviation for your package or organization; the same prefix you
10520 begin local Autoconf macros with, except lowercase by convention.
10521 For cache values used by the distributed Autoconf macros, this value is
10522 @samp{ac}.
10524 @item @code{_cv_}
10525 Indicates that this shell variable is a cache value.  This string
10526 @emph{must} be present in the variable name, including the leading
10527 underscore.
10529 @item @var{value-type}
10530 A convention for classifying cache values, to produce a rational naming
10531 system.  The values used in Autoconf are listed in @ref{Macro Names}.
10533 @item @var{specific-value}
10534 Which member of the class of cache values this test applies to.
10535 For example, which function (@samp{alloca}), program (@samp{gcc}), or
10536 output variable (@samp{INSTALL}).
10538 @item @var{additional-options}
10539 Any particular behavior of the specific member that this test applies to.
10540 For example, @samp{broken} or @samp{set}.  This part of the name may
10541 be omitted if it does not apply.
10542 @end table
10544 The values assigned to cache variables may not contain newlines.
10545 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10546 names of files or functions; so this is not an important restriction.
10547 @ref{Cache Variable Index} for an index of cache variables with
10548 documented semantics.
10551 @node Cache Files
10552 @subsection Cache Files
10554 A cache file is a shell script that caches the results of configure
10555 tests run on one system so they can be shared between configure scripts
10556 and configure runs.  It is not useful on other systems.  If its contents
10557 are invalid for some reason, the user may delete or edit it, or override
10558 documented cache variables on the @command{configure} command line.
10560 By default, @command{configure} uses no cache file,
10561 to avoid problems caused by accidental
10562 use of stale cache files.
10564 To enable caching, @command{configure} accepts @option{--config-cache} (or
10565 @option{-C}) to cache results in the file @file{config.cache}.
10566 Alternatively, @option{--cache-file=@var{file}} specifies that
10567 @var{file} be the cache file.  The cache file is created if it does not
10568 exist already.  When @command{configure} calls @command{configure} scripts in
10569 subdirectories, it uses the @option{--cache-file} argument so that they
10570 share the same cache.  @xref{Subdirectories}, for information on
10571 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10573 @file{config.status} only pays attention to the cache file if it is
10574 given the @option{--recheck} option, which makes it rerun
10575 @command{configure}.
10577 It is wrong to try to distribute cache files for particular system types.
10578 There is too much room for error in doing that, and too much
10579 administrative overhead in maintaining them.  For any features that
10580 can't be guessed automatically, use the standard method of the canonical
10581 system type and linking files (@pxref{Manual Configuration}).
10583 The site initialization script can specify a site-wide cache file to
10584 use, instead of the usual per-program cache.  In this case, the cache
10585 file gradually accumulates information whenever someone runs a new
10586 @command{configure} script.  (Running @command{configure} merges the new cache
10587 results with the existing cache file.)  This may cause problems,
10588 however, if the system configuration (e.g., the installed libraries or
10589 compilers) changes and the stale cache file is not deleted.
10591 If @command{configure} is interrupted at the right time when it updates
10592 a cache file outside of the build directory where the @command{configure}
10593 script is run, it may leave behind a temporary file named after the
10594 cache file with digits following it.  You may safely delete such a file.
10597 @node Cache Checkpointing
10598 @subsection Cache Checkpointing
10600 If your configure script, or a macro called from @file{configure.ac}, happens
10601 to abort the configure process, it may be useful to checkpoint the cache
10602 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
10603 reduces the amount of time it takes to rerun the configure script with
10604 (hopefully) the error that caused the previous abort corrected.
10606 @c FIXME: Do we really want to document this guy?
10607 @defmac AC_CACHE_LOAD
10608 @acindex{CACHE_LOAD}
10609 Loads values from existing cache file, or creates a new cache file if a
10610 cache file is not found.  Called automatically from @code{AC_INIT}.
10611 @end defmac
10613 @defmac AC_CACHE_SAVE
10614 @acindex{CACHE_SAVE}
10615 Flushes all cached values to the cache file.  Called automatically from
10616 @code{AC_OUTPUT}, but it can be quite useful to call
10617 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10618 @end defmac
10620 For instance:
10622 @example
10623 @r{ @dots{} AC_INIT, etc. @dots{}}
10624 @group
10625 # Checks for programs.
10626 AC_PROG_CC
10627 AC_PROG_AWK
10628 @r{ @dots{} more program checks @dots{}}
10629 AC_CACHE_SAVE
10630 @end group
10632 @group
10633 # Checks for libraries.
10634 AC_CHECK_LIB([nsl], [gethostbyname])
10635 AC_CHECK_LIB([socket], [connect])
10636 @r{ @dots{} more lib checks @dots{}}
10637 AC_CACHE_SAVE
10638 @end group
10640 @group
10641 # Might abort@dots{}
10642 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10643 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10644 @end group
10645 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
10646 @end example
10648 @node Printing Messages
10649 @section Printing Messages
10650 @cindex Messages, from @command{configure}
10652 @command{configure} scripts need to give users running them several kinds
10653 of information.  The following macros print messages in ways appropriate
10654 for each kind.  The arguments to all of them get enclosed in shell
10655 double quotes, so the shell performs variable and back-quote
10656 substitution on them.
10658 These macros are all wrappers around the @command{echo} shell command.
10659 They direct output to the appropriate file descriptor (@pxref{File
10660 Descriptor Macros}).
10661 @command{configure} scripts should rarely need to run @command{echo} directly
10662 to print messages for the user.  Using these macros makes it easy to
10663 change how and when each kind of message is printed; such changes need
10664 only be made to the macro definitions and all the callers change
10665 automatically.
10667 To diagnose static issues, i.e., when @command{autoconf} is run, see
10668 @ref{Diagnostic Macros}.
10670 @defmac AC_MSG_CHECKING (@var{feature-description})
10671 @acindex{MSG_CHECKING}
10672 Notify the user that @command{configure} is checking for a particular
10673 feature.  This macro prints a message that starts with @samp{checking }
10674 and ends with @samp{...} and no newline.  It must be followed by a call
10675 to @code{AC_MSG_RESULT} to print the result of the check and the
10676 newline.  The @var{feature-description} should be something like
10677 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10678 _Alignof}.
10680 This macro prints nothing if @command{configure} is run with the
10681 @option{--quiet} or @option{--silent} option.
10682 @end defmac
10684 @anchor{AC_MSG_RESULT}
10685 @defmac AC_MSG_RESULT (@var{result-description})
10686 @acindex{MSG_RESULT}
10687 Notify the user of the results of a check.  @var{result-description} is
10688 almost always the value of the cache variable for the check, typically
10689 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
10690 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10691 the completion of the message printed by the call to
10692 @code{AC_MSG_CHECKING}.
10694 This macro prints nothing if @command{configure} is run with the
10695 @option{--quiet} or @option{--silent} option.
10696 @end defmac
10698 @anchor{AC_MSG_NOTICE}
10699 @defmac AC_MSG_NOTICE (@var{message})
10700 @acindex{MSG_NOTICE}
10701 Deliver the @var{message} to the user.  It is useful mainly to print a
10702 general description of the overall purpose of a group of feature checks,
10703 e.g.,
10705 @example
10706 AC_MSG_NOTICE([checking if stack overflow is detectable])
10707 @end example
10709 This macro prints nothing if @command{configure} is run with the
10710 @option{--quiet} or @option{--silent} option.
10711 @end defmac
10713 @anchor{AC_MSG_ERROR}
10714 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10715 @acindex{MSG_ERROR}
10716 Notify the user of an error that prevents @command{configure} from
10717 completing.  This macro prints an error message to the standard error
10718 output and exits @command{configure} with @var{exit-status} (@samp{$?}
10719 by default, except that @samp{0} is converted to @samp{1}).
10720 @var{error-description} should be something like @samp{invalid value
10721 $HOME for \$HOME}.
10723 The @var{error-description} should start with a lower-case letter, and
10724 ``cannot'' is preferred to ``can't''.
10725 @end defmac
10727 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10728 @acindex{MSG_FAILURE}
10729 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10730 prevents @command{configure} from completing @emph{and} that additional
10731 details are provided in @file{config.log}.  This is typically used when
10732 abnormal results are found during a compilation.
10733 @end defmac
10735 @anchor{AC_MSG_WARN}
10736 @defmac AC_MSG_WARN (@var{problem-description})
10737 @acindex{MSG_WARN}
10738 Notify the @command{configure} user of a possible problem.  This macro
10739 prints the message to the standard error output; @command{configure}
10740 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10741 provide a default (back-up) behavior for the situations they warn about.
10742 @var{problem-description} should be something like @samp{ln -s seems to
10743 make hard links}.
10744 @end defmac
10748 @c ====================================================== Programming in M4.
10750 @node Programming in M4
10751 @chapter Programming in M4
10752 @cindex M4
10754 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10755 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10756 provides macros dedicated to shell script generation.
10758 As of this version of Autoconf, these two layers still contain
10759 experimental macros, whose interface might change in the future.  As a
10760 matter of fact, @emph{anything that is not documented must not be used}.
10762 @menu
10763 * M4 Quotation::                Protecting macros from unwanted expansion
10764 * Using autom4te::              The Autoconf executables backbone
10765 * Programming in M4sugar::      Convenient pure M4 macros
10766 * Debugging via autom4te::      Figuring out what M4 was doing
10767 @end menu
10769 @node M4 Quotation
10770 @section M4 Quotation
10771 @cindex M4 quotation
10772 @cindex quotation
10774 The most common problem with existing macros is an improper quotation.
10775 This section, which users of Autoconf can skip, but which macro writers
10776 @emph{must} read, first justifies the quotation scheme that was chosen
10777 for Autoconf and then ends with a rule of thumb.  Understanding the
10778 former helps one to follow the latter.
10780 @menu
10781 * Active Characters::           Characters that change the behavior of M4
10782 * One Macro Call::              Quotation and one macro call
10783 * Quoting and Parameters::      M4 vs. shell parameters
10784 * Quotation and Nested Macros::  Macros calling macros
10785 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
10786 * Quadrigraphs::                Another way to escape special characters
10787 * Balancing Parentheses::       Dealing with unbalanced parentheses
10788 * Quotation Rule Of Thumb::     One parenthesis, one quote
10789 @end menu
10791 @node Active Characters
10792 @subsection Active Characters
10794 To fully understand where proper quotation is important, you first need
10795 to know what the special characters are in Autoconf: @samp{#} introduces
10796 a comment inside which no macro expansion is performed, @samp{,}
10797 separates arguments, @samp{[} and @samp{]} are the quotes
10798 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10799 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10800 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10801 @samp{$} inside a macro definition.
10803 In order to understand the delicate case of macro calls, we first have
10804 to present some obvious failures.  Below they are ``obvious-ified'',
10805 but when you find them in real life, they are usually in disguise.
10807 Comments, introduced by a hash and running up to the newline, are opaque
10808 tokens to the top level: active characters are turned off, and there is
10809 no macro expansion:
10811 @example
10812 # define([def], ine)
10813 @result{}# define([def], ine)
10814 @end example
10816 Each time there can be a macro expansion, there is a quotation
10817 expansion, i.e., one level of quotes is stripped:
10819 @example
10820 int tab[10];
10821 @result{}int tab10;
10822 [int tab[10];]
10823 @result{}int tab[10];
10824 @end example
10826 Without this in mind, the reader might try hopelessly to use her macro
10827 @code{array}:
10829 @example
10830 define([array], [int tab[10];])
10831 array
10832 @result{}int tab10;
10833 [array]
10834 @result{}array
10835 @end example
10837 @noindent
10838 How can you correctly output the intended results@footnote{Using
10839 @code{defn}.}?
10842 @node One Macro Call
10843 @subsection One Macro Call
10845 Let's proceed on the interaction between active characters and macros
10846 with this small macro, which just returns its first argument:
10848 @example
10849 define([car], [$1])
10850 @end example
10852 @noindent
10853 The two pairs of quotes above are not part of the arguments of
10854 @code{define}; rather, they are understood by the top level when it
10855 tries to find the arguments of @code{define}.  Therefore, assuming
10856 @code{car} is not already defined, it is equivalent to write:
10858 @example
10859 define(car, $1)
10860 @end example
10862 @noindent
10863 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10864 quotes, it is bad practice for Autoconf macros which must both be more
10865 robust and also advocate perfect style.
10867 At the top level, there are only two possibilities: either you
10868 quote or you don't:
10870 @example
10871 car(foo, bar, baz)
10872 @result{}foo
10873 [car(foo, bar, baz)]
10874 @result{}car(foo, bar, baz)
10875 @end example
10877 Let's pay attention to the special characters:
10879 @example
10880 car(#)
10881 @error{}EOF in argument list
10882 @end example
10884 The closing parenthesis is hidden in the comment; with a hypothetical
10885 quoting, the top level understood it this way:
10887 @example
10888 car([#)]
10889 @end example
10891 @noindent
10892 Proper quotation, of course, fixes the problem:
10894 @example
10895 car([#])
10896 @result{}#
10897 @end example
10899 Here are more examples:
10901 @example
10902 car(foo, bar)
10903 @result{}foo
10904 car([foo, bar])
10905 @result{}foo, bar
10906 car((foo, bar))
10907 @result{}(foo, bar)
10908 car([(foo], [bar)])
10909 @result{}(foo
10910 define([a], [b])
10911 @result{}
10912 car(a)
10913 @result{}b
10914 car([a])
10915 @result{}b
10916 car([[a]])
10917 @result{}a
10918 car([[[a]]])
10919 @result{}[a]
10920 @end example
10922 @node Quoting and Parameters
10923 @subsection Quoting and Parameters
10925 When M4 encounters @samp{$} within a macro definition, followed
10926 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10927 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10928 expansion.  This happens regardless of how many layers of quotes the
10929 parameter expansion is nested within, or even if it occurs in text that
10930 will be rescanned as a comment.
10932 @example
10933 define([none], [$1])
10934 @result{}
10935 define([one], [[$1]])
10936 @result{}
10937 define([two], [[[$1]]])
10938 @result{}
10939 define([comment], [# $1])
10940 @result{}
10941 define([active], [ACTIVE])
10942 @result{}
10943 none([active])
10944 @result{}ACTIVE
10945 one([active])
10946 @result{}active
10947 two([active])
10948 @result{}[active]
10949 comment([active])
10950 @result{}# active
10951 @end example
10953 On the other hand, since autoconf generates shell code, you often want
10954 to output shell variable expansion, rather than performing M4 parameter
10955 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10956 from the next character in the definition of your macro.  If the macro
10957 definition occurs in single-quoted text, then insert another level of
10958 quoting; if the usage is already inside a double-quoted string, then
10959 split it into concatenated strings.
10961 @example
10962 define([foo], [a single-quoted $[]1 definition])
10963 @result{}
10964 define([bar], [[a double-quoted $][1 definition]])
10965 @result{}
10967 @result{}a single-quoted $1 definition
10969 @result{}a double-quoted $1 definition
10970 @end example
10972 Posix states that M4 implementations are free to provide implementation
10973 extensions when @samp{$@{} is encountered in a macro definition.
10974 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10975 extensions that will be available in the future GNU M4 2.0,
10976 but guarantees that all other instances of @samp{$@{} will be output
10977 literally.  Therefore, this idiom can also be used to output shell code
10978 parameter references:
10980 @example
10981 define([first], [$@{1@}])first
10982 @result{}$@{1@}
10983 @end example
10985 Posix also states that @samp{$11} should expand to the first parameter
10986 concatenated with a literal @samp{1}, although some versions of
10987 GNU M4 expand the eleventh parameter instead.  For
10988 portability, you should only use single-digit M4 parameter expansion.
10990 With this in mind, we can explore the cases where macros invoke
10991 macros@enddots{}
10993 @node Quotation and Nested Macros
10994 @subsection Quotation and Nested Macros
10996 The examples below use the following macros:
10998 @example
10999 define([car], [$1])
11000 define([active], [ACT, IVE])
11001 define([array], [int tab[10]])
11002 @end example
11004 Each additional embedded macro call introduces other possible
11005 interesting quotations:
11007 @example
11008 car(active)
11009 @result{}ACT
11010 car([active])
11011 @result{}ACT, IVE
11012 car([[active]])
11013 @result{}active
11014 @end example
11016 In the first case, the top level looks for the arguments of @code{car},
11017 and finds @samp{active}.  Because M4 evaluates its arguments
11018 before applying the macro, @samp{active} is expanded, which results in:
11020 @example
11021 car(ACT, IVE)
11022 @result{}ACT
11023 @end example
11025 @noindent
11026 In the second case, the top level gives @samp{active} as first and only
11027 argument of @code{car}, which results in:
11029 @example
11030 active
11031 @result{}ACT, IVE
11032 @end example
11034 @noindent
11035 i.e., the argument is evaluated @emph{after} the macro that invokes it.
11036 In the third case, @code{car} receives @samp{[active]}, which results in:
11038 @example
11039 [active]
11040 @result{}active
11041 @end example
11043 @noindent
11044 exactly as we already saw above.
11046 The example above, applied to a more realistic example, gives:
11048 @example
11049 car(int tab[10];)
11050 @result{}int tab10;
11051 car([int tab[10];])
11052 @result{}int tab10;
11053 car([[int tab[10];]])
11054 @result{}int tab[10];
11055 @end example
11057 @noindent
11058 Huh?  The first case is easily understood, but why is the second wrong,
11059 and the third right?  To understand that, you must know that after
11060 M4 expands a macro, the resulting text is immediately subjected
11061 to macro expansion and quote removal.  This means that the quote removal
11062 occurs twice---first before the argument is passed to the @code{car}
11063 macro, and second after the @code{car} macro expands to the first
11064 argument.
11066 As the author of the Autoconf macro @code{car}, you then consider it to
11067 be incorrect that your users have to double-quote the arguments of
11068 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
11069 quoted car:
11071 @example
11072 define([qar], [[$1]])
11073 @end example
11075 @noindent
11076 and check that @code{qar} is properly fixed:
11078 @example
11079 qar([int tab[10];])
11080 @result{}int tab[10];
11081 @end example
11083 @noindent
11084 Ahhh!  That's much better.
11086 But note what you've done: now that the result of @code{qar} is always
11087 a literal string, the only time a user can use nested macros is if she
11088 relies on an @emph{unquoted} macro call:
11090 @example
11091 qar(active)
11092 @result{}ACT
11093 qar([active])
11094 @result{}active
11095 @end example
11097 @noindent
11098 leaving no way for her to reproduce what she used to do with @code{car}:
11100 @example
11101 car([active])
11102 @result{}ACT, IVE
11103 @end example
11105 @noindent
11106 Worse yet: she wants to use a macro that produces a set of @code{cpp}
11107 macros:
11109 @example
11110 define([my_includes], [#include <stdio.h>])
11111 car([my_includes])
11112 @result{}#include <stdio.h>
11113 qar(my_includes)
11114 @error{}EOF in argument list
11115 @end example
11117 This macro, @code{qar}, because it double quotes its arguments, forces
11118 its users to leave their macro calls unquoted, which is dangerous.
11119 Commas and other active symbols are interpreted by M4 before
11120 they are given to the macro, often not in the way the users expect.
11121 Also, because @code{qar} behaves differently from the other macros,
11122 it's an exception that should be avoided in Autoconf.
11124 @node Changequote is Evil
11125 @subsection @code{changequote} is Evil
11126 @cindex @code{changequote}
11128 The temptation is often high to bypass proper quotation, in particular
11129 when it's late at night.  Then, many experienced Autoconf hackers
11130 finally surrender to the dark side of the force and use the ultimate
11131 weapon: @code{changequote}.
11133 The M4 builtin @code{changequote} belongs to a set of primitives that
11134 allow one to adjust the syntax of the language to adjust it to one's
11135 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
11136 quotes, but in the context of shell programming (and actually of most
11137 programming languages), that's about the worst choice one can make:
11138 because of strings and back-quoted expressions in shell code (such as
11139 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
11140 programming languages (as in @samp{'0'}), there are many unbalanced
11141 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
11142 not impossible.  In order to make M4 useful in such a context, its
11143 designers have equipped it with @code{changequote}, which makes it
11144 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
11145 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
11146 because they are unlikely characters, but @emph{because they are
11147 characters unlikely to be unbalanced}.
11149 There are other magic primitives, such as @code{changecom} to specify
11150 what syntactic forms are comments (it is common to see
11151 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
11152 @code{changeword} and @code{changesyntax} to change other syntactic
11153 details (such as the character to denote the @var{n}th argument, @samp{$} by
11154 default, the parentheses around arguments, etc.).
11156 These primitives are really meant to make M4 more useful for specific
11157 domains: they should be considered like command line options:
11158 @option{--quotes}, @option{--comments}, @option{--words}, and
11159 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
11160 it makes M4 libraries self contained (no need for additional options).
11162 There lies the problem@enddots{}
11164 @sp 1
11166 The problem is that it is then tempting to use them in the middle of an
11167 M4 script, as opposed to its initialization.  This, if not carefully
11168 thought out, can lead to disastrous effects: @emph{you are changing the
11169 language in the middle of the execution}.  Changing and restoring the
11170 syntax is often not enough: if you happened to invoke macros in between,
11171 these macros are lost, as the current syntax is probably not
11172 the one they were implemented with.
11174 @c FIXME: I've been looking for a short, real case example, but I
11175 @c lost them all :(
11178 @node Quadrigraphs
11179 @subsection Quadrigraphs
11180 @cindex quadrigraphs
11181 @cindex @samp{@@S|@@}
11182 @cindex @samp{@@&t@@}
11183 @c Info cannot handle ':' in index entries.
11184 @ifnotinfo
11185 @cindex @samp{@@<:@@}
11186 @cindex @samp{@@:>@@}
11187 @cindex @samp{@@%:@@}
11188 @cindex @samp{@@@{:@@}
11189 @cindex @samp{@@:@}@@}
11190 @end ifnotinfo
11192 When writing an Autoconf macro you may occasionally need to generate
11193 special characters that are difficult to express with the standard
11194 Autoconf quoting rules.  For example, you may need to output the regular
11195 expression @samp{[^[]}, which matches any character other than @samp{[}.
11196 This expression contains unbalanced brackets so it cannot be put easily
11197 into an M4 macro.
11199 Additionally, there are a few m4sugar macros (such as @code{m4_split}
11200 and @code{m4_expand}) which internally use special markers in addition
11201 to the regular quoting characters.  If the arguments to these macros
11202 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
11203 might behave incorrectly.
11205 You can work around these problems by using one of the following
11206 @dfn{quadrigraphs}:
11208 @table @samp
11209 @item @@<:@@
11210 @samp{[}
11211 @item @@:>@@
11212 @samp{]}
11213 @item @@S|@@
11214 @samp{$}
11215 @item @@%:@@
11216 @samp{#}
11217 @item @@@{:@@
11218 @samp{(}
11219 @item @@:@}@@
11220 @samp{)}
11221 @item @@&t@@
11222 Expands to nothing.
11223 @end table
11225 Quadrigraphs are replaced at a late stage of the translation process,
11226 after @command{m4} is run, so they do not get in the way of M4 quoting.
11227 For example, the string @samp{^@@<:@@}, independently of its quotation,
11228 appears as @samp{^[} in the output.
11230 The empty quadrigraph can be used:
11232 @itemize @minus
11233 @item to mark trailing spaces explicitly
11235 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
11237 @item to produce quadrigraphs and other strings reserved by m4sugar
11239 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
11240 contrived example:
11242 @example
11243 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
11244 m4_split([a )@}>=- b -=<@{( c])
11245 @result{}[a], [], [B], [], [c]
11246 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
11247 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
11248 @end example
11250 @item to escape @emph{occurrences} of forbidden patterns
11252 For instance you might want to mention @code{AC_FOO} in a comment, while
11253 still being sure that @command{autom4te} still catches unexpanded
11254 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
11255 @end itemize
11257 The name @samp{@@&t@@} was suggested by Paul Eggert:
11259 @quotation
11260 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
11261 own invention, but the @samp{t} came from the source code of the
11262 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
11263 and which used @samp{mt} to denote the empty string.  In C, it would
11264 have looked like something like:
11266 @example
11267 char const mt[] = "";
11268 @end example
11270 @noindent
11271 but of course the source code was written in Algol 68.
11273 I don't know where he got @samp{mt} from: it could have been his own
11274 invention, and I suppose it could have been a common pun around the
11275 Cambridge University computer lab at the time.
11276 @end quotation
11279 @node Balancing Parentheses
11280 @subsection Dealing with unbalanced parentheses
11281 @cindex balancing parentheses
11282 @cindex parentheses, balancing
11283 @cindex unbalanced parentheses, managing
11285 One of the pitfalls of portable shell programming is that
11286 if you intend your script to run with obsolescent shells,
11287 @command{case} statements require unbalanced parentheses.
11288 @xref{case, , Limitations of Shell Builtins}.
11289 With syntax highlighting
11290 editors, the presence of unbalanced @samp{)} can interfere with editors
11291 that perform syntax highlighting of macro contents based on finding the
11292 matching @samp{(}.  Another concern is how much editing must be done
11293 when transferring code snippets between shell scripts and macro
11294 definitions.  But most importantly, the presence of unbalanced
11295 parentheses can introduce expansion bugs.
11297 For an example, here is an underquoted attempt to use the macro
11298 @code{my_case}, which happens to expand to a portable @command{case}
11299 statement:
11301 @example
11302 AC_DEFUN([my_case],
11303 [case $file_name in
11304   *.c) echo "C source code";;
11305 esac])
11306 AS_IF(:, my_case)
11307 @end example
11309 @noindent
11310 In the above example, the @code{AS_IF} call under-quotes its arguments.
11311 As a result, the unbalanced @samp{)} generated by the premature
11312 expansion of @code{my_case} results in expanding @code{AS_IF} with a
11313 truncated parameter, and the expansion is syntactically invalid:
11315 @example
11316 if :; then
11317   case $file_name in
11318   *.c
11319 fi echo "C source code";;
11320 esac)
11321 @end example
11323 If nothing else, this should emphasize the importance of the quoting
11324 arguments to macro calls.  On the other hand, there are several
11325 variations for defining @code{my_case} to be more robust, even when used
11326 without proper quoting, each with some benefits and some drawbacks.
11328 @itemize @w{}
11329 @item Use left parenthesis before pattern
11330 @example
11331 AC_DEFUN([my_case],
11332 [case $file_name in
11333   (*.c) echo "C source code";;
11334 esac])
11335 @end example
11336 @noindent
11337 This is simple and provides balanced parentheses.  Although this is not
11338 portable to obsolescent shells (notably Solaris 10 @command{/bin/sh}),
11339 platforms with these shells invariably have a more-modern shell
11340 available somewhere so this approach typically suffices nowadays.
11342 @item Creative literal shell comment
11343 @example
11344 AC_DEFUN([my_case],
11345 [case $file_name in #(
11346   *.c) echo "C source code";;
11347 esac])
11348 @end example
11349 @noindent
11350 This version provides balanced parentheses to several editors, and can
11351 be copied and pasted into a terminal as is.  Unfortunately, it is still
11352 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
11353 that masks the normal properties of @samp{(}.
11355 @item Quadrigraph shell comment
11356 @example
11357 AC_DEFUN([my_case],
11358 [case $file_name in @@%:@@(
11359   *.c) echo "C source code";;
11360 esac])
11361 @end example
11362 @noindent
11363 This version provides balanced parentheses to even more editors, and can
11364 be used as a balanced Autoconf argument.  Unfortunately, it requires
11365 some editing before it can be copied and pasted into a terminal, and the
11366 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
11368 @item Quoting just the parenthesis
11369 @example
11370 AC_DEFUN([my_case],
11371 [case $file_name in
11372   *.c[)] echo "C source code";;
11373 esac])
11374 @end example
11375 @noindent
11376 This version quotes the @samp{)}, so that it can be used as a balanced
11377 Autoconf argument.  As written, this is not balanced to an editor, but
11378 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
11379 still requires some edits before it can be copied and pasted into a
11380 terminal.
11382 @item Double-quoting the entire statement
11383 @example
11384 AC_DEFUN([my_case],
11385 [[case $file_name in #(
11386   *.c) echo "C source code";;
11387 esac]])
11388 @end example
11389 @noindent
11390 Since the entire macro is double-quoted, there is no problem with using
11391 this as an Autoconf argument; and since the double-quoting is over the
11392 entire statement, this code can be easily copied and pasted into a
11393 terminal.  However, the double quoting prevents the expansion of any
11394 macros inside the case statement, which may cause its own set of
11395 problems.
11397 @item Using @code{AS_CASE}
11398 @example
11399 AC_DEFUN([my_case],
11400 [AS_CASE([$file_name],
11401   [*.c], [echo "C source code"])])
11402 @end example
11403 @noindent
11404 This version avoids the balancing issue altogether, by relying on
11405 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
11406 expansion of @code{AC_REQUIRE} to occur prior to the entire case
11407 statement, rather than within a branch of the case statement that might
11408 not be taken.  However, the abstraction comes with a penalty that it is
11409 no longer a quick copy, paste, and edit to get back to shell code.
11410 @end itemize
11413 @node Quotation Rule Of Thumb
11414 @subsection Quotation Rule Of Thumb
11416 To conclude, the quotation rule of thumb is:
11418 @center @emph{One pair of quotes per pair of parentheses.}
11420 Never over-quote, never under-quote, in particular in the definition of
11421 macros.  In the few places where the macros need to use brackets
11422 (usually in C program text or regular expressions), properly quote
11423 @emph{the arguments}!
11425 It is common to read Autoconf programs with snippets like:
11427 @example
11428 AC_TRY_LINK(
11429 changequote(<<, >>)dnl
11430 <<#include <time.h>
11431 #ifndef tzname /* For SGI.  */
11432 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11433 #endif>>,
11434 changequote([, ])dnl
11435 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11436 @end example
11438 @noindent
11439 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11440 double quoting, so you just need:
11442 @example
11443 AC_TRY_LINK(
11444 [#include <time.h>
11445 #ifndef tzname /* For SGI.  */
11446 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11447 #endif],
11448             [atoi (*tzname);],
11449             [ac_cv_var_tzname=yes],
11450             [ac_cv_var_tzname=no])
11451 @end example
11453 @noindent
11454 The M4-fluent reader might note that these two examples are rigorously
11455 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11456 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11457 quotes are not part of the arguments!
11459 Simplified, the example above is just doing this:
11461 @example
11462 changequote(<<, >>)dnl
11463 <<[]>>
11464 changequote([, ])dnl
11465 @end example
11467 @noindent
11468 instead of simply:
11470 @example
11471 [[]]
11472 @end example
11474 With macros that do not double quote their arguments (which is the
11475 rule), double-quote the (risky) literals:
11477 @example
11478 AC_LINK_IFELSE([AC_LANG_PROGRAM(
11479 [[#include <time.h>
11480 #ifndef tzname /* For SGI.  */
11481 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11482 #endif]],
11483                                 [atoi (*tzname);])],
11484                [ac_cv_var_tzname=yes],
11485                [ac_cv_var_tzname=no])
11486 @end example
11488 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11489 should be using @code{AC_LINK_IFELSE} instead.
11491 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
11492 where quoting does not suffice.
11494 When you create a @command{configure} script using newly written macros,
11495 examine it carefully to check whether you need to add more quotes in
11496 your macros.  If one or more words have disappeared in the M4
11497 output, you need more quotes.  When in doubt, quote.
11499 However, it's also possible to put on too many layers of quotes.  If
11500 this happens, the resulting @command{configure} script may contain
11501 unexpanded macros.  The @command{autoconf} program checks for this problem
11502 by looking for the string @samp{AC_} in @file{configure}.  However, this
11503 heuristic does not work in general: for example, it does not catch
11504 overquoting in @code{AC_DEFINE} descriptions.
11507 @c ---------------------------------------- Using autom4te
11509 @node Using autom4te
11510 @section Using @command{autom4te}
11512 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11513 to Autoconf per se, heavily rely on M4.  All these different uses
11514 revealed common needs factored into a layer over M4:
11515 @command{autom4te}@footnote{
11517 Yet another great name from Lars J. Aas.
11521 @command{autom4te} is a preprocessor that is like @command{m4}.
11522 It supports M4 extensions designed for use in tools like Autoconf.
11524 @menu
11525 * autom4te Invocation::         A GNU M4 wrapper
11526 * Customizing autom4te::        Customizing the Autoconf package
11527 @end menu
11529 @node autom4te Invocation
11530 @subsection Invoking @command{autom4te}
11532 The command line arguments are modeled after M4's:
11534 @example
11535 autom4te @var{options} @var{files}
11536 @end example
11538 @noindent
11539 @evindex M4
11540 where the @var{files} are directly passed to @command{m4}.  By default,
11541 GNU M4 is found during configuration, but the environment
11542 variable
11543 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
11544 to the regular expansion, it handles the replacement of the quadrigraphs
11545 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11546 output.  It supports an extended syntax for the @var{files}:
11548 @table @file
11549 @item @var{file}.m4f
11550 This file is an M4 frozen file.  Note that @emph{all the previous files
11551 are ignored}.  See the @option{--melt} option for the rationale.
11553 @item @var{file}?
11554 If found in the library path, the @var{file} is included for expansion,
11555 otherwise it is ignored instead of triggering a failure.
11556 @end table
11558 @sp 1
11560 Of course, it supports the Autoconf common subset of options:
11562 @table @option
11563 @item --help
11564 @itemx -h
11565 Print a summary of the command line options and exit.
11567 @item --version
11568 @itemx -V
11569 Print the version number of Autoconf and exit.
11571 @item --verbose
11572 @itemx -v
11573 Report processing steps.
11575 @item --debug
11576 @itemx -d
11577 Don't remove the temporary files and be even more verbose.
11579 @item --include=@var{dir}
11580 @itemx -I @var{dir}
11581 Also look for input files in @var{dir}.  Multiple invocations
11582 accumulate.
11584 @item --output=@var{file}
11585 @itemx -o @var{file}
11586 Save output (script or trace) to @var{file}.  The file @option{-} stands
11587 for the standard output.
11588 @end table
11590 @sp 1
11592 As an extension of @command{m4}, it includes the following options:
11594 @table @option
11596 @item --warnings=@var{category}[,@var{category}...]
11597 @itemx -W@var{category}[,@var{category}...]
11598 @evindex WARNINGS
11599 Enable or disable warnings related to each @var{category}.
11600 @xref{m4_warn}, for a comprehensive list of categories.
11601 Special values include:
11603 @table @samp
11604 @item all
11605 Enable all categories of warnings.
11607 @item none
11608 Disable all categories of warnings.
11610 @item error
11611 Treat all warnings as errors.
11613 @item no-@var{category}
11614 Disable warnings falling into @var{category}.
11615 @end table
11617 The enviroment variable @env{WARNINGS} may also be set to a
11618 comma-separated list of warning categories to enable or disable.
11619 It is interpreted exactly the same way as the argument of
11620 @option{--warnings}, but unknown categories are silently ignored.
11621 The command line takes precedence; for instance, if @env{WARNINGS}
11622 is set to @code{obsolete}, but @option{-Wnone} is given on the
11623 command line, no warnings will be issued.
11625 Some categories of warnings are on by default.
11626 Again, for details see @ref{m4_warn}.
11628 @item --melt
11629 @itemx -M
11630 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
11631 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
11632 are executed only when the files are frozen, typically
11633 @code{m4_define}.  For instance, running:
11635 @example
11636 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11637 @end example
11639 @noindent
11640 is roughly equivalent to running:
11642 @example
11643 m4 1.m4 2.m4 3.m4 4.m4 input.m4
11644 @end example
11646 @noindent
11647 while
11649 @example
11650 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11651 @end example
11653 @noindent
11654 is equivalent to:
11656 @example
11657 m4 --reload-state=4.m4f input.m4
11658 @end example
11660 @item --freeze
11661 @itemx -F
11662 Produce a frozen state file.  @command{autom4te} freezing is stricter
11663 than M4's: it must produce no warnings, and no output other than empty
11664 lines (a line with white space is @emph{not} empty) and comments
11665 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
11666 this option takes no argument:
11668 @example
11669 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11670 @end example
11672 @noindent
11673 corresponds to
11675 @example
11676 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11677 @end example
11679 @item --mode=@var{octal-mode}
11680 @itemx -m @var{octal-mode}
11681 Set the mode of the non-traces output to @var{octal-mode}; by default
11682 @samp{0666}.
11683 @end table
11685 @sp 1
11687 @cindex @file{autom4te.cache}
11688 As another additional feature over @command{m4}, @command{autom4te}
11689 caches its results.  GNU M4 is able to produce a regular
11690 output and traces at the same time.  Traces are heavily used in the
11691 GNU Build System: @command{autoheader} uses them to build
11692 @file{config.h.in}, @command{autoreconf} to determine what
11693 GNU Build System components are used, @command{automake} to
11694 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
11695 traces are cached while performing regular expansion,
11696 and conversely.  This cache is (actually, the caches are) stored in
11697 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
11698 at any moment (especially if for some reason @command{autom4te}
11699 considers it trashed).
11701 @table @option
11702 @item --cache=@var{directory}
11703 @itemx -C @var{directory}
11704 Specify the name of the directory where the result should be cached.
11705 Passing an empty value disables caching.  Be sure to pass a relative
11706 file name, as for the time being, global caches are not supported.
11708 @item --no-cache
11709 Don't cache the results.
11711 @item --force
11712 @itemx -f
11713 If a cache is used, consider it obsolete (but update it anyway).
11714 @end table
11716 @sp 1
11718 Because traces are so important to the GNU Build System,
11719 @command{autom4te} provides high level tracing features as compared to
11720 M4, and helps exploiting the cache:
11722 @table @option
11723 @item --trace=@var{macro}[:@var{format}]
11724 @itemx -t @var{macro}[:@var{format}]
11725 Trace the invocations of @var{macro} according to the @var{format}.
11726 Multiple @option{--trace} arguments can be used to list several macros.
11727 Multiple @option{--trace} arguments for a single macro are not
11728 cumulative; instead, you should just make @var{format} as long as
11729 needed.
11731 The @var{format} is a regular string, with newlines if desired, and
11732 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
11733 use the following special escapes:
11735 @table @samp
11736 @item $$
11737 @c $$ restore font-lock
11738 The character @samp{$}.
11740 @item $f
11741 The file name from which @var{macro} is called.
11743 @item $l
11744 The line number from which @var{macro} is called.
11746 @item $d
11747 The depth of the @var{macro} call.  This is an M4 technical detail that
11748 you probably don't want to know about.
11750 @item $n
11751 The name of the @var{macro}.
11753 @item $@var{num}
11754 The @var{num}th argument of the call to @var{macro}.
11756 @item $@@
11757 @itemx $@var{sep}@@
11758 @itemx $@{@var{separator}@}@@
11759 All the arguments passed to @var{macro}, separated by the character
11760 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
11761 argument is quoted, i.e., enclosed in a pair of square brackets.
11763 @item $*
11764 @itemx $@var{sep}*
11765 @itemx $@{@var{separator}@}*
11766 As above, but the arguments are not quoted.
11768 @item $%
11769 @itemx $@var{sep}%
11770 @itemx $@{@var{separator}@}%
11771 As above, but the arguments are not quoted, all new line characters in
11772 the arguments are smashed, and the default separator is @samp{:}.
11774 The escape @samp{$%} produces single-line trace outputs (unless you put
11775 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11776 not.
11777 @end table
11779 @xref{autoconf Invocation}, for examples of trace uses.
11781 @item --preselect=@var{macro}
11782 @itemx -p @var{macro}
11783 Cache the traces of @var{macro}, but do not enable traces.  This is
11784 especially important to save CPU cycles in the future.  For instance,
11785 when invoked, @command{autoconf} pre-selects all the macros that
11786 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11787 trace, so that running @command{m4} is not needed to trace them: the
11788 cache suffices.  This results in a huge speed-up.
11789 @end table
11791 @sp 1
11793 @cindex Autom4te Library
11794 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11795 libraries}.  They consists in a powerful yet extremely simple feature:
11796 sets of combined command line arguments:
11798 @table @option
11799 @item --language=@var{language}
11800 @itemx -l @var{language}
11801 Use the @var{language} Autom4te library.  Current languages include:
11803 @table @code
11804 @item M4sugar
11805 create M4sugar output.
11807 @item M4sh
11808 create M4sh executable shell scripts.
11810 @item Autotest
11811 create Autotest executable test suites.
11813 @item Autoconf-without-aclocal-m4
11814 create Autoconf executable configure scripts without
11815 reading @file{aclocal.m4}.
11817 @item Autoconf
11818 create Autoconf executable configure scripts.  This language inherits
11819 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11820 additionally reads @file{aclocal.m4}.
11821 @end table
11823 @item --prepend-include=@var{dir}
11824 @itemx -B @var{dir}
11825 Prepend directory @var{dir} to the search path.  This is used to include
11826 the language-specific files before any third-party macros.
11828 @end table
11830 @cindex @file{autom4te.cfg}
11831 As an example, if Autoconf is installed in its default location,
11832 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11833 strictly equivalent to the command:
11835 @example
11836 autom4te --prepend-include /usr/local/share/autoconf \
11837   m4sugar/m4sugar.m4f foo.m4
11838 @end example
11840 @noindent
11841 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11842 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11843 foo.m4}, i.e.:
11845 @example
11846 autom4te --prepend-include /usr/local/share/autoconf \
11847   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11848 @end example
11850 @noindent
11851 The definition of the languages is stored in @file{autom4te.cfg}.
11853 @node Customizing autom4te
11854 @subsection Customizing @command{autom4te}
11856 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11857 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11858 as found in the directory from which @command{autom4te} is run).  The
11859 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11860 then @file{./.autom4te.cfg}, and finally the command line arguments.
11862 In these text files, comments are introduced with @code{#}, and empty
11863 lines are ignored.  Customization is performed on a per-language basis,
11864 wrapped in between a @samp{begin-language: "@var{language}"},
11865 @samp{end-language: "@var{language}"} pair.
11867 Customizing a language stands for appending options (@pxref{autom4te
11868 Invocation}) to the current definition of the language.  Options, and
11869 more generally arguments, are introduced by @samp{args:
11870 @var{arguments}}.  You may use the traditional shell syntax to quote the
11871 @var{arguments}.
11873 As an example, to disable Autoconf caches (@file{autom4te.cache})
11874 globally, include the following lines in @file{~/.autom4te.cfg}:
11876 @verbatim
11877 ## ------------------ ##
11878 ## User Preferences.  ##
11879 ## ------------------ ##
11881 begin-language: "Autoconf-without-aclocal-m4"
11882 args: --no-cache
11883 end-language: "Autoconf-without-aclocal-m4"
11884 @end verbatim
11887 @node Programming in M4sugar
11888 @section Programming in M4sugar
11890 @cindex M4sugar
11891 M4 by itself provides only a small, but sufficient, set of all-purpose
11892 macros.  M4sugar introduces additional generic macros.  Its name was
11893 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11894 M4sugar''.
11896 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11897 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
11898 define your own macros into these namespaces.
11900 @menu
11901 * Redefined M4 Macros::         M4 builtins changed in M4sugar
11902 * Diagnostic Macros::           Diagnostic messages from M4sugar
11903 * Diversion support::           Diversions in M4sugar
11904 * Conditional constructs::      Conditions in M4
11905 * Looping constructs::          Iteration in M4
11906 * Evaluation Macros::           More quotation and evaluation control
11907 * Text processing Macros::      String manipulation in M4
11908 * Number processing Macros::    Arithmetic computation in M4
11909 * Set manipulation Macros::     Set manipulation in M4
11910 * Forbidden Patterns::          Catching unexpanded macros
11911 @end menu
11913 @node Redefined M4 Macros
11914 @subsection Redefined M4 Macros
11916 @msindex{builtin}
11917 @msindex{changecom}
11918 @msindex{changequote}
11919 @msindex{debugfile}
11920 @msindex{debugmode}
11921 @msindex{decr}
11922 @msindex{define}
11923 @msindex{divnum}
11924 @msindex{errprint}
11925 @msindex{esyscmd}
11926 @msindex{eval}
11927 @msindex{format}
11928 @msindex{ifdef}
11929 @msindex{incr}
11930 @msindex{index}
11931 @msindex{indir}
11932 @msindex{len}
11933 @msindex{pushdef}
11934 @msindex{shift}
11935 @msindex{substr}
11936 @msindex{syscmd}
11937 @msindex{sysval}
11938 @msindex{traceoff}
11939 @msindex{traceon}
11940 @msindex{translit}
11941 With a few exceptions, all the M4 native macros are moved in the
11942 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11943 @code{m4_define} etc.
11945 The list of macros unchanged from M4, except for their name, is:
11946 @itemize @minus
11947 @item m4_builtin
11948 @item m4_changecom
11949 @item m4_changequote
11950 @item m4_debugfile
11951 @item m4_debugmode
11952 @item m4_decr
11953 @item m4_define
11954 @item m4_divnum
11955 @item m4_errprint
11956 @item m4_esyscmd
11957 @item m4_eval
11958 @item m4_format
11959 @item m4_ifdef
11960 @item m4_incr
11961 @item m4_index
11962 @item m4_indir
11963 @item m4_len
11964 @item m4_pushdef
11965 @item m4_shift
11966 @item m4_substr
11967 @item m4_syscmd
11968 @item m4_sysval
11969 @item m4_traceoff
11970 @item m4_traceon
11971 @item m4_translit
11972 @end itemize
11974 Some M4 macros are redefined, and are slightly incompatible with their
11975 native equivalent.
11977 @defmac __file__
11978 @defmacx __line__
11979 @MSindex __file__
11980 @MSindex __line__
11981 All M4 macros starting with @samp{__} retain their original name: for
11982 example, no @code{m4__file__} is defined.
11983 @end defmac
11985 @defmac __oline__
11986 @MSindex __oline__
11987 This is not technically a macro, but a feature of Autom4te.  The
11988 sequence @code{__oline__} can be used similarly to the other m4sugar
11989 location macros, but rather than expanding to the location of the input
11990 file, it is translated to the line number where it appears in the output
11991 file after all other M4 expansions.
11992 @end defmac
11994 @defmac dnl
11995 @MSindex dnl
11996 This macro kept its original name: no @code{m4_dnl} is defined.
11997 @end defmac
11999 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
12000 @msindex{bpatsubst}
12001 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
12002 is kept for future versions of M4sugar, once GNU M4 2.0 is
12003 released and supports extended regular expression syntax.
12004 @end defmac
12006 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
12007 @msindex{bregexp}
12008 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
12009 is kept for future versions of M4sugar, once GNU M4 2.0 is
12010 released and supports extended regular expression syntax.
12011 @end defmac
12013 @defmac m4_copy (@var{source}, @var{dest})
12014 @defmacx m4_copy_force (@var{source}, @var{dest})
12015 @defmacx m4_rename (@var{source}, @var{dest})
12016 @defmacx m4_rename_force (@var{source}, @var{dest})
12017 @msindex{copy}
12018 @msindex{copy_force}
12019 @msindex{rename}
12020 @msindex{rename_force}
12021 These macros aren't directly builtins, but are closely related to
12022 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
12023 @code{m4_rename} ensure that @var{dest} is undefined, while
12024 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
12025 definition.  All four macros then proceed to copy the entire pushdef
12026 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
12027 and @code{m4_copy_force} preserve the source (including in the special
12028 case where @var{source} is undefined), while @code{m4_rename} and
12029 @code{m4_rename_force} undefine the original macro name (making it an
12030 error to rename an undefined @var{source}).
12032 Note that attempting to invoke a renamed macro might not work, since the
12033 macro may have a dependence on helper macros accessed via composition of
12034 @samp{$0} but that were not also renamed; likewise, other macros may
12035 have a hard-coded dependence on @var{source} and could break if
12036 @var{source} has been deleted.  On the other hand, it is always safe to
12037 rename a macro to temporarily move it out of the way, then rename it
12038 back later to restore original semantics.
12039 @end defmac
12041 @defmac m4_defn (@var{macro}@dots{})
12042 @msindex{defn}
12043 This macro fails if @var{macro} is not defined, even when using older
12044 versions of M4 that did not warn.  See @code{m4_undefine}.
12045 Unfortunately, in order to support these older versions of M4, there are
12046 some situations involving unbalanced quotes where concatenating multiple
12047 macros together will work in newer M4 but not in m4sugar; use
12048 quadrigraphs to work around this.
12049 @end defmac
12051 @defmac m4_divert (@var{diversion})
12052 @msindex{divert}
12053 M4sugar relies heavily on diversions, so rather than behaving as a
12054 primitive, @code{m4_divert} behaves like:
12055 @example
12056 m4_divert_pop()m4_divert_push([@var{diversion}])
12057 @end example
12058 @noindent
12059 @xref{Diversion support}, for more details about the use of the
12060 diversion stack.  In particular, this implies that @var{diversion}
12061 should be a named diversion rather than a raw number.  But be aware that
12062 it is seldom necessary to explicitly change the diversion stack, and
12063 that when done incorrectly, it can lead to syntactically invalid
12064 scripts.
12065 @end defmac
12067 @defmac m4_dumpdef (@var{name}@dots{})
12068 @defmacx m4_dumpdefs (@var{name}@dots{})
12069 @msindex{dumpdef}
12070 @msindex{dumpdefs}
12071 @code{m4_dumpdef} is like the M4 builtin, except that this version
12072 requires at least one argument, output always goes to standard error
12073 rather than the current debug file, no sorting is done on multiple
12074 arguments, and an error is issued if any
12075 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
12076 calls @code{m4_dumpdef} for all of the
12077 @code{m4_pushdef} stack of definitions, starting with the current, and
12078 silently does nothing if @var{name} is undefined.
12080 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
12081 builtin is output as the empty string.  This behavior is rectified by
12082 using M4 1.6 or newer.  However, this behavior difference means that
12083 @code{m4_dumpdef} should only be used while developing m4sugar macros,
12084 and never in the final published form of a macro.
12085 @end defmac
12087 @defmac m4_esyscmd_s (@var{command})
12088 @msindex{esyscmd_s}
12089 Like @code{m4_esyscmd}, this macro expands to the result of running
12090 @var{command} in a shell.  The difference is that any trailing newlines
12091 are removed, so that the output behaves more like shell command
12092 substitution.
12093 @end defmac
12095 @defmac m4_exit (@var{exit-status})
12096 @msindex{exit}
12097 This macro corresponds to @code{m4exit}.
12098 @end defmac
12100 @defmac m4_if (@var{comment})
12101 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
12102 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
12103   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
12104 @msindex{if}
12105 This macro corresponds to @code{ifelse}.  @var{string-1} and
12106 @var{string-2} are compared literally, so usually one of the two
12107 arguments is passed unquoted.  @xref{Conditional constructs}, for more
12108 conditional idioms.
12109 @end defmac
12111 @defmac m4_include (@var{file})
12112 @defmacx m4_sinclude (@var{file})
12113 @msindex{include}
12114 @msindex{sinclude}
12115 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
12116 @end defmac
12118 @defmac m4_mkstemp (@var{template})
12119 @defmacx m4_maketemp (@var{template})
12120 @msindex{maketemp}
12121 @msindex{mkstemp}
12122 Posix requires @code{maketemp} to replace the trailing @samp{X}
12123 characters in @var{template} with the process id, without regards to the
12124 existence of a file by that name, but this a security hole.  When this
12125 was pointed out to the Posix folks, they agreed to invent a new macro
12126 @code{mkstemp} that always creates a uniquely named file, but not all
12127 versions of GNU M4 support the new macro.  In M4sugar,
12128 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
12129 and both have the secure semantics regardless of which macro the
12130 underlying M4 provides.
12131 @end defmac
12133 @defmac m4_popdef (@var{macro}@dots{})
12134 @msindex{popdef}
12135 This macro fails if @var{macro} is not defined, even when using older
12136 versions of M4 that did not warn.  See @code{m4_undefine}.
12137 @end defmac
12139 @defmac m4_undefine (@var{macro}@dots{})
12140 @msindex{undefine}
12141 This macro fails if @var{macro} is not defined, even when using older
12142 versions of M4 that did not warn.  Use
12144 @example
12145 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
12146 @end example
12148 @noindent
12149 if you are not sure whether @var{macro} is defined.
12150 @end defmac
12152 @defmac m4_undivert (@var{diversion}@dots{})
12153 @msindex{undivert}
12154 Unlike the M4 builtin, at least one @var{diversion} must be specified.
12155 Also, since the M4sugar diversion stack prefers named
12156 diversions, the use of @code{m4_undivert} to include files is risky.
12157 @xref{Diversion support}, for more details about the use of the
12158 diversion stack.  But be aware that it is seldom necessary to explicitly
12159 change the diversion stack, and that when done incorrectly, it can lead
12160 to syntactically invalid scripts.
12161 @end defmac
12163 @defmac m4_wrap (@var{text})
12164 @defmacx m4_wrap_lifo (@var{text})
12165 @msindex{wrap}
12166 @msindex{wrap_lifo}
12167 These macros correspond to @code{m4wrap}.  Posix requires arguments of
12168 multiple wrap calls to be reprocessed at EOF in the same order
12169 as the original calls (first-in, first-out).  GNU M4 versions
12170 through 1.4.10, however, reprocess them in reverse order (last-in,
12171 first-out).  Both orders are useful, therefore, you can rely on
12172 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
12173 LIFO semantics, regardless of the underlying GNU M4 version.
12175 Unlike the GNU M4 builtin, these macros only recognize one
12176 argument, and avoid token pasting between consecutive invocations.  On
12177 the other hand, nested calls to @code{m4_wrap} from within wrapped text
12178 work just as in the builtin.
12179 @end defmac
12182 @node Diagnostic Macros
12183 @subsection Diagnostic messages from M4sugar
12184 @cindex Messages, from @command{M4sugar}
12186 When macros statically diagnose abnormal situations, benign or fatal,
12187 they should report them using these macros.  For issuing dynamic issues,
12188 i.e., when @command{configure} is run, see @ref{Printing Messages}.
12190 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
12191 @msindex{assert}
12192 Assert that the arithmetic @var{expression} evaluates to non-zero.
12193 Otherwise, issue a fatal error, and exit @command{autom4te} with
12194 @var{exit-status}.
12195 @end defmac
12197 @defmac m4_errprintn (@var{message})
12198 @msindex{errprintn}
12199 Similar to the builtin @code{m4_errprint}, except that a newline is
12200 guaranteed after @var{message}.
12201 @end defmac
12203 @anchor{m4_fatal}
12204 @defmac m4_fatal (@var{message})
12205 @msindex{fatal}
12206 Report a severe error @var{message} prefixed with the current location,
12207 and have @command{autom4te} die.
12208 @end defmac
12210 @defmac m4_location
12211 @msindex{location}
12212 Useful as a prefix in a message line.  Short for:
12213 @example
12214 __file__:__line__
12215 @end example
12216 @end defmac
12218 @anchor{m4_warn}
12219 @defmac m4_warn (@var{category}, @var{message})
12220 @msindex{warn}
12221 Report @var{message} as a warning (or as an error if requested by the
12222 user) if warnings of the @var{category} are turned on.  If the message
12223 is emitted, it is prefixed with the current location, and followed by a
12224 call trace of all macros defined via @code{AC_DEFUN} used to get to the
12225 current expansion.
12227 The @var{category} must be one of:
12229 @table @samp
12230 @item cross
12231 Warnings about constructs that may interfere with cross-compilation,
12232 such as using @code{AC_RUN_IFELSE} without a default.
12234 @item gnu
12235 Warnings related to the GNU Coding Standards
12236 (@pxref{Top,,, standards, The GNU Coding Standards}).
12237 On by default.
12239 @item obsolete
12240 Warnings about obsolete features.  On by default.
12242 @item override
12243 Warnings about redefinitions of Autoconf internals.
12245 @item portability
12246 Warnings about non-portable constructs.
12248 @item portability-recursive
12249 Warnings about recursive Make variable expansions (@code{$(foo$(x))}).
12251 @item extra-portability
12252 Extra warnings about non-portable constructs, covering rarely-used
12253 tools.
12255 @item syntax
12256 Warnings about questionable syntactic constructs, incorrectly ordered
12257 macro calls, typos, etc.  On by default.
12259 @item unsupported
12260 Warnings about unsupported features.  On by default.
12261 @end table
12263 @strong{Hacking Note:} The set of categories is defined by code in
12264 @command{autom4te}, not by M4sugar itself.  Additions should be
12265 coordinated with Automake, so that both sets of tools accept the same
12266 options.
12267 @end defmac
12269 @node Diversion support
12270 @subsection Diversion support
12272 M4sugar makes heavy use of diversions under the hood, because it is
12273 often the case that
12274 text that must appear early in the output is not discovered until late
12275 in the input.  Additionally, some of the topological sorting algorithms
12276 used in resolving macro dependencies use diversions.  However, most
12277 macros should not need to change diversions directly, but rather rely on
12278 higher-level M4sugar macros to manage diversions transparently.  If you
12279 change diversions improperly, you risk generating a syntactically
12280 invalid script, because an incorrect diversion will violate assumptions
12281 made by many macros about whether prerequisite text has been previously
12282 output.  In short, if you manually change the diversion, you should not
12283 expect any macros provided by the Autoconf package to work until you
12284 have restored the diversion stack back to its original state.
12286 In the rare case that it is necessary to write a macro that explicitly
12287 outputs text to a different diversion, it is important to be aware of an
12288 M4 limitation regarding diversions: text only goes to a diversion if it
12289 is not part of argument collection.  Therefore, any macro that changes
12290 the current diversion cannot be used as an unquoted argument to another
12291 macro, but must be expanded at the top level.  The macro
12292 @code{m4_expand} will diagnose any attempt to change diversions, since
12293 it is generally useful only as an argument to another macro.  The
12294 following example shows what happens when diversion manipulation is
12295 attempted within macro arguments:
12297 @example
12298 m4_do([normal text]
12299 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
12300 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
12301 @result{}normal text
12302 @result{}unwanted
12303 @end example
12305 @noindent
12306 Notice that the unquoted text @code{unwanted} is output, even though it
12307 was processed while the current diversion was @code{KILL}, because it
12308 was collected as part of the argument to @code{m4_do}.  However, the
12309 text @code{discarded} disappeared as desired, because the diversion
12310 changes were single-quoted, and were not expanded until the top-level
12311 rescan of the output of @code{m4_do}.
12313 To make diversion management easier, M4sugar uses the concept of named
12314 diversions.  Rather than using diversion numbers directly, it is nicer
12315 to associate a name with each diversion.  The diversion number associated
12316 with a particular diversion name is an implementation detail, and a
12317 syntax warning is issued if a diversion number is used instead of a
12318 name.  In general, you should not output text
12319 to a named diversion until after calling the appropriate initialization
12320 routine for your language (@code{m4_init}, @code{AS_INIT},
12321 @code{AT_INIT}, @dots{}), although there are some exceptions documented
12322 below.
12324 M4sugar defines two named diversions.
12325 @table @code
12326 @item KILL
12327 Text written to this diversion is discarded.  This is the default
12328 diversion once M4sugar is initialized.
12329 @item GROW
12330 This diversion is used behind the scenes by topological sorting macros,
12331 such as @code{AC_REQUIRE}.
12332 @end table
12334 M4sh adds several more named diversions.
12335 @table @code
12336 @item BINSH
12337 This diversion is reserved for the @samp{#!} interpreter line.
12338 @item HEADER-REVISION
12339 This diversion holds text from @code{AC_REVISION}.
12340 @item HEADER-COMMENT
12341 This diversion holds comments about the purpose of a file.
12342 @item HEADER-COPYRIGHT
12343 This diversion is managed by @code{AC_COPYRIGHT}.
12344 @item M4SH-SANITIZE
12345 This diversion contains M4sh sanitization code, used to ensure M4sh is
12346 executing in a reasonable shell environment.
12347 @item M4SH-INIT
12348 This diversion contains M4sh initialization code, initializing variables
12349 that are required by other M4sh macros.
12350 @item BODY
12351 This diversion contains the body of the shell code, and is the default
12352 diversion once M4sh is initialized.
12353 @end table
12355 Autotest inherits diversions from M4sh, and changes the default
12356 diversion from @code{BODY} back to @code{KILL}.  It also adds several
12357 more named diversions, with the following subset designed for developer
12358 use.
12359 @table @code
12360 @item PREPARE_TESTS
12361 This diversion contains initialization sequences which are executed
12362 after @file{atconfig} and @file{atlocal}, and after all command line
12363 arguments have been parsed, but prior to running any tests.  It can be
12364 used to set up state that is required across all tests.  This diversion
12365 will work even before @code{AT_INIT}.
12366 @end table
12368 Autoconf inherits diversions from M4sh, and adds the following named
12369 diversions which developers can utilize.
12370 @table @code
12371 @item DEFAULTS
12372 This diversion contains shell variable assignments to set defaults that
12373 must be in place before arguments are parsed.  This diversion is placed
12374 early enough in @file{configure} that it is unsafe to expand any
12375 autoconf macros into this diversion.
12376 @item HELP_ENABLE
12377 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
12378 diversion will be included as part of a quoted here-doc providing all of
12379 the @option{--help} output of @file{configure} related to options
12380 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
12381 @item INIT_PREPARE
12382 This diversion occurs after all command line options have been parsed,
12383 but prior to the main body of the @file{configure} script.  This
12384 diversion is the last chance to insert shell code such as variable
12385 assignments or shell function declarations that will used by the
12386 expansion of other macros.
12387 @end table
12389 For now, the remaining named diversions of Autoconf, Autoheader, and
12390 Autotest are not documented.  In other words,
12391 intentionally outputting text into an undocumented diversion is subject
12392 to breakage in a future release of Autoconf.
12394 @defmac m4_cleardivert (@var{diversion}@dots{})
12395 @msindex{cleardivert}
12396 Permanently discard any text that has been diverted into
12397 @var{diversion}.
12398 @end defmac
12400 @defmac m4_divert_once (@var{diversion}, @ovar{content})
12401 @msindex{divert_once}
12402 Similar to @code{m4_divert_text}, except that @var{content} is only
12403 output to @var{diversion} if this is the first time that
12404 @code{m4_divert_once} has been called with its particular arguments.
12405 @end defmac
12407 @defmac m4_divert_pop (@ovar{diversion})
12408 @msindex{divert_pop}
12409 If provided, check that the current diversion is indeed @var{diversion}.
12410 Then change to the diversion located earlier on the stack, giving an
12411 error if an attempt is made to pop beyond the initial m4sugar diversion
12412 of @code{KILL}.
12413 @end defmac
12415 @defmac m4_divert_push (@var{diversion})
12416 @msindex{divert_push}
12417 Remember the former diversion on the diversion stack, and output
12418 subsequent text into @var{diversion}.  M4sugar maintains a diversion
12419 stack, and issues an error if there is not a matching pop for every
12420 push.
12421 @end defmac
12423 @anchor{m4_divert_text}
12424 @defmac m4_divert_text (@var{diversion}, @ovar{content})
12425 @msindex{divert_text}
12426 Output @var{content} and a newline into @var{diversion}, without
12427 affecting the current diversion.  Shorthand for:
12428 @example
12429 m4_divert_push([@var{diversion}])@var{content}
12430 m4_divert_pop([@var{diversion}])dnl
12431 @end example
12433 One use of @code{m4_divert_text} is to develop two related macros, where
12434 macro @samp{MY_A} does the work, but adjusts what work is performed
12435 based on whether the optional macro @samp{MY_B} has also been expanded.
12436 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
12437 require that @samp{MY_B} occurs first, if it occurs at all.  But this
12438 imposes an ordering restriction on the user; it would be nicer if macros
12439 @samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
12440 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
12441 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
12442 expanded.
12444 @example
12445 AC_DEFUN([MY_A],
12446 [# various actions
12447 if test -n "$b_was_used"; then
12448   # extra action
12449 fi])
12450 AC_DEFUN([MY_B],
12451 [AC_REQUIRE([MY_A])dnl
12452 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12453 @end example
12455 @end defmac
12457 @defmac m4_init
12458 @msindex{init}
12459 Initialize the M4sugar environment, setting up the default named
12460 diversion to be @code{KILL}.
12461 @end defmac
12463 @node Conditional constructs
12464 @subsection Conditional constructs
12466 The following macros provide additional conditional constructs as
12467 convenience wrappers around @code{m4_if}.
12469 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12470   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12471 @msindex{bmatch}
12472 The string @var{string} is repeatedly compared against a series of
12473 @var{regex} arguments; if a match is found, the expansion is the
12474 corresponding @var{value}, otherwise, the macro moves on to the next
12475 @var{regex}.  If no @var{regex} match, then the result is the optional
12476 @var{default}, or nothing.
12477 @end defmac
12479 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12480   @ovar{regex-2}, @ovar{subst-2}, @dots{})
12481 @msindex{bpatsubsts}
12482 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12483 as if by:
12484 @example
12485 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12486 @end example
12488 @noindent
12489 The result of the substitution is then passed through the next set of
12490 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
12491 deletion of any matched portions in the current string.  Note that this
12492 macro over-quotes @var{string}; this behavior is intentional, so that
12493 the result of each step of the recursion remains as a quoted string.
12494 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12495 will line up with the extra quotations, and not the characters of the
12496 original string.  The overquoting is removed after the final
12497 substitution.
12498 @end defmac
12500 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12501   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12502 @msindex{case}
12503 Test @var{string} against multiple @var{value} possibilities, resulting
12504 in the first @var{if-value} for a match, or in the optional
12505 @var{default}.  This is shorthand for:
12506 @example
12507 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12508       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12509       [@var{default}])
12510 @end example
12511 @end defmac
12513 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12514   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12515 @msindex{cond}
12516 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
12517 except that each @var{test} is expanded only when it is encountered.
12518 This is useful for short-circuiting expensive tests; while @code{m4_if}
12519 requires all its strings to be expanded up front before doing
12520 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12521 tests have failed.
12523 For an example, these two sequences give the same result, but in the
12524 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12525 version only expands @code{m4_index} once, instead of five times, for
12526 faster computation if this is a common case for @samp{$1}.  Notice that
12527 every third argument is unquoted for @code{m4_if}, and quoted for
12528 @code{m4_cond}:
12530 @example
12531 m4_if(m4_index([$1], [\]), [-1], [$2],
12532       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12533       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12534       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12535       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12536       [$2])
12537 m4_cond([m4_index([$1], [\])], [-1], [$2],
12538         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12539         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12540         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12541         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12542         [$2])
12543 @end example
12544 @end defmac
12546 @defmac m4_default (@var{expr-1}, @var{expr-2})
12547 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12548 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12549 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12550 @msindex{default}
12551 @msindex{default_quoted}
12552 @msindex{default_nblank}
12553 @msindex{default_nblank_quoted}
12554 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
12555 @code{m4_default} expands the result, while @code{m4_default_quoted}
12556 does not.  Useful for providing a fixed default if the expression that
12557 results in @var{expr-1} would otherwise be empty.  The difference
12558 between @code{m4_default} and @code{m4_default_nblank} is whether an
12559 argument consisting of just blanks (space, tab, newline) is
12560 significant.  When using the expanding versions, note that an argument
12561 may contain text but still expand to an empty string.
12563 @example
12564 m4_define([active], [ACTIVE])dnl
12565 m4_define([empty], [])dnl
12566 m4_define([demo1], [m4_default([$1], [$2])])dnl
12567 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12568 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12569 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12570 demo1([active], [default])
12571 @result{}ACTIVE
12572 demo1([], [active])
12573 @result{}ACTIVE
12574 demo1([empty], [text])
12575 @result{}
12576 -demo1([ ], [active])-
12577 @result{}- -
12578 demo2([active], [default])
12579 @result{}active
12580 demo2([], [active])
12581 @result{}active
12582 demo2([empty], [text])
12583 @result{}empty
12584 -demo2([ ], [active])-
12585 @result{}- -
12586 demo3([active], [default])
12587 @result{}ACTIVE
12588 demo3([], [active])
12589 @result{}ACTIVE
12590 demo3([empty], [text])
12591 @result{}
12592 -demo3([ ], [active])-
12593 @result{}-ACTIVE-
12594 demo4([active], [default])
12595 @result{}active
12596 demo4([], [active])
12597 @result{}active
12598 demo4([empty], [text])
12599 @result{}empty
12600 -demo4([ ], [active])-
12601 @result{}-active-
12602 @end example
12603 @end defmac
12605 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
12606 @msindex{define_default}
12607 If @var{macro} does not already have a definition, then define it to
12608 @var{default-definition}.
12609 @end defmac
12611 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12612 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12613 @msindex{ifblank}
12614 @msindex{ifnblank}
12615 If @var{cond} is empty or consists only of blanks (space, tab, newline),
12616 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
12617 variants exist, in order to make it easier to select the correct logical
12618 sense when using only two parameters.  Note that this is more efficient
12619 than the equivalent behavior of:
12620 @example
12621 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12622 @end example
12623 @end defmac
12625 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12626 @msindex{ifndef}
12627 This is shorthand for:
12628 @example
12629 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12630 @end example
12631 @end defmac
12633 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12634 @msindex{ifset}
12635 If @var{macro} is undefined, or is defined as the empty string, expand
12636 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
12637 @example
12638 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12639 @end example
12640 @noindent
12641 except that it is not an error if @var{macro} is undefined.
12642 @end defmac
12644 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12645 @msindex{ifval}
12646 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12647 @var{if-false}.  This is shorthand for:
12648 @example
12649 m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12650 @end example
12651 @end defmac
12653 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12654 @msindex{ifvaln}
12655 Similar to @code{m4_ifval}, except guarantee that a newline is present
12656 after any non-empty expansion.  Often followed by @code{dnl}.
12657 @end defmac
12659 @defmac m4_n (@var{text})
12660 @msindex{n}
12661 Expand to @var{text}, and add a newline if @var{text} is not empty.
12662 Often followed by @code{dnl}.
12663 @end defmac
12666 @node Looping constructs
12667 @subsection Looping constructs
12669 The following macros are useful in implementing recursive algorithms in
12670 M4, including loop operations.  An M4 list is formed by quoting a list
12671 of quoted elements; generally the lists are comma-separated, although
12672 @code{m4_foreach_w} is whitespace-separated.  For example, the list
12673 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12674 It is common to see lists with unquoted elements when those elements are
12675 not likely to be macro names, as in @samp{[fputc_unlocked,
12676 fgetc_unlocked]}.
12678 Although not generally recommended, it is possible for quoted lists to
12679 have side effects; all side effects are expanded only once, and prior to
12680 visiting any list element.  On the other hand, the fact that unquoted
12681 macros are expanded exactly once means that macros without side effects
12682 can be used to generate lists.  For example,
12684 @example
12685 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12686 @error{}hi
12687 @result{}123
12688 m4_define([list], [[1], [2], [3]])
12689 @result{}
12690 m4_foreach([i], [list], [i])
12691 @result{}123
12692 @end example
12694 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12695 @msindex{argn}
12696 Extracts argument @var{n} (larger than 0) from the remaining arguments.
12697 If there are too few arguments, the empty string is used.  For any
12698 @var{n} besides 1, this is more efficient than the similar
12699 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12700 @end defmac
12702 @defmac m4_car (@var{arg}@dots{})
12703 @msindex{car}
12704 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
12705 to recursively iterate
12706 through a list.  Generally, when using quoted lists of quoted elements,
12707 @code{m4_car} should be called without any extra quotes.
12708 @end defmac
12710 @defmac m4_cdr (@var{arg}@dots{})
12711 @msindex{cdr}
12712 Expands to a quoted list of all but the first @var{arg}, or the empty
12713 string if there was only one argument.  Generally, when using quoted
12714 lists of quoted elements, @code{m4_cdr} should be called without any
12715 extra quotes.
12717 For example, this is a simple implementation of @code{m4_map}; note how
12718 each iteration checks for the end of recursion, then merely applies the
12719 first argument to the first element of the list, then repeats with the
12720 rest of the list.  (The actual implementation in M4sugar is a bit more
12721 involved, to gain some speed and share code with @code{m4_map_sep}, and
12722 also to avoid expanding side effects in @samp{$2} twice).
12723 @example
12724 m4_define([m4_map], [m4_ifval([$2],
12725   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12726 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12727 @result{} 1 2 a
12728 @end example
12729 @end defmac
12731 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12732   @var{expression})
12733 @msindex{for}
12734 Loop over the numeric values between @var{first} and @var{last}
12735 including bounds by increments of @var{step}.  For each iteration,
12736 expand @var{expression} with the numeric value assigned to @var{var}.
12737 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12738 on the order of the limits.  If given, @var{step} has to match this
12739 order.  The number of iterations is determined independently from
12740 definition of @var{var}; iteration cannot be short-circuited or
12741 lengthened by modifying @var{var} from within @var{expression}.
12742 @end defmac
12744 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12745 @msindex{foreach}
12746 Loop over the comma-separated M4 list @var{list}, assigning each value
12747 to @var{var}, and expand @var{expression}.  The following example
12748 outputs two lines:
12750 @example
12751 m4_foreach([myvar], [[foo], [bar, baz]],
12752            [echo myvar
12753 ])dnl
12754 @result{}echo foo
12755 @result{}echo bar, baz
12756 @end example
12758 Note that for some forms of @var{expression}, it may be faster to use
12759 @code{m4_map_args}.
12760 @end defmac
12762 @anchor{m4_foreach_w}
12763 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12764 @msindex{foreach_w}
12765 Loop over the white-space-separated list @var{list}, assigning each value
12766 to @var{var}, and expand @var{expression}.  If @var{var} is only
12767 referenced once in @var{expression}, it is more efficient to use
12768 @code{m4_map_args_w}.
12770 The deprecated macro @code{AC_FOREACH} is an alias of
12771 @code{m4_foreach_w}.
12772 @end defmac
12774 @defmac m4_map (@var{macro}, @var{list})
12775 @defmacx m4_mapall (@var{macro}, @var{list})
12776 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12777 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12778 @msindex{map}
12779 @msindex{mapall}
12780 @msindex{map_sep}
12781 @msindex{mapall_sep}
12782 Loop over the comma separated quoted list of argument descriptions in
12783 @var{list}, and invoke @var{macro} with the arguments.  An argument
12784 description is in turn a comma-separated quoted list of quoted elements,
12785 suitable for @code{m4_apply}.  The macros @code{m4_map} and
12786 @code{m4_map_sep} ignore empty argument descriptions, while
12787 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12788 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12789 additionally expand @var{separator} between invocations of @var{macro}.
12791 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
12792 separating output with commas, this means that the map result can be
12793 used as a series of arguments, by using a single-quoted comma as
12794 @var{separator}, or as a single string, by using a double-quoted comma.
12796 @example
12797 m4_map([m4_count], [])
12798 @result{}
12799 m4_map([ m4_count], [[],
12800                      [[1]],
12801                      [[1], [2]]])
12802 @result{} 1 2
12803 m4_mapall([ m4_count], [[],
12804                         [[1]],
12805                         [[1], [2]]])
12806 @result{} 0 1 2
12807 m4_map_sep([m4_eval], [,], [[[1+2]],
12808                             [[10], [16]]])
12809 @result{}3,a
12810 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12811 @result{}a,b
12812 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12813 @result{}2
12814 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12815 @result{}a,b
12816 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12817 @result{}1
12818 @end example
12819 @end defmac
12821 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12822 @msindex{map_args}
12823 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12824 argument.  In the following example, three solutions are presented with
12825 the same expansion; the solution using @code{m4_map_args} is the most
12826 efficient.
12827 @example
12828 m4_define([active], [ACTIVE])dnl
12829 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12830 @result{} plain active
12831 m4_map([ m4_echo], [[[plain]], [[active]]])
12832 @result{} plain active
12833 m4_map_args([ m4_echo], [plain], [active])
12834 @result{} plain active
12835 @end example
12837 In cases where it is useful to operate on additional parameters besides
12838 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12839 to supply the argument currying necessary to generate the desired
12840 argument list.  In the following example, @code{list_add_n} is more
12841 efficient than @code{list_add_x}.  On the other hand, using
12842 @code{m4_map_args_sep} can be even more efficient.
12844 @example
12845 m4_define([list], [[1], [2], [3]])dnl
12846 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12847 dnl list_add_n(N, ARG...)
12848 dnl Output a list consisting of each ARG added to N
12849 m4_define([list_add_n],
12850 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12851 list_add_n([1], list)
12852 @result{}2,3,4
12853 list_add_n([2], list)
12854 @result{}3,4,5
12855 m4_define([list_add_x],
12856 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12857   [,add([$1],m4_defn([var]))]))])dnl
12858 list_add_x([1], list)
12859 @result{}2,3,4
12860 @end example
12861 @end defmac
12863 @defmac m4_map_args_pair (@var{macro}, @dvarv{macro-end, macro}, @
12864   @var{arg}@dots{})
12865 @msindex{map_args_pair}
12866 For every pair of arguments @var{arg}, invoke @var{macro} with two
12867 arguments.  If there is an odd number of arguments, invoke
12868 @var{macro-end}, which defaults to @var{macro}, with the remaining
12869 argument.
12871 @example
12872 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12873 @result{}, 2, 1, 3
12874 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12875 @result{}, 2, 1, [3]
12876 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12877 @result{}, 2, 1, 4, 3
12878 @end example
12879 @end defmac
12881 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12882 @msindex{map_args_sep}
12883 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12884 argument, additionally expanding @var{sep} between arguments.  One
12885 common use of this macro is constructing a macro call, where the opening
12886 and closing parentheses are split between @var{pre} and @var{post}; in
12887 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12888 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
12889 macro provides the most efficient means for iterating over an arbitrary
12890 list of arguments, particularly when repeatedly constructing a macro
12891 call with more arguments than @var{arg}.
12892 @end defmac
12894 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12895 @msindex{map_args_w}
12896 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12897 the whitespace-separated @var{string}, additionally expanding @var{sep}
12898 between words.  This macro provides the most efficient means for
12899 iterating over a whitespace-separated string.  In particular,
12900 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12901 efficient than @code{m4_foreach_w([var], [@var{string}],
12902 [@var{action}(m4_defn([var]))])}.
12903 @end defmac
12905 @defmac m4_shiftn (@var{count}, @dots{})
12906 @defmacx m4_shift2 (@dots{})
12907 @defmacx m4_shift3 (@dots{})
12908 @msindex{shift2}
12909 @msindex{shift3}
12910 @msindex{shiftn}
12911 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12912 along with validation that enough arguments were passed in to match the
12913 shift count, and that the count is positive.  @code{m4_shift2} and
12914 @code{m4_shift3} are specializations
12915 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12916 for two and three shifts, respectively.
12917 @end defmac
12919 @defmac m4_stack_foreach (@var{macro}, @var{action})
12920 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12921 @msindex{stack_foreach}
12922 @msindex{stack_foreach_lifo}
12923 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12924 @var{action} with the single argument of a definition of @var{macro}.
12925 @code{m4_stack_foreach} starts with the oldest definition, while
12926 @code{m4_stack_foreach_lifo} starts with the current definition.
12927 @var{action} should not push or pop definitions of @var{macro}, nor is
12928 there any guarantee that the current definition of @var{macro} matches
12929 the argument that was passed to @var{action}.  The macro @code{m4_curry}
12930 can be used if @var{action} needs more than one argument, although in
12931 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12933 Due to technical limitations, there are a few low-level m4sugar
12934 functions, such as @code{m4_pushdef}, that cannot be used as the
12935 @var{macro} argument.
12937 @example
12938 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12939 m4_stack_foreach([a], [ m4_incr])
12940 @result{} 2 3
12941 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12942 @result{} cd bcd
12943 @end example
12944 @end defmac
12946 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12947 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12948   @ovar{sep})
12949 @msindex{stack_foreach_sep}
12950 @msindex{stack_foreach_sep_lifo}
12951 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12952 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12953 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
12954 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12955 the current definition first.  This macro provides the most efficient
12956 means for iterating over a pushdef stack.  In particular,
12957 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12958 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12959 @end defmac
12961 @node Evaluation Macros
12962 @subsection Evaluation Macros
12964 The following macros give some control over the order of the evaluation
12965 by adding or removing levels of quotes.
12967 @defmac m4_apply (@var{macro}, @var{list})
12968 @msindex{apply}
12969 Apply the elements of the quoted, comma-separated @var{list} as the
12970 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12971 without arguments.  Note the difference between @code{m4_indir}, which
12972 expects its first argument to be a macro name but can use names that are
12973 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12974 other text, but must end in a valid macro name.
12975 @example
12976 m4_apply([m4_count], [])
12977 @result{}0
12978 m4_apply([m4_count], [[]])
12979 @result{}1
12980 m4_apply([m4_count], [[1], [2]])
12981 @result{}2
12982 m4_apply([m4_join], [[|], [1], [2]])
12983 @result{}1|2
12984 @end example
12985 @end defmac
12987 @defmac m4_count (@var{arg}, @dots{})
12988 @msindex{count}
12989 This macro returns the number of arguments it was passed.
12990 @end defmac
12992 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12993 @msindex{curry}
12994 This macro performs argument currying.  The expansion of this macro is
12995 another macro name that expects exactly one argument; that argument is
12996 then appended to the @var{arg} list, and then @var{macro} is expanded
12997 with the resulting argument list.
12999 @example
13000 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
13001 @result{}3, 2, 1
13002 @end example
13004 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
13005 pass the definition of a builtin macro as the argument to the output of
13006 @code{m4_curry}; the empty string is used instead of the builtin token.
13007 This behavior is rectified by using M4 1.6 or newer.
13008 @end defmac
13010 @defmac m4_do (@var{arg}, @dots{})
13011 @msindex{do}
13012 This macro loops over its arguments and expands each @var{arg} in
13013 sequence.  Its main use is for readability; it allows the use of
13014 indentation and fewer @code{dnl} to result in the same expansion.  This
13015 macro guarantees that no expansion will be concatenated with subsequent
13016 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
13017 @var{arg@dots{}}))}.
13019 @example
13020 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
13021 m4_do([a],[b])c
13022 @result{}abc
13023 m4_unquote(m4_join([],[a],[b]))c
13024 @result{}3
13025 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
13026 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
13027 m4_do([a],[b])c
13028 @result{}ABC
13029 m4_unquote(m4_join([],[a],[b]))c
13030 @result{}3
13031 @end example
13032 @end defmac
13034 @defmac m4_dquote (@var{arg}, @dots{})
13035 @msindex{dquote}
13036 Return the arguments as a quoted list of quoted arguments.
13037 Conveniently, if there is just one @var{arg}, this effectively adds a
13038 level of quoting.
13039 @end defmac
13041 @defmac m4_dquote_elt (@var{arg}, @dots{})
13042 @msindex{dquote_elt}
13043 Return the arguments as a series of double-quoted arguments.  Whereas
13044 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
13045 as many arguments as it was passed.
13046 @end defmac
13048 @defmac m4_echo (@var{arg}, @dots{})
13049 @msindex{echo}
13050 Return the arguments, with the same level of quoting.  Other than
13051 discarding whitespace after unquoted commas, this macro is a no-op.
13052 @end defmac
13054 @defmac m4_expand (@var{arg})
13055 @msindex{expand}
13056 Return the expansion of @var{arg} as a quoted string.  Whereas
13057 @code{m4_quote} is designed to collect expanded text into a single
13058 argument, @code{m4_expand} is designed to perform one level of expansion
13059 on quoted text.  One distinction is in the treatment of whitespace
13060 following a comma in the original @var{arg}.  Any time multiple
13061 arguments are collected into one with @code{m4_quote}, the M4 argument
13062 collection rules discard the whitespace.  However, with @code{m4_expand},
13063 whitespace is preserved, even after the expansion of macros contained in
13064 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
13065 would involve an unterminated comment, whereas expanding that same text
13066 as the argument to @code{m4_quote} runs into difficulty in finding the
13067 end of the argument.  Since manipulating diversions during argument
13068 collection is inherently unsafe, @code{m4_expand} issues an error if
13069 @var{arg} attempts to change the current diversion (@pxref{Diversion
13070 support}).
13072 @example
13073 m4_define([active], [ACT, IVE])dnl
13074 m4_define([active2], [[ACT, IVE]])dnl
13075 m4_quote(active, active)
13076 @result{}ACT,IVE,ACT,IVE
13077 m4_expand([active, active])
13078 @result{}ACT, IVE, ACT, IVE
13079 m4_quote(active2, active2)
13080 @result{}ACT, IVE,ACT, IVE
13081 m4_expand([active2, active2])
13082 @result{}ACT, IVE, ACT, IVE
13083 m4_expand([# m4_echo])
13084 @result{}# m4_echo
13085 m4_quote(# m4_echo)
13087 @result{}# m4_echo)
13088 @result{}
13089 @end example
13091 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
13092 literal unbalanced quotes, but that quadrigraphs can be used when
13093 unbalanced output is necessary.  Likewise, unbalanced parentheses should
13094 be supplied with double quoting or a quadrigraph.
13096 @example
13097 m4_define([pattern], [[!@@<:@@]])dnl
13098 m4_define([bar], [BAR])dnl
13099 m4_expand([case $foo in
13100   m4_defn([pattern])@@:@}@@ bar ;;
13101   *[)] blah ;;
13102 esac])
13103 @result{}case $foo in
13104 @result{}  [![]) BAR ;;
13105 @result{}  *) blah ;;
13106 @result{}esac
13107 @end example
13108 @end defmac
13110 @defmac m4_ignore (@dots{})
13111 @msindex{ignore}
13112 This macro was introduced in Autoconf 2.62.  Expands to nothing,
13113 ignoring all of its arguments.  By itself, this isn't very useful.
13114 However, it can be used to conditionally ignore an arbitrary number of
13115 arguments, by deciding which macro name to apply to a list of arguments.
13116 @example
13117 dnl foo outputs a message only if [debug] is defined.
13118 m4_define([foo],
13119 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
13120 @end example
13122 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
13123 serve the same purpose, although it is less readable.
13124 @end defmac
13126 @defmac m4_make_list (@var{arg}, @dots{})
13127 @msindex{make_list}
13128 This macro exists to aid debugging of M4sugar algorithms.  Its net
13129 effect is similar to @code{m4_dquote}---it produces a quoted list of
13130 quoted arguments, for each @var{arg}.  The difference is that this
13131 version uses a comma-newline separator instead of just comma, to improve
13132 readability of the list; with the result that it is less efficient than
13133 @code{m4_dquote}.
13134 @example
13135 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
13136 m4_dquote(zero, [one], [[two]])
13137 @result{}[0],[one],[[two]]
13138 m4_make_list(zero, [one], [[two]])
13139 @result{}[0],
13140 @result{}[one],
13141 @result{}[[two]]
13142 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
13143 @result{} 0 1 two
13144 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
13145 @result{} 0 1 two
13146 @end example
13147 @end defmac
13149 @c m4_noquote is too dangerous to document - it invokes macros that
13150 @c probably rely on @samp{[]} nested quoting for proper operation.  The
13151 @c user should generally prefer m4_unquote instead.
13153 @defmac m4_quote (@var{arg}, @dots{})
13154 @msindex{quote}
13155 Return the arguments as a single entity, i.e., wrap them into a pair of
13156 quotes.  This effectively collapses multiple arguments into one,
13157 although it loses whitespace after unquoted commas in the process.
13158 @end defmac
13160 @defmac m4_reverse (@var{arg}, @dots{})
13161 @msindex{reverse}
13162 Outputs each argument with the same level of quoting, but in reverse
13163 order, and with space following each comma for readability.
13165 @example
13166 m4_define([active], [ACT,IVE])
13167 @result{}
13168 m4_reverse(active, [active])
13169 @result{}active, IVE, ACT
13170 @end example
13171 @end defmac
13173 @defmac m4_unquote (@var{arg}, @dots{})
13174 @msindex{unquote}
13175 This macro was introduced in Autoconf 2.62.  Expand each argument,
13176 separated by commas.  For a single @var{arg}, this effectively removes a
13177 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
13178 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
13179 this results in an unquoted list of expansions.  This is commonly used
13180 with @code{m4_split}, in order to convert a single quoted list into a
13181 series of quoted elements.
13182 @end defmac
13184 The following example aims at emphasizing the difference between several
13185 scenarios: not using these macros, using @code{m4_defn}, using
13186 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
13188 @example
13189 $ @kbd{cat example.m4}
13190 dnl Overquote, so that quotes are visible.
13191 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
13192 m4_define([a], [A])
13193 m4_define([mkargs], [1, 2[,] 3])
13194 m4_define([arg1], [[$1]])
13195 m4_divert([0])dnl
13196 show(a, b)
13197 show([a, b])
13198 show(m4_quote(a, b))
13199 show(m4_dquote(a, b))
13200 show(m4_expand([a, b]))
13202 arg1(mkargs)
13203 arg1([mkargs])
13204 arg1(m4_defn([mkargs]))
13205 arg1(m4_quote(mkargs))
13206 arg1(m4_dquote(mkargs))
13207 arg1(m4_expand([mkargs]))
13208 $ @kbd{autom4te -l m4sugar example.m4}
13209 $1 = A, $@@ = [A],[b]
13210 $1 = a, b, $@@ = [a, b]
13211 $1 = A,b, $@@ = [A,b]
13212 $1 = [A],[b], $@@ = [[A],[b]]
13213 $1 = A, b, $@@ = [A, b]
13216 mkargs
13217 1, 2[,] 3
13218 1,2, 3
13219 [1],[2, 3]
13220 1, 2, 3
13221 @end example
13224 @node Text processing Macros
13225 @subsection String manipulation in M4
13227 The following macros may be used to manipulate strings in M4.  Many of
13228 the macros in this section intentionally result in quoted strings as
13229 output, rather than subjecting the arguments to further expansions.  As
13230 a result, if you are manipulating text that contains active M4
13231 characters, the arguments are passed with single quoting rather than
13232 double.
13234 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
13235 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
13236   @ovar{if-uniq}, @ovar{if-duplicate})
13237 @msindex{append}
13238 @msindex{append_uniq}
13239 Redefine @var{macro-name} to its former contents with @var{separator}
13240 and @var{string} added at the end.  If @var{macro-name} was undefined
13241 before (but not if it was defined but empty), then no @var{separator} is
13242 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
13243 are expanded during this macro; instead, they are expanded when
13244 @var{macro-name} is invoked.
13246 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
13247 to grow strings without duplicating substrings.  Additionally,
13248 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
13249 @var{if-uniq} is expanded if @var{string} was appended, and
13250 @var{if-duplicate} is expanded if @var{string} was already present.
13251 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
13252 occurs within @var{string}, since that can lead to duplicates.
13254 Note that @code{m4_append} can scale linearly in the length of the final
13255 string, depending on the quality of the underlying M4 implementation,
13256 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
13257 If an algorithm can tolerate duplicates in the final string, use the
13258 former for speed.  If duplicates must be avoided, consider using
13259 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
13261 @example
13262 m4_define([active], [ACTIVE])dnl
13263 m4_append([sentence], [This is an])dnl
13264 m4_append([sentence], [ active ])dnl
13265 m4_append([sentence], [symbol.])dnl
13266 sentence
13267 @result{}This is an ACTIVE symbol.
13268 m4_undefine([active])dnl
13269 @result{}This is an active symbol.
13270 m4_append_uniq([list], [one], [, ], [new], [existing])
13271 @result{}new
13272 m4_append_uniq([list], [one], [, ], [new], [existing])
13273 @result{}existing
13274 m4_append_uniq([list], [two], [, ], [new], [existing])
13275 @result{}new
13276 m4_append_uniq([list], [three], [, ], [new], [existing])
13277 @result{}new
13278 m4_append_uniq([list], [two], [, ], [new], [existing])
13279 @result{}existing
13280 list
13281 @result{}one, two, three
13282 m4_dquote(list)
13283 @result{}[one],[two],[three]
13284 m4_append([list2], [one], [[, ]])dnl
13285 m4_append_uniq([list2], [two], [[, ]])dnl
13286 m4_append([list2], [three], [[, ]])dnl
13287 list2
13288 @result{}one, two, three
13289 m4_dquote(list2)
13290 @result{}[one, two, three]
13291 @end example
13292 @end defmac
13294 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
13295 @msindex{append_uniq_w}
13296 This macro was introduced in Autoconf 2.62.  It is similar to
13297 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
13298 separated list of words to append, and only appends unique words.
13299 @var{macro-name} is updated with a single space between new words.
13300 @example
13301 m4_append_uniq_w([numbers], [1 1 2])dnl
13302 m4_append_uniq_w([numbers], [ 2 3 ])dnl
13303 numbers
13304 @result{}1 2 3
13305 @end example
13306 @end defmac
13308 @defmac m4_chomp (@var{string})
13309 @defmacx m4_chomp_all (@var{string})
13310 @msindex{chomp}
13311 @msindex{chomp_all}
13312 Output @var{string} in quotes, but without a trailing newline.  The
13313 macro @code{m4_chomp} is slightly faster, and removes at most one
13314 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
13315 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
13316 and backslash does not influence the result.
13317 @end defmac
13319 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
13320   @var{suffix-1}, @ovar{suffix-2}, @dots{})
13321 @msindex{combine}
13322 This macro produces a quoted string containing the pairwise combination
13323 of every element of the quoted, comma-separated @var{prefix-list}, and
13324 every element from the @var{suffix} arguments.  Each pairwise
13325 combination is joined with @var{infix} in the middle, and successive
13326 pairs are joined by @var{separator}.  No expansion occurs on any of the
13327 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
13328 list is empty, but the lists can contain empty elements.
13329 @example
13330 m4_define([a], [oops])dnl
13331 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
13332 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
13333 m4_combine([, ], [[a], [b]], [-])
13334 @result{}
13335 m4_combine([, ], [[a], [b]], [-], [])
13336 @result{}a-, b-
13337 m4_combine([, ], [], [-], [1], [2])
13338 @result{}
13339 m4_combine([, ], [[]], [-], [1], [2])
13340 @result{}-1, -2
13341 @end example
13342 @end defmac
13344 @defmac m4_escape (@var{string})
13345 @msindex{escape}
13346 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
13347 within @var{string} into their respective quadrigraphs.  The result is
13348 still a quoted string.
13349 @end defmac
13351 @defmac m4_flatten (@var{string})
13352 @msindex{flatten}
13353 Flatten @var{string} into a single line.  Delete all backslash-newline
13354 pairs, and replace all remaining newlines with a space.  The result is
13355 still a quoted string.
13356 @end defmac
13358 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
13359 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
13360 @msindex{join}
13361 @msindex{joinall}
13362 Concatenate each @var{arg}, separated by @var{separator}.
13363 @code{joinall} uses every argument, while @code{join} omits empty
13364 arguments so that there are no back-to-back separators in the output.
13365 The result is a quoted string.
13366 @example
13367 m4_define([active], [ACTIVE])dnl
13368 m4_join([|], [one], [], [active], [two])
13369 @result{}one|active|two
13370 m4_joinall([|], [one], [], [active], [two])
13371 @result{}one||active|two
13372 @end example
13374 Note that if all you intend to do is join @var{args} with commas between
13375 them, to form a quoted list suitable for @code{m4_foreach}, it is more
13376 efficient to use @code{m4_dquote}.
13377 @end defmac
13379 @defmac m4_newline (@ovar{text})
13380 @msindex{newline}
13381 This macro was introduced in Autoconf 2.62, and expands to a newline,
13382 followed by any @var{text}.
13383 It is primarily useful for maintaining macro formatting, and ensuring
13384 that M4 does not discard leading whitespace during argument collection.
13385 @end defmac
13387 @defmac m4_normalize (@var{string})
13388 @msindex{normalize}
13389 Remove leading and trailing spaces and tabs, sequences of
13390 backslash-then-newline, and replace multiple spaces, tabs, and newlines
13391 with a single space.  This is a combination of @code{m4_flatten} and
13392 @code{m4_strip}.  To determine if @var{string} consists only of bytes
13393 that would be removed by @code{m4_normalize}, you can use
13394 @code{m4_ifblank}.
13395 @end defmac
13397 @defmac m4_re_escape (@var{string})
13398 @msindex{re_escape}
13399 Backslash-escape all characters in @var{string} that are active in
13400 regexps.
13401 @end defmac
13403 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13404 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
13405 @msindex{split}
13406 Split @var{string} into an M4 list of elements quoted by @samp{[} and
13407 @samp{]}, while keeping white space at the beginning and at the end.
13408 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
13409 If @var{string} is empty, the result is an empty list.
13410 @end defmac
13412 @defmac m4_strip (@var{string})
13413 @msindex{strip}
13414 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
13415 reduced to a single space, then leading and trailing spaces are removed.
13416 The result is still a quoted string.  Note that this does not interfere
13417 with newlines; if you want newlines stripped as well, consider
13418 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
13419 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
13420 @end defmac
13422 @defmac m4_text_box (@var{message}, @dvar{frame, -})
13423 @msindex{text_box}
13424 Add a text box around @var{message}, using @var{frame} as the border
13425 character above and below the message.  The @var{frame} argument must be
13426 a single byte, and does not support quadrigraphs.
13427 The frame correctly accounts for
13428 the subsequent expansion of @var{message}.  For example:
13429 @example
13430 m4_define([macro], [abc])dnl
13431 m4_text_box([macro])
13432 @result{}## --- ##
13433 @result{}## abc ##
13434 @result{}## --- ##
13435 @end example
13437 The @var{message} must contain balanced quotes and parentheses, although
13438 quadrigraphs can be used to work around this.
13439 @end defmac
13441 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
13442   @dvarv{prefix1, prefix}, @dvar{width, 79})
13443 @msindex{text_wrap}
13444 Break @var{string} into a series of whitespace-separated words, then
13445 output those words separated by spaces, and wrapping lines any time the
13446 output would exceed @var{width} columns.  If given, @var{prefix1} begins
13447 the first line, and @var{prefix} begins all wrapped lines.  If
13448 @var{prefix1} is longer than @var{prefix}, then the first line consists
13449 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
13450 padding is inserted so that the first word of @var{string} begins at the
13451 same indentation as all wrapped lines.  Note that using literal tab
13452 characters in any of the arguments will interfere with the calculation
13453 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
13454 words of @var{string}, although quadrigraphs are recognized.
13456 For some examples:
13457 @example
13458 m4_text_wrap([Short string */], [   ], [/* ], [20])
13459 @result{}/* Short string */
13460 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
13461 @result{}/* Much longer
13462 @result{}   string */
13463 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
13464 @result{}  --short Short doc.
13465 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
13466 @result{}  --too-wide
13467 @result{}          Short doc.
13468 m4_text_wrap([Super long documentation.], [     ],
13469              [  --too-wide ], 30)
13470 @result{}  --too-wide
13471 @result{}     Super long
13472 @result{}     documentation.
13473 @end example
13474 @end defmac
13476 @defmac m4_tolower (@var{string})
13477 @defmacx m4_toupper (@var{string})
13478 @msindex{tolower}
13479 @msindex{toupper}
13480 Return @var{string} with letters converted to upper or lower case,
13481 respectively.
13482 @end defmac
13484 @node Number processing Macros
13485 @subsection Arithmetic computation in M4
13487 The following macros facilitate integer arithmetic operations.
13489 Where a parameter is documented as taking an arithmetic expression, you
13490 can use anything that can be parsed by @code{m4_eval}.
13491 Any other numeric parameter should consist of an optional sign followed
13492 by one or more decimal digits; it is treated as a decimal integer.
13494 Macros that expand to a number do so as either @samp{0}, or an optional
13495 @samp{-} followed by a nonzero decimal digit followed by zero or more
13496 decimal digits.
13498 Due to @command{m4} limitations, arithmetic expressions and numeric
13499 parameters should use only numbers that fit into a 32-bit signed
13500 integer.
13502 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
13503 @msindex{cmp}
13504 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13505 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13506 equal, and @samp{1} if @var{expr-1} is larger.
13507 @end defmac
13509 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
13510 @msindex{list_cmp}
13511 Compare the two M4 lists consisting of comma-separated arithmetic
13512 expressions, left to right.  Expand to @samp{-1} for the first element
13513 pairing where the value from @var{list-1} is smaller, @samp{1} where the
13514 value from @var{list-2} is smaller, or @samp{0} if both lists have the
13515 same values.  If one list is shorter than the other, the remaining
13516 elements of the longer list are compared against zero.
13517 @example
13518 m4_list_cmp([1, 0],       [1])
13519 @result{}0
13520 m4_list_cmp([1, [1 * 0]], [1, 0])
13521 @result{}0
13522 m4_list_cmp([1, 2],       [1, 0])
13523 @result{}1
13524 m4_list_cmp([1, [1+1], 3],[1, 2])
13525 @result{}1
13526 m4_list_cmp([1, 2, -3],   [1, 2])
13527 @result{}-1
13528 m4_list_cmp([1, 0],       [1, 2])
13529 @result{}-1
13530 m4_list_cmp([1],          [1, 2])
13531 @result{}-1
13532 @end example
13533 @end defmac
13535 @defmac m4_max (@var{arg}, @dots{})
13536 @msindex{max}
13537 This macro was introduced in Autoconf 2.62.  Expand to the value
13538 of the maximum arithmetic expression among all the arguments.
13539 @end defmac
13541 @defmac m4_min (@var{arg}, @dots{})
13542 @msindex{min}
13543 This macro was introduced in Autoconf 2.62.  Expand to the value
13544 of the minimum arithmetic expression among all the arguments.
13545 @end defmac
13547 @defmac m4_sign (@var{expr})
13548 @msindex{sign}
13549 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13550 @samp{1} if it is positive, and @samp{0} if it is zero.
13551 @end defmac
13553 @anchor{m4_version_compare}
13554 @defmac m4_version_compare (@var{version-1}, @var{version-2})
13555 @msindex{version_compare}
13556 This macro was introduced in Autoconf 2.53, but had a number of
13557 usability limitations that were not lifted until Autoconf 2.62.  Compare
13558 the version strings @var{version-1} and @var{version-2}, and expand to
13559 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13560 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
13561 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13562 element is a number along with optional case-insensitive letters
13563 designating beta releases.  The comparison stops at the leftmost element
13564 that contains a difference, although a 0 element compares equal to a
13565 missing element.
13567 It is permissible to include commit identifiers in @var{version}, such
13568 as an abbreviated SHA1 of the commit, provided there is still a
13569 monotonically increasing prefix to allow for accurate version-based
13570 comparisons.  For example, this paragraph was written when the
13571 development snapshot of autoconf claimed to be at version
13572 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13573 abbreviated commit identification of @samp{dc51}.
13575 @example
13576 m4_version_compare([1.1], [2.0])
13577 @result{}-1
13578 m4_version_compare([2.0b], [2.0a])
13579 @result{}1
13580 m4_version_compare([1.1.1], [1.1.1a])
13581 @result{}-1
13582 m4_version_compare([1.2], [1.1.1a])
13583 @result{}1
13584 m4_version_compare([1.0], [1])
13585 @result{}0
13586 m4_version_compare([1.1pre], [1.1PRE])
13587 @result{}0
13588 m4_version_compare([1.1a], [1,10])
13589 @result{}-1
13590 m4_version_compare([2.61a], [2.61a-248-dc51])
13591 @result{}-1
13592 m4_version_compare([2.61b], [2.61a-248-dc51])
13593 @result{}1
13594 @end example
13595 @end defmac
13597 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13598   @dvar{if-old, m4_fatal})
13599 @msindex{version_prereq}
13600 Compares @var{version} against the version of Autoconf currently
13601 running.  If the running version is at @var{version} or newer, expand
13602 @var{if-new-enough}, but if @var{version} is larger than the version
13603 currently executing, expand @var{if-old}, which defaults to printing an
13604 error message and exiting m4sugar with status 63.  When given only one
13605 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13606 Remember that the autoconf philosophy favors feature checks over version
13607 checks.
13608 @end defmac
13610 @node Set manipulation Macros
13611 @subsection Set manipulation in M4
13612 @cindex Set manipulation
13613 @cindex Data structure, set
13614 @cindex Unordered set manipulation
13616 Sometimes, it is necessary to track a set of data, where the order does
13617 not matter and where there are no duplicates in the set.  The following
13618 macros facilitate set manipulations.  Each set is an opaque object,
13619 which can only be accessed via these basic operations.  The underlying
13620 implementation guarantees linear scaling for set creation, which is more
13621 efficient than using the quadratic @code{m4_append_uniq}.  Both set
13622 names and values can be arbitrary strings, except for unbalanced quotes.
13623 This implementation ties up memory for removed elements until the next
13624 operation that must traverse all the elements of a set; and although
13625 that may slow down some operations until the memory for removed elements
13626 is pruned, it still guarantees linear performance.
13628 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13629 @msindex{set_add}
13630 Adds the string @var{value} as a member of set @var{set}.  Expand
13631 @var{if-uniq} if the element was added, or @var{if-dup} if it was
13632 previously in the set.  Operates in amortized constant time, so that set
13633 creation scales linearly.
13634 @end defmac
13636 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13637 @msindex{set_add_all}
13638 Adds each @var{value} to the set @var{set}.  This is slightly more
13639 efficient than repeatedly invoking @code{m4_set_add}.
13640 @end defmac
13642 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13643  @ovar{if-absent})
13644 @msindex{set_contains}
13645 Expands @var{if-present} if the string @var{value} is a member of
13646 @var{set}, otherwise @var{if-absent}.
13648 @example
13649 m4_set_contains([a], [1], [yes], [no])
13650 @result{}no
13651 m4_set_add([a], [1], [added], [dup])
13652 @result{}added
13653 m4_set_add([a], [1], [added], [dup])
13654 @result{}dup
13655 m4_set_contains([a], [1], [yes], [no])
13656 @result{}yes
13657 m4_set_remove([a], [1], [removed], [missing])
13658 @result{}removed
13659 m4_set_contains([a], [1], [yes], [no])
13660 @result{}no
13661 m4_set_remove([a], [1], [removed], [missing])
13662 @result{}missing
13663 @end example
13664 @end defmac
13666 @defmac m4_set_contents (@var{set}, @ovar{sep})
13667 @defmacx m4_set_dump (@var{set}, @ovar{sep})
13668 @msindex{set_contents}
13669 @msindex{set_dump}
13670 Expands to a single string consisting of all the members of the set
13671 @var{set}, each separated by @var{sep}, which is not expanded.
13672 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13673 memory occupied by removed elements, while @code{m4_set_dump} is a
13674 faster one-shot action that also deletes the set.  No provision is made
13675 for disambiguating members that contain a non-empty @var{sep} as a
13676 substring; use @code{m4_set_empty} to distinguish between an empty set
13677 and the set containing only the empty string.  The order of the output
13678 is unspecified; in the current implementation, part of the speed of
13679 @code{m4_set_dump} results from using a different output order than
13680 @code{m4_set_contents}.  These macros scale linearly in the size of the
13681 set before memory pruning, and @code{m4_set_contents([@var{set}],
13682 [@var{sep}])} is faster than
13683 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13685 @example
13686 m4_set_add_all([a], [1], [2], [3])
13687 @result{}
13688 m4_set_contents([a], [-])
13689 @result{}1-2-3
13690 m4_joinall([-]m4_set_listc([a]))
13691 @result{}1-2-3
13692 m4_set_dump([a], [-])
13693 @result{}3-2-1
13694 m4_set_contents([a])
13695 @result{}
13696 m4_set_add([a], [])
13697 @result{}
13698 m4_set_contents([a], [-])
13699 @result{}
13700 @end example
13701 @end defmac
13703 @defmac m4_set_delete (@var{set})
13704 @msindex{set_delete}
13705 Delete all elements and memory associated with @var{set}.  This is
13706 linear in the set size, and faster than removing one element at a time.
13707 @end defmac
13709 @defmac m4_set_difference (@var{seta}, @var{setb})
13710 @defmacx m4_set_intersection (@var{seta}, @var{setb})
13711 @defmacx m4_set_union (@var{seta}, @var{setb})
13712 @msindex{set_difference}
13713 @msindex{set_intersection}
13714 @msindex{set_union}
13715 Compute the relation between @var{seta} and @var{setb}, and output the
13716 result as a list of quoted arguments without duplicates and with a
13717 leading comma.  Set difference selects the elements in @var{seta} but
13718 not @var{setb}, intersection selects only elements in both sets, and
13719 union selects elements in either set.  These actions are linear in the
13720 sum of the set sizes.  The leading comma is necessary to distinguish
13721 between no elements and the empty string as the only element.
13723 @example
13724 m4_set_add_all([a], [1], [2], [3])
13725 @result{}
13726 m4_set_add_all([b], [3], [], [4])
13727 @result{}
13728 m4_set_difference([a], [b])
13729 @result{},1,2
13730 m4_set_difference([b], [a])
13731 @result{},,4
13732 m4_set_intersection([a], [b])
13733 @result{},3
13734 m4_set_union([a], [b])
13735 @result{},1,2,3,,4
13736 @end example
13737 @end defmac
13739 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13740 @msindex{set_empty}
13741 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13742 expand @var{if-elements}.  This macro operates in constant time.  Using
13743 this macro can help disambiguate output from @code{m4_set_contents} or
13744 @code{m4_set_list}.
13745 @end defmac
13747 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13748 @msindex{set_foreach}
13749 For each element in the set @var{set}, expand @var{action} with the
13750 macro @var{variable} defined as the set element.  Behavior is
13751 unspecified if @var{action} recursively lists the contents of @var{set}
13752 (although listing other sets is acceptable), or if it modifies the set
13753 in any way other than removing the element currently contained in
13754 @var{variable}.  This macro is faster than the corresponding
13755 @code{m4_foreach([@var{variable}],
13756 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13757 although @code{m4_set_map} might be faster still.
13759 @example
13760 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13761 @result{}
13762 m4_set_contents([a])
13763 @result{}12345
13764 m4_set_foreach([a], [i],
13765   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13766 @result{}24
13767 m4_set_contents([a])
13768 @result{}135
13769 @end example
13770 @end defmac
13772 @defmac m4_set_list (@var{set})
13773 @defmacx m4_set_listc (@var{set})
13774 @msindex{set_list}
13775 @msindex{set_listc}
13776 Produce a list of arguments, where each argument is a quoted element
13777 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
13778 by adding a leading comma if there are any set elements, whereas the
13779 variant @code{m4_set_list} cannot distinguish between an empty set and a
13780 set containing only the empty string.  These can be directly used in
13781 macros that take multiple arguments, such as @code{m4_join} or
13782 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13783 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
13784 memory occupied by removed elements is reclaimed during these macros.
13786 @example
13787 m4_set_add_all([a], [1], [2], [3])
13788 @result{}
13789 m4_set_list([a])
13790 @result{}1,2,3
13791 m4_set_list([b])
13792 @result{}
13793 m4_set_listc([b])
13794 @result{}
13795 m4_count(m4_set_list([b]))
13796 @result{}1
13797 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13798 @result{}0
13799 m4_set_add([b], [])
13800 @result{}
13801 m4_set_list([b])
13802 @result{}
13803 m4_set_listc([b])
13804 @result{},
13805 m4_count(m4_set_list([b]))
13806 @result{}1
13807 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13808 @result{}1
13809 @end example
13810 @end defmac
13812 @defmac m4_set_map (@var{set}, @var{action})
13813 @msindex{set_map}
13814 For each element in the set @var{set}, expand @var{action} with a single
13815 argument of the set element.  Behavior is unspecified if @var{action}
13816 recursively lists the contents of @var{set} (although listing other sets
13817 is acceptable), or if it modifies the set in any way other than removing
13818 the element passed as an argument.  This macro is faster than either
13819 corresponding counterpart of
13820 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13821 @code{m4_set_foreach([@var{set}], [var],
13822 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
13823 if more than one argument is needed for @var{action}, although it is
13824 more efficient to use @code{m4_set_map_sep} in that case.
13825 @end defmac
13827 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13828 @msindex{set_map_sep}
13829 For each element in the set @var{set}, expand
13830 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13831 between elements.  Behavior is unspecified if the expansion recursively
13832 lists the contents of @var{set} (although listing other sets
13833 is acceptable), or if it modifies the set in any way other than removing
13834 the element visited by the expansion.  This macro provides the most
13835 efficient means for non-destructively visiting the elements of a set; in
13836 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13837 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13838 @end defmac
13840 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13841  @ovar{if-absent})
13842 @msindex{set_remove}
13843 If @var{value} is an element in the set @var{set}, then remove it and
13844 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
13845 operates in constant time so that multiple removals will scale linearly
13846 rather than quadratically; but when used outside of
13847 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13848 until the set is later
13849 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
13850 other set operations are then less efficient between the time of element
13851 removal and subsequent memory compaction, but still maintain their
13852 guaranteed scaling performance.
13853 @end defmac
13855 @defmac m4_set_size (@var{set})
13856 @msindex{set_size}
13857 Expand to the size of the set @var{set}.  This implementation operates
13858 in constant time, and is thus more efficient than
13859 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13860 @end defmac
13863 @node Forbidden Patterns
13864 @subsection Forbidden Patterns
13865 @cindex Forbidden patterns
13866 @cindex Patterns, forbidden
13868 M4sugar provides a means to define suspicious patterns, patterns
13869 describing tokens which should not be found in the output.  For
13870 instance, if an Autoconf @file{configure} script includes tokens such as
13871 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13872 wrong (typically a macro was not evaluated because of overquotation).
13874 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13875 Additional layers, such as M4sh and Autoconf, add additional forbidden
13876 patterns to the list.
13878 @defmac m4_pattern_forbid (@var{pattern})
13879 @msindex{pattern_forbid}
13880 Declare that no token matching @var{pattern} must be found in the
13881 output.  The output file is (temporarily) split into one word per line
13882 as part of the @command{autom4te} post-processing, with each line (and
13883 therefore word) then being checked against the Perl regular expression
13884 @var{pattern}.  If the regular expression matches, and
13885 @code{m4_pattern_allow} does not also match, then an error is raised.
13887 Comments are not checked; this can be a problem if, for instance, you
13888 have some macro left unexpanded after an @samp{#include}.  No consensus
13889 is currently found in the Autoconf community, as some people consider it
13890 should be valid to name macros in comments (which doesn't make sense to
13891 the authors of this documentation: input, such as macros, should be
13892 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13893 document the output).
13895 As an example, if you define your own macros that begin with @samp{M_}
13896 and are composed from capital letters and underscores, the specification
13897 of @code{m4_pattern_forbid([^M_[A-Z_]+])} will ensure all your macros
13898 are expanded when not used in comments.
13900 As an example of a common use of this macro, consider what happens in
13901 packages that want to use the @command{pkg-config} script via the
13902 third-party @code{PKG_CHECK_MODULES} macro.  By default, if a developer
13903 checks out the development tree but has not yet installed the pkg-config
13904 macros locally, they can manage to successfully run @command{autoconf}
13905 on the package, but the resulting @file{configure} file will likely
13906 result in a confusing shell message about a syntax error on the line
13907 mentioning the unexpanded @code{PKG_CHECK_MODULES} macro.  On the other hand,
13908 if @file{configure.ac} includes @code{m4_pattern_forbid([^PKG_])}, the
13909 missing pkg-config macros will be detected immediately without allowing
13910 @command{autoconf} to succeed.
13911 @end defmac
13913 Of course, you might encounter exceptions to these generic rules, for
13914 instance you might have to refer to @samp{$m4_flags}.
13916 @defmac m4_pattern_allow (@var{pattern})
13917 @msindex{pattern_allow}
13918 Any token matching @var{pattern} is allowed, including if it matches an
13919 @code{m4_pattern_forbid} pattern.
13921 For example, Gnulib uses @code{m4_pattern_forbid([^gl_])} to reserve the
13922 @code{gl_} namespace for itself, but also uses
13923 @code{m4_pattern_allow([^gl_ES$])} to avoid a false negative on the
13924 valid locale name.
13925 @end defmac
13927 @node Debugging via autom4te
13928 @section Debugging via autom4te
13929 @cindex debugging tips
13930 @cindex autom4te debugging tips
13931 @cindex m4sugar debugging tips
13932 At times, it is desirable to see what was happening inside m4, to see
13933 why output was not matching expectations.  However, post-processing done
13934 by @command{autom4te} means that directly using the m4 builtin
13935 @code{m4_traceon} is likely to interfere with operation.  Also, frequent
13936 diversion changes and the concept of forbidden tokens make it difficult
13937 to use @code{m4_defn} to generate inline comments in the final output.
13939 There are a couple of tools to help with this.  One is the use of the
13940 @option{--trace} option provided by @command{autom4te} (as well as each
13941 of the programs that wrap @command{autom4te}, such as
13942 @command{autoconf}), in order to inspect when a macro is called and with
13943 which arguments.  For example, when this paragraph was written, the
13944 autoconf version could be found by:
13946 @example
13947 $ @kbd{autoconf --trace=AC_INIT}
13948 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13949 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13950 version is 2.63b.95-3963
13951 @end example
13953 Another trick is to print out the expansion of various m4 expressions to
13954 standard error or to an independent file, with no further m4 expansion,
13955 and without interfering with diversion changes or the post-processing
13956 done to standard output.  @code{m4_errprintn} shows a given expression
13957 on standard error.  For example, if you want to see the expansion of an
13958 autoconf primitive or of one of your autoconf macros, you can do it like
13959 this:
13961 @example
13962 $ @kbd{cat <<\EOF > configure.ac}
13963 AC_INIT
13964 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13965 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13966 AC_OUTPUT
13968 $ @kbd{autoconf}
13969 @error{}The definition of AC_DEFINE_UNQUOTED:
13970 @error{}_AC_DEFINE_Q([], $@@)
13971 @end example
13973 @node Programming in M4sh
13974 @chapter Programming in M4sh
13976 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13977 scripts.  This name was coined by Lars J. Aas, who notes that,
13978 according to the Webster's Revised Unabridged Dictionary (1913):
13980 @quotation
13981 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
13982 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
13984 @enumerate 1
13985 @item
13986 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13987 pressure@enddots{}
13989 @item
13990 A mixture of meal or bran and water fed to animals.
13992 @item
13993 A mess; trouble.  [Obs.] --Beau.@: & Fl.
13994 @end enumerate
13995 @end quotation
13997 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13998 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
13999 and environment variable namespace @samp{^as_}, and the here-document
14000 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
14001 define your own macros or output shell code that conflicts with these
14002 namespaces.
14004 @menu
14005 * Common Shell Constructs::     Portability layer for common shell constructs
14006 * Polymorphic Variables::       Support for indirect variable names
14007 * Initialization Macros::       Macros to establish a sane shell environment
14008 * File Descriptor Macros::      File descriptor macros for input and output
14009 @end menu
14011 @node Common Shell Constructs
14012 @section Common Shell Constructs
14014 M4sh provides portable alternatives for some common shell constructs
14015 that unfortunately are not portable in practice.
14017 @c Deprecated, to be replaced by a better API
14018 @ignore
14019 @defmac AS_BASENAME (@var{file-name})
14020 @asindex{BASENAME}
14021 Output the non-directory portion of @var{file-name}.  For example,
14022 if @code{$file} is @samp{/one/two/three}, the command
14023 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
14024 @end defmac
14025 @end ignore
14027 @defmac AS_BOX (@var{text}, @dvar{char, -})
14028 @asindex{BOX}
14029 Expand into shell code that will output @var{text} surrounded by a box
14030 with @var{char} in the top and bottom border.  @var{text} should not
14031 contain a newline, but may contain shell expansions valid for unquoted
14032 here-documents.  @var{char} defaults to @samp{-}, but can be any
14033 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
14034 @samp{&}, or @samp{`}.  This is useful for outputting a comment box into
14035 log files to separate distinct phases of script operation.
14036 @end defmac
14038 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
14039   @dots{}, @ovar{default})
14040 @asindex{CASE}
14041 Expand into a shell @samp{case} statement, where @var{word} is matched
14042 against one or more patterns.  @var{if-matched} is run if the
14043 corresponding pattern matched @var{word}, else @var{default} is run.
14044 @xref{Prerequisite Macros} for why
14045 this macro should be used instead of plain @samp{case} in code
14046 outside of an @code{AC_DEFUN} macro, when the contents of the
14047 @samp{case} use @code{AC_REQUIRE} directly or indirectly.
14048 @xref{case, , Limitations of Shell Builtins},
14049 for how this macro avoids some portability issues.
14050 @xref{Balancing Parentheses}
14051 for how this macro lets you write code with balanced parentheses
14052 even if your code must run on obsolescent shells.
14053 @end defmac
14055 @c Deprecated, to be replaced by a better API
14056 @defmac AS_DIRNAME (@var{file-name})
14057 @asindex{DIRNAME}
14058 Output the directory portion of @var{file-name}.  For example,
14059 if @code{$file} is @samp{/one/two/three}, the command
14060 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
14062 This interface may be improved in the future to avoid forks and losing
14063 trailing newlines.
14064 @end defmac
14066 @defmac AS_ECHO (@var{word})
14067 @asindex{ECHO}
14068 Emits @var{word} to the standard output, followed by a newline.  @var{word}
14069 must be a single shell word (typically a quoted string).  The bytes of
14070 @var{word} are output as-is, even if it starts with "-" or contains "\".
14071 Redirections can be placed outside the macro invocation.  This is much
14072 more portable than using @command{echo} (@pxref{echo, , Limitations of
14073 Shell Builtins}).
14074 @end defmac
14076 @defmac AS_ECHO_N (@var{word})
14077 @asindex{ECHO_N}
14078 Emits @var{word} to the standard output, without a following newline.
14079 @var{word} must be a single shell word (typically a quoted string) and,
14080 for portability, should not include more than one newline.  The bytes of
14081 @var{word} are output as-is, even if it starts with "-" or contains "\".
14082 Redirections can be placed outside the macro invocation.
14083 @end defmac
14085 @c We cannot use @dvar because the macro expansion mistreats backslashes.
14086 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
14087 @asindex{ESCAPE}
14088 Expands to @var{string}, with any characters in @var{chars} escaped with
14089 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
14090 and only contain characters from the set @samp{`\"$}; however,
14091 characters may be safely listed more than once in @var{chars} for the
14092 sake of syntax highlighting editors.  The current implementation expands
14093 @var{string} after adding escapes; if @var{string} contains macro calls
14094 that in turn expand to text needing shell quoting, you can use
14095 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
14097 The default for @var{chars} (@samp{\"$`}) is the set of characters
14098 needing escapes when @var{string} will be used literally within double
14099 quotes.  One common variant is the set of characters to protect when
14100 @var{string} will be used literally within back-ticks or an unquoted
14101 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
14102 be used to form a double-quoted string containing the same expansions
14103 that would have occurred if @var{string} were expanded in an unquoted
14104 here-document; however, when using this variant, care must be taken that
14105 @var{string} does not use double quotes within complex variable
14106 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
14107 with improper escapes.
14109 This macro is often used with @code{AS_ECHO}.  For an example, observe
14110 the output generated by the shell code generated from this snippet:
14112 @example
14113 foo=bar
14114 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
14115 @result{}"$foo" = "bar"
14116 m4_define([macro], [a, [\b]])
14117 AS_ECHO(["AS_ESCAPE([[macro]])"])
14118 @result{}macro
14119 AS_ECHO(["AS_ESCAPE([macro])"])
14120 @result{}a, b
14121 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
14122 @result{}a, \b
14123 @end example
14125 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
14126 @comment the case of @var{string} that does not contain '.
14127 To escape a string that will be placed within single quotes, use:
14129 @example
14130 m4_bpatsubst([[@var{string}]], ['], ['\\''])
14131 @end example
14132 @end defmac
14134 @defmac AS_EXECUTABLE_P (@var{file})
14135 @asindex{EXECUTABLE_P}
14136 Emit code to probe whether @var{file} is a regular file with executable
14137 permissions (and not a directory with search permissions).  The caller
14138 is responsible for quoting @var{file}.
14139 @end defmac
14141 @defmac AS_EXIT (@dvar{status, $?})
14142 @asindex{EXIT}
14143 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
14144 This macro
14145 works around shells that see the exit status of the command prior to
14146 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
14147 of Shell Builtins}).
14148 @end defmac
14150 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
14151 @asindex{IF}
14152 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
14153 run shell code @var{run-if-true1}, else examine further tests.  If no test
14154 exits with a zero status, run shell code @var{run-if-false}, with
14155 simplifications if either @var{run-if-true1} or @var{run-if-false}
14156 is empty.  For example,
14158 @example
14159 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
14160       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
14161       [echo foo not specified])
14162 @end example
14164 @noindent
14165 ensures any required macros of @code{HANDLE_FOO}
14166 are expanded before the first test.
14168 This macro should be used instead of plain @samp{if} in code
14169 outside of an @code{AC_DEFUN} macro, when the contents of the @samp{if}
14170 use @code{AC_REQUIRE} directly or indirectly (@pxref{Prerequisite Macros}).
14171 @end defmac
14173 @defmac AS_MKDIR_P (@var{file-name})
14174 @asindex{MKDIR_P}
14175 Make the directory @var{file-name}, including intervening directories
14176 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
14177 except that it is portable to older versions of @command{mkdir} that
14178 lack support for the @option{-p} option or for the @option{--}
14179 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
14180 @code{AS_MKDIR_P}
14181 succeeds if @var{file-name} is a symbolic link to an existing directory,
14182 even though Posix is unclear whether @samp{mkdir -p} should
14183 succeed in that case.  If creation of @var{file-name} fails, exit the
14184 script.
14186 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
14187 @end defmac
14189 @defmac AS_SET_STATUS (@var{status})
14190 @asindex{SET_STATUS}
14191 Emit shell code to set the value of @samp{$?} to @var{status}, as
14192 efficiently as possible.  However, this is not guaranteed to abort a
14193 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
14194 Builtins}).  This should also be used at the end of a complex shell
14195 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
14196 a DJGPP shell bug.
14197 @end defmac
14199 @defmac AS_TR_CPP (@var{expression})
14200 @asindex{TR_CPP}
14201 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
14202 For example:
14204 @example
14205 # This outputs "#define HAVE_CHAR_P 1".
14206 # Notice the m4 quoting around #, to prevent an m4 comment
14207 type="char *"
14208 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
14209 @end example
14210 @end defmac
14212 @defmac AS_TR_SH (@var{expression})
14213 @asindex{TR_SH}
14214 Transform @var{expression} into shell code that generates a valid shell
14215 variable name.  The result is literal when possible at m4 time, but must
14216 be used with @code{eval} if @var{expression} causes shell indirections.
14217 For example:
14219 @example
14220 # This outputs "Have it!".
14221 header="sys/some file.h"
14222 eval AS_TR_SH([HAVE_$header])=yes
14223 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
14224 @end example
14225 @end defmac
14227 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
14228 @asindex{SET_CATFILE}
14229 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
14230 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
14231 @var{file} is absolute, etc.).
14232 @end defmac
14234 @defmac AS_UNSET (@var{var})
14235 @asindex{UNSET}
14236 Unsets the shell variable @var{var}, working around bugs in older
14237 shells (@pxref{unset, , Limitations of Shell
14238 Builtins}).  @var{var} can be a literal or indirect variable name.
14239 @end defmac
14241 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
14242   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
14243 @asindex{VERSION_COMPARE}
14244 Compare two strings @var{version-1} and @var{version-2}, possibly
14245 containing shell variables, as version strings, and expand
14246 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
14247 depending upon the result.
14248 The algorithm to compare is similar to the one used by strverscmp in
14249 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
14250 The GNU C Library}).
14251 @end defmac
14253 @node Polymorphic Variables
14254 @section Support for indirect variable names
14255 @cindex variable name indirection
14256 @cindex polymorphic variable name
14257 @cindex indirection, variable name
14259 Often, it is convenient to write a macro that will emit shell code
14260 operating on a shell variable.  The simplest case is when the variable
14261 name is known.  But a more powerful idiom is writing shell code that can
14262 work through an indirection, where another variable or command
14263 substitution produces the name of the variable to actually manipulate.
14264 M4sh supports the notion of polymorphic shell variables, making it easy
14265 to write a macro that can deal with either literal or indirect variable
14266 names and output shell code appropriate for both use cases.  Behavior is
14267 undefined if expansion of an indirect variable does not result in a
14268 literal variable name.
14270 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
14271   @dvarv{if-simple-ref, if-not})
14272 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
14273   @ovar{if-not}, @dvarv{if-simple-ref, if-not})
14274 @asindex{LITERAL_IF}
14275 @asindex{LITERAL_WORD_IF}
14276 If the expansion of @var{expression} is definitely a shell literal,
14277 expand @var{if-literal}.  If the expansion of @var{expression} looks
14278 like it might contain shell indirections (such as @code{$var} or
14279 @code{`expr`}), then @var{if-not} is expanded.  Sometimes, it is
14280 possible to output optimized code if @var{expression} consists only of
14281 shell variable expansions (such as @code{$@{var@}}), in which case
14282 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
14283 should always be safe.  @code{AS_LITERAL_WORD_IF} only expands
14284 @var{if-literal} if @var{expression} looks like a single shell word,
14285 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
14286 in @var{expression}.
14288 In order to reduce the time spent recognizing whether an
14289 @var{expression} qualifies as a literal or a simple indirection, the
14290 implementation is somewhat conservative: @var{expression} must be a
14291 single shell word (possibly after stripping whitespace), consisting only
14292 of bytes that would have the same meaning whether unquoted or enclosed
14293 in double quotes (for example, @samp{a.b} results in @var{if-literal},
14294 even though it is not a valid shell variable name; while both @samp{'a'}
14295 and @samp{[$]} result in @var{if-not}, because they behave differently
14296 than @samp{"'a'"} and @samp{"[$]"}).  This macro can be used in contexts
14297 for recognizing portable file names (such as in the implementation of
14298 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
14299 valid variable names (such as in the implementation of @code{AS_TR_SH},
14300 which uses an additional @code{m4_translit} to convert @samp{.} to
14301 @samp{_}).
14303 This example shows how to read the contents of the shell variable
14304 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}.  It
14305 results in a script that will output the line @samp{hello} three times.
14307 @example
14308 AC_DEFUN([MY_ACTION],
14309 [AS_LITERAL_IF([$1],
14310   [echo "$$1"],
14311 @c $$
14312   [AS_VAR_COPY([var], [$1])
14313    echo "$var"],
14314   [eval 'echo "$'"$1"\"])])
14315 foo=bar bar=hello
14316 MY_ACTION([bar])
14317 MY_ACTION([`echo bar`])
14318 MY_ACTION([$foo])
14319 @end example
14320 @end defmac
14322 @defmac AS_VAR_APPEND (@var{var}, @var{text})
14323 @asindex{VAR_APPEND}
14324 Emit shell code to append the shell expansion of @var{text} to the end
14325 of the current contents of the polymorphic shell variable @var{var},
14326 taking advantage of shells that provide the @samp{+=} extension for more
14327 efficient scaling.
14329 For situations where the final contents of @var{var} are relatively
14330 short (less than 256 bytes), it is more efficient to use the simpler
14331 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
14332 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
14333 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}).  But in the case
14334 when the script will be repeatedly appending text into @code{var},
14335 issues of scaling start to become apparent.  A naive implementation
14336 requires execution time linear to the length of the current contents of
14337 @var{var} as well as the length of @var{text} for a single append, for
14338 an overall quadratic scaling with multiple appends.  This macro takes
14339 advantage of shells which provide the extension
14340 @code{@var{var}+=@var{text}}, which can provide amortized constant time
14341 for a single append, for an overall linear scaling with multiple
14342 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
14343 @var{text} be quoted properly to avoid field splitting and file name
14344 expansion.
14345 @end defmac
14347 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
14348 @asindex{VAR_ARITH}
14349 Emit shell code to compute the arithmetic expansion of @var{expression},
14350 assigning the result as the contents of the polymorphic shell variable
14351 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
14352 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
14353 syntax for a valid @var{expression} is rather limited: all operators
14354 must occur as separate shell arguments and with proper quoting;
14355 the only operators supported are @samp{*}, @samp{/}, @samp{%}, binary
14356 @samp{+}, binary @samp{-}, @samp{>}, @samp{>=}, @samp{<}, @samp{<=},
14357 @samp{!=}, @samp{&}, and @samp{|};
14358 all variables containing numbers must be expanded prior to the computation;
14359 the first shell argument must not start with @samp{-};
14360 and each number must be an optional @samp{-} followed by one or more
14361 decimal digits, where the first digit is nonzero if there is more than
14362 one digit.  In the following example, this snippet
14363 will print @samp{(2+3)*4 == 20}.
14365 @example
14366 bar=3
14367 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
14368 echo "(2+$bar)*4 == $foo"
14369 @end example
14370 @end defmac
14372 @defmac AS_VAR_COPY (@var{dest}, @var{source})
14373 @asindex{VAR_COPY}
14374 Emit shell code to assign the contents of the polymorphic shell variable
14375 @var{source} to the polymorphic shell variable @var{dest}.  For example,
14376 executing this M4sh snippet will output @samp{bar hi}:
14378 @example
14379 foo=bar bar=hi
14380 AS_VAR_COPY([a], [foo])
14381 AS_VAR_COPY([b], [$foo])
14382 echo "$a $b"
14383 @end example
14385 When it is necessary to access the contents of an indirect variable
14386 inside a shell double-quoted context, the recommended idiom is to first
14387 copy the contents into a temporary literal shell variable.
14389 @smallexample
14390 for header in stdint_h inttypes_h ; do
14391   AS_VAR_COPY([var], [ac_cv_header_$header])
14392   echo "$header detected: $var"
14393 done
14394 @end smallexample
14395 @end defmac
14397 @comment AS_VAR_GET is intentionally undocumented; it can't handle
14398 @comment trailing newlines uniformly, and forks too much.
14400 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
14401   @ovar{if-not-equal})
14402 @asindex{VAR_IF}
14403 Output a shell conditional statement.  If the contents of the
14404 polymorphic shell variable @var{var} match the string @var{word},
14405 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  @var{word}
14406 must be a single shell word (typically a quoted string).  Avoids
14407 shell bugs if an interrupt signal arrives while a command substitution
14408 in @var{var} is being expanded.
14409 @end defmac
14411 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
14412 @defmacx AS_VAR_POPDEF (@var{m4-name})
14413 @asindex{VAR_PUSHDEF}
14414 @asindex{VAR_POPDEF}
14415 @cindex composing variable names
14416 @cindex variable names, composing
14417 A common M4sh idiom involves composing shell variable names from an m4
14418 argument (for example, writing a macro that uses a cache variable).
14419 @var{value} can be an arbitrary string, which will be transliterated
14420 into a valid shell name by @code{AS_TR_SH}.  In order to access the
14421 composed variable name based on @var{value}, it is easier to declare a
14422 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
14423 that macro as the argument to subsequent @code{AS_VAR} macros as a
14424 polymorphic variable name, and finally free the temporary macro with
14425 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
14426 to avoid excess newlines in the output.
14428 Here is an involved example, that shows the power of writing macros that
14429 can handle composed shell variable names:
14431 @example
14432 m4_define([MY_CHECK_HEADER],
14433 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
14434 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
14435 AS_VAR_POPDEF([my_Header])dnl
14437 MY_CHECK_HEADER([stdint.h])
14438 for header in inttypes.h stdlib.h ; do
14439   MY_CHECK_HEADER([$header])
14440 done
14441 @end example
14443 @noindent
14444 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
14445 variable names.  In the first invocation, the m4 argument is
14446 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
14447 As a result, the temporary macro @code{my_Header} expands to the literal
14448 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
14449 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
14450 temporary macro @code{my_Header} expands to the indirect shell name
14451 @samp{$as_my_Header}.  During the shell execution of the for loop, when
14452 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
14453 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
14454 platform where all three headers have been previously detected, the
14455 output of the script will include:
14457 @smallexample
14458 header stdint.h detected
14459 header inttypes.h detected
14460 header stdlib.h detected
14461 @end smallexample
14462 @end defmac
14464 @defmac AS_VAR_SET (@var{var}, @ovar{value})
14465 @asindex{VAR_SET}
14466 Emit shell code to assign the contents of the polymorphic shell variable
14467 @var{var} to the shell expansion of @var{value}.  @var{value} is not
14468 subject to field splitting or file name expansion, so if command
14469 substitution is used, it may be done with @samp{`""`} rather than using
14470 an intermediate variable (@pxref{Shell Substitutions}).  However,
14471 @var{value} does undergo rescanning for additional macro names; behavior
14472 is unspecified if late expansion results in any shell meta-characters.
14473 @end defmac
14475 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
14476 @asindex{VAR_SET_IF}
14477 Emit a shell conditional statement, which executes @var{if-set} if the
14478 polymorphic shell variable @code{var} is set to any value, and
14479 @var{if-undef} otherwise.
14480 @end defmac
14482 @defmac AS_VAR_TEST_SET (@var{var})
14483 @asindex{VAR_TEST_SET}
14484 Emit a shell statement that results in a successful exit status only if
14485 the polymorphic shell variable @code{var} is set.
14486 @end defmac
14488 @node Initialization Macros
14489 @section Initialization Macros
14491 @defmac AS_BOURNE_COMPATIBLE
14492 @asindex{BOURNE_COMPATIBLE}
14493 Set up the shell to be more compatible with the Bourne shell as
14494 standardized by Posix, if possible.  This may involve setting
14495 environment variables, or setting options, or similar
14496 implementation-specific actions.  This macro is deprecated, since
14497 @code{AS_INIT} already invokes it.
14498 @end defmac
14500 @defmac AS_INIT
14501 @asindex{INIT}
14502 @evindex LC_ALL
14503 @evindex SHELL
14504 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
14505 outputs the @code{#! /bin/sh} line, a notice about where the output was
14506 generated from, and code to sanitize the environment for the rest of the
14507 script.  Among other initializations, this sets @env{SHELL} to the shell
14508 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14509 ensure the C locale.  Finally, it changes the current diversion to
14510 @code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
14511 and @code{AT_INIT}, so shell code in @file{configure},
14512 @file{config.status}, and @file{testsuite} all benefit from a sanitized
14513 shell environment.
14514 @end defmac
14516 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14517 @asindex{INIT_GENERATED}
14518 Emit shell code to start the creation of a subsidiary shell script in
14519 @var{file}, including changing @var{file} to be executable.  This macro
14520 populates the child script with information learned from the parent
14521 (thus, the emitted code is equivalent in effect, but more efficient,
14522 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14523 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
14524 beginning of the child, prior to the shell initialization code, and is
14525 subject to parameter expansion, command substitution, and backslash
14526 quote removal.  The
14527 parent script should check the exit status after this macro, in case
14528 @var{file} could not be properly created (for example, if the disk was
14529 full).  If successfully created, the parent script can then proceed to
14530 append additional M4sh constructs into the child script.
14532 Note that the child script starts life without a log file open, so if
14533 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14534 must temporarily disable any attempts to use the log file until after
14535 emitting code to open a log within the child.  On the other hand, if the
14536 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14537 @samp{1}, then the child script already has code that copies stdout to
14538 that descriptor.  Currently, the suggested
14539 idiom for writing a M4sh shell script from within another script is:
14541 @example
14542 AS_INIT_GENERATED([@var{file}], [[# My child script.
14543 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14544 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14545 cat >> "@var{file}" <<\__EOF__
14546 # Code to initialize AS_MESSAGE_LOG_FD
14547 m4_popdef([AS_MESSAGE_LOG_FD])dnl
14548 # Additional code
14549 __EOF__
14550 @end example
14552 This, however, may change in the future as the M4sh interface is
14553 stabilized further.
14555 Also, be aware that use of @env{LINENO} within the child script may
14556 report line numbers relative to their location in the parent script,
14557 even when using @code{AS_LINENO_PREPARE}, if the parent script was
14558 unable to locate a shell with working @env{LINENO} support.
14559 @end defmac
14561 @defmac AS_LINENO_PREPARE
14562 @asindex{LINENO_PREPARE}
14563 @evindex LINENO
14564 Find a shell that supports the special variable @env{LINENO}, which
14565 contains the number of the currently executing line.  This macro is
14566 automatically invoked by @code{AC_INIT} in configure scripts.
14567 @end defmac
14569 @defmac AS_ME_PREPARE
14570 @asindex{ME_PREPARE}
14571 Set up variable @env{as_me} to be the basename of the currently executing
14572 script.  This macro is automatically invoked by @code{AC_INIT} in
14573 configure scripts.
14574 @end defmac
14576 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14577 @asindex{TMPDIR}
14578 @evindex TMPDIR
14579 @ovindex tmp
14580 Create, as safely as possible, a temporary sub-directory within
14581 @var{dir} with a name starting with @var{prefix}.  @var{prefix} should
14582 be 2--4 characters, to make it slightly easier to identify the owner of
14583 the directory.  If @var{dir} is omitted, then the value of @env{TMPDIR}
14584 will be used (defaulting to @samp{/tmp}).  On success, the name of the
14585 newly created directory is stored in the shell variable @code{tmp}.  On
14586 error, the script is aborted.
14588 Typically, this macro is coupled with some exit traps to delete the created
14589 directory and its contents on exit or interrupt.  However, there is a
14590 slight window between when the directory is created and when the name is
14591 actually known to the shell, so an interrupt at the right moment might
14592 leave the temporary directory behind.  Hence it is important to use a
14593 @var{prefix} that makes it easier to determine if a leftover temporary
14594 directory from an interrupted script is safe to delete.
14596 The use of the output variable @samp{$tmp} rather than something in the
14597 @samp{as_} namespace is historical; it has the unfortunate consequence
14598 that reusing this otherwise common name for any other purpose inside
14599 your script has the potential to break any cleanup traps designed to
14600 remove the temporary directory.
14601 @end defmac
14603 @defmac AS_SHELL_SANITIZE
14604 @asindex{SHELL_SANITIZE}
14605 Initialize the shell suitably for @command{configure} scripts.  This has
14606 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14607 environment variables for predictable results from configuration tests.
14608 For example, it sets @env{LC_ALL} to change to the default C locale.
14609 @xref{Special Shell Variables}.  This macro is deprecated, since
14610 @code{AS_INIT} already invokes it.
14611 @end defmac
14614 @node File Descriptor Macros
14615 @section File Descriptor Macros
14616 @cindex input
14617 @cindex standard input
14618 @cindex file descriptors
14619 @cindex descriptors
14620 @cindex low-level output
14621 @cindex output, low-level
14623 The following macros define file descriptors used to output messages
14624 (or input values) from @file{configure} scripts.
14625 For example:
14627 @example
14628 echo "$wombats found" >&AS_MESSAGE_LOG_FD
14629 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
14630 read kangaroos <&AS_ORIGINAL_STDIN_FD`
14631 @end example
14633 @noindent
14634 However doing so is seldom needed, because Autoconf provides higher
14635 level macros as described below.
14637 @defmac AS_MESSAGE_FD
14638 @asindex{MESSAGE_FD}
14639 The file descriptor for @samp{checking for...}  messages and results.
14640 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14641 clients.  However, @code{AC_INIT} shuffles things around to another file
14642 descriptor, in order to allow the @option{-q} option of
14643 @command{configure} to choose whether messages should go to the script's
14644 standard output or be discarded.
14646 If you want to display some messages, consider using one of the printing
14647 macros (@pxref{Printing Messages}) instead.  Copies of messages output
14648 via these macros are also recorded in @file{config.log}.
14649 @end defmac
14651 @anchor{AS_MESSAGE_LOG_FD}
14652 @defmac AS_MESSAGE_LOG_FD
14653 @asindex{MESSAGE_LOG_FD}
14654 This must either be empty, or expand to a file descriptor for log
14655 messages.  By default, @code{AS_INIT} sets this macro to the empty
14656 string for standalone M4sh clients, thus disabling logging.  However,
14657 @code{AC_INIT} shuffles things around so that both @command{configure}
14658 and @command{config.status} use @file{config.log} for log messages.
14659 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14660 Compiler}), redirect all output to this descriptor.  You may want to do
14661 so if you develop such a low-level macro.
14662 @end defmac
14664 @defmac AS_ORIGINAL_STDIN_FD
14665 @asindex{ORIGINAL_STDIN_FD}
14666 This must expand to a file descriptor for the original standard input.
14667 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14668 M4sh clients.  However, @code{AC_INIT} shuffles things around for
14669 safety.
14671 When @command{configure} runs, it may accidentally execute an
14672 interactive command that has the same name as the non-interactive meant
14673 to be used or checked.  If the standard input was the terminal, such
14674 interactive programs would cause @command{configure} to stop, pending
14675 some user input.  Therefore @command{configure} redirects its standard
14676 input from @file{/dev/null} during its initialization.  This is not
14677 normally a problem, since @command{configure} normally does not need
14678 user input.
14680 In the extreme case where your @file{configure} script really needs to
14681 obtain some values from the original standard input, you can read them
14682 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14683 @end defmac
14686 @c =================================================== Writing Autoconf Macros.
14688 @node Writing Autoconf Macros
14689 @chapter Writing Autoconf Macros
14691 When you write a feature test that could be applicable to more than one
14692 software package, the best thing to do is encapsulate it in a new macro.
14693 Here are some instructions and guidelines for writing Autoconf macros.
14694 You should also familiarize yourself with M4sugar (@pxref{Programming in M4})
14695 and M4sh (@pxref{Programming in M4sh}).
14697 @menu
14698 * Macro Definitions::           Basic format of an Autoconf macro
14699 * Macro Names::                 What to call your new macros
14700 * Dependencies Between Macros::  What to do when macros depend on other macros
14701 * Obsoleting Macros::           Warning about old ways of doing things
14702 * Coding Style::                Writing Autoconf macros @`a la Autoconf
14703 @end menu
14705 @node Macro Definitions
14706 @section Macro Definitions
14708 @defmac AC_DEFUN (@var{name}, @ovar{body})
14709 @acindex{DEFUN}
14710 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14711 similar to the M4 builtin @code{m4_define} macro; this creates a macro
14712 named @var{name} and with @var{body} as its expansion.  In addition to
14713 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14714 constrain the order in which macros are called, while avoiding redundant
14715 output (@pxref{Prerequisite Macros}).
14716 @end defmac
14718 An Autoconf macro definition looks like this:
14720 @example
14721 AC_DEFUN(@var{macro-name}, @var{macro-body})
14722 @end example
14724 You can refer to any arguments passed to the macro as @samp{$1},
14725 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4,
14726 GNU M4}, for more complete information on writing M4 macros.
14728 Most macros fall in one of two general categories.  The first category
14729 includes macros which take arguments, in order to generate output
14730 parameterized by those arguments.  Macros in this category are designed
14731 to be directly expanded, often multiple times, and should not be used as
14732 the argument to @code{AC_REQUIRE}.  The other category includes macros
14733 which are shorthand for a fixed block of text, and therefore do not take
14734 arguments.  For this category of macros, directly expanding the macro
14735 multiple times results in redundant output, so it is more common to use
14736 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14737 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14739 Be sure to properly quote both the @var{macro-body} @emph{and} the
14740 @var{macro-name} to avoid any problems if the macro happens to have
14741 been previously defined.
14743 Each macro should have a header comment that gives its prototype, and a
14744 brief description.  When arguments have default values, display them in
14745 the prototype.  For example:
14747 @example
14748 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14749 # --------------------------------------
14750 m4_define([AC_MSG_ERROR],
14751   [@{ AS_MESSAGE([error: $1], [2])
14752      exit m4_default([$2], [1]); @}])
14753 @end example
14755 Comments about the macro should be left in the header comment.  Most
14756 other comments make their way into @file{configure}, so just keep
14757 using @samp{#} to introduce comments.
14759 @cindex @code{dnl}
14760 If you have some special comments about pure M4 code, comments
14761 that make no sense in @file{configure} and in the header comment, then
14762 use the builtin @code{dnl}: it causes M4 to discard the text
14763 through the next newline.
14765 Keep in mind that @code{dnl} is rarely needed to introduce comments;
14766 @code{dnl} is more useful to get rid of the newlines following macros
14767 that produce no output, such as @code{AC_REQUIRE}.
14769 Public third-party macros need to use @code{AC_DEFUN}, and not
14770 @code{m4_define}, in order to be found by @command{aclocal}
14771 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14772 Additionally, if it is ever determined that a macro should be made
14773 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14774 in order to have @command{autoupdate} assist the user in choosing a
14775 better alternative, but there is no corresponding way to make
14776 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14778 There is another subtle, but important, difference between using
14779 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14780 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
14781 block of text with a @code{m4_define} macro that will expand to the same
14782 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
14783 the same content does not necessarily give the same results, because it
14784 changes the location where any embedded but unsatisfied
14785 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
14786 example of this, see @ref{Expanded Before Required}.
14788 @node Macro Names
14789 @section Macro Names
14791 All of the public Autoconf macros have all-uppercase names in the
14792 namespace @samp{^AC_} to prevent them from accidentally conflicting with
14793 other text; Autoconf also reserves the namespace @samp{^_AC_} for
14794 internal macros.  All shell variables that they use for internal
14795 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
14796 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
14797 @command{configure}, files produced by Autoconf make heavy use of the
14798 file system namespace @samp{^conf}.
14800 Since Autoconf is built on top of M4sugar (@pxref{Programming in
14801 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14802 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
14803 @file{configure.ac} is also designed to be scanned by Autoheader,
14804 Autoscan, Autoupdate, and Automake, you should be aware of the
14805 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
14806 the namespace of a package that does not own the macro or shell code you
14807 are writing.
14809 To ensure that your macros don't conflict with present or future
14810 Autoconf macros, you should prefix your own macro names and any shell
14811 variables they use with some other sequence.  Possibilities include your
14812 initials, or an abbreviation for the name of your organization or
14813 software package.  Historically, people have not always followed the
14814 rule of using a namespace appropriate for their package, and this has
14815 made it difficult for determining the origin of a macro (and where to
14816 report bugs about that macro), as well as difficult for the true
14817 namespace owner to add new macros without interference from pre-existing
14818 uses of third-party macros.  Perhaps the best example of this confusion
14819 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14820 to Gettext.
14822 Most of the Autoconf macros' names follow a structured naming convention
14823 that indicates the kind of feature check by the name.  The macro names
14824 consist of several words, separated by underscores, going from most
14825 general to most specific.  The names of their cache variables use the
14826 same convention (@pxref{Cache Variable Names}, for more information on
14827 them).
14829 The first word of the name after the namespace initials (such as
14830 @samp{AC_}) usually tells the category
14831 of the feature being tested.  Here are the categories used in Autoconf for
14832 specific test macros, the kind of macro that you are more likely to
14833 write.  They are also used for cache variables, in all-lowercase.  Use
14834 them where applicable; where they're not, invent your own categories.
14836 @table @code
14837 @item C
14838 C language builtin features.
14839 @item DECL
14840 Declarations of C variables in header files.
14841 @item FUNC
14842 Functions in libraries.
14843 @item GROUP
14844 Posix group owners of files.
14845 @item HEADER
14846 Header files.
14847 @item LIB
14848 C libraries.
14849 @item PROG
14850 The base names of programs.
14851 @item MEMBER
14852 Members of aggregates.
14853 @item SYS
14854 Operating system features.
14855 @item TYPE
14856 C builtin or declared types.
14857 @item VAR
14858 C variables in libraries.
14859 @end table
14861 After the category comes the name of the particular feature being
14862 tested.  Any further words in the macro name indicate particular aspects
14863 of the feature.  For example, @code{AC_PROG_MAKE_SET} checks whether
14864 @command{make} sets a variable to its own name.
14866 An internal macro should have a name that starts with an underscore;
14867 Autoconf internals should therefore start with @samp{_AC_}.
14868 Additionally, a macro that is an internal subroutine of another macro
14869 should have a name that starts with an underscore and the name of that
14870 other macro, followed by one or more words saying what the internal
14871 macro does.  For example, @code{AC_PATH_X} has internal macros
14872 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14874 @node Dependencies Between Macros
14875 @section Dependencies Between Macros
14876 @cindex Dependencies between macros
14878 Some Autoconf macros depend on other macros having been called first in
14879 order to work correctly.  Autoconf provides a way to ensure that certain
14880 macros are called if needed and a way to warn the user if macros are
14881 called in an order that might cause incorrect operation.
14883 @menu
14884 * Prerequisite Macros::         Ensuring required information
14885 * Suggested Ordering::          Warning about possible ordering problems
14886 * One-Shot Macros::             Ensuring a macro is called only once
14887 @end menu
14889 @node Prerequisite Macros
14890 @subsection Prerequisite Macros
14891 @cindex Prerequisite macros
14892 @cindex Macros, prerequisites
14894 A macro that you write might need to use values that have previously
14895 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
14896 examines the output of @code{flex} or @code{lex}, so it depends on
14897 @code{AC_PROG_LEX} having been called first to set the shell variable
14898 @code{LEX}.
14900 Rather than forcing the user of the macros to keep track of the
14901 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14902 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
14903 called if it is needed, and only called once.
14905 @defmac AC_REQUIRE (@var{macro-name})
14906 @acindex{REQUIRE}
14907 If the M4 macro @var{macro-name} has not already been called, call it
14908 (without any arguments).  Make sure to quote @var{macro-name} with
14909 square brackets.  @var{macro-name} must have been defined using
14910 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14911 that it has been called.
14913 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14914 must not be called from the top level.  Also, it does not make sense to
14915 require a macro that takes parameters.
14916 @end defmac
14918 @code{AC_REQUIRE} is often misunderstood.  It really implements
14919 dependencies between macros in the sense that if one macro depends upon
14920 another, the latter is expanded @emph{before} the body of the
14921 former.  To be more precise, the required macro is expanded before
14922 the outermost defined macro in the current expansion stack.
14923 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14924 @code{FOO}.  For instance, this definition of macros:
14926 @example
14927 @group
14928 AC_DEFUN([TRAVOLTA],
14929 [test "$body_temperature_in_celsius" -gt 38 &&
14930   dance_floor=occupied])
14931 AC_DEFUN([NEWTON_JOHN],
14932 [test "x$hair_style" = xcurly &&
14933   dance_floor=occupied])
14934 @end group
14936 @group
14937 AC_DEFUN([RESERVE_DANCE_FLOOR],
14938 [if test "x`date +%A`" = xSaturday; then
14939   AC_REQUIRE([TRAVOLTA])
14940   AC_REQUIRE([NEWTON_JOHN])
14941 fi])
14942 @end group
14943 @end example
14945 @noindent
14946 with this @file{configure.ac}
14948 @example
14949 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14950 RESERVE_DANCE_FLOOR
14951 if test "x$dance_floor" = xoccupied; then
14952   AC_MSG_ERROR([cannot pick up here, let's move])
14954 @end example
14956 @noindent
14957 does not leave you with a better chance to meet a kindred soul on
14958 days other than Saturday, since the call to @code{RESERVE_DANCE_FLOOR}
14959 expands to:
14961 @example
14962 @group
14963 test "$body_temperature_in_Celsius" -gt 38 &&
14964   dance_floor=occupied
14965 test "x$hair_style" = xcurly &&
14966   dance_floor=occupied
14968 if test "x`date +%A`" = xSaturday; then
14972 @end group
14973 @end example
14975 This behavior was chosen on purpose: (i) it prevents messages in
14976 required macros from interrupting the messages in the requiring macros;
14977 (ii) it avoids bad surprises when shell conditionals are used, as in:
14979 @example
14980 @group
14981 if @dots{}; then
14982   AC_REQUIRE([SOME_CHECK])
14984 @dots{}
14985 SOME_CHECK
14986 @end group
14987 @end example
14989 However, this implementation can lead to another class of problems.
14990 Consider the case where an outer macro first expands, then indirectly
14991 requires, an inner macro:
14993 @example
14994 AC_DEFUN([TESTA], [[echo in A
14995 if test -n "$SEEN_A" ; then echo duplicate ; fi
14996 SEEN_A=:]])
14997 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14998 if test -z "$SEEN_A" ; then echo bug ; fi]])
14999 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
15000 AC_DEFUN([OUTER], [[echo in OUTER]
15001 TESTA
15002 TESTC])
15003 OUTER
15004 @end example
15006 @noindent
15007 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
15008 recognized that @code{TESTB} needed to be hoisted prior to the expansion
15009 of @code{OUTER}, but because @code{TESTA} had already been directly
15010 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
15011 @code{TESTB} occurs prior to its prerequisites, leading to the following
15012 output:
15014 @example
15015 in B
15017 in OUTER
15018 in A
15019 in C
15020 @end example
15022 @noindent
15023 Newer Autoconf is smart enough to recognize this situation, and hoists
15024 @code{TESTA} even though it has already been expanded, but issues a
15025 syntax warning in the process.  This is because the hoisted expansion of
15026 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
15027 redundant code, and causes its own set of problems if the hoisted macro
15028 is not idempotent:
15030 @example
15031 in A
15032 in B
15033 in OUTER
15034 in A
15035 duplicate
15036 in C
15037 @end example
15039 The bug is not in Autoconf, but in the macro definitions.  If you ever
15040 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
15041 that the macro only needs to be expanded once.  But to enforce this,
15042 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
15043 this only helps in Autoconf 2.64 or newer), or all
15044 uses of that macro should be through @code{AC_REQUIRE}; directly
15045 expanding the macro defeats the point of using @code{AC_REQUIRE} to
15046 eliminate redundant expansion.  In the example, this rule of thumb was
15047 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
15048 directly expands it.  One way of fixing the bug is to factor
15049 @code{TESTA} into two macros, the portion designed for direct and
15050 repeated use (here, named @code{TESTA}), and the portion designed for
15051 one-shot output and used only inside @code{AC_REQUIRE} (here, named
15052 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
15053 calling convention according to their needs:
15055 @example
15056 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
15057 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
15058 if test -n "$SEEN_A" ; then echo duplicate ; fi
15059 SEEN_A=:]])
15060 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
15061 if test -z "$SEEN_A" ; then echo bug ; fi]])
15062 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
15063 AC_DEFUN([OUTER], [[echo in OUTER]
15064 TESTA
15065 TESTC])
15066 OUTER
15067 @end example
15069 @noindent
15070 the resulting output will then obey all dependency rules and avoid any
15071 syntax warnings, whether the script is built with old or new Autoconf
15072 versions:
15074 @example
15075 in A_PREREQ
15076 in B
15077 in OUTER
15078 in A
15079 in C
15080 @end example
15082 You can use the helper macros @code{AS_IF} and @code{AS_CASE} in
15083 top-level code to enforce expansion of required macros outside of shell
15084 conditional constructs; these helpers are not needed in the bodies of
15085 macros defined by @code{AC_DEFUN}.
15086 You are furthermore encouraged, although not required, to
15087 put all @code{AC_REQUIRE} calls
15088 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
15089 lines they leave.
15091 Autoconf will normally warn if an @code{AC_REQUIRE} call refers to a
15092 macro that has not been defined.  However, the @command{aclocal} tool
15093 relies on parsing an incomplete set of input files to trace which macros
15094 have been required, in order to then pull in additional files that
15095 provide those macros; for this particular use case, pre-defining the
15096 macro @code{m4_require_silent_probe} will avoid the warnings.
15098 @node Suggested Ordering
15099 @subsection Suggested Ordering
15100 @cindex Macros, ordering
15101 @cindex Ordering macros
15103 Some macros should be run before another macro if both are called, but
15104 neither @emph{requires} that the other be called.  For example, a macro
15105 that changes the behavior of the C compiler should be called before any
15106 macros that run the C compiler.  Many of these dependencies are noted in
15107 the documentation.
15109 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
15110 with this kind of dependency appear out of order in a
15111 @file{configure.ac} file.  The warning occurs when creating
15112 @command{configure} from @file{configure.ac}, not when running
15113 @command{configure}.
15115 For example, @code{AC_PROG_CPP} checks whether the C compiler
15116 can run the C preprocessor when given the @option{-E} option.  It should
15117 therefore be called after any macros that change which C compiler is
15118 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
15120 @example
15121 AC_BEFORE([$0], [AC_PROG_CPP])dnl
15122 @end example
15124 @noindent
15125 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
15126 when @code{AC_PROG_CC} is called.
15128 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
15129 @acindex{BEFORE}
15130 Make M4 print a warning message to the standard error output if
15131 @var{called-macro-name} has already been called.  @var{this-macro-name}
15132 should be the name of the macro that is calling @code{AC_BEFORE}.  The
15133 macro @var{called-macro-name} must have been defined using
15134 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
15135 that it has been called.
15136 @end defmac
15138 @node One-Shot Macros
15139 @subsection One-Shot Macros
15140 @cindex One-shot macros
15141 @cindex Macros, called once
15143 Some macros should be called only once, either because calling them
15144 multiple time is unsafe, or because it is bad style.  For instance
15145 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
15146 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
15147 sense to run these expensive checks more than once.  Such one-shot
15148 macros can be defined using @code{AC_DEFUN_ONCE}.
15150 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
15151 @acindex{DEFUN_ONCE}
15152 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
15153 Definitions}), but add additional logic that guarantees that only the
15154 first use of the macro (whether by direct expansion or
15155 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
15156 expansion will occur before the start of any enclosing macro defined by
15157 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
15158 Generally, it does not make sense for @var{macro-body} to use parameters
15159 such as @code{$1}.
15160 @end defmac
15162 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
15163 emit a warning if it was directly expanded a second time, so for
15164 portability, it is better to use @code{AC_REQUIRE} than direct
15165 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
15166 (@pxref{Prerequisite Macros}).
15168 @node Obsoleting Macros
15169 @section Obsoleting Macros
15170 @cindex Obsoleting macros
15171 @cindex Macros, obsoleting
15173 Configuration and portability technology has evolved over the years.
15174 Often better ways of solving a particular problem are developed, or
15175 ad-hoc approaches are systematized.  This process has occurred in many
15176 parts of Autoconf.  One result is that some of the macros are now
15177 considered @dfn{obsolete}; they still work, but are no longer considered
15178 the best thing to do, hence they should be replaced with more modern
15179 macros.  Ideally, @command{autoupdate} should replace the old macro calls
15180 with their modern implementation.
15182 Autoconf provides a simple means to obsolete a macro.
15184 @anchor{AU_DEFUN}
15185 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message}, @ovar{silent})
15186 @auindex{DEFUN}
15187 Define @var{old-macro} as @var{implementation}, just like
15188 @code{AC_DEFUN}, but also declare @var{old-macro} to be obsolete.
15189 When @command{autoupdate} is run, occurrences of @var{old-macro} will
15190 be replaced by the text of @var{implementation} in the updated
15191 @file{configure.ac} file.
15193 If a simple textual replacement is not enough to finish the job of
15194 updating a @file{configure.ac} to modern style, provide instructions for
15195 whatever additional manual work is required as @var{message}.  These
15196 instructions will be printed by @command{autoupdate}, and embedded in the
15197 updated @file{configure.ac} file, next to the text of @var{implementation}.
15199 Normally, @command{autoconf} will also issue a warning (in the
15200 ``obsolete'' category) when it expands @var{old-macro}.  This warning
15201 does not include @var{message}; it only advises the maintainer to run
15202 @command{autoupdate}.  If it is inappropriate to issue this warning, set
15203 the @var{silent} argument to the word @code{silent}.  One might want to
15204 use a silent @code{AU_DEFUN} when @var{old-macro} is used in a
15205 widely-distributed third-party macro.  If that macro's maintainers are
15206 aware of the need to update their code, it's unnecessary to nag all
15207 of the transitive users of @var{old-macro} as well.  This capability
15208 was added to @code{AU_DEFUN} in Autoconf 2.70; older versions of
15209 autoconf will ignore the @var{silent} argument and issue the warning
15210 anyway.
15212 @strong{Caution:} If @var{implementation} contains M4 or M4sugar macros,
15213 they will be evaluated when @command{autoupdate} is run, not emitted
15214 verbatim like the rest of @var{implementation}.  This cannot be avoided
15215 with extra quotation, because then @var{old-macro} will not work when
15216 it is called normally.  See the definition of @code{AC_FOREACH} in
15217 @file{general.m4} for a workaround.
15218 @end defmac
15220 @defmac AU_ALIAS (@var{old-name}, @var{new-name}, @ovar{silent})
15221 @auindex{ALIAS}
15222 A shorthand version of @code{AU_DEFUN}, to be used when a macro has
15223 simply been renamed.  @command{autoupdate} will replace calls to
15224 @var{old-name} with calls to @var{new-name}, keeping any arguments
15225 intact.  No instructions for additional manual work will be printed.
15227 The @var{silent} argument works the same as the @var{silent} argument
15228 to @code{AU_DEFUN}.  It was added to @code{AU_ALIAS} in Autoconf 2.70.
15230 @strong{Caution:} @code{AU_ALIAS} cannot be used when @var{new-name} is
15231 an M4 or M4sugar macro.  See above.
15232 @end defmac
15234 @node Coding Style
15235 @section Coding Style
15236 @cindex Coding style
15238 The Autoconf macros follow a strict coding style.  You are encouraged to
15239 follow this style, especially if you intend to distribute your macro,
15240 either by contributing it to Autoconf itself or the
15241 @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
15242 Archive}, or by other means.
15244 The first requirement is to pay great attention to the quotation.  For
15245 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
15247 Do not try to invent new interfaces.  It is likely that there is a macro
15248 in Autoconf that resembles the macro you are defining: try to stick to
15249 this existing interface (order of arguments, default values, etc.).  We
15250 @emph{are} conscious that some of these interfaces are not perfect;
15251 nevertheless, when harmless, homogeneity should be preferred over
15252 creativity.
15254 Be careful about clashes both between M4 symbols and between shell
15255 variables.
15257 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
15258 you are unlikely to generate conflicts.  Nevertheless, when you need to
15259 set a special value, @emph{avoid using a regular macro name}; rather,
15260 use an ``impossible'' name.  For instance, up to version 2.13, the macro
15261 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
15262 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
15263 But since there is a macro named @code{AC_SUBST_FILE}, it was just
15264 impossible to @samp{AC_SUBST(FILE)}!  In this case,
15265 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
15266 have been used (yes, with the parentheses).
15267 @c or better yet, high-level macros such as @code{m4_expand_once}
15269 No Autoconf macro should ever enter the user-variable name space; i.e.,
15270 except for the variables that are the actual result of running the
15271 macro, all shell variables should start with @code{ac_}.  In
15272 addition, small macros or any macro that is likely to be embedded in
15273 other macros should be careful not to use obvious names.
15275 @cindex @code{dnl}
15276 Do not use @code{dnl} to introduce comments: most of the comments you
15277 are likely to write are either header comments which are not output
15278 anyway, or comments that should make their way into @file{configure}.
15279 There are exceptional cases where you do want to comment special M4
15280 constructs, in which case @code{dnl} is right, but keep in mind that it
15281 is unlikely.
15283 M4 ignores the leading blanks and newlines before each argument.
15284 Use this feature to
15285 indent in such a way that arguments are (more or less) aligned with the
15286 opening parenthesis of the macro being called.  For instance, instead of
15288 @example
15289 AC_CACHE_CHECK(for EMX OS/2 environment,
15290 ac_cv_emxos2,
15291 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
15292 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
15293 @end example
15295 @noindent
15296 write
15298 @example
15299 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15300 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15301                    [ac_cv_emxos2=yes],
15302                    [ac_cv_emxos2=no])])
15303 @end example
15305 @noindent
15306 or even
15308 @example
15309 AC_CACHE_CHECK([for EMX OS/2 environment],
15310                [ac_cv_emxos2],
15311                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
15312                                                    [return __EMX__;])],
15313                                   [ac_cv_emxos2=yes],
15314                                   [ac_cv_emxos2=no])])
15315 @end example
15317 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
15318 cross-compiling, provide a pessimistic value (typically @samp{no}).
15320 Feel free to use various tricks to prevent auxiliary tools, such as
15321 syntax-highlighting editors, from behaving improperly.  For instance,
15322 instead of:
15324 @example
15325 m4_bpatsubst([$1], [$"])
15326 @end example
15328 @noindent
15331 @example
15332 m4_bpatsubst([$1], [$""])
15333 @end example
15335 @noindent
15336 so that Emacsen do not open an endless ``string'' at the first quote.
15337 For the same reasons, avoid:
15339 @example
15340 test $[#] != 0
15341 @end example
15343 @noindent
15344 and use:
15346 @example
15347 test $[@@%:@@] != 0
15348 @end example
15350 @noindent
15351 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
15352 breaking the bracket-matching highlighting from Emacsen.  Note the
15353 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
15354 not escape when it is unnecessary.  Common examples of useless quotation
15355 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
15356 etc.  If you add portability issues to the picture, you'll prefer
15357 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
15358 better than hacking Autoconf @code{:-)}.
15360 When using @command{sed}, don't use @option{-e} except for indenting
15361 purposes.  With the @code{s} and @code{y} commands, the preferred
15362 separator is @samp{/} unless @samp{/} itself might appear in the pattern
15363 or replacement, in which case you should use @samp{|}, or optionally
15364 @samp{,} if you know the pattern and replacement cannot contain a file
15365 name.  If none of these characters will do, choose a printable character
15366 that cannot appear in the pattern or replacement.  Characters from the
15367 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
15368 replacement might contain a file name, since they have special meaning
15369 to the shell and are less likely to occur in file names.
15371 @xref{Macro Definitions}, for details on how to define a macro.  If a
15372 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
15373 of an @code{AC_REQUIRE} directive, and macros required by other macros
15374 inside arguments do not need to be expanded before this macro, then
15375 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
15376 Also take into account that public third-party macros need to use
15377 @code{AC_DEFUN} in order to be found by @command{aclocal}
15378 (@pxref{Extending aclocal,,, automake, GNU Automake}).
15379 All the @code{AC_REQUIRE} statements should be at the beginning of the
15380 macro, and each statement should be followed by @code{dnl}.
15382 You should not rely on the number of arguments: instead of checking
15383 whether an argument is missing, test that it is not empty.  It provides
15384 both a simpler and a more predictable interface to the user, and saves
15385 room for further arguments.
15387 Unless the macro is short, try to leave the closing @samp{])} at the
15388 beginning of a line, followed by a comment that repeats the name of the
15389 macro being defined.  This introduces an additional newline in
15390 @command{configure}; normally, that is not a problem, but if you want to
15391 remove it you can use @samp{[]dnl} on the last line.  You can similarly
15392 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
15393 is recommended instead of @samp{dnl} to ensure that M4 does not
15394 interpret the @samp{dnl} as being attached to the preceding text or
15395 macro output.  For example, instead of:
15397 @example
15398 AC_DEFUN([AC_PATH_X],
15399 [AC_MSG_CHECKING([for X])
15400 AC_REQUIRE_CPP()
15401 @r{# @dots{}omitted@dots{}}
15402   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15403 fi])
15404 @end example
15406 @noindent
15407 you would write:
15409 @example
15410 AC_DEFUN([AC_PATH_X],
15411 [AC_REQUIRE_CPP()[]dnl
15412 AC_MSG_CHECKING([for X])
15413 @r{# @dots{}omitted@dots{}}
15414   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15415 fi[]dnl
15416 ])# AC_PATH_X
15417 @end example
15419 If the macro is long, try to split it into logical chunks.  Typically,
15420 macros that check for a bug in a function and prepare its
15421 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
15422 this setup.  Do not hesitate to introduce auxiliary macros to factor
15423 your code.
15425 In order to highlight the recommended coding style, here is a macro
15426 written the old way:
15428 @example
15429 dnl Check for EMX on OS/2.
15430 dnl _AC_EMXOS2
15431 AC_DEFUN(_AC_EMXOS2,
15432 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
15433 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
15434 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
15435 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
15436 @end example
15438 @noindent
15439 and the new way:
15441 @example
15442 # _AC_EMXOS2
15443 # ----------
15444 # Check for EMX on OS/2.
15445 m4_define([_AC_EMXOS2],
15446 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15447 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15448                    [ac_cv_emxos2=yes],
15449                    [ac_cv_emxos2=no])])
15450 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
15451 ])# _AC_EMXOS2
15452 @end example
15457 @c ============================================= Portable Shell Programming
15459 @node Portable Shell
15460 @chapter Portable Shell Programming
15461 @cindex Portable shell programming
15463 When writing your own checks, there are some shell-script programming
15464 techniques you should avoid in order to make your code portable.  The
15465 Bourne shell and upward-compatible shells like the Korn shell and Bash
15466 have evolved over the years, and many features added to the original
15467 System7 shell are now supported on all interesting porting targets.
15468 However, the following discussion between Russ Allbery and Robert Lipe
15469 is worth reading:
15471 @noindent
15472 Russ Allbery:
15474 @quotation
15475 The GNU assumption that @command{/bin/sh} is the one and only shell
15476 leads to a permanent deadlock.  Vendors don't want to break users'
15477 existing shell scripts, and there are some corner cases in the Bourne
15478 shell that are not completely compatible with a Posix shell.  Thus,
15479 vendors who have taken this route will @emph{never} (OK@dots{}``never say
15480 never'') replace the Bourne shell (as @command{/bin/sh}) with a
15481 Posix shell.
15482 @end quotation
15484 @noindent
15485 Robert Lipe:
15487 @quotation
15488 This is exactly the problem.  While most (at least most System V's) do
15489 have a Bourne shell that accepts shell functions most vendor
15490 @command{/bin/sh} programs are not the Posix shell.
15492 So while most modern systems do have a shell @emph{somewhere} that meets the
15493 Posix standard, the challenge is to find it.
15494 @end quotation
15496 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15497 is to find such a shell.  But to prevent trouble, if you're not using
15498 M4sh you should not take advantage of features that were added after Unix
15499 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15500 negated character classes, or even @command{unset}.  @code{#} comments,
15501 while not in Unix version 7, were retrofitted in the original Bourne
15502 shell and can be assumed to be part of the least common denominator.
15504 On the other hand, if you're using M4sh you can assume that the shell
15505 has the features that were added in SVR2 (circa 1984), including shell
15506 functions,
15507 @command{return}, @command{unset}, and I/O redirection for builtins.  For
15508 more information, refer to @uref{https://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15509 However, some pitfalls have to be avoided for portable use of these
15510 constructs; these will be documented in the rest of this chapter.
15511 See in particular @ref{Shell Functions} and @ref{Limitations of
15512 Builtins, , Limitations of Shell Builtins}.
15514 Some ancient systems have quite
15515 small limits on the length of the @samp{#!} line; for instance, 32
15516 bytes (not including the newline) on SunOS 4.
15517 However, these ancient systems are no longer of practical concern.
15519 The set of external programs you should run in a @command{configure} script
15520 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
15521 Makefiles, standards, The GNU Coding Standards}, for the list.  This
15522 restriction allows users to start out with a fairly small set of
15523 programs and build the rest, avoiding too many interdependencies between
15524 packages.
15526 Some of these external utilities have a portable subset of features; see
15527 @ref{Limitations of Usual Tools}.
15529 There are other sources of documentation about shells.  The
15530 specification for the Posix
15531 @uref{https://@/pubs.opengroup.org/@/onlinepubs/@/9699919799/@/utilities/@/V3_chap02.html,
15532 Shell Command Language}, though more generous than the restrictive shell
15533 subset described above, is fairly portable nowadays.  Also please see
15534 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15536 @menu
15537 * Shellology::                  A zoology of shells
15538 * Invoking the Shell::          Invoking the shell as a command
15539 * Here-Documents::              Quirks and tricks
15540 * File Descriptors::            FDs and redirections
15541 * Signal Handling::             Shells, signals, and headaches
15542 * File System Conventions::     File names
15543 * Shell Pattern Matching::      Pattern matching
15544 * Shell Substitutions::         Variable and command expansions
15545 * Assignments::                 Varying side effects of assignments
15546 * Parentheses::                 Parentheses in shell scripts
15547 * Slashes::                     Slashes in shell scripts
15548 * Special Shell Variables::     Variables you should not change
15549 * Shell Functions::             What to look out for if you use them
15550 * Limitations of Builtins::     Portable use of not so portable /bin/sh
15551 * Limitations of Usual Tools::  Portable use of portable tools
15552 @end menu
15554 @node Shellology
15555 @section Shellology
15556 @cindex Shellology
15558 There are several families of shells, most prominently the Bourne family
15559 and the C shell family which are deeply incompatible.  If you want to
15560 write portable shell scripts, avoid members of the C shell family.  The
15561 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15562 Shell difference FAQ} includes a small history of Posix shells, and a
15563 comparison between several of them.
15565 Below we describe some of the members of the Bourne shell family.
15567 @table @asis
15568 @item Ash
15569 @cindex Ash
15570 Ash is often used on GNU/Linux and BSD
15571 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
15572 bugs that are fixed in the 0.3.x series, but portable shell scripts
15573 should work around them, since version 0.2 is still shipped with many
15574 GNU/Linux distributions.
15576 To be compatible with Ash 0.2:
15578 @itemize @minus
15579 @item
15580 don't use @samp{$?} after expanding empty or unset variables,
15581 or at the start of an @command{eval}:
15583 @example
15584 foo=
15585 false
15586 $foo
15587 echo "Do not use it: $?"
15588 false
15589 eval 'echo "Do not use it: $?"'
15590 @end example
15592 @item
15593 don't use command substitution within variable expansion:
15595 @example
15596 cat $@{FOO=`bar`@}
15597 @end example
15599 @item
15600 beware that single builtin substitutions are not performed by a
15601 subshell, hence their effect applies to the current shell!  @xref{Shell
15602 Substitutions}, item ``Command Substitution''.
15603 @end itemize
15605 @item Bash
15606 @cindex Bash
15607 To detect whether you are running Bash, test whether
15608 @code{BASH_VERSION} is set.  To require
15609 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
15610 Mode, , Bash Posix Mode, bash, The GNU Bash Reference
15611 Manual}, for details.
15613 @item Bash 2.05 and later
15614 @cindex Bash 2.05 and later
15615 Versions 2.05 and later of Bash use a different format for the
15616 output of the @command{set} builtin, designed to make evaluating its
15617 output easier.  However, this output is not compatible with earlier
15618 versions of Bash (or with many other shells, probably).  So if
15619 you use Bash 2.05 or higher to execute @command{configure},
15620 you'll need to use Bash 2.05 for all other build tasks as well.
15622 @item Ksh
15623 @cindex Ksh
15624 @cindex Korn shell
15625 @prindex @samp{ksh}
15626 @prindex @samp{ksh88}
15627 @prindex @samp{ksh93}
15628 The Korn shell is compatible with the Bourne family and it mostly
15629 conforms to Posix.  It has two major variants commonly
15630 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15631 release.  It is usually called @command{ksh}, but is called @command{sh}
15632 on some hosts if you set your path appropriately.
15634 On Solaris 11, @command{/bin/sh} and @command{/usr/bin/ksh} are both
15635 @samp{ksh93}.  On Solaris 10 and earlier, @command{/bin/sh} is a
15636 pre-Posix Bourne shell and the Korn shell is found elsewhere:
15637 @prindex @command{/usr/bin/ksh} on Solaris
15638 @command{/usr/bin/ksh} is @samp{ksh88} on Solaris 2.0 through 10,
15639 @prindex @command{/usr/xpg4/bin/sh} on Solaris
15640 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
15641 @samp{ksh88} on Solaris 9 and later,
15642 @prindex @command{/usr/dt/bin/dtksh} on Solaris
15643 and @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15644 Variants that are not standard may be parts of optional
15645 packages.  There is no extra charge for these packages, but they are
15646 not part of a minimal OS install and therefore some installations may
15647 not have it.
15649 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
15650 is also available as @command{/usr/bin/posix/sh}.  If the environment
15651 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15652 the standard shell conform to Posix.
15654 @item Pdksh
15655 @prindex @samp{pdksh}
15656 A public-domain clone of the Korn shell called @command{pdksh} is widely
15657 available: it has most of the @samp{ksh88} features along with a few of
15658 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
15659 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15660 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
15661 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
15662 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
15663 at least one respect, see @ref{Shell Substitutions}.
15665 @item Zsh
15666 @cindex Zsh
15667 To detect whether you are running @command{zsh}, test whether
15668 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
15669 compatible with the Bourne shell: you must execute @samp{emulate sh},
15670 and for @command{zsh} versions before 3.1.6-dev-18 you must also
15671 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
15672 zsh, The Z Shell Manual}, for details.
15674 The default Mac OS X @command{sh} was originally Zsh; it was changed to
15675 Bash in Mac OS X 10.2.
15676 @end table
15678 @node Invoking the Shell
15679 @section Invoking the Shell
15680 @cindex invoking the shell
15681 @cindex shell invocation
15683 The Korn shell (up to at least version M-12/28/93d) has a bug when
15684 invoked on a file whose name does not contain a slash.  It first
15685 searches for the file's name in @env{PATH}, and if found it executes
15686 that rather than the original file.  For example, assuming there is a
15687 binary executable @file{/usr/bin/script} in your @env{PATH}, the last
15688 command in the following example fails because the Korn shell finds
15689 @file{/usr/bin/script} and refuses to execute it as a shell script:
15691 @example
15692 $ @kbd{touch xxyzzyz script}
15693 $ @kbd{ksh xxyzzyz}
15694 $ @kbd{ksh ./script}
15695 $ @kbd{ksh script}
15696 ksh: script: cannot execute
15697 @end example
15699 Bash 2.03 has a bug when invoked with the @option{-c} option: if the
15700 option-argument ends in backslash-newline, Bash incorrectly reports a
15701 syntax error.  The problem does not occur if a character follows the
15702 backslash:
15704 @example
15705 $ @kbd{$ bash -c 'echo foo \}
15706 > @kbd{'}
15707 bash: -c: line 2: syntax error: unexpected end of file
15708 $ @kbd{bash -c 'echo foo \}
15709 > @kbd{ '}
15711 @end example
15713 @noindent
15714 @xref{Backslash-Newline-Empty}, for how this can cause problems in makefiles.
15716 @node Here-Documents
15717 @section Here-Documents
15718 @cindex Here-documents
15719 @cindex Shell here-documents
15721 Because unquoted here-documents are subject to parameter expansion and
15722 command substitution, the characters @samp{$} and @samp{`} are special
15723 in unquoted here-documents and should be escaped by @samp{\} if you want
15724 them as-is.  Also, @samp{\} is special if it precedes @samp{$},
15725 @samp{`}, newline or @samp{\} itself, so @samp{\} should be doubled if
15726 it appears before these characters and you want it as-is.
15728 Using command substitutions in a here-document that is fed to a shell
15729 function is not portable.  For example, with Solaris 10 @command{/bin/sh}:
15731 @example
15732 $ @kbd{kitty () @{ cat; @}}
15733 $ @kbd{kitty <<EOF
15734 > `echo ok`
15735 > EOF}
15736 /tmp/sh199886: cannot open
15737 $ @kbd{echo $?}
15739 @end example
15741 Some shells mishandle large here-documents: for example,
15742 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
15743 derived from Korn shell version M-12/28/93d, mishandle braced variable
15744 expansion that crosses a 1024- or 4096-byte buffer boundary
15745 within a here-document.  Only the part of the variable name after the boundary
15746 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
15747 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
15748 boundary, the shell reports an error, as if you used @code{$@{@}}.
15749 Instead of @code{$@{variable-default@}}, the shell may expand
15750 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
15751 be worked around by omitting the braces: @code{$variable}.  The bug was
15752 fixed in
15753 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15754 still shipping older versions with the bug.
15756 Empty here-documents are not portable either; with the following code,
15757 @command{zsh} up to at least version 4.3.10 creates a file with a single
15758 newline, whereas other shells create an empty file:
15760 @example
15761 cat >file <<EOF
15763 @end example
15765 Many shells (including the Bourne shell) implement here-documents
15766 inefficiently.  In particular, some shells can be extremely inefficient when
15767 a single statement contains many here-documents.  For instance if your
15768 @file{configure.ac} includes something like:
15770 @example
15771 @group
15772 if <cross_compiling>; then
15773   assume this and that
15774 else
15775   check this
15776   check that
15777   check something else
15778   @dots{}
15779   on and on forever
15780   @dots{}
15782 @end group
15783 @end example
15785 A shell parses the whole @code{if}/@code{fi} construct, creating
15786 temporary files for each here-document in it.  Some shells create links
15787 for such here-documents on every @code{fork}, so that the clean-up code
15788 they had installed correctly removes them.  It is creating the links
15789 that can take the shell forever.
15791 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15792 @code{if}/@code{fi} constructs, would improve the performance
15793 significantly.  Anyway, this kind of construct is not exactly the
15794 typical use of Autoconf.  In fact, it's even not recommended, because M4
15795 macros can't look into shell conditionals, so we may fail to expand a
15796 macro when it was expanded before in a conditional path, and the
15797 condition turned out to be false at runtime, and we end up not
15798 executing the macro at all.
15800 Be careful with the use of @samp{<<-} to unindent here-documents.  The
15801 behavior is only portable for stripping leading @key{TAB}s, and things
15802 can silently break if an overzealous editor converts to using leading
15803 spaces (not all shells are nice enough to warn about unterminated
15804 here-documents).
15806 @example
15807 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
15810 done
15811 $ @kbd{printf 'cat <<-x\n 1\n  2\n x\n' | bash-3.2 && echo done}
15813   2
15815 done
15816 @end example
15818 @node File Descriptors
15819 @section File Descriptors
15820 @cindex Descriptors
15821 @cindex File descriptors
15822 @cindex Shell file descriptors
15824 Most shells, if not all (including Bash, Zsh, Ash), output traces on
15825 stderr, even for subshells.  This might result in undesirable content
15826 if you meant to capture the standard-error output of the inner command:
15828 @example
15829 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15830 $ @kbd{cat stderr}
15831 + eval echo foo >&2
15832 + echo foo
15834 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15835 $ @kbd{cat stderr}
15836 + eval 'echo foo >&2'
15837 ++ echo foo
15839 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15840 @i{# Traces on startup files deleted here.}
15841 $ @kbd{cat stderr}
15842 +zsh:1> eval echo foo >&2
15843 +zsh:1> echo foo
15845 @end example
15847 @noindent
15848 One workaround is to grep out uninteresting lines, hoping not to remove
15849 good ones.
15851 If you intend to redirect both standard error and standard output,
15852 redirect standard output first.  This works better with HP-UX,
15853 since its shell mishandles tracing if standard error is redirected
15854 first:
15856 @example
15857 $ @kbd{sh -x -c ': 2>err >out'}
15858 + :
15859 + 2> err $ @kbd{cat err}
15860 1> out
15861 @end example
15863 Don't try to redirect the standard error of a command substitution.  It
15864 must be done @emph{inside} the command substitution.  When running
15865 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15866 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15868 On the other hand, some shells, such as Solaris or FreeBSD
15869 @command{/bin/sh}, warn about missing programs before performing
15870 redirections.  Therefore, to silently check whether a program exists, it
15871 is necessary to perform redirections on a subshell or brace group:
15872 @example
15873 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15874 nosuch: not found
15875 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15876 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15877 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15878 @end example
15880 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15881 shell pipeline.
15883 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15884 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15886 Some shells, like @command{ash}, don't recognize bi-directional
15887 redirection (@samp{<>}).  And even on shells that recognize it, it is
15888 not portable to use on fifos: Posix does not require read-write support
15889 for named pipes, and Cygwin does not support it:
15891 @example
15892 $ @kbd{mkfifo fifo}
15893 $ @kbd{exec 5<>fifo}
15894 $ @kbd{echo hi >&5}
15895 bash: echo: write error: Communication error on send
15896 @end example
15898 @noindent
15899 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15900 regular files when using @samp{<>}:
15902 @example
15903 $ @kbd{echo a > file}
15904 $ @kbd{bash -c ': 1<>file'; cat file}
15906 $ @kbd{dash -c ': 1<>file'; cat file}
15907 $ rm a
15908 @end example
15910 Solaris 10 @code{/bin/sh} executes redirected compound commands
15911 in a subshell, while other shells don't:
15913 @example
15914 $ @kbd{/bin/sh -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15916 $ @kbd{ksh -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15918 $ @kbd{bash -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15920 @end example
15922 When catering to old systems, don't redirect the same file descriptor
15923 several times, as you are doomed to failure under Ultrix.
15925 @example
15926 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
15927 UWS V4.4 (Rev. 11)
15928 $ @kbd{eval 'echo matter >fullness' >void}
15929 illegal io
15930 $ @kbd{eval '(echo matter >fullness)' >void}
15931 illegal io
15932 $ @kbd{(eval '(echo matter >fullness)') >void}
15933 Ambiguous output redirect.
15934 @end example
15936 @noindent
15937 In each case the expected result is of course @file{fullness} containing
15938 @samp{matter} and @file{void} being empty.  However, this bug is
15939 probably not of practical concern to modern platforms.
15941 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15942 (even if it is redirected) in a loop after the first iteration, or in a
15943 shell function after the first call:
15945 @example
15946 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15947 $ @kbd{ls x*}
15949 $ @kbd{f () @{ : >$1; @}; f y1; f y2; f y3;}
15950 $ @kbd{ls y*}
15952 @end example
15954 @noindent
15955 As a workaround, @command{echo} or @command{eval} can be used.
15957 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15958 subsidiary program.  If any of these descriptors is closed, the
15959 operating system may open an unspecified file for the descriptor in the
15960 new process image.  Posix 2008 says this may be done only if the
15961 subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15962 it even for ordinary programs, and the next version of Posix will allow
15963 HP-UX behavior.
15965 If you want a file descriptor above 2 to be inherited into a child
15966 process, then you must use redirections specific to that command or a
15967 containing subshell or command group, rather than relying on
15968 @command{exec} in the shell. In @command{ksh} as well as HP-UX
15969 @command{sh}, file descriptors above 2 which are opened using
15970 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15971 that involved in the fork-and-exec which runs a program or script):
15973 @example
15974 $ @kbd{echo 'echo hello >&5' >k}
15975 $ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15976 hello
15977 $ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15978 hello
15979 $ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15980 ./k[1]: 5: cannot open [Bad file number]
15981 $ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
15982 hello
15983 $ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
15984 hello
15985 $ @kbd{ksh -c '5>t ksh ./k; cat t}
15986 hello
15987 @end example
15989 Don't rely on duplicating a closed file descriptor to cause an
15990 error.  With Solaris 10 @command{/bin/sh}, failed duplication is silently
15991 ignored, which can cause unintended leaks to the original file
15992 descriptor.  In this example, observe the leak to standard output:
15994 @example
15995 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15996 bash: 3: Bad file descriptor
15998 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
16001 @end example
16003 Fortunately, an attempt to close an already closed file descriptor will
16004 portably succeed.  Likewise, it is safe to use either style of
16005 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
16006 even if it doesn't match the read/write mode that the file descriptor
16007 was opened with.
16009 DOS variants cannot rename or remove open files, such as in
16010 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
16011 perfectly portable among Posix hosts.
16013 A few ancient systems reserved some file descriptors.  By convention,
16014 file descriptor 3 was opened to @file{/dev/tty} when you logged into
16015 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
16016 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
16017 1990), though we don't now remember what it was.  Both these systems are
16018 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
16019 other file descriptors.
16021 On the other hand, you can't portably use multi-digit file descriptors.
16022 @command{dash} and Solaris @command{ksh} don't understand any file
16023 descriptor larger than @samp{9}:
16025 @example
16026 $ @kbd{bash -c 'exec 10>&-'; echo $?}
16028 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
16030 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
16031 ksh[1]: exec: 10: not found
16033 $ @kbd{dash -c 'exec 9>&-'; echo $?}
16035 $ @kbd{dash -c 'exec 10>&-'; echo $?}
16036 exec: 1: 10: not found
16038 @end example
16040 @c <https://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
16041 @node Signal Handling
16042 @section Signal Handling
16043 @cindex Signal handling in the shell
16044 @cindex Signals, shells and
16046 Portable handling of signals within the shell is another major source of
16047 headaches.  This is worsened by the fact that various different, mutually
16048 incompatible approaches are possible in this area, each with its
16049 distinctive merits and demerits.  A detailed description of these possible
16050 approaches, as well as of their pros and cons, can be found in
16051 @uref{https://www.cons.org/cracauer/sigint.html, this article}.
16053 Solaris 10 @command{/bin/sh} automatically traps most signals by default;
16054 the shell still exits with error upon termination by one of those signals,
16055 but in such a case the exit status might be somewhat unexpected (even if
16056 allowed by POSIX, strictly speaking):
16057 @c FIXME: We had a reference for this behavior but the website no longer
16058 @c exists and the page is not in the Internet Archive. --zw 2020-07-10.
16060 @example
16061 $ @kbd{bash -c 'kill -1 $$'; echo $?} # Will exit 128 + (signal number).
16062 Hangup
16064 $ @kbd{/bin/ksh -c 'kill -15 $$'; echo $?} # Likewise.
16065 Terminated
16067 $ @kbd{for sig in 1 2 3 15; do}
16068 > @kbd{  echo $sig:}
16069 > @kbd{  /bin/sh -c "kill -$s \$\$"; echo $?}
16070 > @kbd{done}
16071 signal 1:
16072 Hangup
16074 signal 2:
16076 signal 3:
16078 signal 15:
16080 @end example
16082 This gets even worse if one is using the POSIX ``wait'' interface to get
16083 details about the shell process terminations: it will result in the shell
16084 having exited normally, rather than by receiving a signal.
16086 @example
16087 $ @kbd{cat > foo.c <<'END'}
16088 #include <stdio.h>    /* for printf */
16089 #include <stdlib.h>   /* for system */
16090 #include <sys/wait.h> /* for WIF* macros */
16091 int main(void)
16093   int status = system ("kill -15 $$");
16094   printf ("Terminated by signal: %s\n",
16095           WIFSIGNALED (status) ? "yes" : "no");
16096   printf ("Exited normally: %s\n",
16097           WIFEXITED (status) ? "yes" : "no");
16098   return 0;
16101 @c $$ font-lock
16102 $ @kbd{cc -o foo foo.c}
16103 $ @kbd{./a.out} # On GNU/Linux
16104 Terminated by signal: no
16105 Exited normally: yes
16106 $ @kbd{./a.out} # On Solaris 10
16107 Terminated by signal: yes
16108 Exited normally: no
16109 @end example
16111 Various shells seem to handle @code{SIGQUIT} specially: they ignore it even
16112 if it is not blocked, and even if the shell is not running interactively
16113 (in fact, even if the shell has no attached tty); among these shells
16114 are at least Bash (from version 2 onward), Zsh 4.3.12, Solaris 10
16115 @code{/bin/ksh} and @code{/usr/xpg4/bin/sh}, and AT&T @code{ksh93} (2011).
16116 Still, @code{SIGQUIT} seems to be trappable quite portably within all
16117 these shells.  OTOH, some other shells doesn't special-case the handling
16118 of @code{SIGQUIT}; among these shells are at least @code{pdksh} 5.2.14,
16119 Solaris 10 and NetBSD 5.1 @code{/bin/sh}, and the Almquist Shell 0.5.5.1.
16121 Some shells (especially Korn shells and derivatives) might try to
16122 propagate to themselves a signal that has killed a child process; this is
16123 not a bug, but a conscious design choice (although its overall value might
16124 be debatable).  The exact details of how this is attained vary from shell
16125 to shell.  For example, upon running @code{perl -e 'kill 2, $$'}, after
16126 the perl process has been interrupted, AT&T @code{ksh93} (2011) will
16127 proceed to send itself a @code{SIGINT}, while Solaris 10 @code{/bin/ksh}
16128 and @code{/usr/xpg4/bin/sh} will proceed to exit with status 130 (i.e.,
16129 128 + 2). In any case, if there is an active trap associated with
16130 @code{SIGINT}, those shells will correctly execute it.
16132 @c See: <https://www.austingroupbugs.net/view.php?id=51>
16133 Some Korn shells, when a child process die due receiving a signal with
16134 signal number @var{n}, can leave in @samp{$?} an exit status of
16135 256+@var{n} instead of the more common 128+@var{n}.  Observe the
16136 difference between AT&T @code{ksh93} (2011) and @code{bash} 4.1.5 on
16137 Debian:
16139 @example
16140 $ @kbd{/bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?'}
16141 /bin/ksh: line 1: 7837: Hangup
16143 $ @kbd{/bin/bash -c 'sh -c "kill -1 \$\$"; echo $?'}
16144 /bin/bash: line 1:  7861 Hangup        (sh -c "kill -1 \$\$")
16146 @end example
16148 @noindent
16149 This @command{ksh} behavior is allowed by POSIX, if implemented with
16150 due care; see this @uref{https://www.austingroupbugs.net/view.php?id=51,
16151 Austin Group discussion} for more background.  However, if it is not
16152 implemented with proper care, such a behavior might cause problems
16153 in some corner cases.  To see why, assume we have a ``wrapper'' script
16154 like this:
16156 @example
16157 #!/bin/sh
16158 # Ignore some signals in the shell only, not in its child processes.
16159 trap : 1 2 13 15
16160 wrapped_command "$@@"
16161 ret=$?
16162 other_command
16163 exit $ret
16164 @end example
16166 @noindent
16167 If @command{wrapped_command} is interrupted by a @code{SIGHUP} (which
16168 has signal number 1), @code{ret} will be set to 257.  Unless the
16169 @command{exit} shell builtin is smart enough to understand that such
16170 a value can only have originated from a signal, and adjust the final
16171 wait status of the shell appropriately, the value 257 will just get
16172 truncated to 1 by the closing @code{exit} call, so that a caller of
16173 the script will have no way to determine that termination by a signal
16174 was involved.  Observe the different behavior of AT&T @code{ksh93}
16175 (2011) and @code{bash} 4.1.5 on Debian:
16177 @example
16178 $ @kbd{cat foo.sh}
16179 #!/bin/sh
16180 sh -c 'kill -1 $$'
16181 ret=$?
16182 echo $ret
16183 exit $ret
16184 $ @kbd{/bin/ksh foo.sh; echo $?}
16185 foo.sh: line 2: 12479: Hangup
16188 $ @kbd{/bin/bash foo.sh; echo $?}
16189 foo.sh: line 2: 12487 Hangup        (sh -c 'kill -1 $$')
16192 @end example
16194 @node File System Conventions
16195 @section File System Conventions
16196 @cindex File system conventions
16198 Autoconf uses shell-script processing extensively, so the file names
16199 that it processes should not contain characters that are special to the
16200 shell.  Special characters include space, tab, newline, NUL, and
16201 the following:
16203 @example
16204 " # $ & ' ( ) * ; < = > ? [ \ ` |
16205 @end example
16207 Also, file names should not begin with @samp{~} or @samp{-}, and should
16208 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
16209 immediately after @samp{:}.  On Posix-like platforms, directory names
16210 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
16211 path separator.
16213 These restrictions apply not only to the files that you distribute, but
16214 also to the absolute file names of your source, build, and destination
16215 directories.
16217 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
16218 they should be avoided.
16220 Posix lets implementations treat leading @file{//} specially, but
16221 requires leading @file{///} and beyond to be equivalent to @file{/}.
16222 Most Unix variants treat @file{//} like @file{/}.  However, some treat
16223 @file{//} as a ``super-root'' that can provide access to files that are
16224 not otherwise reachable from @file{/}.  The super-root tradition began
16225 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
16226 has revived it.
16228 While @command{autoconf} and friends are usually run on some Posix
16229 variety, they can be used on other systems, most notably DOS
16230 variants.  This impacts several assumptions regarding file names.
16232 @noindent
16233 For example, the following code:
16235 @example
16236 case $foo_dir in
16237   /*) # Absolute
16238      ;;
16239   *)
16240      foo_dir=$dots$foo_dir ;;
16241 esac
16242 @end example
16244 @noindent
16245 fails to properly detect absolute file names on those systems, because
16246 they can use a drivespec, and usually use a backslash as directory
16247 separator.  If you want to be portable to DOS variants (at the
16248 price of rejecting valid but oddball Posix file names like @file{a:\b}),
16249 you can check for absolute file names like this:
16251 @cindex absolute file names, detect
16252 @example
16253 case $foo_dir in
16254   [\\/]* | ?:[\\/]* ) # Absolute
16255      ;;
16256   *)
16257      foo_dir=$dots$foo_dir ;;
16258 esac
16259 @end example
16261 @noindent
16262 Make sure you quote the brackets if appropriate and keep the backslash as
16263 first character.  @xref{case, , Limitations of Shell Builtins}.
16265 Also, because the colon is used as part of a drivespec, these systems don't
16266 use it as path separator.  When creating or accessing paths, you can use the
16267 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
16268 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
16269 starts up.
16271 File names need extra care as well.  While DOS variants
16272 that are Posixy enough to run @command{autoconf} (such as DJGPP)
16273 are usually able to handle long file names properly, there are still
16274 limitations that can seriously break packages.  Several of these issues
16275 can be easily detected by the
16276 @uref{https://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
16277 package.
16279 A short overview follows; problems are marked with SFN/LFN to
16280 indicate where they apply: SFN means the issues are only relevant to
16281 plain DOS, not to DOS under Microsoft Windows
16282 variants, while LFN identifies problems that exist even under
16283 Microsoft Windows variants.
16285 @table @asis
16286 @item No multiple dots (SFN)
16287 DOS cannot handle multiple dots in file names.  This is an especially
16288 important thing to remember when building a portable configure script,
16289 as @command{autoconf} uses a .in suffix for template files.
16291 This is perfectly OK on Posix variants:
16293 @example
16294 AC_CONFIG_HEADERS([config.h])
16295 AC_CONFIG_FILES([source.c foo.bar])
16296 AC_OUTPUT
16297 @end example
16299 @noindent
16300 but it causes problems on DOS, as it requires @samp{config.h.in},
16301 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
16302 to DOS-based environments, you should use this instead:
16304 @example
16305 AC_CONFIG_HEADERS([config.h:config.hin])
16306 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
16307 AC_OUTPUT
16308 @end example
16310 @item No leading dot (SFN)
16311 DOS cannot handle file names that start with a dot.  This is usually
16312 not important for @command{autoconf}.
16314 @item Case insensitivity (LFN)
16315 DOS is case insensitive, so you cannot, for example, have both a
16316 file called @samp{INSTALL} and a directory called @samp{install}.  This
16317 also affects @command{make}; if there's a file called @samp{INSTALL} in
16318 the directory, @samp{make install} does nothing (unless the
16319 @samp{install} target is marked as PHONY).
16321 @item The 8+3 limit (SFN)
16322 Because the DOS file system only stores the first 8 characters of
16323 the file name and the first 3 of the extension, those must be unique.
16324 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
16325 @file{foobar-prettybird.c} all resolve to the same file name
16326 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
16327 @file{foo.bartender}.
16329 The 8+3 limit is not usually a problem under Microsoft Windows, as it
16330 uses numeric
16331 tails in the short version of file names to make them unique.  However, a
16332 registry setting can turn this behavior off.  While this makes it
16333 possible to share file trees containing long file names between SFN
16334 and LFN environments, it also means the above problem applies there
16335 as well.
16337 @item Invalid characters (LFN)
16338 Some characters are invalid in DOS file names, and should therefore
16339 be avoided.  In a LFN environment, these are @samp{/}, @samp{\},
16340 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
16341 In a SFN environment, other characters are also invalid.  These
16342 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
16344 @item Invalid names (LFN)
16345 Some DOS file names are reserved, and cause problems if you
16346 try to use files with those names.  These names include @file{CON},
16347 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
16348 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
16349 File names are case insensitive, so even names like
16350 @file{aux/config.guess} are disallowed.
16352 @end table
16354 @node Shell Pattern Matching
16355 @section Shell Pattern Matching
16356 @cindex Shell pattern matching
16358 Nowadays portable patterns can use negated character classes like
16359 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
16360 some shells but not others; hence portable scripts should never use
16361 @samp{^} as the first character of a bracket pattern.
16363 Outside the C locale, patterns like @samp{[a-z]} are problematic since
16364 they may match characters that are not lower-case letters.
16366 @node Shell Substitutions
16367 @section Shell Substitutions
16368 @cindex Shell substitutions
16370 Contrary to a persistent urban legend, the Bourne shell does not
16371 systematically split variables and back-quoted expressions, in particular
16372 on the right-hand side of assignments and in the argument of @code{case}.
16373 For instance, the following code:
16375 @example
16376 case "$given_srcdir" in
16377 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
16378 *)  top_srcdir="$dots$given_srcdir" ;;
16379 esac
16380 @end example
16382 @noindent
16383 is more readable when written as:
16385 @example
16386 case $given_srcdir in
16387 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
16388 *)  top_srcdir=$dots$given_srcdir ;;
16389 esac
16390 @end example
16392 @noindent
16393 and in fact it is even @emph{more} portable: in the first case of the
16394 first attempt, the computation of @code{top_srcdir} is not portable,
16395 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
16396 for example Solaris 10 @command{ksh}:
16398 @example
16399 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
16400 ksh: : cannot execute
16401 ksh: bar | sed 's, ,,': cannot execute
16402 @end example
16404 @noindent
16405 Posix does not specify behavior for this sequence.  On the other hand,
16406 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by Posix,
16407 but in practice, not all shells understand it the same way: pdksh 5.2.14
16408 prints spurious quotes when in Posix mode:
16410 @example
16411 $ @kbd{echo "`echo \"hello\"`"}
16412 hello
16413 $ @kbd{set -o posix}
16414 $ @kbd{echo "`echo \"hello\"`"}
16415 "hello"
16416 @end example
16418 @noindent
16419 There is just no portable way to use double-quoted strings inside
16420 double-quoted back-quoted expressions (pfew!).
16422 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
16423 parameter expansions are elided during word splitting.  Meanwhile, zsh
16424 does not perform word splitting except when in Bourne compatibility
16425 mode.  In the example below, the correct behavior is to have five
16426 arguments to the function, and exactly two spaces on either side of the
16427 middle @samp{-}, since word splitting collapses multiple spaces in
16428 @samp{$f} but leaves empty arguments intact.
16430 @example
16431 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16432 3- - -
16433 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16434 5-  -  -
16435 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16436 3-   -   -
16437 $ @kbd{zsh -c 'emulate sh;}
16438 > @kbd{n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16439 5-  -  -
16440 @end example
16442 @noindent
16443 You can work around this by doing manual word splitting, such as using
16444 @samp{"$str" $list} rather than @samp{"$str"$list}.
16446 There are also portability pitfalls with particular expansions:
16448 @table @code
16449 @item $@@
16450 @cindex @code{"$@@"}
16451 One of the most famous shell-portability issues is related to
16452 @samp{"$@@"}.  When there are no positional arguments, Posix says
16453 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
16454 original Unix version 7 Bourne shell treated it as equivalent to
16455 @samp{""} instead, and this behavior survives in later implementations
16456 like Digital Unix 5.0.
16458 The traditional way to work around this portability problem is to use
16459 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
16460 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
16461 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
16463 @example
16464 zsh $ @kbd{emulate sh}
16465 zsh $ @kbd{for i in "$@@"; do echo $i; done}
16466 Hello World
16468 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
16469 Hello
16470 World
16472 @end example
16474 @noindent
16475 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
16476 @samp{"$@@"} because of the portability problems mentioned above.
16477 One workaround relies on Zsh's ``global aliases'' to convert
16478 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
16480 @example
16481 test $@{ZSH_VERSION+y@} && alias -g '$@{1+"$@@"@}'='"$@@"'
16482 @end example
16484 Zsh only recognizes this alias when a shell word matches it exactly;
16485 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
16486 case always yields at least one shell word, use plain @samp{"$@@"}.
16488 A more conservative workaround is to avoid @samp{"$@@"} if it is
16489 possible that there may be no positional arguments.  For example,
16490 instead of:
16492 @example
16493 cat conftest.c "$@@"
16494 @end example
16496 you can use this instead:
16498 @example
16499 case $# in
16500 0) cat conftest.c;;
16501 *) cat conftest.c "$@@";;
16502 esac
16503 @end example
16505 Autoconf macros often use the @command{set} command to update
16506 @samp{$@@}, so if you are writing shell code intended for
16507 @command{configure} you should not assume that the value of @samp{$@@}
16508 persists for any length of time.
16511 @item $@{10@}
16512 @cindex positional parameters
16513 The 10th, 11th, @dots{} positional parameters can be accessed only after
16514 a @code{shift}.  The 7th Edition shell reported an error if given
16515 @code{$@{10@}}, and
16516 Solaris 10 @command{/bin/sh} still acts that way:
16518 @example
16519 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
16520 $ @kbd{echo $@{10@}}
16521 bad substitution
16522 @end example
16524 Conversely, not all shells obey the Posix rule that when braces are
16525 omitted, multiple digits beyond a @samp{$} imply the single-digit
16526 positional parameter expansion concatenated with the remaining literal
16527 digits.  To work around the issue, you must use braces.
16529 @example
16530 $ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16531 a0 a0
16532 $ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16533 j a0
16534 @end example
16536 @item $@{@var{var}:-@var{value}@}
16537 @itemx $@{@var{var}:=@var{value}@}
16538 @itemx $@{@var{var}:?@var{value}@}
16539 @itemx $@{@var{var}:+@var{value}@}
16540 @c Info cannot handle ':' in index entries.
16541 @ifnotinfo
16542 @cindex @code{$@{@var{var}:-@var{value}@}}
16543 @cindex @code{$@{@var{var}:=@var{value}@}}
16544 @cindex @code{$@{@var{var}:?@var{value}@}}
16545 @cindex @code{$@{@var{var}:+@var{value}@}}
16546 @end ifnotinfo
16547 Old BSD shells, including the Ultrix @code{sh}, don't accept the
16548 colon for any shell substitution, and complain and die.
16549 Similarly for @code{$@{@var{var}:=@var{value}@}},
16550 @code{$@{@var{var}:?@var{value}@}}, etc.
16551 However, all shells that support functions allow the use of colon in
16552 shell substitution, and since m4sh requires functions, you can portably
16553 use null variable substitution patterns in configure scripts.
16555 @item $@{@var{var}-@var{value}@}
16556 @itemx $@{@var{var}:-@var{value}@}
16557 @itemx $@{@var{var}=@var{value}@}
16558 @itemx $@{@var{var}:=@var{value}@}
16559 @itemx $@{@var{var}?@var{value}@}
16560 @itemx $@{@var{var}:?@var{value}@}
16561 @itemx $@{@var{var}+@var{value}@}
16562 @itemx $@{@var{var}:+@var{value}@}
16563 @cindex @code{$@{@var{var}-@var{value}@}}
16564 @cindex @code{$@{@var{var}=@var{value}@}}
16565 @cindex @code{$@{@var{var}?@var{value}@}}
16566 @cindex @code{$@{@var{var}+@var{value}@}}
16567 @c Info cannot handle ':' in index entries.
16568 @ifnotinfo
16569 @cindex @code{$@{@var{var}:-@var{value}@}}
16570 @cindex @code{$@{@var{var}:=@var{value}@}}
16571 @cindex @code{$@{@var{var}:?@var{value}@}}
16572 @cindex @code{$@{@var{var}:+@var{value}@}}
16573 @end ifnotinfo
16574 When using @samp{$@{@var{var}-@var{value}@}} or
16575 similar notations that modify a parameter expansion,
16576 Posix requires that @var{value} must be a single shell word,
16577 which can contain quoted strings but cannot contain unquoted spaces.
16578 If this requirement is not met Solaris 10 @command{/bin/sh}
16579 sometimes complains, and anyway the behavior is not portable.
16581 @example
16582 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
16583 /bin/sh: bad substitution
16584 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
16585 b c
16586 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
16587 b c
16588 $ @kbd{/bin/sh -c 'cat <<EOF
16589 $@{a-b c@}
16590 EOF}
16591 b c
16592 @end example
16594 Most shells treat the special parameters @code{*} and @code{@@} as being
16595 unset if there are no positional parameters.  However, some shells treat
16596 them as being set to the empty string.  Posix does not clearly specify
16597 either behavior.
16599 @example
16600 $ @kbd{bash -c 'echo "* is $@{*-unset@}."'}
16601 * is unset.
16602 $ @kbd{dash -c 'echo "* is $@{*-unset@}."'}
16603 * is .
16604 @end example
16606 According to Posix, if an expansion occurs inside double quotes, then
16607 the use of unquoted double quotes within @var{value} is unspecified, and
16608 any single quotes become literal characters; in that case, escaping must
16609 be done with backslash.  Likewise, the use of unquoted here-documents is
16610 a case where double quotes have unspecified results:
16612 @example
16613 $ @kbd{/bin/sh -c 'echo "$@{a-"b  c"@}"'}
16614 /bin/sh: bad substitution
16615 $ @kbd{ksh -c 'echo "$@{a-"b  c"@}"'}
16616 b c
16617 $ @kbd{bash -c 'echo "$@{a-"b  c"@}"'}
16618 b  c
16619 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b  c'\''@}'}
16620 b  c
16621 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b  c'\''@}"'}
16622 'b  c'
16623 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b  c\"@}"'}
16624 "b  c"
16625 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b  c@}"'}
16626 b  c
16627 $ @kbd{/bin/sh -c 'cat <<EOF
16628 $@{a-"b  c"@}
16629 EOF'}
16630 "b  c"
16631 $ @kbd{/bin/sh -c 'cat <<EOF
16632 $@{a-'b  c'@}
16633 EOF'}
16634 'b  c'
16635 $ @kbd{bash -c 'cat <<EOF
16636 $@{a-"b  c"@}
16637 EOF'}
16638 b  c
16639 $ @kbd{bash -c 'cat <<EOF
16640 $@{a-'b  c'@}
16641 EOF'}
16642 'b  c'
16643 @end example
16645 Perhaps the easiest way to work around quoting issues in a manner
16646 portable to all shells is to place the results in a temporary variable,
16647 then use @samp{$t} as the @var{value}, rather than trying to inline
16648 the expression needing quoting.
16650 @example
16651 $ @kbd{/bin/sh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16652 b  c"'@}\
16653 $ @kbd{ksh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16654 b  c"'@}\
16655 $ @kbd{bash -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16656 b  c"'@}\
16657 @end example
16659 @item $@{@var{var}=@var{value}@}
16660 @cindex @code{$@{@var{var}=@var{value}@}}
16661 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
16662 to @var{var}, remember that even though the assignment to @var{var} does
16663 not undergo file name expansion, the result of the variable expansion
16664 does unless the expansion occurred within double quotes.  In particular,
16665 when using @command{:} followed by unquoted variable expansion for the
16666 side effect of setting a default value, if the final value of
16667 @samp{$var} contains any globbing characters (either from @var{value} or
16668 from prior contents), the shell has to spend time performing file name
16669 expansion and field splitting even though those results will not be
16670 used.  Therefore, it is a good idea to consider double quotes when performing
16671 default initialization; while remembering how this impacts any quoting
16672 characters appearing in @var{value}.
16674 @example
16675 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
16676 /usr/bin/*
16678 real    0m0.005s
16679 user    0m0.002s
16680 sys     0m0.003s
16681 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
16682 /usr/bin/*
16684 real    0m0.039s
16685 user    0m0.026s
16686 sys     0m0.009s
16687 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
16688 /usr/bin/*
16690 real    0m0.031s
16691 user    0m0.020s
16692 sys     0m0.010s
16694 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
16695 /usr/bin/*
16697 real    0m0.006s
16698 user    0m0.002s
16699 sys     0m0.003s
16700 @end example
16702 As with @samp{+} and @samp{-}, @var{value} must be a single shell word,
16703 otherwise some shells, such as Solaris 10 @command{/bin/sh} or on Digital
16704 Unix V 5.0, die because of a ``bad substitution''.  Meanwhile, Posix
16705 requires that with @samp{=}, quote removal happens prior to the
16706 assignment, and the expansion be the final contents of @var{var} without
16707 quoting (and thus subject to field splitting), in contrast to the
16708 behavior with @samp{-} passing the quoting through to the final
16709 expansion.  However, @command{bash} 4.1 does not obey this rule.
16711 @example
16712 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16713 a  b
16714 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16715 a b
16716 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16717 a  b
16718 @end example
16720 Finally, Posix states that when mixing @samp{$@{a=b@}} with regular
16721 commands, it is unspecified whether the assignments affect the parent
16722 shell environment.  It is best to perform assignments independently from
16723 commands, to avoid the problems demonstrated in this example:
16725 @example
16726 $ @kbd{bash -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16727 +b+b+
16729 $ @kbd{/bin/sh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16730 ++b+
16732 $ @kbd{ksh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16733 +b+b+
16735 @end example
16737 @item $@{@var{var}=@var{value}@}
16738 @cindex @code{$@{@var{var}=@var{literal}@}}
16739 Solaris 10 @command{/bin/sh} has a frightening bug in its handling of
16740 literal assignments.  Imagine you need set a variable to a string containing
16741 @samp{@}}.  This @samp{@}} character confuses Solaris 10 @command{/bin/sh}
16742 when the affected variable was already set.  This bug can be exercised
16743 by running:
16745 @example
16746 $ @kbd{unset foo}
16747 $ @kbd{foo=$@{foo='@}'@}}
16748 $ @kbd{echo $foo}
16750 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
16751 $ @kbd{echo $foo}
16753 $ @kbd{foo=$@{foo='@}'@}}
16754 $ @kbd{echo $foo}
16755 @}@}
16756  ^ ugh!
16757 @end example
16759 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16760 though it is enclosed in single quotes.  The problem doesn't happen
16761 using double quotes, or when using a temporary variable holding the
16762 problematic string.
16764 @item $@{@var{var}=@var{expanded-value}@}
16765 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
16766 On Ultrix,
16767 running
16769 @example
16770 default="yu,yaa"
16771 : $@{var="$default"@}
16772 @end example
16774 @noindent
16775 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
16776 each char is set.  You don't observe the phenomenon using a simple
16777 @samp{echo $var} since apparently the shell resets the 8th bit when it
16778 expands $var.  Here are two means to make this shell confess its sins:
16780 @example
16781 $ @kbd{cat -v <<EOF
16782 $var
16783 EOF}
16784 @end example
16786 @noindent
16789 @example
16790 $ @kbd{set | grep '^var=' | cat -v}
16791 @end example
16793 One classic incarnation of this bug is:
16795 @example
16796 default="a b c"
16797 : $@{list="$default"@}
16798 for c in $list; do
16799   echo $c
16800 done
16801 @end example
16803 @noindent
16804 You'll get @samp{a b c} on a single line.  Why?  Because there are no
16805 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
16806 bit set, hence no IFS splitting is performed!!!
16808 One piece of good news is that Ultrix works fine with @samp{:
16809 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
16810 then that QNX 4.25 then sets @var{list} to the @emph{last} item of
16811 @var{default}!
16813 The portable way out consists in using a double assignment, to switch
16814 the 8th bit twice on Ultrix:
16816 @example
16817 list=$@{list="$default"@}
16818 @end example
16820 @noindent
16821 @dots{}but beware of the @samp{@}} bug from Solaris 10 (see above).
16822 For safety, use:
16824 @example
16825 test $@{var+y@} || var=@var{@{value@}}
16826 @end example
16828 @item $@{#@var{var}@}
16829 @itemx $@{@var{var}%@var{word}@}
16830 @itemx $@{@var{var}%%@var{word}@}
16831 @itemx $@{@var{var}#@var{word}@}
16832 @itemx $@{@var{var}##@var{word}@}
16833 @cindex @code{$@{#@var{var}@}}
16834 @cindex @code{$@{@var{var}%@var{word}@}}
16835 @cindex @code{$@{@var{var}%%@var{word}@}}
16836 @cindex @code{$@{@var{var}#@var{word}@}}
16837 @cindex @code{$@{@var{var}##@var{word}@}}
16838 Posix requires support for these usages, but they do not work with many
16839 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16841 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
16842 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16843 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16844 yields the empty string.
16847 @item `@var{commands}`
16848 @cindex @code{`@var{commands}`}
16849 @cindex Command Substitution
16850 Posix requires shells to trim all trailing newlines from command
16851 output before substituting it, so assignments like
16852 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
16853 @samp{$file} ends in a newline.
16855 While in general it makes no sense, do not substitute a single builtin
16856 with side effects, because Ash 0.2, trying to optimize, does not fork a
16857 subshell to perform the command.
16859 For instance, if you wanted to check that @command{cd} is silent, do not
16860 use @samp{test -z "`cd /`"} because the following can happen:
16862 @example
16863 $ @kbd{pwd}
16864 /tmp
16865 $ @kbd{test -z "`cd /`" && pwd}
16867 @end example
16869 @noindent
16870 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16872 The MSYS shell leaves a stray byte in the expansion of a double-quoted
16873 command substitution of a native program, if the end of the substitution
16874 is not aligned with the end of the double quote.  This may be worked
16875 around by inserting another pair of quotes:
16877 @example
16878 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16879 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16880 - broken differ: char 4, line 1
16881 @end example
16883 Upon interrupt or SIGTERM, some shells may abort a command substitution,
16884 replace it with a null string, and wrongly evaluate the enclosing
16885 command before entering the trap or ending the script.  This can lead to
16886 spurious errors:
16888 @example
16889 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16890 $ @kbd{^C}
16891 sh: test: hi: unexpected operator/operand
16892 @end example
16894 @noindent
16895 You can avoid this by assigning the command substitution to a temporary
16896 variable:
16898 @example
16899 $ @kbd{sh -c 'res=`sleep 5; echo hi`
16900          if test "x$res" = xhi; then echo yes; fi'}
16901 $ @kbd{^C}
16902 @end example
16904 @item $(@var{commands})
16905 @cindex @code{$(@var{commands})}
16906 This construct is meant to replace @samp{`@var{commands}`},
16907 and it has most of the problems listed under @code{`@var{commands}`}.
16909 This construct can be
16910 nested while this is impossible to do portably with back quotes.
16911 Although it is almost universally supported, unfortunately Solaris 10
16912 and earlier releases lack it:
16914 @example
16915 $ @kbd{showrev -c /bin/sh | grep version}
16916 Command version: SunOS 5.10 Generic 142251-02 Sep 2010
16917 $ @kbd{echo $(echo blah)}
16918 syntax error: `(' unexpected
16919 @end example
16921 @noindent
16922 nor does IRIX 6.5's Bourne shell:
16923 @example
16924 $ @kbd{uname -a}
16925 IRIX firebird-image 6.5 07151432 IP22
16926 $ @kbd{echo $(echo blah)}
16927 $(echo blah)
16928 @end example
16930 If you do use @samp{$(@var{commands})}, make sure that the commands
16931 do not start with a parenthesis, as that would cause confusion with
16932 a different notation @samp{$((@var{expression}))} that in modern
16933 shells is an arithmetic expression not a command.  To avoid the
16934 confusion, insert a space between the two opening parentheses.
16936 Avoid @var{commands} that contain unbalanced parentheses in
16937 here-documents, comments, or case statement patterns, as many shells
16938 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
16939 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16941 @example
16942 echo $(case x in x) echo hello;; esac)
16943 @end example
16946 @item $((@var{expression}))
16947 @cindex @code{$((@var{expression}))}
16948 Arithmetic expansion is not portable as some shells (most
16949 notably Solaris 10 @command{/bin/sh}) don't support it.
16951 Among shells that do support @samp{$(( ))}, not all of them obey the
16952 Posix rule that octal and hexadecimal constants must be recognized:
16954 @example
16955 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
16957 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
16959 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
16961 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16962 pdksh:  010 + 0x10 : bad number `0x10'
16963 $ @kbd{pdksh -c 'echo $(( 010 ))'}
16965 @end example
16967 When it is available, using arithmetic expansion provides a noticeable
16968 speedup in script execution; but testing for support requires
16969 @command{eval} to avoid syntax errors.  The following construct is used
16970 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16971 arguments are decimal integers without leading zeros, and all
16972 operators are properly quoted and appear as distinct arguments:
16974 @example
16975 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16976   eval 'func_arith ()
16977   @{
16978     func_arith_result=$(( $* ))
16979   @}'
16980 else
16981   func_arith ()
16982   @{
16983     func_arith_result=`expr "$@@"`
16984   @}
16986 func_arith 1 + 1
16987 foo=$func_arith_result
16988 @end example
16991 @item ^
16992 @cindex @code{^} quoting
16993 Always quote @samp{^}, otherwise traditional shells such as
16994 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
16996 @end table
16999 @node Assignments
17000 @section Assignments
17001 @cindex Shell assignments
17003 When setting several variables in a row, be aware that the order of the
17004 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
17005 gives @samp{1} with Solaris 10 @command{/bin/sh}, but @samp{2} with Bash.
17006 You must use
17007 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
17009 Don't rely on the following to find @file{subdir/program}:
17011 @example
17012 PATH=subdir$PATH_SEPARATOR$PATH program
17013 @end example
17015 @noindent
17016 as this does not work with Zsh 3.0.6.  Use something like this
17017 instead:
17019 @example
17020 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
17021 @end example
17023 Don't rely on the exit status of an assignment: Ash 0.2 does not change
17024 the status and propagates that of the last statement:
17026 @example
17027 $ @kbd{false || foo=bar; echo $?}
17029 $ @kbd{false || foo=`:`; echo $?}
17031 @end example
17033 @noindent
17034 and to make things even worse, QNX 4.25 just sets the exit status
17035 to 0 in any case:
17037 @example
17038 $ @kbd{foo=`exit 1`; echo $?}
17040 @end example
17042 To assign default values, follow this algorithm:
17044 @enumerate
17045 @item
17046 If the default value is a literal and does not contain any closing
17047 brace, use:
17049 @example
17050 : "$@{var='my literal'@}"
17051 @end example
17053 @item
17054 If the default value contains no closing brace, has to be expanded, and
17055 the variable being initialized is not intended to be IFS-split
17056 (i.e., it's not a list), then use:
17058 @example
17059 : $@{var="$default"@}
17060 @end example
17062 @item
17063 If the default value contains no closing brace, has to be expanded, and
17064 the variable being initialized is intended to be IFS-split (i.e., it's a list),
17065 then use:
17067 @example
17068 var=$@{var="$default"@}
17069 @end example
17071 @item
17072 If the default value contains a closing brace, then use:
17074 @example
17075 test $@{var+y@} || var="has a '@}'"
17076 @end example
17077 @end enumerate
17079 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
17080 doubt, just use the last form.  @xref{Shell Substitutions}, items
17081 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
17082 for the rationale.
17084 @node Parentheses
17085 @section Parentheses in Shell Scripts
17086 @cindex Shell parentheses
17088 Beware of two opening parentheses in a row, as many shell
17089 implementations treat them specially, and Posix says that a portable
17090 script cannot use @samp{((} outside the @samp{$((} form used for shell
17091 arithmetic.  In traditional shells, @samp{((cat))} behaves like
17092 @samp{(cat)}; but many shells, including
17093 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
17094 expression equivalent to @samp{let "cat"}, and may or may not report an
17095 error when they detect that @samp{cat} is not a number.  As another
17096 example, @samp{pdksh} 5.2.14 does not treat the following code
17097 as a traditional shell would:
17099 @example
17100 if ((true) || false); then
17101   echo ok
17103 @end example
17105 @noindent
17106 To work around this problem, insert a space between the two opening
17107 parentheses.  There is a similar problem and workaround with
17108 @samp{$((}; see @ref{Shell Substitutions}.
17110 @node Slashes
17111 @section Slashes in Shell Scripts
17112 @cindex Shell slashes
17114 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
17115 arguments that contain two trailing slashes:
17117 @example
17118 $ @kbd{echo / // /// //// .// //.}
17119 / / // /// ./ //.
17120 $ @kbd{x=//}
17121 $ @kbd{eval "echo \$x"}
17123 $ @kbd{set -x}
17124 $ @kbd{echo abc | tr -t ab //}
17125 + echo abc
17126 + tr -t ab /
17128 @end example
17130 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
17131 variable is empty and the second double-quote is followed by a word that
17132 begins and ends with slash:
17134 @example
17135 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
17137 + echo //ouch/
17138 //ouch/
17139 @end example
17141 However, our understanding is that patches are available, so perhaps
17142 it's not worth worrying about working around these horrendous bugs.
17144 @node Special Shell Variables
17145 @section Special Shell Variables
17146 @cindex Shell variables
17147 @cindex Special shell variables
17149 Some shell variables should not be used, since they can have a deep
17150 influence on the behavior of the shell.  In order to recover a sane
17151 behavior from the shell, some variables should be unset; M4sh takes
17152 care of this and provides fallback values, whenever needed, to cater
17153 for a very old @file{/bin/sh} that does not support @command{unset}.
17154 (@pxref{Portable Shell, , Portable Shell Programming}).
17156 As a general rule, shell variable names containing a lower-case letter
17157 are safe; you can define and use these variables without worrying about
17158 their effect on the underlying system, and without worrying about
17159 whether the shell changes them unexpectedly.  (The exception is the
17160 shell variable @code{status}, as described below.)
17162 Here is a list of names that are known to cause trouble.  This list is
17163 not exhaustive, but you should be safe if you avoid the name
17164 @code{status} and names containing only upper-case letters and
17165 underscores.
17167 @c Alphabetical order, case insensitive, 'A' before 'a'.
17168 @table @code
17169 @item ?
17170 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
17171 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
17172 correctly in shell functions (@pxref{Shell Functions}) or in traps
17173 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
17174 @samp{$?} to zero after an empty command.
17176 @example
17177 $ @kbd{bash -c 'false; $empty; echo $?'}
17179 $ @kbd{zsh -c 'false; $empty; echo $?'}
17181 @end example
17183 @item _
17184 @evindex _
17185 Many shells reserve @samp{$_} for various purposes, e.g., the name of
17186 the last command executed.
17188 @item BIN_SH
17189 @evindex BIN_SH
17190 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
17191 the standard shell conform to Posix.
17193 @item CDPATH
17194 @evindex CDPATH
17195 When this variable is set it specifies a list of directories to search
17196 when invoking @code{cd} with a relative file name that did not start
17197 with @samp{./} or @samp{../}.  Posix
17198 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
17199 is used successfully, @code{cd} prints the resulting absolute
17200 file name.  Unfortunately this output can break idioms like
17201 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
17202 Also, many shells do not conform to this part of Posix; for
17203 example, @command{zsh} prints the result only if a directory name
17204 other than @file{.} was chosen from @env{CDPATH}.
17206 In practice the shells that have this problem also support
17207 @command{unset}, so you can work around the problem as follows:
17209 @example
17210 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
17211 @end example
17213 You can also avoid output by ensuring that your directory name is
17214 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
17216 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
17217 possible, so you need not worry about this problem in those scripts.
17219 @item CLICOLOR_FORCE
17220 @evindex CLICOLOR_FORCE
17221 When this variable is set, some implementations of tools like
17222 @command{ls} attempt to add color to their output via terminal escape
17223 sequences, even when the output is not directed to a terminal, and can
17224 thus cause spurious failures in scripts.  Configure scripts use M4sh,
17225 which automatically unsets this variable.
17227 @item DUALCASE
17228 @evindex DUALCASE
17229 In the MKS shell, case statements and file name generation are
17230 case-insensitive unless @env{DUALCASE} is nonzero.
17231 Autoconf-generated scripts export this variable when they start up.
17233 @item ENV
17234 @itemx MAIL
17235 @itemx MAILPATH
17236 @itemx PS1
17237 @itemx PS2
17238 @itemx PS4
17239 @evindex ENV
17240 @evindex MAIL
17241 @evindex MAILPATH
17242 @evindex PS1
17243 @evindex PS2
17244 @evindex PS4
17245 These variables should not matter for shell scripts, since they are
17246 supposed to affect only interactive shells.  However, at least one
17247 shell (the pre-3.0 UWIN Korn shell) gets confused about
17248 whether it is interactive, which means that (for example) a @env{PS1}
17249 with a side effect can unexpectedly modify @samp{$?}.  To work around
17250 this bug, M4sh scripts (including @file{configure} scripts) do something
17251 like this:
17253 @example
17254 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
17255 PS1='$ '
17256 PS2='> '
17257 PS4='+ '
17258 @end example
17260 @noindent
17261 (actually, there is some complication due to bugs in @command{unset};
17262 @pxref{unset, , Limitations of Shell Builtins}).
17264 @item FPATH
17265 @evindex FPATH
17266 The Korn shell uses @env{FPATH} to find shell functions, so avoid
17267 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
17268 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
17269 to find whether a command exists, since they might report the wrong
17270 result if @env{FPATH} is also set.
17272 @item GREP_OPTIONS
17273 @evindex GREP_OPTIONS
17274 When this variable is set, some implementations of @command{grep} honor
17275 these options, even if the options include direction to enable colored
17276 output via terminal escape sequences, and the result can cause spurious
17277 failures when the output is not directed to a terminal.  Configure
17278 scripts use M4sh, which automatically unsets this variable.
17280 @item IFS
17281 @evindex IFS
17282 Long ago, shell scripts inherited @env{IFS} from the environment,
17283 but this caused many problems so modern shells ignore any environment
17284 settings for @env{IFS}.
17286 Don't set the first character of @env{IFS} to backslash.  Indeed,
17287 Bourne shells use the first character (backslash) when joining the
17288 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
17289 backslash escapes, so you can end up with backspace and other strange
17290 characters.
17292 The proper value for @env{IFS} (in regular code, not when performing
17293 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
17294 especially important, as it is used to join the arguments in @samp{$*};
17295 however, note that traditional shells, but also bash-2.04, fail to adhere
17296 to this and join with a space anyway.
17298 M4sh guarantees that @env{IFS} will have the default value at the
17299 beginning of a script, and many macros within autoconf rely on this
17300 setting.  It is okay to use blocks of shell code that temporarily change
17301 the value of @env{IFS} in order to split on another character, but
17302 remember to restore it before expanding further macros.
17304 Unsetting @code{IFS} instead of resetting it to the default sequence
17305 is not suggested, since code that tries to save and restore the
17306 variable's value will incorrectly reset it to an empty value, thus
17307 disabling field splitting:
17309 @example
17310 unset IFS
17311 # default separators used for field splitting
17313 save_IFS=$IFS
17314 IFS=:
17315 # ...
17316 IFS=$save_IFS
17317 # no field splitting performed
17318 @end example
17320 @item LANG
17321 @itemx LC_ALL
17322 @itemx LC_COLLATE
17323 @itemx LC_CTYPE
17324 @itemx LC_MESSAGES
17325 @itemx LC_MONETARY
17326 @itemx LC_NUMERIC
17327 @itemx LC_TIME
17328 @evindex LANG
17329 @evindex LC_ALL
17330 @evindex LC_COLLATE
17331 @evindex LC_CTYPE
17332 @evindex LC_MESSAGES
17333 @evindex LC_MONETARY
17334 @evindex LC_NUMERIC
17335 @evindex LC_TIME
17337 You should set all these variables to @samp{C} because so much
17338 configuration code assumes the C locale and Posix requires that locale
17339 environment variables be set to @samp{C} if the C locale is desired;
17340 @file{configure} scripts and M4sh do that for you.
17341 Export these variables after setting them.
17343 @c  However, some older, nonstandard
17344 @c  systems (notably SCO) break if locale environment variables
17345 @c  are set to @samp{C}, so when running on these systems
17346 @c  Autoconf-generated scripts unset the variables instead.
17348 @item LANGUAGE
17349 @evindex LANGUAGE
17351 @env{LANGUAGE} is not specified by Posix, but it is a GNU
17352 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
17353 should set it too.
17355 @item LC_ADDRESS
17356 @itemx LC_IDENTIFICATION
17357 @itemx LC_MEASUREMENT
17358 @itemx LC_NAME
17359 @itemx LC_PAPER
17360 @itemx LC_TELEPHONE
17361 @evindex LC_ADDRESS
17362 @evindex LC_IDENTIFICATION
17363 @evindex LC_MEASUREMENT
17364 @evindex LC_NAME
17365 @evindex LC_PAPER
17366 @evindex LC_TELEPHONE
17368 These locale environment variables are GNU extensions.  They
17369 are treated like their Posix brethren (@env{LC_COLLATE},
17370 etc.)@: as described above.
17372 @item LINENO
17373 @evindex LINENO
17374 Most modern shells provide the current line number in @code{LINENO}.
17375 Its value is the line number of the beginning of the current command.
17376 M4sh, and hence Autoconf, attempts to execute @command{configure} with
17377 a shell that supports @code{LINENO}.  If no such shell is available, it
17378 attempts to implement @code{LINENO} with a Sed prepass that replaces each
17379 instance of the string @code{$LINENO} (not followed by an alphanumeric
17380 character) with the line's number.  In M4sh scripts you should execute
17381 @code{AS_LINENO_PREPARE} so that these workarounds are included in
17382 your script; configure scripts do this automatically in @code{AC_INIT}.
17384 You should not rely on @code{LINENO} within @command{eval} or shell
17385 functions, as the behavior differs in practice.  The presence of a
17386 quoted newline within simple commands can alter which line number is
17387 used as the starting point for @code{$LINENO} substitutions within that
17388 command.  Also, the possibility of the Sed prepass means that you should
17389 not rely on @code{$LINENO} when quoted, when in here-documents, or when
17390 line continuations are used.  Subshells should be OK, though.  In the
17391 following example, lines 1, 9, and 14 are portable, but the other
17392 instances of @code{$LINENO} do not have deterministic values:
17394 @example
17395 @group
17396 $ @kbd{cat lineno}
17397 echo 1. $LINENO
17398 echo "2. $LINENO
17399 3. $LINENO"
17400 cat <<EOF
17401 5. $LINENO
17402 6. $LINENO
17403 7. \$LINENO
17405 ( echo 9. $LINENO )
17406 eval 'echo 10. $LINENO'
17407 eval 'echo 11. $LINENO
17408 echo 12. $LINENO'
17409 echo 13. '$LINENO'
17410 echo 14. $LINENO '
17411 15.' $LINENO
17412 f () @{ echo $1 $LINENO;
17413 echo $1 $LINENO @}
17414 f 18.
17415 echo 19. \
17416 $LINENO
17417 @end group
17418 @group
17419 $ @kbd{bash-3.2 ./lineno}
17420 1. 1
17421 2. 3
17422 3. 3
17423 5. 4
17424 6. 4
17425 7. $LINENO
17426 9. 9
17427 10. 10
17428 11. 12
17429 12. 13
17430 13. $LINENO
17431 14. 14
17432 15. 14
17433 18. 16
17434 18. 17
17435 19. 19
17436 @end group
17437 @group
17438 $ @kbd{zsh-4.3.4 ./lineno}
17439 1. 1
17440 2. 2
17441 3. 2
17442 5. 4
17443 6. 4
17444 7. $LINENO
17445 9. 9
17446 10. 1
17447 11. 1
17448 12. 2
17449 13. $LINENO
17450 14. 14
17451 15. 14
17452 18. 0
17453 18. 1
17454 19. 19
17455 @end group
17456 @group
17457 $ @kbd{pdksh-5.2.14 ./lineno}
17458 1. 1
17459 2. 2
17460 3. 2
17461 5. 4
17462 6. 4
17463 7. $LINENO
17464 9. 9
17465 10. 0
17466 11. 0
17467 12. 0
17468 13. $LINENO
17469 14. 14
17470 15. 14
17471 18. 16
17472 18. 17
17473 19. 19
17474 @end group
17475 @group
17476 $ @kbd{sed '=' <lineno |}
17477 > @kbd{  sed '}
17478 > @kbd{    N}
17479 > @kbd{    s,$,-,}
17480 > @kbd{    t loop}
17481 > @kbd{    :loop}
17482 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
17483 > @kbd{    t loop}
17484 > @kbd{    s,-$,,}
17485 > @kbd{    s,^[0-9]*\n,,}
17486 > @kbd{  ' |}
17487 > @kbd{  sh}
17488 1. 1
17489 2. 2
17490 3. 3
17491 5. 5
17492 6. 6
17493 7. \7
17494 9. 9
17495 10. 10
17496 11. 11
17497 12. 12
17498 13. 13
17499 14. 14
17500 15. 15
17501 18. 16
17502 18. 17
17503 19. 20
17504 @end group
17505 @end example
17507 In particular, note that @file{config.status} (and any other subsidiary
17508 script created by @code{AS_INIT_GENERATED}) might report line numbers
17509 relative to the parent script as a result of the potential Sed pass.
17511 @item NULLCMD
17512 @evindex NULLCMD
17513 When executing the command @samp{>foo}, @command{zsh} executes
17514 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
17515 compatibility mode and the @command{zsh} version is newer
17516 than 3.1.6-dev-18.  If you are using an older @command{zsh}
17517 and forget to set @env{NULLCMD},
17518 your script might be suspended waiting for data on its standard input.
17520 @item options
17521 @evindex options
17522 For @command{zsh} 4.3.10, @env{options} is treated as an associative
17523 array even after @code{emulate sh}, so it should not be used.
17525 @item PATH_SEPARATOR
17526 @evindex PATH_SEPARATOR
17527 On DJGPP systems, the @env{PATH_SEPARATOR} environment
17528 variable can be set to either @samp{:} or @samp{;} to control the path
17529 separator Bash uses to set up certain environment variables (such as
17530 @env{PATH}).  You can set this variable to @samp{;} if you want
17531 @command{configure} to use @samp{;} as a separator; this might be useful
17532 if you plan to use non-Posix shells to execute files.  @xref{File System
17533 Conventions}, for more information about @code{PATH_SEPARATOR}.
17535 @item POSIXLY_CORRECT
17536 @evindex POSIXLY_CORRECT
17537 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
17538 (even empty) causes programs to try harder to conform to Posix.
17539 Autoconf does not directly manipulate this variable, but @command{bash}
17540 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
17541 running in Posix mode.  Therefore, take care when exporting or unsetting
17542 this variable, so as not to change whether @command{bash} is in Posix
17543 mode.
17545 @example
17546 $ @kbd{bash --posix -c 'set -o | grep posix}
17547 > @kbd{unset POSIXLY_CORRECT}
17548 > @kbd{set -o | grep posix'}
17549 posix           on
17550 posix           off
17551 @end example
17553 @item PWD
17554 @evindex PWD
17555 Posix 1003.1-2001 requires that @command{cd} and
17556 @command{pwd} must update the @env{PWD} environment variable to point
17557 to the logical name of the current directory, but traditional shells
17558 do not support this.  This can cause confusion if one shell instance
17559 maintains @env{PWD} but a subsidiary and different shell does not know
17560 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
17561 points to the wrong directory.  Use @samp{`pwd`} rather than
17562 @samp{$PWD}.
17564 @item RANDOM
17565 @evindex RANDOM
17566 Many shells provide @code{RANDOM}, a variable that returns a different
17567 integer each time it is used.  Most of the time, its value does not
17568 change when it is not used, but on IRIX 6.5 the value changes all
17569 the time.  This can be observed by using @command{set}.  It is common
17570 practice to use @code{$RANDOM} as part of a file name, but code
17571 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
17573 @item status
17574 @evindex status
17575 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
17576 hence read-only.  Do not use it.
17577 @end table
17579 @node Shell Functions
17580 @section Shell Functions
17581 @cindex Shell Functions
17583 Nowadays, it is difficult to find a shell that does not support
17584 shell functions at all.  However, some differences should be expected.
17586 When declaring a shell function, you must include whitespace between the
17587 @samp{)} after the function name and the start of the compound
17588 expression, to avoid upsetting @command{ksh}.  While it is possible to
17589 use any compound command, most scripts use @samp{@{@dots{}@}}.
17591 @example
17592 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
17594 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
17595 ksh: syntax error at line 1: `@}' unexpected
17596 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
17598 @end example
17600 Inside a shell function, you should not rely on the error status of a
17601 subshell if the last command of that subshell was @code{exit} or
17602 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
17603 find a shell that does not exhibit the bug, zsh might be the only shell
17604 present on the user's machine.
17606 Likewise, the state of @samp{$?} is not reliable when entering a shell
17607 function.  This has the effect that using a function as the first
17608 command in a @command{trap} handler can cause problems.
17610 @example
17611 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17614 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17617 @end example
17619 DJGPP bash 2.04 has a bug in that @command{return} from a
17620 shell function which also used a command substitution causes a
17621 segmentation fault.  To work around the issue, you can use
17622 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
17623 in the execution flow of the function (@pxref{Common Shell Constructs}).
17625 Not all shells treat shell functions as simple commands impacted by
17626 @samp{set -e}, for example with Solaris 10 @command{/bin/sh}:
17628 @example
17629 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17630 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17631 oops
17632 @end example
17634 Shell variables and functions may share the same namespace, for example
17635 with Solaris 10 @command{/bin/sh}:
17637 @example
17638 $ @kbd{f () @{ :; @}; f=; f}
17639 f: not found
17640 @end example
17642 @noindent
17643 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
17644 uses the prefix @samp{as_fn_} for its functions.
17646 Handling of positional parameters and shell options varies among shells.
17647 For example, Korn shells reset and restore trace output (@samp{set -x})
17648 and other options upon function entry and exit.  Inside a function,
17649 IRIX sh sets @samp{$0} to the function name.
17651 It is not portable to pass temporary environment variables to shell
17652 functions.  Solaris 10 @command{/bin/sh} does not see the variable.
17653 Meanwhile, not all shells follow the Posix rule that the assignment must
17654 affect the current environment in the same manner as special built-ins.
17656 @example
17657 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17658 @result{}
17659 @result{}
17660 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17661 @result{}1
17662 @result{}
17663 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
17664 @result{}1
17665 @result{}1
17666 @end example
17668 Some ancient Bourne shell variants with function support did not reset
17669 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
17670 arguments of the script were lost after the first function invocation.
17671 It is probably not worth worrying about these shells any more.
17673 With AIX sh, a @command{trap} on 0 installed in a shell function
17674 triggers at function exit rather than at script exit.  @xref{trap, ,
17675 Limitations of Shell Builtins}.
17677 @node Limitations of Builtins
17678 @section Limitations of Shell Builtins
17679 @cindex Shell builtins
17680 @cindex Limitations of shell builtins
17682 No, no, we are serious: some shells do have limitations!  :)
17684 You should always keep in mind that any builtin or command may support
17685 options, and therefore differ in behavior with arguments
17686 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
17687 can give unexpected results when @code{word} starts with a dash.  It is
17688 often possible to avoid this problem using @samp{echo "x$word"}, taking
17689 the @samp{x} into account later in the pipe.  Many of these limitations
17690 can be worked around using M4sh (@pxref{Programming in M4sh}).
17692 @c This table includes things like '@command{test} (files)', so we can't
17693 @c use @table @command.
17694 @table @asis
17695 @item @command{.}
17696 @c --------------
17697 @prindex @command{.}
17698 Use @command{.} only with regular files (use @samp{test -f}).  Bash
17699 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
17700 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
17701 some shells, including bash 3.2, implicitly append the current directory
17702 to this @env{PATH} search, even though Posix forbids it.  So if you want
17703 to use @command{.} on a file @file{foo} in the current directory, you
17704 must use @samp{. ./foo}.
17706 Not all shells gracefully handle syntax errors within a sourced file.
17707 On one extreme, some non-interactive shells abort the entire script.  On
17708 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17709 syntax error.
17711 @example
17712 $ @kbd{echo 'fi' > syntax}
17713 $ @kbd{bash -c '. ./syntax; echo $?'}
17714 ./syntax: line 1: syntax error near unexpected token `fi'
17715 ./syntax: line 1: `fi'
17717 $ @kbd{ash -c '. ./syntax; echo $?'}
17718 ./syntax: 1: Syntax error: "fi" unexpected
17719 $ @kbd{zsh -c '. ./syntax; echo $?'}
17720 ./syntax:1: parse error near `fi'
17722 @end example
17724 @item @command{!}
17725 @c --------------
17726 @prindex @command{!}
17727 The Unix version 7 shell did not support
17728 negating the exit status of commands with @command{!}, and this feature
17729 is still absent from some shells (e.g., Solaris 10 @command{/bin/sh}).
17730 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17731 bugs when using @command{!}:
17733 @example
17734 $ @kbd{sh -c '! : | :'; echo $?}
17736 $ @kbd{ash -c '! : | :'; echo $?}
17738 $ @kbd{sh -c '! @{ :; @}'; echo $?}
17740 $ @kbd{ash -c '! @{ :; @}'; echo $?}
17741 @{: not found
17742 Syntax error: "@}" unexpected
17744 @end example
17746 Shell code like this:
17748 @example
17749 if ! cmp file1 file2 >/dev/null 2>&1; then
17750   echo files differ or trouble
17752 @end example
17754 is therefore not portable in practice.  Typically it is easy to rewrite
17755 such code, e.g.:
17757 @example
17758 cmp file1 file2 >/dev/null 2>&1 ||
17759   echo files differ or trouble
17760 @end example
17762 More generally, one can always rewrite @samp{! @var{command}} as:
17764 @example
17765 if @var{command}; then (exit 1); else :; fi
17766 @end example
17769 @item @command{@{...@}}
17770 @c --------------------
17771 @prindex @command{@{...@}}
17772 Bash 3.2 (and earlier versions) sometimes does not properly set
17773 @samp{$?} when failing to write redirected output of a compound command.
17774 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17775 not occur with @samp{(@dots{})}.  For example:
17777 @example
17778 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17779 bash: line 1: /bad: Permission denied
17781 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17782 bash: line 1: /bad: Permission denied
17784 @end example
17786 To work around the bug, prepend @samp{:;}:
17788 @example
17789 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17790 bash: line 1: /bad: Permission denied
17792 @end example
17794 Posix requires a syntax error if a brace list has no contents.  However,
17795 not all shells obey this rule; and on shells where empty lists are
17796 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
17797 ensure that a brace list is never empty.
17799 @example
17800 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17801 bash: line 1: syntax error near unexpected token `@}'
17802 bash: line 1: `false; @{ @}; echo $?'
17804 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
17806 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
17808 @end example
17811 @item @command{break}
17812 @c ------------------
17813 @prindex @command{break}
17814 The use of @samp{break 2} etc.@: is safe.
17817 @anchor{case}
17818 @item @command{case}
17819 @c -----------------
17820 @prindex @command{case}
17821 You don't need to quote the argument; no splitting is performed.
17823 You don't need the final @samp{;;}, but you should use it.
17825 Posix requires support for @code{case} patterns with opening
17826 parentheses like this:
17828 @example
17829 case $file_name in
17830   (*.c) echo "C source code";;
17831 esac
17832 @end example
17834 @noindent
17835 but the @code{(} in this example is not portable to a few obsolescent Bourne
17836 shell implementations, which is a pity for those of us using tools that
17837 rely on balanced parentheses.  For instance, with Solaris 10
17838 @command{/bin/sh}:
17840 @example
17841 $ @kbd{case foo in (foo) echo foo;; esac}
17842 @error{}syntax error: `(' unexpected
17843 @end example
17845 @noindent
17846 The leading @samp{(} can be omitted safely.  Unfortunately, there are
17847 contexts where unbalanced parentheses cause other problems, such as when
17848 using a syntax-highlighting editor that searches for the balancing
17849 counterpart, or more importantly, when using a case statement as an
17850 underquoted argument to an Autoconf macro.  @xref{Balancing
17851 Parentheses}, for trade-offs involved in various styles of dealing with
17852 unbalanced @samp{)}.
17854 Zsh handles pattern fragments derived from parameter expansions or
17855 command substitutions as though quoted:
17857 @example
17858 $ pat=\?; case aa in ?$pat) echo match;; esac
17859 $ pat=\?; case a? in ?$pat) echo match;; esac
17860 match
17861 @end example
17863 @noindent
17864 Because of a bug in its @code{fnmatch}, Bash fails to properly
17865 handle backslashes in character classes:
17867 @example
17868 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17869 bash-2.02$
17870 @end example
17872 @noindent
17873 This is extremely unfortunate, since you are likely to use this code to
17874 handle Posix or MS-DOS absolute file names.  To work around this
17875 bug, always put the backslash first:
17877 @example
17878 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17880 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17882 @end example
17884 Many Bourne shells cannot handle closing brackets in character classes
17885 correctly.
17887 Some shells also have problems with backslash escaping in case you do not want
17888 to match the backslash: both a backslash and the escaped character match this
17889 pattern.  To work around this, specify the character class in a variable, so
17890 that quote removal does not apply afterwards, and the special characters don't
17891 have to be backslash-escaped:
17893 @example
17894 $ @kbd{case '\' in [\<]) echo OK;; esac}
17896 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17898 @end example
17900 Even with this, Solaris @command{ksh} matches a backslash if the set
17901 contains any
17902 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17904 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
17905 a closing parenthesis if not specified in a character class:
17907 @example
17908 $ @kbd{case foo in *\)*) echo fail ;; esac}
17909 fail
17910 $ @kbd{case foo in *')'*) echo fail ;; esac}
17911 fail
17912 @end example
17914 Some shells, such as Ash 0.3.8, are confused by an empty
17915 @code{case}/@code{esac}:
17917 @example
17918 ash-0.3.8 $ @kbd{case foo in esac;}
17919 @error{}Syntax error: ";" unexpected (expecting ")")
17920 @end example
17922 Posix requires @command{case} to give an exit status of 0 if no cases
17923 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
17924 rule.  Meanwhile, it is unclear whether a case that matches, but
17925 contains no statements, must also change the exit status to 0.  The M4sh
17926 macro @code{AS_CASE} works around these inconsistencies.
17928 @example
17929 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
17931 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17933 @end example
17936 @item @command{cd}
17937 @c ---------------
17938 @prindex @command{cd}
17939 Posix 1003.1-2001 requires that @command{cd} must support
17940 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17941 with @option{-L} being the default.  However, traditional shells do
17942 not support these options, and their @command{cd} command has the
17943 @option{-P} behavior.
17945 Portable scripts should assume neither option is supported, and should
17946 assume neither behavior is the default.  This can be a bit tricky,
17947 since the Posix default behavior means that, for example,
17948 @samp{ls ..} and @samp{cd ..} may refer to different directories if
17949 the current logical directory is a symbolic link.  It is safe to use
17950 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17951 Also, Autoconf-generated scripts check for this problem when computing
17952 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17953 so it is safe to @command{cd} to these variables.
17955 Posix states that behavior is undefined if @command{cd} is given an
17956 explicit empty argument.  Some shells do nothing, some change to the
17957 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
17958 the shell rather than returning an error.  Unfortunately, this means
17959 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
17960 than @samp{cd $var} (at least the latter is well-behaved in all shells
17961 at changing to @env{HOME}, although this is probably not what you wanted
17962 in a script).  You should check that a directory name was supplied
17963 before trying to change locations.
17965 @xref{Special Shell Variables}, for portability problems involving
17966 @command{cd} and the @env{CDPATH} environment variable.
17967 Also please see the discussion of the @command{pwd} command.
17970 @anchor{echo}
17971 @item @command{echo}
17972 @c -----------------
17973 @prindex @command{echo}
17974 The simple @command{echo} is probably the most surprising source of
17975 portability troubles.  It is not possible to use @samp{echo} portably
17976 unless both options and escape sequences are omitted.  Don't expect any
17977 option.
17979 Do not use backslashes in the arguments, as there is no consensus on
17980 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
17981 Solaris 10 outputs 2,
17982 but Bash and Zsh (in @command{sh} emulation mode) output 1.
17983 The problem is truly @command{echo}: all the shells
17984 understand @samp{'\n'} as the string composed of a backslash and an
17985 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
17986 mess up the internal state of ksh88 on AIX 6.1 so that it will print
17987 the first character @samp{s} only, followed by a newline, and then
17988 entirely drop the output of the next echo in a command substitution.
17990 Because of these problems, do not pass a string containing arbitrary
17991 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
17992 only if you know that @var{foo}'s value cannot contain backslashes and
17993 cannot start with @samp{-}.
17995 Normally, @command{printf} is safer and easier to use than @command{echo}
17996 and @command{echo -n}.  Thus, you should use @command{printf "%s\n"}
17997 instead of @command{echo}, and similarly use @command{printf %s} instead
17998 of @command{echo -n}.
18000 Older scripts, written before @command{printf} was portable,
18001 sometimes used a here-document as a safer alternative to @command{echo},
18002 like this:
18004 @example
18005 cat <<EOF
18006 $foo
18008 @end example
18011 @item @command{eval}
18012 @c -----------------
18013 @prindex @command{eval}
18014 The @command{eval} command is useful in limited circumstances, e.g.,
18015 using commands like @samp{eval table_$key=\$value} and @samp{eval
18016 value=table_$key} to simulate a hash table when the key is known to be
18017 alphanumeric.
18019 You should also be wary of common bugs in @command{eval} implementations.
18020 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
18021 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
18022 4.2.5), the arguments of @samp{eval} are evaluated in a context where
18023 @samp{$?} is 0, so they exhibit behavior like this:
18025 @example
18026 $ @kbd{false; eval 'echo $?'}
18028 @end example
18030 The correct behavior here is to output a nonzero value,
18031 but portable scripts should not rely on this.
18033 You should not rely on @code{LINENO} within @command{eval}.
18034 @xref{Special Shell Variables}.
18036 Note that, even though these bugs are easily avoided,
18037 @command{eval} is tricky to use on arbitrary arguments.
18038 It is obviously unwise to use @samp{eval $cmd} if the string value of
18039 @samp{cmd} was derived from an untrustworthy source.  But even if the
18040 string value is valid, @samp{eval $cmd} might not work as intended,
18041 since it causes field splitting and file name expansion to occur twice,
18042 once for the @command{eval} and once for the command itself.  It is
18043 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
18044 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
18045 equivalent of @samp{cat test;.c} if there happens to be a file named
18046 @file{test;.c} in the current directory; and this in turn
18047 mistakenly attempts to invoke @command{cat} on the file @file{test} and
18048 then execute the command @command{.c}.  To avoid this problem, use
18049 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
18051 However, suppose that you want to output the text of the evaluated
18052 command just before executing it.  Assuming the previous example,
18053 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
18054 this output doesn't show the user that @samp{test;.c} is the actual name
18055 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
18056 works on this example, but it fails with @samp{cmd='cat foo >bar'},
18057 since it mistakenly replaces the contents of @file{bar} by the
18058 string @samp{cat foo}.  No simple, general, and portable solution to
18059 this problem is known.
18061 @item @command{exec}
18062 @c -----------------
18063 @prindex @command{exec}
18064 Posix describes several categories of shell built-ins.  Special
18065 built-ins (such as @command{exit}) must impact the environment of the
18066 current shell, and need not be available through @command{exec}.  All
18067 other built-ins are regular, and must not propagate variable assignments
18068 to the environment of the current shell.  However, the group of regular
18069 built-ins is further distinguished by commands that do not require a
18070 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
18071 are offered as a more efficient version of something that must still be
18072 found in a @env{PATH} search (such as @command{echo}).  Posix is not
18073 clear on whether @command{exec} must work with the list of 17 utilities
18074 that are invoked without a @env{PATH} search, and many platforms lack an
18075 executable for some of those built-ins:
18077 @example
18078 $ @kbd{sh -c 'exec cd /tmp'}
18079 sh: line 0: exec: cd: not found
18080 @end example
18082 All other built-ins that provide utilities specified by Posix must have
18083 a counterpart executable that exists on @env{PATH}, although Posix
18084 allows @command{exec} to use the built-in instead of the executable.
18085 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
18087 @example
18088 $ @kbd{bash -c 'pwd --version' | head -n1}
18089 bash: line 0: pwd: --: invalid option
18090 pwd: usage: pwd [-LP]
18091 $ @kbd{bash -c 'exec pwd --version' | head -n1}
18092 pwd (GNU coreutils) 6.10
18093 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
18094 pdksh: pwd: --: unknown option
18095 @end example
18097 When it is desired to avoid a regular shell built-in, the workaround is
18098 to use some other forwarding command, such as @command{env} or
18099 @command{nice}, that will ensure a path search:
18101 @example
18102 $ @kbd{pdksh -c 'exec true --version' | head -n1}
18103 $ @kbd{pdksh -c 'nice true --version' | head -n1}
18104 true (GNU coreutils) 6.10
18105 $ @kbd{pdksh -c 'env true --version' | head -n1}
18106 true (GNU coreutils) 6.10
18107 @end example
18109 @item @command{exit}
18110 @c -----------------
18111 @prindex @command{exit}
18112 The default value of @command{exit} is supposed to be @code{$?};
18113 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
18114 perform @samp{exit 0}.
18116 @example
18117 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
18118 fail
18119 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
18120 fail
18121 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
18122 bash-2.04$
18123 @end example
18125 Using @samp{exit $?} restores the expected behavior.
18127 Some shell scripts, such as those generated by @command{autoconf}, use a
18128 trap to clean up before exiting.  If the last shell command exited with
18129 nonzero status, the trap also exits with nonzero status so that the
18130 invoker can tell that an error occurred.
18132 Unfortunately, in some shells, such as Solaris 10 @command{/bin/sh}, an exit
18133 trap ignores the @code{exit} command's argument.  In these shells, a trap
18134 cannot determine whether it was invoked by plain @code{exit} or by
18135 @code{exit 1}.  Instead of calling @code{exit} directly, use the
18136 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
18139 @anchor{export}
18140 @item @command{export}
18141 @c -------------------
18142 @prindex @command{export}
18143 The builtin @command{export} dubs a shell variable @dfn{environment
18144 variable}.  Each update of exported variables corresponds to an update
18145 of the environment variables.  Conversely, each environment variable
18146 received by the shell when it is launched should be imported as a shell
18147 variable marked as exported.
18149 Alas, many shells, such as Solaris 10 @command{/bin/sh},
18150 IRIX 6.3, IRIX 5.2,
18151 AIX 4.1.5, and Digital Unix 4.0, forget to
18152 @command{export} the environment variables they receive.  As a result,
18153 two variables coexist: the environment variable and the shell
18154 variable.  The following code demonstrates this failure:
18156 @example
18157 #!/bin/sh
18158 echo $FOO
18159 FOO=bar
18160 echo $FOO
18161 exec /bin/sh $0
18162 @end example
18164 @noindent
18165 when run with @samp{FOO=foo} in the environment, these shells print
18166 alternately @samp{foo} and @samp{bar}, although they should print only
18167 @samp{foo} and then a sequence of @samp{bar}s.
18169 Therefore you should @command{export} again each environment variable
18170 that you update; the export can occur before or after the assignment.
18172 Posix is not clear on whether the @command{export} of an undefined
18173 variable causes the variable to be defined with the value of an empty
18174 string, or merely marks any future definition of a variable by that name
18175 for export.  Various shells behave differently in this regard:
18177 @example
18178 $ @kbd{sh -c 'export foo; env | grep foo'}
18179 $ @kbd{ash -c 'export foo; env | grep foo'}
18180 foo=
18181 @end example
18183 Posix requires @command{export} to honor assignments made as arguments,
18184 but older shells do not support this, including @command{/bin/sh} in
18185 Solaris 10.  Portable scripts should separate assignments and exports
18186 into different statements.
18188 @example
18189 $ @kbd{bash -c 'export foo=bar; echo $foo'}
18191 $ @kbd{/bin/sh -c 'export foo=bar; echo $foo'}
18192 /bin/sh: foo=bar: is not an identifier
18193 $ @kbd{/bin/sh -c 'export foo; foo=bar; echo $foo'}
18195 @end example
18197 Posix requires @command{export} to work with any arbitrary value for the
18198 contents of the variable being exported, as long as the total size of
18199 the environment combined with arguments doesn't exceed @code{ARG_MAX}
18200 when executing a child process.  However, some shells have extensions
18201 that involve interpreting some environment values specially, regardless
18202 of the variable name.  We currently know of one case: all versions of
18203 Bash released prior to 27 September 2014 interpret an environment
18204 variable with an initial content substring of @code{() @{} as an
18205 exported function definition (this is the ``Shellshock'' remote
18206 execution bug, CVE-2014-6271 and friends, where it was possible to
18207 exploit the function parser to cause remote code execution on child bash
18208 startup; newer versions of Bash use special environment variable
18209 @emph{names} instead of values to implement the same feature).
18211 There may be entries inherited into the environment that are not valid
18212 as shell variable names; Posix states that processes should be tolerant
18213 of these names.  Some shells such as @command{dash} do this by removing
18214 those names from the environment at startup, while others such as
18215 @command{bash} hide the entry from shell access but still pass it on to
18216 child processes.  While you can set such names using @command{env} for a
18217 direct child process, you cannot rely on them being preserved through an
18218 intermediate pass through the shell.
18220 @item @command{false}
18221 @c ------------------
18222 @prindex @command{false}
18223 Don't expect @command{false} to exit with status 1: in native
18224 Solaris @file{/bin/false} exits with status 255.
18227 @item @command{for}
18228 @c ----------------
18229 @prindex @command{for}
18230 To loop over positional arguments, use:
18232 @example
18233 for arg
18235   echo "$arg"
18236 done
18237 @end example
18239 @noindent
18240 You may @emph{not} leave the @code{do} on the same line as @code{for},
18241 since some shells improperly grok:
18243 @example
18244 for arg; do
18245   echo "$arg"
18246 done
18247 @end example
18249 If you want to explicitly refer to the positional arguments, given the
18250 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
18252 @example
18253 for arg in $@{1+"$@@"@}; do
18254   echo "$arg"
18255 done
18256 @end example
18258 @noindent
18259 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
18260 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
18261 item @samp{$@@}, for more.
18263 Posix requires support for a @command{for} loop with no list after
18264 @code{in}.  However, Solaris 10 @command{/bin/sh} treats that as a syntax
18265 error.  It is possible to work around this by providing any shell word
18266 that expands to nothing, or by ignoring an obvious sentinel.
18268 @example
18269 $ @kbd{/bin/sh -c 'for a in $empty; do echo hi; done'}
18270 $ @kbd{/bin/sh -c 'for a in ; do echo hi; done'}
18271 /bin/sh: syntax error at line 1: `;' unexpected
18272 @end example
18274 This syntax problem is most frequently encountered in code that goes
18275 through several layers of expansion, such as an m4 macro or makefile
18276 variable used as a list body, where the first layer of expansion (m4 or
18277 make) can end up expanding to nothing in the version handed to the
18278 shell.  In the makefile context, one common workaround is to use a shell
18279 variable rather than a make variable as the source of the list.
18281 @example
18282 $ @kbd{cat Makefile}
18283 list =
18284 bad:
18285         @@for arg in $(list); do echo $$arg; done
18286 good:
18287         @@list='$(list)'; for arg in $$list; do echo $$arg; done
18288 $ @kbd{make bad 2&>1 | head -n1}
18289 sh: syntax error at line 1: `;' unexpected
18290 $ @kbd{make bad list='a b'}
18293 $ @kbd{make good}
18294 $ @kbd{make good list='a b'}
18297 @end example
18299 In Solaris 10 @command{/bin/sh}, when the list of arguments of a
18300 @command{for} loop starts with @emph{unquoted} tokens looking like
18301 variable assignments, the loop is not executed on those tokens:
18303 @example
18304 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
18307 @end example
18309 @noindent
18310 Thankfully, quoting the assignment-like tokens, or starting the list
18311 with other tokens (including unquoted variable expansion that results in
18312 an assignment-like result), avoids the problem, so it is easy to work
18313 around:
18315 @example
18316 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
18318 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
18321 @end example
18323 @anchor{if}
18324 @item @command{if}
18325 @c ---------------
18326 @prindex @command{if}
18327 Using @samp{!} is not portable.  Instead of:
18329 @example
18330 if ! cmp -s file file.new; then
18331   mv file.new file
18333 @end example
18335 @noindent
18336 use:
18338 @example
18339 if cmp -s file file.new; then :; else
18340   mv file.new file
18342 @end example
18344 @noindent
18345 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
18346 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
18347 of conditionals:
18349 @example
18350 AS_IF([cmp -s file file.new], [], [mv file.new file])
18351 @end example
18353 This is especially useful in other M4 macros, where the @dfn{then} and
18354 @dfn{else} branches might be macro arguments.
18356 Some very old shells did not reset the exit status from an @command{if}
18357 with no @command{else}:
18359 @example
18360 $ @kbd{if (exit 42); then true; fi; echo $?}
18362 @end example
18364 @noindent
18365 whereas a proper shell should have printed @samp{0}.  But this is no
18366 longer a portability problem; any shell that supports functions gets it
18367 correct.  However, it explains why some makefiles have lengthy
18368 constructs:
18370 @example
18371 if test -f "$file"; then
18372   install "$file" "$dest"
18373 else
18374   :
18376 @end example
18379 @item @command{printf}
18380 @c ------------------
18381 @prindex @command{printf}
18382 A format string starting with a @samp{-} can cause problems.
18383 Bash interprets it as an option and
18384 gives an error.  And @samp{--} to mark the end of options is not good
18385 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
18386 literally as the format string.  Putting the @samp{-} in a @samp{%c}
18387 or @samp{%s} is probably easiest:
18389 @example
18390 printf %s -foo
18391 @end example
18393 AIX 7.2 @command{sh} mishandles octal escapes in multi-byte locales by
18394 treating them as characters instead of bytes.  For example, in a locale
18395 using the UTF-8 encoding, @samp{printf '\351'} outputs the two bytes C3,
18396 A9 (the UTF-8 encoding for U+00E9) instead of the desired single byte E9.
18397 To work around the bug, use the C locale.
18399 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
18401 @example
18402 $ @kbd{printf '\045'}
18403 bash: printf: `%': missing format character
18404 @end example
18406 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
18407 example, @file{/usr/bin/printf} is buggy, so when using
18408 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
18409 core.
18411 Since @command{printf} is not always a shell builtin, there is a
18412 potential speed penalty for using @code{printf '%s\n'} as a replacement
18413 for an @command{echo} that does not interpret @samp{\} or leading
18414 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
18415 -r --} for this role instead.
18417 @xref{echo, , Limitations of Shell Builtins}, for a discussion of
18418 portable alternatives to both @command{printf} and @command{echo}.
18421 @item @command{pwd}
18422 @c ----------------
18423 @prindex @command{pwd}
18424 With modern shells, plain @command{pwd} outputs a ``logical''
18425 directory name, some of whose components may be symbolic links.  These
18426 directory names are in contrast to ``physical'' directory names, whose
18427 components are all directories.
18429 Posix 1003.1-2001 requires that @command{pwd} must support
18430 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
18431 with @option{-L} being the default.  However, traditional shells do
18432 not support these options, and their @command{pwd} command has the
18433 @option{-P} behavior.
18435 Portable scripts should assume neither option is supported, and should
18436 assume neither behavior is the default.  Also, on many hosts
18437 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
18438 does not require this behavior and portable scripts should not rely on
18441 Typically it's best to use plain @command{pwd}.  On modern hosts this
18442 outputs logical directory names, which have the following advantages:
18444 @itemize @bullet
18445 @item
18446 Logical names are what the user specified.
18447 @item
18448 Physical names may not be portable from one installation
18449 host to another due to network file system gymnastics.
18450 @item
18451 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
18452 some parent directory, but plain @command{pwd} cannot fail for this
18453 reason.
18454 @end itemize
18456 Also please see the discussion of the @command{cd} command.
18459 @item @command{read}
18460 @c -----------------
18461 @prindex @command{read}
18462 No options are portable, not even support @option{-r} (Solaris 10
18463 @command{/bin/sh} for example).  Tru64/OSF 5.1 @command{sh} treats
18464 @command{read} as a special built-in, so it may exit if input is
18465 redirected from a non-existent or unreadable file.
18468 @anchor{set}
18469 @item @command{set}
18470 @c ----------------
18471 @prindex @command{set}
18472 With the FreeBSD 6.0 shell, the @command{set} command (without
18473 any options) does not sort its output.
18475 The @command{set} builtin faces the usual problem with arguments
18476 starting with a
18477 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
18478 the end of the options (any argument after @option{--} is a parameter,
18479 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
18480 10 @command{/bin/sh}) simply stop option
18481 processing as soon as a non-option argument is found.  Therefore, use
18482 @samp{dummy} or simply @samp{x} to end the option processing, and use
18483 @command{shift} to pop it out:
18485 @example
18486 set x $my_list; shift
18487 @end example
18489 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
18490 longer requires support for this command, and in traditional shells
18491 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
18492 makes scripts harder to debug.
18494 Some nonstandard shells do not recognize more than one option
18495 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
18496 better to combine them:
18498 @example
18499 set -ex
18500 @end example
18502 @cindex @command{set -e}
18503 The @option{-e} option has historically been under-specified, with enough
18504 ambiguities to cause numerous differences across various shell
18505 implementations; see for example
18506 @uref{https://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
18507 or @uref{https://www.austingroupbugs.net/@/view.php?id=52, this link},
18508 documenting a change to Posix 2008 to match @command{ksh88} behavior.
18509 Note that mixing @code{set -e} and shell functions is asking for surprises:
18511 @example
18512 set -e
18513 doit()
18515   rm file
18516   echo one
18518 doit || echo two
18519 @end example
18521 @noindent
18522 According to the recommendation, @samp{one} should always be output
18523 regardless of whether the @command{rm} failed, because it occurs within
18524 the body of the shell function @samp{doit} invoked on the left side of
18525 @samp{||}, where the effects of @samp{set -e} are not enforced.
18526 Likewise, @samp{two} should never be printed, since the failure of
18527 @command{rm} does not abort the function, such that the status of
18528 @samp{doit} is 0.
18530 The BSD shell has had several problems with the @option{-e}
18531 option.  Older versions of the BSD
18532 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
18533 @samp{case} when @option{-e} was in effect, causing the shell to exit
18534 unexpectedly in some cases.  This was particularly a problem with
18535 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
18536 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
18537 wrapper works around the bug (@pxref{Failure in Make Rules}).
18539 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
18540 wrongly exit with @option{-e} if the last command within a compound
18541 statement fails and is guarded by an @samp{&&} only.  For example:
18543 @example
18544 #! /bin/sh
18545 set -e
18546 foo=''
18547 test -n "$foo" && exit 1
18548 echo one
18549 if :; then
18550   test -n "$foo" && exit 1
18551   echo two
18552   test -n "$foo" && exit 1
18554 echo three
18555 @end example
18557 @noindent
18558 does not print @samp{three}.  One workaround is to change the last
18559 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
18560 "$foo"; then exit 1; fi} instead.  Another possibility is to warn BSD
18561 users not to use @samp{sh -e}.
18563 When @samp{set -e} is in effect, a failed command substitution in
18564 Solaris 10 @command{/bin/sh} cannot be ignored, even with @samp{||}.
18566 @example
18567 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
18568 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
18571 @end example
18573 @noindent
18574 Moreover, a command substitution, successful or not, causes this shell to
18575 exit from a failing outer command even in presence of an @samp{&&} list:
18577 @example
18578 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
18580 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
18582 @end example
18584 Portable scripts should not use @samp{set -e} if @command{trap} is used
18585 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
18586 sometimes enters the trap handler with the exit status of the command
18587 prior to the one that triggered the errexit handler:
18589 @example
18590 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
18592 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
18594 @end example
18596 @noindent
18597 Thus, when writing a script in M4sh, rather than trying to rely on
18598 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
18599 statement where it is desirable to abort on failure.
18601 @cindex @command{set -b}
18602 @cindex @command{set -m}
18603 Job control is not provided by all shells, so the use of @samp{set -m}
18604 or @samp{set -b} must be done with care.  When using @command{zsh} in
18605 native mode, asynchronous notification (@samp{set -b}) is enabled by
18606 default, and using @samp{emulate sh} to switch to Posix mode does not
18607 clear this setting (although asynchronous notification has no impact
18608 unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
18609 earlier have a bug where job control can be manipulated in interactive
18610 shells, but not in subshells or scripts.  Furthermore, some shells, like
18611 @command{pdksh}, fail to treat subshells as interactive, even though the
18612 parent shell was.
18614 @example
18615 $ @kbd{echo $ZSH_VERSION}
18616 4.3.10
18617 $ @kbd{set -m; echo $?}
18619 $ @kbd{zsh -c 'set -m; echo $?'}
18620 set: can't change option: -m
18621 $ @kbd{(set -m); echo $?}
18622 set: can't change option: -m
18624 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
18627 @end example
18629 @cindex @command{set -n}
18630 Use of @command{set -n} (typically via @command{sh -n script}) to
18631 validate a script is not foolproof.  Modern @command{ksh93} tries to be
18632 helpful by informing you about better syntax, but switching the script
18633 to use the suggested syntax in order to silence the warnings would
18634 render the script no longer portable to older shells:
18636 @example
18637 $ @kbd{ksh -nc '``'}
18638 ksh: warning: line 1: `...` obsolete, use $(...)
18640 @end example
18642 Furthermore, on ancient hosts, such as SunOS 4, @command{sh -n} could go
18643 into an infinite loop; even with that bug fixed, Solaris 8
18644 @command{/bin/sh} takes extremely long to parse large scripts.  Autoconf
18645 itself uses @command{sh -n} within its testsuite to check that correct
18646 scripts were generated, but only after first probing for other shell
18647 features (such as @code{test $@{BASH_VERSION+y@}}) that indicate
18648 a reasonably fast and working implementation.
18650 @item @command{shift}
18651 @c ------------------
18652 @prindex @command{shift}
18653 Not only is @command{shift}ing a bad idea when there is nothing left to
18654 shift, but in addition it is not portable: the shell of MIPS
18655 RISC/OS 4.52 refuses to do it.
18657 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
18658 it is also absent in many pre-Posix shells.
18661 @item @command{source}
18662 @c -------------------
18663 @prindex @command{source}
18664 This command is not portable, as Posix does not require it; use
18665 @command{.} instead.
18668 @item @command{test}
18669 @c -----------------
18670 @prindex @command{test}
18671 The @code{test} program is the way to perform many file and string
18672 tests.  It is often invoked by the alternate name @samp{[}, but using
18673 that name in Autoconf code is asking for trouble since it is an M4 quote
18674 character.
18676 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
18677 present in all implementations, and have been marked obsolete by Posix
18678 2008.  This is because there are inherent ambiguities in using them.
18679 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
18680 check whether two strings are both non-empty, but if @samp{$1} is the
18681 literal @samp{!}, then some implementations of @command{test} treat it
18682 as a negation of the unary operator @option{-a}.
18684 Thus, portable uses of @command{test} should never have more than four
18685 arguments, and scripts should use shell constructs like @samp{&&} and
18686 @samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
18687 statement, keep in mind that they have equal precedence, so it is often
18688 better to parenthesize even when this is redundant.  For example:
18690 @smallexample
18691 # Not portable:
18692 test "X$a" = "X$b" -a \
18693   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
18695 # Portable:
18696 test "X$a" = "X$b" &&
18697   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
18698 @end smallexample
18700 @command{test} does not process options like most other commands do; for
18701 example, it does not recognize the @option{--} argument as marking the
18702 end of options.
18704 It is safe to use @samp{!} as a @command{test} operator.  For example,
18705 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
18706 -d foo; @dots{}} is not.
18709 @item @command{test} (files)
18710 @c -------------------------
18711 To enable @command{configure} scripts to support cross-compilation, they
18712 shouldn't do anything that tests features of the build system instead of
18713 the host system.  But occasionally you may find it necessary to check
18714 whether some arbitrary file exists.  To do so, use @samp{test -f},
18715 @samp{test -r}, or @samp{test -x}.  Do not use @samp{test -e}, because
18716 Solaris 10 @command{/bin/sh}
18717 lacks it.  To test for symbolic links on systems that have them, use
18718 @samp{test -h} rather than @samp{test -L}; either form conforms to
18719 Posix 1003.1-2001, but older shells like Solaris 8
18720 @code{/bin/sh} support only @option{-h}.
18722 For historical reasons, Posix reluctantly allows implementations of
18723 @samp{test -x} that will succeed for the root user, even if no execute
18724 permissions are present.  Furthermore, shells do not all agree on
18725 whether Access Control Lists should affect @samp{test -r}, @samp{test
18726 -w}, and @samp{test -x}; some shells base test results strictly on the
18727 current user id compared to file owner and mode, as if by
18728 @code{stat(2)}; while other shells base test results on whether the
18729 current user has the given right, even if that right is only granted by
18730 an ACL, as if by @code{faccessat(2)}.  Furthermore, there is a classic
18731 time of check to time of use race between any use of @command{test}
18732 followed by operating on the just-checked file.  Therefore, it is a good
18733 idea to write scripts that actually attempt an operation, and are
18734 prepared for the resulting failure if permission is denied, rather than
18735 trying to avoid an operation based solely on whether @command{test}
18736 guessed that it might not be permitted.
18738 @item @command{test} (strings)
18739 @c ---------------------------
18740 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
18741 not null, but this usage is not portable to traditional platforms like
18742 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
18743 @samp{-n}.  However, it @emph{is} portable to test if a variable is set
18744 to a non-empty value, by using @samp{test $@{var+y@}}, since all known
18745 implementations properly distinguish between no arguments and a
18746 known-safe string of @samp{y}.
18748 Posix also says that @samp{test ! "@var{string}"},
18749 @samp{test -n "@var{string}"} and
18750 @samp{test -z "@var{string}"} work with any string, but many
18751 shells (such as Solaris 10, AIX 3.2, UNICOS 10.0.0.6,
18752 Digital Unix 4, etc.)@: get confused if
18753 @var{string} looks like an operator:
18755 @example
18756 $ @kbd{test -n =}
18757 test: argument expected
18758 $ @kbd{test ! -n}
18759 test: argument expected
18760 $ @kbd{test -z ")"; echo $?}
18762 @end example
18764 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
18765 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
18766 strings, but in practice this is not true for troublesome strings that
18767 look like operators or parentheses, or that begin with @samp{-}.
18769 It is best to protect such strings with a leading @samp{X}, e.g.,
18770 @samp{test "X@var{string}" != X} rather than @samp{test -n
18771 "@var{string}"} or @samp{test ! "@var{string}"}.
18773 It is common to find variations of the following idiom:
18775 @example
18776 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
18777   @var{action}
18778 @end example
18780 @noindent
18781 to take an action when a token matches a given pattern.  Such constructs
18782 should be avoided by using:
18784 @example
18785 case $ac_feature in
18786   *[!-a-zA-Z0-9_]*) @var{action};;
18787 esac
18788 @end example
18790 If the pattern is a complicated regular expression that cannot be
18791 expressed as a shell pattern, use something like this instead:
18793 @example
18794 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
18795   @var{action}
18796 @end example
18798 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
18799 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
18800 @samp{@var{foo}} contains backslashes.
18803 @anchor{trap}
18804 @item @command{trap}
18805 @c -----------------
18806 @prindex @command{trap}
18807 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
18808 trap 0, i.e., have the @command{trap} run when the script ends (either via an
18809 explicit @command{exit}, or the end of the script).  The trap for 0 should be
18810 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
18811 will invoke the trap at the end of this function.
18813 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
18814 specified signals to their default values, but many common shells (e.g.,
18815 Solaris 10 @command{/bin/sh}) misinterpret this and attempt to execute a
18816 ``command'' named @command{-} when the specified conditions arise.
18817 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18818 reset traps, as this is supported by a larger set of shells, but there
18819 are still shells like @command{dash} that mistakenly try to execute
18820 @command{1} instead of resetting the traps.  Therefore, there is no
18821 portable workaround, except for @samp{trap - 0}, for which
18822 @samp{trap '' 0} is a portable substitute.
18824 Although Posix is not absolutely clear on this point, it is widely
18825 admitted that when entering the trap @samp{$?} should be set to the exit
18826 status of the last command run before the trap.  The ambiguity can be
18827 summarized as: ``when the trap is launched by an @command{exit}, what is
18828 the @emph{last} command run: that before @command{exit}, or
18829 @command{exit} itself?''
18831 Bash considers @command{exit} to be the last command, while Zsh and
18832 Solaris 10 @command{/bin/sh} consider that when the trap is run it is
18833 @emph{still} in the @command{exit}, hence it is the previous exit status
18834 that the trap receives:
18836 @example
18837 $ @kbd{cat trap.sh}
18838 trap 'echo $?' 0
18839 (exit 42); exit 0
18840 $ @kbd{zsh trap.sh}
18842 $ @kbd{bash trap.sh}
18844 @end example
18846 The portable solution is then simple: when you want to @samp{exit 42},
18847 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18848 set the exit status to 42 for Zsh, and the second to trigger the trap
18849 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
18850 @code{AS_EXIT}.
18852 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18853 reset to 0 by empty lines if the code is inside @command{trap}.
18855 @example
18856 $ @kbd{trap 'false}
18858 echo $?' 0
18859 $ @kbd{exit}
18861 @end example
18863 @noindent
18864 Fortunately, this bug only affects @command{trap}.
18866 Several shells fail to execute an exit trap that is defined inside a
18867 subshell, when the last command of that subshell is not a builtin.  A
18868 workaround is to use @samp{exit $?} as the shell builtin.
18870 @example
18871 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18873 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18874 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18876 @end example
18878 @noindent
18879 Likewise, older implementations of @command{bash} failed to preserve
18880 @samp{$?} across an exit trap consisting of a single cleanup command.
18882 @example
18883 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
18885 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
18887 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
18889 @end example
18891 Be aware that a trap can be called from any number of places in your
18892 script, and therefore the trap handler should not make assumptions about
18893 shell state.  For some examples, if your script temporarily modifies
18894 @env{IFS}, then the trap should include an initialization back to its
18895 typical value of space-tab-newline (autoconf does this for generated
18896 @file{configure} files).  Likewise, if your script changes the current
18897 working directory at some point after the trap is installed, then your
18898 trap cannot assume which directory it is in, and should begin by
18899 changing directories to an absolute path if that is important to the
18900 cleanup efforts (autotest does this for generated @file{testsuite}
18901 files).
18903 @item @command{true}
18904 @c -----------------
18905 @prindex @command{true}
18906 @c Info cannot handle ':' in index entries.
18907 @c @prindex @command{:}
18908 Don't worry: as far as we know @command{true} is portable.
18909 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18910 portable shell community tends to prefer using @command{:}.  This has a
18911 funny side effect: when asked whether @command{false} is more portable
18912 than @command{true} Alexandre Oliva answered:
18914 @quotation
18915 In a sense, yes, because if it doesn't exist, the shell will produce an
18916 exit status of failure, which is correct for @command{false}, but not
18917 for @command{true}.
18918 @end quotation
18920 Remember that even though @samp{:} ignores its arguments, it still takes
18921 time to compute those arguments.  It is a good idea to use double quotes
18922 around any arguments to @samp{:} to avoid time spent in field splitting
18923 and file name expansion.
18926 @anchor{unset}
18927 @item @command{unset}
18928 @c ------------------
18929 @prindex @command{unset}
18930 In some nonconforming shells (e.g., Solaris 10 @command{/bin/ksh} and
18931 @command{/usr/xpg4/bin/sh}, NetBSD 5.99.43 sh, or Bash 2.05a),
18932 @code{unset FOO} fails when @code{FOO} is not set.  This can interfere
18933 with @code{set -e} operation.  You can use
18935 @smallexample
18936 FOO=; unset FOO
18937 @end smallexample
18939 @noindent
18940 if you are not sure that @code{FOO} is set.
18942 A few ancient shells lack @command{unset} entirely.  For some variables
18943 such as @code{PS1}, you can use a neutralizing value instead:
18945 @smallexample
18946 PS1='$ '
18947 @end smallexample
18949 Usually, shells that do not support @command{unset} need less effort to
18950 make the environment sane, so for example is not a problem if you cannot
18951 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
18952 @code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18953 So, you should do something like
18955 @smallexample
18956 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18957 @end smallexample
18959 @noindent
18960 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
18961 @ref{export, , Limitations of Builtins}, for
18962 the case of environment variables.
18964 @item @command{wait}
18965 @c -----------------
18966 @prindex @command{wait}
18967 The exit status of @command{wait} is not always reliable.
18968 @end table
18970 @node Limitations of Usual Tools
18971 @section Limitations of Usual Tools
18972 @cindex Limitations of usual tools
18974 The small set of tools you can expect to find on any machine can still
18975 include some limitations you should be aware of.
18977 @comment Between this list and the list of builtins above, we should
18978 @comment mention all the tools in GNU Coding Standards ``Utilities in
18979 @comment Makefiles''.
18981 @c This table includes things like '@command{expr} (|)', so we can't
18982 @c use @table @command.
18983 @table @asis
18984 @anchor{awk}
18985 @item @command{awk}
18986 @c ----------------
18987 @prindex @command{awk}
18988 Don't leave white space before the opening parenthesis in a user function call.
18989 Posix does not allow this and GNU Awk rejects it:
18991 @example
18992 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18993         BEGIN @{ die () @}'}
18994 gawk: cmd. line:2:         BEGIN @{ die () @}
18995 gawk: cmd. line:2:                      ^ parse error
18996 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18997         BEGIN @{ die() @}'}
18998 Aaaaarg!
18999 @end example
19001 Posix says that if a program contains only @samp{BEGIN} actions, and
19002 contains no instances of @code{getline}, then the program merely
19003 executes the actions without reading input.  However, traditional Awk
19004 implementations (such as Solaris 10 @command{awk}) read and discard
19005 input in this case.  Portable scripts can redirect input from
19006 @file{/dev/null} to work around the problem.  For example:
19008 @example
19009 awk 'BEGIN @{print "hello world"@}' </dev/null
19010 @end example
19012 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
19013 @samp{$1}) retain their value from the last record read, if no
19014 intervening @samp{getline} occurred.  However, some implementations
19015 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
19016 @samp{awk}) reset these variables.  A workaround is to use an
19017 intermediate variable prior to the @samp{END} block.  For example:
19019 @example
19020 $ @kbd{cat end.awk}
19021 @{ tmp = $1 @}
19022 END @{ print "a", $1, $NF, "b", tmp @}
19023 $ @kbd{echo 1 | awk -f end.awk}
19024 a   b 1
19025 $ @kbd{echo 1 | gawk -f end.awk}
19026 a 1 1 b 1
19027 @end example
19029 If you want your program to be deterministic, don't depend on @code{for}
19030 on arrays:
19032 @example
19033 $ @kbd{cat for.awk}
19034 END @{
19035   arr["foo"] = 1
19036   arr["bar"] = 1
19037   for (i in arr)
19038     print i
19040 $ @kbd{gawk -f for.awk </dev/null}
19043 $ @kbd{nawk -f for.awk </dev/null}
19046 @end example
19048 Some Awk implementations, such as HP-UX 11.0's native one,
19049 mishandle anchors:
19051 @example
19052 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
19053 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
19055 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
19056 xfoo
19057 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
19059 @end example
19061 @noindent
19062 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
19063 or use a simple test to reject such implementations.
19065 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
19066 after @code{%u}:
19068 @example
19069 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
19070 0 0
19071 @end example
19073 AIX version 5.2 has an arbitrary limit of 399 on the
19074 length of regular expressions and literal strings in an Awk program.
19076 Traditional Awk implementations derived from Unix version 7, such as
19077 Solaris @command{/bin/awk}, have many limitations and do not
19078 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
19079 Programs}) finds you an Awk that doesn't have these problems, but if
19080 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
19081 address them.  For more detailed descriptions, see @ref{Language
19082 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
19084 Traditional Awk does not support multidimensional arrays or user-defined
19085 functions.
19087 Traditional Awk does not support the @option{-v} option.  You can use
19088 assignments after the program instead, e.g., @code{$AWK '@{print v
19089 $1@}' v=x}; however, don't forget that such assignments are not
19090 evaluated until they are encountered (e.g., after any @code{BEGIN}
19091 action).
19093 Traditional Awk does not support the keywords @code{delete} or @code{do}.
19095 Traditional Awk does not support the expressions
19096 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
19097 or @code{@var{a}^=@var{b}}.
19099 Traditional Awk does not support the predefined @code{CONVFMT} or
19100 @code{ENVIRON} variables.
19102 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
19103 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
19104 @code{sqrt}, and @code{substr}.
19106 Traditional Awk @code{getline} is not at all compatible with Posix;
19107 avoid it.
19109 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
19110 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
19112 In code portable to both traditional and modern Awk, @code{FS} must be a
19113 string containing just one ordinary character, and similarly for the
19114 field-separator argument to @code{split}.
19116 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
19117 implementations, like Tru64's, split the input even if you don't refer
19118 to any field in the script, to circumvent this problem, set @samp{FS}
19119 to an unusual character and use @code{split}.
19121 Traditional Awk has a limit of at most 99 bytes in a number formatted by
19122 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
19123 dumps core.
19125 The original version of Awk had a limit of at most 99 bytes per
19126 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
19127 per run of non-special characters in a @code{printf} format, but these
19128 bugs have been fixed on all practical hosts that we know of.
19130 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
19131 of at most 3070 bytes.
19133 @item @command{basename}
19134 @c ---------------------
19135 @prindex @command{basename}
19136 Not all hosts have a working @command{basename}.
19137 You can use @command{expr} instead.
19139 @c AS_BASENAME is to be replaced by a better API.
19140 @ignore
19141 Not all hosts have a working @command{basename}, and you should instead
19142 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
19143 @command{expr} if you need to strip a suffix.  For example:
19145 @example
19146 a=`basename "$aname"`       # This is not portable.
19147 a=`AS_BASENAME(["$aname"])` # This is more portable.
19149 # This is not portable.
19150 c=`basename "$cname" .c`
19152 # This is more portable.
19153 c=`AS_BASENAME(["$cname"])`
19154 case $c in
19155 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
19156 esac
19157 @end example
19158 @end ignore
19161 @item @command{cat}
19162 @c ----------------
19163 @prindex @command{cat}
19164 Don't rely on any option.
19167 @item @command{cc}
19168 @c ---------------
19169 @prindex @command{cc}
19170 The command @samp{cc -c foo.c} traditionally produces an object file
19171 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
19172 with @option{-o} to specify a different object file name, but
19173 Posix does not require this combination and a few compilers
19174 lack support for it.  @xref{C Compiler}, for how GNU Make
19175 tests for this feature with @code{AC_PROG_CC_C_O}.
19177 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
19178 (such as CDS on Reliant Unix) leave a @file{foo.o}.
19180 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
19181 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
19182 nothing.
19184 The default executable, produced by @samp{cc foo.c}, can be
19186 @itemize
19187 @item @file{a.out} -- usual Posix convention.
19188 @item @file{b.out} -- i960 compilers (including @command{gcc}).
19189 @item @file{a.exe} -- DJGPP port of @command{gcc}.
19190 @item @file{a_out.exe} -- GNV @command{cc} wrapper for DEC C on OpenVMS.
19191 @item @file{foo.exe} -- various MS-DOS compilers.
19192 @end itemize
19194 The C compiler's traditional name is @command{cc}, but other names like
19195 @command{gcc} are common.  Posix 1003.1-2001 and 1003.1-2008 specify the
19196 name @command{c99}, but older Posix editions specified
19197 @command{c89}, future POSIX standards will likely specify
19198 @command{c11}, and anyway these standard names are rarely used in
19199 practice.  Typically the C compiler is invoked from makefiles that use
19200 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
19201 compiler name.
19203 @item @command{chgrp}
19204 @itemx @command{chown}
19205 @c -------------------
19206 @prindex @command{chgrp}
19207 @prindex @command{chown}
19208 It is not portable to change a file's group to a group that the owner
19209 does not belong to.
19211 @item @command{chmod}
19212 @c ------------------
19213 @prindex @command{chmod}
19214 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
19215 instead, for two reasons.  First, plain @option{-w} does not necessarily
19216 make the file unwritable, since it does not affect mode bits that
19217 correspond to bits in the file mode creation mask.  Second,
19218 Posix says that the @option{-w} might be interpreted as an
19219 implementation-specific option, not as a mode; Posix suggests
19220 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
19221 @samp{--} does not work on some older hosts.
19224 @item @command{cmp}
19225 @c ----------------
19226 @prindex @command{cmp}
19227 @command{cmp} performs a raw data comparison of two files, while
19228 @command{diff} compares two text files.  Therefore, if you might compare
19229 DOS files, even if only checking whether two files are different, use
19230 @command{diff} to avoid spurious differences due to differences of
19231 newline encoding.
19234 @item @command{cp}
19235 @c ---------------
19236 @prindex @command{cp}
19237 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
19238 obsolescent and its behavior on special files is implementation-defined.
19239 Use @option{-R} instead.  On GNU hosts the two options
19240 are equivalent, but on Solaris hosts (for example) @code{cp -r}
19241 reads from pipes instead of replicating them.  AIX 5.3 @code{cp -R} may
19242 corrupt its own memory with some directory hierarchies and error out or
19243 dump core:
19245 @example
19246 @kbd{mkdir -p 12345678/12345678/12345678/12345678}
19247 @kbd{touch 12345678/12345678/x}
19248 @kbd{cp -R 12345678 t}
19249 cp: 0653-440 12345678/12345678/: name too long.
19250 @end example
19252 Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
19253 trailing slashes at the end of nonexistent destination directories.  To
19254 avoid this problem, omit the trailing slashes.  For example, use
19255 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
19256 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
19258 The @option{-f} option is portable nowadays.
19260 @cindex timestamp resolution
19261 Traditionally, file timestamps had 1-second resolution, and @samp{cp
19262 -p} copied the timestamps exactly.  However, many modern file systems
19263 have timestamps with 1-nanosecond resolution.  Unfortunately, some older
19264 @samp{cp -p} implementations truncate timestamps when copying files,
19265 which can cause the destination file to appear to be older than the
19266 source.  The exact amount of truncation depends on the resolution of
19267 the system calls that @command{cp} uses.  Traditionally this was
19268 @code{utime}, which has 1-second resolution.  Less-ancient @command{cp}
19269 implementations such as GNU Core Utilities 5.0.91 (2003) use
19270 @code{utimes}, which has 1-microsecond resolution.  Modern
19271 implementations such as GNU Core Utilities 6.12 (2008) can set timestamps to
19272 the full nanosecond resolution, using the modern system calls
19273 @code{futimens} and @code{utimensat} when they are available.  As of
19274 2011, though, many platforms do not yet fully support these new system
19275 calls.
19277 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
19278 ownerships.  But whether it actually does copy ownerships or not is a
19279 system dependent policy decision implemented by the kernel.  If the
19280 kernel allows it then it happens.  If the kernel does not allow it then
19281 it does not happen.  It is not something @command{cp} itself has control
19282 over.
19284 In Unix System V any user can chown files to any other user, and System
19285 V also has a non-sticky @file{/tmp}.  That probably derives from the
19286 heritage of System V in a business environment without hostile users.
19287 BSD changed this
19288 to be a more secure model where only root can @command{chown} files and
19289 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
19290 of BSD in a campus environment.
19292 GNU/Linux and Solaris by default follow BSD, but
19293 can be configured to allow a System V style @command{chown}.  On the
19294 other hand, HP-UX follows System V, but can
19295 be configured to use the modern security model and disallow
19296 @command{chown}.  Since it is an administrator-configurable parameter
19297 you can't use the name of the kernel as an indicator of the behavior.
19301 @item @command{date}
19302 @c -----------------
19303 @prindex @command{date}
19304 Some versions of @command{date} do not recognize special @samp{%} directives,
19305 and unfortunately, instead of complaining, they just pass them through,
19306 and exit with success:
19308 @example
19309 $ @kbd{uname -a}
19310 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
19311 $ @kbd{date "+%s"}
19313 @end example
19316 @item @command{diff}
19317 @c -----------------
19318 @prindex @command{diff}
19319 Option @option{-u} is nonportable.
19321 Some implementations, such as Tru64's, fail when comparing to
19322 @file{/dev/null}.  Use an empty file instead.
19325 @item @command{dirname}
19326 @c --------------------
19327 @prindex @command{dirname}
19328 Not all hosts have a working @command{dirname}, and you should instead
19329 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
19331 @example
19332 dir=`dirname "$file"`       # This is not portable.
19333 dir=`AS_DIRNAME(["$file"])` # This is more portable.
19334 @end example
19337 @item @command{egrep}
19338 @c ------------------
19339 @prindex @command{egrep}
19340 Although Posix stopped requiring @command{egrep} in 2001,
19341 a few traditional hosts (notably Solaris) do not support the Posix
19342 replacement @code{grep -E}.  Also, some traditional implementations do
19343 not work on long input lines.  To work around these problems, invoke
19344 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
19346 Portable extended regular expressions should use @samp{\} only to escape
19347 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
19348 is not portable, even though it typically matches @samp{@}}.
19350 The empty alternative is not portable.  Use @samp{?} instead.  For
19351 instance with Digital Unix v5.0:
19353 @example
19354 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
19355 |foo
19356 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
19357 bar|
19358 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
19360 |bar
19361 @end example
19363 @command{$EGREP} also suffers the limitations of @command{grep}
19364 (@pxref{grep, , Limitations of Usual Tools}).
19366 @item @command{expr}
19367 @c -----------------
19368 @prindex @command{expr}
19369 Not all implementations obey the Posix rule that @samp{--} separates
19370 options from arguments; likewise, not all implementations provide the
19371 extension to Posix that the first argument can be treated as part of a
19372 valid expression rather than an invalid option if it begins with
19373 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
19374 @samp{$var} might be a negative number, to keep @command{expr} from
19375 interpreting it as an option.
19377 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
19378 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
19379 misinterpreting @var{word}.
19381 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
19383 @item @command{expr} (@samp{|})
19384 @prindex @command{expr} (@samp{|})
19385 You can use @samp{|}.  Although Posix does require that @samp{expr
19386 ''} return the empty string, it does not specify the result when you
19387 @samp{|} together the empty string (or zero) with the empty string.  For
19388 example:
19390 @example
19391 expr '' \| ''
19392 @end example
19394 Posix 1003.2-1992 returns the empty string
19395 for this case, but traditional Unix returns @samp{0} (Solaris is
19396 one such example).  In Posix 1003.1-2001, the specification was
19397 changed to match traditional Unix's behavior (which is
19398 bizarre, but it's too late to fix this).  Please note that the same
19399 problem does arise when the empty string results from a computation,
19400 as in:
19402 @example
19403 expr bar : foo \| foo : bar
19404 @end example
19406 @noindent
19407 Avoid this portability problem by avoiding the empty string.
19410 @item @command{expr} (@samp{:})
19411 @c ----------------------------
19412 @prindex @command{expr}
19413 Portable @command{expr} regular expressions should use @samp{\} to
19414 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
19415 For example, alternation, @samp{\|}, is common but Posix does not
19416 require its support, so it should be avoided in portable scripts.
19417 Similarly, @samp{\+} and @samp{\?} should be avoided.
19419 Portable @command{expr} regular expressions should not begin with
19420 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
19421 not needed anyway.
19423 On the other hand, the behavior of the @samp{$} anchor is not portable
19424 on multi-line strings.  Posix is ambiguous whether the anchor applies to
19425 each line, as was done in older versions of the GNU Core Utilities, or
19426 whether it applies only to the end of the overall string, as in
19427 Coreutils 6.0 and most other implementations.
19429 @example
19430 $ @kbd{baz='foo}
19431 > @kbd{bar'}
19432 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
19434 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
19436 @end example
19438 The Posix standard is ambiguous as to whether
19439 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
19440 In practice, it outputs the empty string on most platforms, but portable
19441 scripts should not assume this.  For instance, the QNX 4.25 native
19442 @command{expr} returns @samp{0}.
19444 One might think that a way to get a uniform behavior would be to use
19445 the empty string as a default value:
19447 @example
19448 expr a : '\(b\)' \| ''
19449 @end example
19451 @noindent
19452 Unfortunately this behaves exactly as the original expression; see the
19453 @command{expr} (@samp{|}) entry for more information.
19455 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
19456 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
19457 @command{expr} to fail if the matched substring is longer than 120
19458 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
19459 @command{expr} fails.  Nowadays this is of practical importance only for
19460 the rare installer who mistakenly puts @file{/usr/ucb} before
19461 @file{/usr/bin} in @env{PATH}.
19463 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
19464 some cases.  For example, the command
19465 @example
19466 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
19467 @end example
19469 @noindent
19470 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
19471 This particular case can be worked around by substituting @samp{[^--]}
19472 for @samp{[^-]}.
19474 Don't leave, there is some more!
19476 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
19477 the empty string, has a funny behavior in its exit status: it's always 1
19478 when parentheses are used!
19480 @example
19481 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
19482 0: 1
19483 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
19484 1: 0
19486 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
19487 1: a
19488 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
19489 1: 0
19490 @end example
19492 @noindent
19493 In practice this can be a big problem if you are ready to catch failures
19494 of @command{expr} programs with some other method (such as using
19495 @command{sed}), since you may get twice the result.  For instance
19497 @example
19498 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
19499 @end example
19501 @noindent
19502 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25.  A
19503 simple workaround consists of testing @command{expr} and using a variable
19504 set to @command{expr} or to @command{false} according to the result.
19506 Tru64 @command{expr} incorrectly treats the result as a number, if it
19507 can be interpreted that way:
19509 @example
19510 $ @kbd{expr 00001 : '.*\(...\)'}
19512 @end example
19514 On HP-UX 11, @command{expr} only supports a single
19515 sub-expression.
19517 @example
19518 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
19519 expr: More than one '\(' was used.
19520 @end example
19523 @item @command{fgrep}
19524 @c ------------------
19525 @prindex @command{fgrep}
19526 Although Posix stopped requiring @command{fgrep} in 2001,
19527 a few traditional hosts (notably Solaris) do not support the Posix
19528 replacement @code{grep -F}.  Also, some traditional implementations do
19529 not work on long input lines.  To work around these problems, invoke
19530 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
19532 Tru64/OSF 5.1 @command{fgrep} does not match an empty pattern.
19535 @item @command{find}
19536 @c -----------------
19537 @prindex @command{find}
19538 Many operands of GNU @command{find} are not standardized by Posix and
19539 are missing on many platforms. These nonportable operands include
19540 @option{-follow}, @option{-maxdepth}, @option{-mindepth},
19541 @option{-printf}, and @option{,}.  See the
19542 @uref{https://@/pubs.opengroup.org/@/onlinepubs/@/9699919799/@/utilities/@/find.html,
19543 Posix spec for @command{find}} for @command{find} operands that
19544 should be portable nowadays.
19546 The replacement of @samp{@{@}} is guaranteed only if the argument is
19547 exactly @emph{@{@}}, not if it's only a part of an argument.  For
19548 instance, on HP-UX 11:
19550 @example
19551 $ @kbd{touch foo}
19552 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
19553 @{@}-@{@}
19554 @end example
19556 @noindent
19557 while GNU @command{find} reports @samp{./foo-./foo}.
19558 Posix allows either behavior.
19561 @anchor{grep}
19562 @item @command{grep}
19563 @c -----------------
19564 @prindex @command{grep}
19565 Portable scripts can rely on the @command{grep} options @option{-c},
19566 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
19567 options.  For example, don't use @option{-w}, as Posix does not require
19568 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
19569 portable scripts should not combine @option{-c} with @option{-l},
19570 as Posix does not allow this.
19572 Some of the options required by Posix are not portable in practice.
19573 Don't use @samp{grep -q} to suppress output, because traditional @command{grep}
19574 implementations (e.g., Solaris) do not support @option{-q}.
19575 Don't use @samp{grep -s} to suppress output either, because Posix
19576 says @option{-s} does not suppress output, only some error messages;
19577 also, the @option{-s} option of traditional @command{grep} behaved
19578 like @option{-q} does in most modern implementations.  Instead,
19579 redirect the standard output and standard error (in case the file
19580 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
19581 status of @code{grep} to determine whether it found a match.
19583 The QNX4 implementation fails to count lines with @code{grep -c '$'},
19584 but works with @code{grep -c '^'}.  Other alternatives for counting
19585 lines are to use @code{sed -n '$='} or @code{wc -l}.
19587 Some traditional @command{grep} implementations do not work on long
19588 input lines.  On AIX the default @code{grep} silently truncates long
19589 lines on the input before matching.
19591 Also, traditional implementations do not support multiple regexps
19592 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
19593 or honor only the last pattern (e.g., IRIX 6.5 and NeXT).  To
19594 work around these problems, invoke @code{AC_PROG_GREP} and then use
19595 @code{$GREP}.
19597 Another possible workaround for the multiple @option{-e} problem is to
19598 separate the patterns by newlines, for example:
19600 @example
19601 grep 'foo
19602 bar' in.txt
19603 @end example
19605 @noindent
19606 except that this fails with traditional @command{grep}
19607 implementations and with OpenBSD 3.8 @command{grep}.
19609 Traditional @command{grep} implementations (e.g., Solaris) do not
19610 support the @option{-E} or @option{-F} options.  To work around these
19611 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
19612 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
19613 willing to require support for Posix @command{grep}, your script should
19614 not use both @option{-E} and @option{-F}, since Posix does not allow
19615 this combination.
19617 Portable @command{grep} regular expressions should use @samp{\} only to
19618 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
19619 alternation, @samp{\|}, is common but Posix does not require its
19620 support in basic regular expressions, so it should be avoided in
19621 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
19622 Similarly, the following escape sequences should also be avoided:
19623 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
19624 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
19626 Posix does not specify the behavior of @command{grep} on binary files.
19627 An example where this matters is using BSD @command{grep} to
19628 search text that includes embedded ANSI escape sequences for
19629 colored output to terminals (@samp{\033[m} is the sequence to restore
19630 normal output); the behavior depends on whether input is seekable:
19632 @example
19633 $ @kbd{printf 'esc\033[mape\n' > sample}
19634 $ @kbd{grep . sample}
19635 Binary file sample matches
19636 $ @kbd{cat sample | grep .}
19637 escape
19638 @end example
19641 @item @command{join}
19642 @c -----------------
19643 @prindex @command{join}
19644 Solaris 8 @command{join} has bugs when the second operand is standard
19645 input, and when standard input is a pipe.  For example, the following
19646 shell script causes Solaris 8 @command{join} to loop forever:
19648 @example
19649 cat >file <<'EOF'
19650 1 x
19651 2 y
19653 cat file | join file -
19654 @end example
19656 Use @samp{join - file} instead.
19658 On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
19659 @command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
19660 the workaround is to use @command{join -a1 file1 file2} instead.
19662 On platforms with the BusyBox tools, the @command{join} command is
19663 entirely missing.  As a workaround, you can simulate special cases of the
19664 @command{join} command using an @command{awk} script.  For an example,
19665 see @url{https://lists.gnu.org/r/bug-gnulib/2021-04/msg00054.html}.
19668 @item @command{ln}
19669 @c ---------------
19670 @prindex @command{ln}
19671 The @option{-f} option is portable nowadays.
19673 @cindex Symbolic links
19674 Symbolic links are not available on some systems; use @samp{$(LN_S)} as
19675 a portable substitute.
19677 For versions of the DJGPP before 2.04,
19678 @command{ln} emulates symbolic links
19679 to executables by generating a stub that in turn calls the real
19680 program.  This feature also works with nonexistent files like in the
19681 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
19682 which attempts to call @file{file.exe} if run.  But this feature only
19683 works for executables, so @samp{cp -p} is used instead for these
19684 systems.  DJGPP versions 2.04 and later have full support
19685 for symbolic links.
19688 @item @command{ls}
19689 @c ---------------
19690 @prindex @command{ls}
19691 @cindex Listing directories
19692 The portable options are @option{-acdilrtu}.  Current practice is for
19693 @option{-l} to output both owner and group, even though ancient versions
19694 of @command{ls} omitted the group.
19696 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
19697 to standard output if @file{foo} did not exist.  Hence a shell command
19698 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
19699 was equivalent to @samp{sources='*.c not found'} in the absence of
19700 @samp{.c} files.  This is no longer a practical problem, since current
19701 @command{ls} implementations send diagnostics to standard error.
19703 The behavior of @command{ls} on a directory that is being concurrently
19704 modified is not always predictable, because of a data race where cached
19705 information returned by @code{readdir} does not match the current
19706 directory state.  In fact, MacOS 10.5 has an intermittent bug where
19707 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
19708 once if other files were added or removed from the directory immediately
19709 prior to the @command{ls} call.  Since @command{ls} already sorts its
19710 output, the duplicate entries can be avoided by piping the results
19711 through @code{uniq}.
19713 @anchor{mkdir}
19714 @item @command{mkdir}
19715 @c ------------------
19716 @prindex @command{mkdir}
19717 @cindex Making directories
19718 No @command{mkdir} option is portable to older systems.  Instead of
19719 @samp{mkdir -p @var{file-name}}, you should use
19720 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
19721 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
19723 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
19724 go-w -p @var{dir}}, often leads to trouble.  FreeBSD
19725 @command{mkdir} incorrectly attempts to change the permissions of
19726 @var{dir} even if it already exists.  HP-UX 11.23 and
19727 IRIX 6.5 @command{mkdir} often assign the wrong permissions to
19728 any newly-created parents of @var{dir}.
19730 Posix does not clearly specify whether @samp{mkdir -p foo}
19731 should succeed when @file{foo} is a symbolic link to an already-existing
19732 directory.  The GNU Core Utilities 5.1.0 @command{mkdir}
19733 succeeds, but Solaris @command{mkdir} fails.
19735 Traditional @code{mkdir -p} implementations suffer from race conditions.
19736 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
19737 at the same time, both processes might detect that @file{a} is missing,
19738 one might create @file{a}, then the other might try to create @file{a}
19739 and fail with a @code{File exists} diagnostic.  The GNU Core
19740 Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
19741 NetBSD 2.0.2, and OpenBSD 2.4 are known to be
19742 race-free when two processes invoke @code{mkdir -p} simultaneously, but
19743 earlier versions are vulnerable.  Solaris @command{mkdir} is still
19744 vulnerable as of Solaris 10, and other traditional Unix systems are
19745 probably vulnerable too.  This possible race is harmful in parallel
19746 builds when several Make rules call @code{mkdir -p} to
19747 construct directories.  You may use
19748 @code{install-sh -d} as a safe replacement, provided this script is
19749 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
19750 OK, but copies from older versions are vulnerable.
19753 @item @command{mkfifo}
19754 @itemx @command{mknod}
19755 @c -------------------
19756 @prindex @command{mkfifo}
19757 @prindex @command{mknod}
19758 The GNU Coding Standards state that @command{mknod} is safe to use on
19759 platforms where it has been tested to exist; but it is generally portable
19760 only for creating named FIFOs, since device numbers are
19761 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
19762 testsuites.  Posix states that behavior is unspecified when opening a
19763 named FIFO for both reading and writing; on at least Cygwin, this
19764 results in failure on any attempt to read or write to that file
19765 descriptor.
19767 @item @command{mktemp}
19768 @c -------------------
19769 @prindex @command{mktemp}
19770 @cindex Creating temporary files
19771 Shell scripts can use temporary files safely with @command{mktemp}, but
19772 it does not exist on all systems.  A portable way to create a safe
19773 temporary file name is to create a temporary directory with mode 700 and
19774 use a file inside this directory.  Both methods prevent attackers from
19775 gaining control, though @command{mktemp} is far less likely to fail
19776 gratuitously under attack.
19778 Here is sample code to create a new temporary directory @samp{$dir} safely:
19780 @example
19781 # Create a temporary directory $dir in $TMPDIR (default /tmp).
19782 # Use mktemp if possible; otherwise fall back on mkdir,
19783 # with $RANDOM to make collisions less likely.
19784 : "$@{TMPDIR:=/tmp@}"
19786   dir=`
19787     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
19788   ` &&
19789   test -d "$dir"
19790 @} || @{
19791   dir=$TMPDIR/foo$$-$RANDOM
19792 @c $$ restore font-lock
19793   (umask 077 && mkdir "$dir")
19794 @} || exit $?
19795 @end example
19798 @item @command{mv}
19799 @c ---------------
19800 @prindex @command{mv}
19801 @cindex Moving open files
19802 The only portable options are @option{-f} and @option{-i}.
19804 Moving individual files between file systems is portable (it was in Unix
19805 version 6),
19806 but it is not always atomic: when doing @samp{mv new existing}, there's
19807 a critical section where neither the old nor the new version of
19808 @file{existing} actually exists.
19810 On some systems moving files from @file{/tmp} can sometimes cause
19811 undesirable (but perfectly valid) warnings, even if you created these
19812 files.  This is because @file{/tmp} belongs to a group that ordinary
19813 users are not members of, and files created in @file{/tmp} inherit
19814 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
19815 a diagnostic without failing:
19817 @smallexample
19818 $ @kbd{touch /tmp/foo}
19819 $ @kbd{mv /tmp/foo .}
19820 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
19821 $ @kbd{echo $?}
19823 $ @kbd{ls foo}
19825 @end smallexample
19827 @noindent
19828 This annoying behavior conforms to Posix, unfortunately.
19830 Moving directories across mount points is not portable, use @command{cp}
19831 and @command{rm}.
19833 DOS variants cannot rename or remove open files, and do not
19834 support commands like @samp{mv foo bar >foo}, even though this is
19835 perfectly portable among Posix hosts.
19838 @item @command{od}
19839 @c ---------------
19840 @prindex @command{od}
19842 In MacOS X versions prior to 10.4.3, @command{od} does not support the
19843 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
19844 @option{-t}, or the XSI option, @option{-s}.  The only
19845 supported Posix option is @option{-v}, and the only supported
19846 XSI options are those in @option{-bcdox}.  The BSD
19847 @command{hexdump} program can be used instead.
19849 In some versions of some operating systems derived from Solaris 11,
19850 @command{od} prints decimal byte values padded with zeros rather than
19851 with spaces:
19853 @smallexample
19854 $ @kbd{printf '#!' | od -A n -t d1 -N 2}
19855          035 033
19856 @end smallexample
19858 @noindent
19859 instead of
19861 @smallexample
19862 $ @kbd{printf '#!' | od -A n -t d1 -N 2}
19863           35  33
19864 @end smallexample
19866 We have observed this on both OpenIndiana and OmniOS;
19867 Illumos may also be affected.
19868 As a workaround, you can use octal output (option @code{-t o1}).
19871 @item @command{rm}
19872 @c ---------------
19873 @prindex @command{rm}
19874 The @option{-f} and @option{-r} options are portable.
19876 It is not portable to invoke @command{rm} without options or operands.
19877 On the other hand, Posix now requires @command{rm -f} to silently
19878 succeed when there are no operands (useful for constructs like
19879 @command{rm -rf $filelist} without first checking if @samp{$filelist}
19880 was empty).  But this was not always portable; at least NetBSD
19881 @command{rm} built before 2008 would fail with a diagnostic.
19883 A file might not be removed even if its parent directory is writable
19884 and searchable.  Many Posix hosts cannot remove a mount point, a named
19885 stream, a working directory, or a last link to a file that is being
19886 executed.
19888 DOS variants cannot rename or remove open files, and do not
19889 support commands like @samp{rm foo >foo}, even though this is
19890 perfectly portable among Posix hosts.
19892 @item @command{rmdir}
19893 @c ------------------
19894 @prindex @command{rmdir}
19895 Just as with @command{rm}, some platforms refuse to remove a working
19896 directory.
19898 @anchor{sed}
19899 @item @command{sed}
19900 @c ----------------
19901 @prindex @command{sed}
19902 Patterns should not include the separator (unless escaped), even as part
19903 of a character class.  In conformance with Posix, the Cray
19904 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
19905 Even when escaped, patterns should not include separators that are also
19906 used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
19907 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19908 before evaluating the basic regular expression.
19910 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
19911 not require support for empty patterns, and Unicos 9 @command{sed} rejects
19912 them.
19914 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
19916 Sed scripts should not use branch labels longer than 7 characters and
19917 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
19918 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
19919 48 labels, which cannot be circumvented by using more than one script
19920 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
19921 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
19922 about 6000 bytes for the internal representation of commands.
19924 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
19925 NetBSD 1.4.2's, incorrectly try to interpret the second
19926 @samp{;} as a command:
19928 @example
19929 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
19930 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
19931 @end example
19933 Some @command{sed} implementations have a buffer limited to 4000 bytes,
19934 and this limits the size of input lines, output lines, and internal
19935 buffers that can be processed portably.  Likewise,
19936 not all @command{sed} implementations can handle embedded @code{NUL} or
19937 a missing trailing newline.
19939 Remember that ranges within a bracket expression of a regular expression
19940 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19941 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19942 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19943 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19944 than to rely on @samp{[A-Z]}.
19946 Additionally, Posix states that regular expressions are only
19947 well-defined on characters.  Unfortunately, there exist platforms such
19948 as MacOS X 10.5 where not all 8-bit byte values are valid characters,
19949 even though that platform has a single-byte @samp{C} locale.  And Posix
19950 allows the existence of a multi-byte @samp{C} locale, although that does
19951 not yet appear to be a common implementation.  At any rate, it means
19952 that not all bytes will be matched by the regular expression @samp{.}:
19954 @example
19955 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
19957 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
19959 @end example
19961 Portable @command{sed} regular expressions should use @samp{\} only to escape
19962 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
19963 alternation, @samp{\|}, is common but Posix does not require its
19964 support, so it should be avoided in portable scripts.  Solaris
19965 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19966 deletes only lines that contain the literal string @samp{a|b}.
19967 Similarly, @samp{\+} and @samp{\?} should be avoided.
19969 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19971 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
19972 quite portable to current hosts, but was not supported by some ancient
19973 @command{sed} implementations like SVR3.
19975 Some @command{sed} implementations, e.g., Solaris, restrict the special
19976 role of the asterisk @samp{*} to one-character regular expressions and
19977 back-references, and the special role of interval expressions
19978 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19979 to one-character regular expressions.  This may lead to unexpected behavior:
19981 @example
19982 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19983 x2x4
19984 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19986 @end example
19988 The @option{-e} option is mostly portable.
19989 However, its argument
19990 cannot start with @samp{a}, @samp{c}, or @samp{i},
19991 as this runs afoul of a Tru64 5.1 bug.
19992 Also, its argument cannot be empty, as this fails on AIX 5.3.
19993 Some people prefer to use @samp{-e}:
19995 @example
19996 sed -e '@var{command-1}' \
19997     -e '@var{command-2}'
19998 @end example
20000 @noindent
20001 as opposed to the equivalent:
20003 @example
20004 sed '
20005   @var{command-1}
20006   @var{command-2}
20008 @end example
20010 @noindent
20011 The following usage is sometimes equivalent:
20013 @example
20014 sed '@var{command-1};@var{command-2}'
20015 @end example
20017 but Posix says that this use of a semicolon has undefined effect if
20018 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
20019 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
20020 should use semicolon only with simple scripts that do not use these
20021 verbs.
20023 Posix up to the 2008 revision requires the argument of the @option{-e}
20024 option to be a syntactically complete script.  GNU @command{sed} allows
20025 to pass multiple script fragments, each as argument of a separate
20026 @option{-e} option, that are then combined, with newlines between the
20027 fragments, and a future Posix revision may allow this as well.  This
20028 approach is not portable with script fragments ending in backslash; for
20029 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
20030 don't allow splitting in this case:
20032 @example
20033 $ @kbd{echo a | sed -n -e 'i\}
20034 @kbd{0'}
20036 $ @kbd{echo a | sed -n -e 'i\' -e 0}
20037 Unrecognized command: 0
20038 @end example
20040 @noindent
20041 In practice, however, this technique of joining fragments
20042 through @option{-e} works for multiple @command{sed} functions within
20043 @samp{@{} and @samp{@}}, even if that is not specified by Posix:
20045 @example
20046 @c The quote around the closing brace silences interactive zsh.
20047 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
20049 @end example
20051 Commands inside @{ @} brackets are further restricted.  Posix 2008 says that
20052 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
20053 each command must be followed immediately by a newline, without any
20054 intervening blanks or semicolons.  The closing bracket must be alone on
20055 a line, other than white space preceding or following it.  However, a
20056 future version of Posix may standardize the use of addresses within brackets.
20058 Contrary to yet another urban legend, you may portably use @samp{&} in
20059 the replacement part of the @code{s} command to mean ``what was
20060 matched''.  All descendants of Unix version 7 @command{sed}
20061 (at least; we
20062 don't have first hand experience with older @command{sed} implementations) have
20063 supported it.
20065 Posix requires that you must not have any white space between
20066 @samp{!} and the following command.  It is OK to have blanks between
20067 the address and the @samp{!}.  For instance, on Solaris:
20069 @example
20070 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
20071 @error{}Unrecognized command: /bar/ ! p
20072 $ @kbd{echo "foo" | sed -n '/bar/! p'}
20073 @error{}Unrecognized command: /bar/! p
20074 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
20076 @end example
20078 Posix also says that you should not combine @samp{!} and @samp{;}.  If
20079 you use @samp{!}, it is best to put it on a command that is delimited by
20080 newlines rather than @samp{;}.
20082 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
20083 @samp{w} commands be followed by exactly one space before their argument.
20084 On the other hand, no white space is allowed between @samp{:} and the
20085 subsequent label name.
20087 If a sed script is specified on the command line and ends in an
20088 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
20089 should be followed by a newline.  Otherwise some @command{sed}
20090 implementations (e.g., OpenBSD 3.9) do not append a newline to the
20091 inserted text.
20093 Many @command{sed} implementations (e.g., MacOS X 10.4,
20094 OpenBSD 3.9, Solaris 10
20095 @command{/usr/ucb/sed}) strip leading white space from the text of
20096 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
20097 work around this incompatibility with Posix:
20099 @example
20100 $ @kbd{echo flushleft | sed 'a\}
20101 > @kbd{   indented}
20102 > @kbd{'}
20103 flushleft
20104 indented
20105 $ @kbd{echo foo | sed 'a\}
20106 > @kbd{\   indented}
20107 > @kbd{'}
20108 flushleft
20109    indented
20110 @end example
20112 Posix requires that with an empty regular expression, the last non-empty
20113 regular expression from either an address specification or substitution
20114 command is applied.  However, busybox 1.6.1 complains when using a
20115 substitution command with a replacement containing a back-reference to
20116 an empty regular expression; the workaround is repeating the regular
20117 expression.
20119 @example
20120 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
20121 sed: No previous regexp.
20122 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
20124 @end example
20126 Portable scripts should be aware of the inconsistencies and options for
20127 handling word boundaries, as these are not specified by POSIX.
20129 @example
20130                 \<      \b      [[:<:]]
20131 Solaris 10      yes     no      no
20132 Solaris XPG4    yes     no      error
20133 NetBSD 5.1      no      no      yes
20134 FreeBSD 9.1     no      no      yes
20135 GNU             yes     yes     error
20136 busybox         yes     yes     error
20137 @end example
20139 @item @command{sed} (@samp{t})
20140 @c ---------------------------
20141 @prindex @command{sed} (@samp{t})
20142 Some old systems have @command{sed} that ``forget'' to reset their
20143 @samp{t} flag when starting a new cycle.  For instance on MIPS
20144 RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
20145 script (the line numbers are not actual part of the texts):
20147 @example
20148 s/keep me/kept/g  # a
20149 t end             # b
20150 s/.*/deleted/g    # c
20151 :end              # d
20152 @end example
20154 @noindent
20157 @example
20158 delete me         # 1
20159 delete me         # 2
20160 keep me           # 3
20161 delete me         # 4
20162 @end example
20164 @noindent
20165 you get
20167 @example
20168 deleted
20169 delete me
20170 kept
20171 deleted
20172 @end example
20174 @noindent
20175 instead of
20177 @example
20178 deleted
20179 deleted
20180 kept
20181 deleted
20182 @end example
20184 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
20185 flag, and the output is produced.  When processing
20186 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
20187 fails to match, but @command{sed} is not supposed to clear the @samp{t}
20188 flag when a substitution fails.  Command (b) sees that the flag is set,
20189 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
20190 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
20191 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
20192 Finally, since the flag is clear, line 4 is processed properly.
20194 There are two things one should remember about @samp{t} in @command{sed}.
20195 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
20196 succeeded, not only the immediately preceding substitution.  Therefore,
20197 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
20198 line, to reset the @samp{t} flag where needed.
20200 Secondly, you cannot rely on @command{sed} to clear the flag at each new
20201 cycle.
20203 One portable implementation of the script above is:
20205 @example
20206 t clear
20207 :clear
20208 s/keep me/kept/g
20209 t end
20210 s/.*/deleted/g
20211 :end
20212 @end example
20214 @item @command{sed} (@samp{w})
20215 @c ---------------------------
20216 @prindex @command{sed} (@samp{w})
20218 When a script contains multiple commands to write lines to the same
20219 output file, BusyBox @command{sed} mistakenly opens a separate output
20220 stream for each command.  This can cause one of the commands to ``win''
20221 and the others to ``lose'', in the sense that their output is discarded.
20222 For example:
20224 @example
20225 sed -n -e '
20226   /a/w xxx
20227   /b/w xxx
20228 ' <<EOF
20232 @end example
20234 This might output only @samp{a} to @file{xxx}; the @samp{b} is lost.
20235 To avoid the problem, a portable script should contain at most one
20236 @samp{w} or @samp{s/.../.../w} command per output file.
20238 @item @command{sleep}
20239 @c ------------------
20240 @prindex @command{sleep}
20241 Using @command{sleep} is generally portable.  However, remember that
20242 adding a @command{sleep} to work around timestamp issues, with a minimum
20243 granularity of one second, doesn't scale well for parallel builds on
20244 modern machines with sub-second process completion.
20246 @item @command{sort}
20247 @c -----------------
20248 @prindex @command{sort}
20249 Remember that sort order is influenced by the current locale.  Inside
20250 @file{configure}, the C locale is in effect, but in Makefile snippets,
20251 you may need to specify @code{LC_ALL=C sort}.
20253 @item @command{tar}
20254 @c ----------------
20255 @prindex @command{tar}
20256 There are multiple file formats for @command{tar}; if you use Automake,
20257 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
20258 level of portability to use.
20260 @anchor{touch}
20261 @item @command{touch}
20262 @c ------------------
20263 @prindex @command{touch}
20264 @cindex timestamp resolution
20265 If you specify the desired timestamp (e.g., with the @option{-r}
20266 option), older @command{touch} implementations use the @code{utime} or
20267 @code{utimes} system call, which can result in the same kind of
20268 timestamp truncation problems that @samp{cp -p} has.
20270 On ancient BSD systems, @command{touch} or any command that
20271 results in an empty file does not update the timestamps, so use a
20272 command like @command{echo} as a workaround.
20273 Also,
20274 GNU @command{touch} 3.16r (and presumably all before that)
20275 fails to work on SunOS 4.1.3 when the empty file is on an
20276 NFS-mounted 4.2 volume.
20277 However, these problems are no longer of practical concern.
20279 @item @command{tr}
20280 @c ---------------
20281 @prindex @command{tr}
20282 @cindex carriage return, deleting
20283 @cindex newline, deleting
20284 @cindex deleting carriage return
20285 Not all versions of @command{tr} handle all backslash character escapes.
20286 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
20287 Solaris contains more modern @command{tr} in other locations.
20288 Using octal escapes is more portable for carriage returns, since
20289 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
20290 literal carriage returns in scripts causes a number of other problems.
20291 But for other characters, like newline, using octal escapes ties the
20292 operation to ASCII, so it is better to use literal characters.
20294 @example
20295 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
20297 light
20298 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
20299 moonlight
20300 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
20301 moonlight
20302 $ @kbd{nl='}
20303 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
20304 moonlight
20305 @end example
20307 Not all versions of @command{tr} recognize direct ranges of characters: at
20308 least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
20309 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in Posix
20310 transliterate to themselves).
20312 @example
20313 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
20314 HAZy FAntAZy
20315 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
20316 HAZY FANTAZY
20317 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
20318 HAZY FANTAZY
20319 @end example
20321 When providing two arguments, be sure the second string is at least as
20322 long as the first.
20324 @example
20325 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
20327 $ @kbd{echo abc | coreutils/tr bc d}
20329 @end example
20331 Posix requires @command{tr} to operate on binary files.  But at least
20332 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
20333 @code{NUL} in the input prior to doing any translation.  When using
20334 @command{tr} to process a binary file that may contain @code{NUL} bytes,
20335 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
20336 @command{/usr/xpg6/bin/tr} if that is available.
20338 @example
20339 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
20340  61 62
20341 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
20342  61 62
20343 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
20344  61 00 62
20345 @end example
20347 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
20348 octal escape for @code{NUL}.
20350 @example
20351 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
20352  61 62 63
20353 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
20354  61 00 64
20355 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
20356  61 00 64
20357 @end example
20359 @end table
20362 @node Portable Make
20363 @chapter Portable Make Programming
20364 @prindex @command{make}
20365 @cindex Limitations of @command{make}
20367 Writing portable makefiles is an art.  Since a makefile's commands are
20368 executed by the shell, you must consider the shell portability issues
20369 already mentioned.  However, other issues are specific to @command{make}
20370 itself.
20372 @menu
20373 * $< in Ordinary Make Rules::   $< in ordinary rules
20374 * Failure in Make Rules::       Failing portably in rules
20375 * Special Chars in Names::      Special Characters in Macro Names
20376 * Backslash-Newline-Empty::     Empty lines after backslash-newline
20377 * Backslash-Newline Comments::  Spanning comments across line boundaries
20378 * Long Lines in Makefiles::     Line length limitations
20379 * Macros and Submakes::         @code{make macro=value} and submakes
20380 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
20381 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
20382 * Parallel Make::               Parallel @command{make} quirks
20383 * Comments in Make Rules::      Other problems with Make comments
20384 * Newlines in Make Rules::      Using literal newlines in rules
20385 * Comments in Make Macros::     Other problems with Make comments in macros
20386 * Trailing whitespace in Make Macros::  Macro substitution problems
20387 * Command-line Macros and whitespace::  Whitespace trimming of values
20388 * obj/ and Make::               Don't name a subdirectory @file{obj}
20389 * make -k Status::              Exit status of @samp{make -k}
20390 * VPATH and Make::              @code{VPATH} woes
20391 * Single Suffix Rules::         Single suffix rules and separated dependencies
20392 * Timestamps and Make::         Sub-second timestamp resolution
20393 @end menu
20395 @node $< in Ordinary Make Rules
20396 @section @code{$<} in Ordinary Make Rules
20398 Posix says that the @samp{$<} construct in makefiles can be
20399 used only in inference rules and in the @samp{.DEFAULT} rule; its
20400 meaning in ordinary rules is unspecified.  Solaris @command{make}
20401 for instance replaces it with the empty string.  OpenBSD (3.0 and
20402 later) @command{make} diagnoses these uses and errors out.
20404 @node Failure in Make Rules
20405 @section Failure in Make Rules
20407 Posix 2008 requires that @command{make} must invoke each command with
20408 the equivalent of a @samp{sh -e -c} subshell, which causes the
20409 subshell to exit immediately if a subsidiary simple-command fails,
20410 although not all @command{make} implementations have historically
20411 followed this rule.  For
20412 example, the command @samp{touch T; rm -f U} may attempt to
20413 remove @file{U} even if the @command{touch} fails, although this is not
20414 permitted with Posix make.  One way to work around failures in simple
20415 commands is to reword them so that they always succeed, e.g., @samp{touch
20416 T || :; rm -f U}.
20417 However, even this approach can run into common bugs in BSD
20418 implementations of the @option{-e} option of @command{sh} and
20419 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
20420 are worried
20421 about porting to buggy BSD shells it may be simpler to migrate
20422 complicated @command{make} actions into separate scripts.
20424 @node Special Chars in Names
20425 @section Special Characters in Make Macro Names
20427 Posix limits macro names to nonempty strings containing only
20428 ASCII letters and digits, @samp{.}, and @samp{_}.  Many
20429 @command{make} implementations allow a wider variety of characters, but
20430 portable makefiles should avoid them.  It is portable to start a name
20431 with a special character, e.g., @samp{$(.FOO)}.
20433 Some ancient @command{make} implementations don't support leading
20434 underscores in macro names.  An example is NEWS-OS 4.2R.
20436 @example
20437 $ @kbd{cat Makefile}
20438 _am_include = #
20439 _am_quote =
20440 all:; @@echo this is test
20441 $ @kbd{make}
20442 Make: Must be a separator on rules line 2.  Stop.
20443 $ @kbd{cat Makefile2}
20444 am_include = #
20445 am_quote =
20446 all:; @@echo this is test
20447 $ @kbd{make -f Makefile2}
20448 this is test
20449 @end example
20451 @noindent
20452 However, this problem is no longer of practical concern.
20454 @node Backslash-Newline-Empty
20455 @section Backslash-Newline Before Empty Lines
20457 A bug in Bash 2.03 can cause problems if a Make rule contains a
20458 backslash-newline followed by line that expands to nothing.
20459 For example, on Solaris 8:
20461 @example
20462 SHELL = /bin/bash
20463 EMPTY =
20464 foo:
20465         touch foo \
20466         $(EMPTY)
20467 @end example
20469 @noindent
20470 executes
20472 @example
20473 /bin/bash -c 'touch foo \
20475 @end example
20477 @noindent
20478 which fails with a syntax error, due to the Bash bug.  To avoid this
20479 problem, avoid nullable macros in the last line of a multi-line command.
20481 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
20482 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
20483 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
20484 On some versions of HP-UX, @command{make} reads multiple newlines
20485 following a backslash, continuing to the next non-empty line.  For
20486 example,
20488 @example
20489 FOO = one \
20491 BAR = two
20493 test:
20494         : FOO is "$(FOO)"
20495         : BAR is "$(BAR)"
20496 @end example
20498 @noindent
20499 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
20500 sensibly let a backslash continue only to the immediately following
20501 line.
20503 @node Backslash-Newline Comments
20504 @section Backslash-Newline in Make Comments
20506 According to Posix, Make comments start with @code{#}
20507 and continue until an unescaped newline is reached.
20509 @example
20510 $ @kbd{cat Makefile}
20511 # A = foo \
20512       bar \
20513       baz
20515 all:
20516         @@echo ok
20517 $ @kbd{make}   # GNU make
20519 @end example
20521 @noindent
20522 However this is not always the case.  Some implementations
20523 discard everything from @code{#} through the end of the line, ignoring any
20524 trailing backslash.
20526 @example
20527 $ @kbd{pmake}  # BSD make
20528 "Makefile", line 3: Need an operator
20529 Fatal errors encountered -- cannot continue
20530 @end example
20532 @noindent
20533 Therefore, if you want to comment out a multi-line definition, prefix each
20534 line with @code{#}, not only the first.
20536 @example
20537 # A = foo \
20538 #     bar \
20539 #     baz
20540 @end example
20542 @node Long Lines in Makefiles
20543 @section Long Lines in Makefiles
20545 Tru64 5.1's @command{make} has been reported to crash when given a
20546 makefile with lines longer than around 20 kB.  Earlier versions are
20547 reported to exit with @code{Line too long} diagnostics.
20549 @node Macros and Submakes
20550 @section @code{make macro=value} and Submakes
20552 A command-line variable definition such as @code{foo=bar} overrides any
20553 definition of @code{foo} in a makefile.  Some @command{make}
20554 implementations (such as GNU @command{make}) propagate this
20555 override to subsidiary invocations of @command{make}.  Some other
20556 implementations do not pass the substitution along to submakes.
20558 @example
20559 $ @kbd{cat Makefile}
20560 foo = foo
20561 one:
20562         @@echo $(foo)
20563         $(MAKE) two
20564 two:
20565         @@echo $(foo)
20566 $ @kbd{make foo=bar}            # GNU make 3.79.1
20568 make two
20569 make[1]: Entering directory `/home/adl'
20571 make[1]: Leaving directory `/home/adl'
20572 $ @kbd{pmake foo=bar}           # BSD make
20574 pmake two
20576 @end example
20578 You have a few possibilities if you do want the @code{foo=bar} override
20579 to propagate to submakes.  One is to use the @option{-e}
20580 option, which causes all environment variables to have precedence over
20581 the makefile macro definitions, and declare foo as an environment
20582 variable:
20584 @example
20585 $ @kbd{env foo=bar make -e}
20586 @end example
20588 The @option{-e} option is propagated to submakes automatically,
20589 and since the environment is inherited between @command{make}
20590 invocations, the @code{foo} macro is overridden in
20591 submakes as expected.
20593 This syntax (@code{foo=bar make -e}) is portable only when used
20594 outside of a makefile, for instance from a script or from the
20595 command line.  When run inside a @command{make} rule, GNU
20596 @command{make} 3.80 and prior versions forget to propagate the
20597 @option{-e} option to submakes.
20599 Moreover, using @option{-e} could have unexpected side effects if your
20600 environment contains some other macros usually defined by the
20601 makefile.  (See also the note about @code{make -e} and @code{SHELL}
20602 below.)
20604 If you can foresee all macros that a user might want to override, then
20605 you can propagate them to submakes manually, from your makefile:
20607 @example
20608 foo = foo
20609 one:
20610         @@echo $(foo)
20611         $(MAKE) foo=$(foo) two
20612 two:
20613         @@echo $(foo)
20614 @end example
20616 Another way to propagate a variable to submakes in a portable way is to
20617 expand an extra variable in every invocation of @samp{$(MAKE)} within
20618 your makefile:
20620 @example
20621 foo = foo
20622 one:
20623         @@echo $(foo)
20624         $(MAKE) $(SUBMAKEFLAGS) two
20625 two:
20626         @@echo $(foo)
20627 @end example
20629 Users must be aware that this technique is in use to take advantage of
20630 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
20631 allows any macro to be overridden.  Makefiles generated by
20632 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
20633 on the command lines of submakes (@pxref{Subdirectories, , Automake,
20634 automake, GNU Automake}).
20636 @node The Make Macro MAKEFLAGS
20637 @section The Make Macro MAKEFLAGS
20638 @cindex @code{MAKEFLAGS} and @command{make}
20639 @cindex @command{make} and @code{MAKEFLAGS}
20641 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
20642 current and recursive invocations of make, but allows implementations
20643 several formats for the variable.  It is tricky to parse
20644 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
20645 or @option{-k} for continued execution are in effect.  For example, you
20646 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
20647 contains single-letter options, since in the Cygwin version of
20648 GNU @command{make} it is either @option{--unix} or
20649 @option{--win32} with the second word containing single-letter options.
20651 @example
20652 $ @kbd{cat Makefile}
20653 all:
20654         @@echo MAKEFLAGS = $(MAKEFLAGS)
20655 $ @kbd{make}
20656 MAKEFLAGS = --unix
20657 $ @kbd{make -k}
20658 MAKEFLAGS = --unix -k
20659 @end example
20661 @node The Make Macro SHELL
20662 @section The Make Macro @code{SHELL}
20663 @cindex @code{SHELL} and @command{make}
20664 @cindex @command{make} and @code{SHELL}
20666 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
20667 macro to spawn shell processes and execute Make rules.  This
20668 is a builtin macro supplied by @command{make}, but it can be modified
20669 by a makefile or by a command-line argument.
20671 Not all @command{make} implementations define this @code{SHELL} macro.
20672 Tru64
20673 @command{make} is an example; this implementation always uses
20674 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
20675 your makefiles.  If you use Autoconf, do
20677 @example
20678 SHELL = @@SHELL@@
20679 @end example
20681 @noindent
20682 If you use Automake, this is done for you.
20684 Do not force @code{SHELL = /bin/sh} because that is not correct
20685 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
20686 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
20687 Additionally, DJGPP lacks @code{/bin/sh}, and when its
20688 GNU @command{make} port sees such a setting it enters a
20689 special emulation mode where features like pipes and redirections are
20690 emulated on top of DOS's @command{command.com}.  Unfortunately this
20691 emulation is incomplete; for instance it does not handle command
20692 substitutions.  Using @code{@@SHELL@@} means that your makefile will
20693 benefit from the same improved shell, such as @command{bash} or
20694 @command{ksh}, that was discovered during @command{configure}, so that
20695 you aren't fighting two different sets of shell bugs between the two
20696 contexts.
20698 Posix-compliant @command{make} should never acquire the value of
20699 $(SHELL) from the environment, even when @code{make -e} is used
20700 (otherwise, think about what would happen to your rules if
20701 @code{SHELL=/bin/tcsh}).
20703 However not all @command{make} implementations have this exception.
20704 For instance it's not surprising that Tru64 @command{make} doesn't
20705 protect @code{SHELL}, since it doesn't use it.
20707 @example
20708 $ @kbd{cat Makefile}
20709 SHELL = /bin/sh
20710 FOO = foo
20711 all:
20712         @@echo $(SHELL)
20713         @@echo $(FOO)
20714 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
20715 /bin/tcsh
20717 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
20718 /bin/sh
20720 @end example
20722 Conversely, @command{make} is not supposed to export any changes to the
20723 macro @code{SHELL} to child processes.  Again, many implementations
20724 break this rule:
20726 @example
20727 $ @kbd{cat Makefile}
20728 all:
20729         @@echo $(SHELL)
20730         @@printenv SHELL
20731 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
20732 /bin/ksh
20733 /bin/ksh
20734 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
20735 /bin/ksh
20737 @end example
20739 @node Parallel Make
20740 @section Parallel Make
20741 @cindex Parallel @command{make}
20743 Support for parallel execution in @command{make} implementation varies.
20744 Generally, using GNU make is your best bet.
20746 When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
20747 reuse the same shell for multiple commands within one recipe.  This can
20748 have various unexpected consequences.  For example, changes of directories
20749 or variables persist between recipes, so that:
20751 @example
20752 all:
20753         @@var=value; cd /; pwd; echo $$var; echo $$$$
20754         @@pwd; echo $$var; echo $$$$
20755 @end example
20757 @noindent
20758 may output the following with @code{make -j1}, at least on NetBSD up to
20759 5.1 and FreeBSD up to 8.2:
20761 @example
20763 value
20764 32235
20766 value
20767 32235
20768 @end example
20770 @noindent
20771 while without @option{-j1}, or with @option{-B}, the output looks less
20772 surprising:
20774 @example
20776 value
20777 32238
20778 /tmp
20780 32239
20781 @end example
20783 @noindent
20784 Another consequence is that, if one command in a recipe uses @code{exit 0}
20785 to indicate a successful exit, the shell will be gone and the remaining
20786 commands of this recipe will not be executed.
20788 The BSD @command{make} implementations, when run in parallel mode,
20789 will also pass the @command{Makefile} recipes to the shell through
20790 its standard input, thus making it unusable from the recipes:
20792 @example
20793 $ @kbd{cat Makefile}
20794 read:
20795         @@read line; echo LINE: $$line
20796 @c $$ @c restore font-lock
20797 $ @kbd{echo foo | make read}
20798 LINE: foo
20799 $ @kbd{echo foo | make -j1 read} # NetBSD 5.1 and FreeBSD 8.2
20800 LINE:
20801 @end example
20803 @noindent
20804 Moreover, when FreeBSD @command{make} (up at least to 8.2) is run in
20805 parallel mode, it implements the @code{@@} and @code{-} ``recipe
20806 modifiers'' by dynamically modifying the active shell flags.  This
20807 behavior has the effects of potentially clobbering the exit status
20808 of recipes silenced with the @code{@@} modifier if they also unset
20809 the @option{errexit} shell flag, and of mangling the output in
20810 unexpected ways:
20812 @example
20813 $ @kbd{cat Makefile}
20815         @@echo $$-; set +e; false
20817         -echo $$-; false; echo set -
20818 $ @kbd{make a; echo status: $?}
20819 ehBc
20820 *** Error code 1
20821 status: 1
20822 $ @kbd{make -j1 a; echo status: $?}
20824 status: 0
20825 $ @kbd{make b}
20826 echo $-; echo set -
20828 set -
20829 $ @kbd{make -j1 b}
20830 echo $-; echo hvB
20831 @end example
20833 @noindent
20834 You can avoid all these issues by using the @option{-B} option to enable
20835 compatibility semantics.  However, that will effectively also disable
20836 all parallelism as that will cause prerequisites to be updated in the
20837 order they are listed in a rule.
20839 Some make implementations (among them, FreeBSD @command{make}, NetBSD
20840 @command{make}, and Solaris @command{dmake}), when invoked with a
20841 @option{-j@var{N}} option, connect the standard output and standard
20842 error of all their child processes to pipes or temporary regular
20843 files.  This can lead to subtly different semantics in the behavior
20844 of the spawned processes.  For example, even if the @command{make}
20845 standard output is connected to a tty, the recipe command will not be:
20847 @example
20848 $ @kbd{cat Makefile}
20849 all:
20850         @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
20851 $ @kbd{make -j 2} # FreeBSD 8.2 make
20852 Is not a tty
20853 $ @kbd{make -j 2} # NetBSD 5.1 make
20854 --- all ---
20855 Is not a tty
20856 $ @kbd{dmake -j 2} # Solaris 10 dmake
20857 @var{hostname} --> 1 job
20858 @var{hostname} --> Job output
20859 Is not a tty
20860 @end example
20862 @noindent
20863 On the other hand:
20865 @example
20866 $ @kbd{make -j 2} # GNU make, Heirloom make
20867 Is a tty
20868 @end example
20870 @noindent
20871 The above examples also show additional status output produced in parallel
20872 mode for targets being updated by Solaris @command{dmake} and NetBSD
20873 @command{make} (but @emph{not} by FreeBSD @command{make}).
20875 Furthermore, parallel runs of those @command{make} implementations will
20876 route standard error from commands that they spawn into their own
20877 standard output, and may remove leading whitespace from output lines.
20880 @node Comments in Make Rules
20881 @section Comments in Make Rules
20882 @cindex Comments in @file{Makefile} rules
20883 @cindex @file{Makefile} rules and comments
20885 Never put comments in a rule.
20887 Some @command{make} treat anything starting with a tab as a command for
20888 the current rule, even if the tab is immediately followed by a @code{#}.
20889 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
20890 makefile runs @code{# foo} through the shell.
20892 @example
20893 all:
20894         # foo
20895 @end example
20897 As a workaround, you can use the @command{:} no-op command with a string
20898 argument that gets ignored:
20900 @example
20901 all:
20902         : "foo"
20903 @end example
20905 Conversely, if you want to use the @samp{#} character in some command,
20906 you can only do so by expanding it inside a rule (@pxref{Comments in
20907 Make Macros}).  So for example, if @samp{COMMENT_CHAR} is substituted by
20908 @command{config.status} as @samp{#}, then the following substitutes
20909 @samp{@@COMMENT_CHAR@@} in a generated header:
20911 @example
20912 foo.h: foo.h.in
20913         sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
20914             $(srcdir)/foo.h.in > $@@
20915 @end example
20917 The funny shell quoting avoids a substitution at @command{config.status}
20918 run time of the left-hand side of the @command{sed} @samp{s} command.
20920 @node Newlines in Make Rules
20921 @section Newlines in Make Rules
20922 @cindex Newlines in @file{Makefile} rules
20923 @cindex @file{Makefile} rules and newlines
20925 In shell scripts, newlines can be used inside string literals.  But in
20926 the shell statements of @file{Makefile} rules, this is not possible:
20927 A newline not preceded by a backslash is a separator between shell
20928 statements.  Whereas a newline that is preceded by a backslash becomes
20929 part of the shell statement according to POSIX, but gets replaced,
20930 together with the backslash that precedes it, by a space in GNU
20931 @command{make} 3.80 and older.  So, how can a newline be used in a string
20932 literal?
20934 The trick is to set up a shell variable that contains a newline:
20936 @example
20937 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"
20938 @end example
20940 For example, in order to create a multi-line @samp{sed} expression that
20941 inserts a blank line after every line of a file, this code can be used:
20943 @example
20944 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"; \
20945 sed -e "s/\$$/\\$$@{nl@}/" < input > output
20946 @end example
20948 @node Comments in Make Macros
20949 @section Comments in Make Macros
20950 @cindex Comments in @file{Makefile} macros
20951 @cindex @file{Makefile} macros and comments
20953 Avoid putting comments in macro values as far as possible.  Posix
20954 specifies that the text starting from the @samp{#} sign until the end of
20955 the line is to be ignored, which has the unfortunate effect of
20956 disallowing them even within quotes.  Thus, the following might lead to
20957 a syntax error at compile time:
20959 @example
20960 CPPFLAGS = "-DCOMMENT_CHAR='#'"
20961 @end example
20963 @noindent
20964 as @samp{CPPFLAGS} may be expanded to @samp{"-DCOMMENT_CHAR='}.
20966 Most @command{make} implementations disregard this and treat single and
20967 double quotes specially here.  Also, GNU @command{make} lets you put
20968 @samp{#} into a macro value by escaping it with a backslash, i.e.,
20969 @samp{\#}.  However, neither of these usages are portable.
20970 @xref{Comments in Make Rules}, for a portable alternative.
20972 Even without quoting involved, comments can have surprising effects,
20973 because the whitespace before them is part of the variable value:
20975 @example
20976 foo = bar # trailing comment
20977 print: ; @@echo "$(foo)."
20978 @end example
20980 @noindent
20981 prints @samp{bar .}, which is usually not intended, and can expose
20982 @command{make} bugs as described below.
20984 @node Trailing whitespace in Make Macros
20985 @section Trailing whitespace in Make Macros
20986 @cindex whitespace in @file{Makefile} macros
20987 @cindex @file{Makefile} macros and whitespace
20989 GNU @command{make} 3.80 mistreats trailing whitespace in macro
20990 substitutions and appends another spurious suffix:
20992 @example
20993 empty =
20994 foo = bar $(empty)
20995 print: ; @@echo $(foo:=.test)
20996 @end example
20998 @noindent
20999 prints @samp{bar.test .test}.
21001 BSD and Solaris @command{make} implementations do not honor trailing
21002 whitespace in macro definitions as Posix requires:
21004 @example
21005 foo = bar # Note the space after "bar".
21006 print: ; @@echo $(foo)t
21007 @end example
21009 @noindent
21010 prints @samp{bart} instead of @samp{bar t}.  To work around this, you
21011 can use a helper macro as in the previous example.
21014 @node Command-line Macros and whitespace
21015 @section Command-line Macros and whitespace
21016 @cindex whitespace in command-line macros
21017 @cindex command-line, macros set on
21018 @cindex environment, macros set from
21020 Some @command{make} implementations may strip trailing whitespace off
21021 of macros set on the command line in addition to leading whitespace.
21022 Further, some may strip leading whitespace off of macros set from
21023 environment variables:
21025 @example
21026 $ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
21027   foo=' f f ' make -f - bar=' b b '}
21028 x f f xb b x  # AIX, BSD, GNU make
21029 xf f xb b x   # HP-UX, IRIX, Tru64/OSF make
21030 x f f xb bx   # Solaris make
21031 @end example
21034 @node obj/ and Make
21035 @section The @file{obj/} Subdirectory and Make
21036 @cindex @file{obj/}, subdirectory
21037 @cindex BSD @command{make} and @file{obj/}
21039 Never name one of your subdirectories @file{obj/} if you don't like
21040 surprises.
21042 If an @file{obj/} directory exists, BSD @command{make} enters it
21043 before reading the makefile.  Hence the makefile in the
21044 current directory is not read.
21046 @example
21047 $ @kbd{cat Makefile}
21048 all:
21049         echo Hello
21050 $ @kbd{cat obj/Makefile}
21051 all:
21052         echo World
21053 $ @kbd{make}      # GNU make
21054 echo Hello
21055 Hello
21056 $ @kbd{pmake}     # BSD make
21057 echo World
21058 World
21059 @end example
21061 @node make -k Status
21062 @section Exit Status of @code{make -k}
21063 @cindex @code{make -k}
21065 Do not rely on the exit status of @code{make -k}.  Some implementations
21066 reflect whether they encountered an error in their exit status; other
21067 implementations always succeed.
21069 @example
21070 $ @kbd{cat Makefile}
21071 all:
21072         false
21073 $ @kbd{make -k; echo exit status: $?}    # GNU make
21074 false
21075 make: *** [all] Error 1
21076 exit status: 2
21077 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
21078 false
21079 *** Error code 1 (continuing)
21080 exit status: 0
21081 @end example
21083 @node VPATH and Make
21084 @section @code{VPATH} and Make
21085 @cindex @code{VPATH}
21087 Posix does not specify the semantics of @code{VPATH}.  Typically,
21088 @command{make} supports @code{VPATH}, but its implementation is not
21089 consistent.
21091 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
21092 portable to recent-enough popular implementations of @command{make}, but
21093 to keep the resulting makefiles portable, a package's makefile
21094 prototypes must take the following issues into account.  These issues
21095 are complicated and are often poorly understood, and installers who use
21096 @code{VPATH} should expect to find many bugs in this area.  If you use
21097 @code{VPATH}, the simplest way to avoid these portability bugs is to
21098 stick with GNU @command{make}, since it is the most
21099 commonly-used @command{make} among Autoconf users.
21101 Here are some known issues with some @code{VPATH}
21102 implementations.
21104 @menu
21105 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
21106 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
21107 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
21108 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
21109 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
21110 * Make Target Lookup::          More details about @code{VPATH} lookup
21111 @end menu
21113 @node Variables listed in VPATH
21114 @subsection Variables listed in @code{VPATH}
21115 @cindex @code{VPATH} and variables
21116 @cindex variables and @code{VPATH}
21118 Do not set @code{VPATH} to the value of another variable, for example
21119 @samp{VPATH = $(srcdir)}, because some ancient versions of
21120 @command{make} do not do variable substitutions on the value of
21121 @code{VPATH}.  For example, use this
21123 @example
21124 srcdir = @@srcdir@@
21125 VPATH = @@srcdir@@
21126 @end example
21128 @noindent
21129 rather than @samp{VPATH = $(srcdir)}.  Note that with GNU
21130 Automake, there is no need to set this yourself.
21132 @node VPATH and Double-colon
21133 @subsection @code{VPATH} and Double-colon Rules
21134 @cindex @code{VPATH} and double-colon rules
21135 @cindex double-colon rules and @code{VPATH}
21137 With ancient versions of Sun @command{make},
21138 any assignment to @code{VPATH} causes @command{make} to execute only
21139 the first set of double-colon rules.
21140 However, this problem is no longer of practical concern.
21142 @node $< in Explicit Rules
21143 @subsection @code{$<} Not Supported in Explicit Rules
21144 @cindex explicit rules, @code{$<}, and @code{VPATH}
21145 @cindex @code{$<}, explicit rules, and @code{VPATH}
21146 @cindex @code{VPATH}, explicit rules, and @code{$<}
21148 Using @code{$<} in explicit rules is not portable.
21149 The prerequisite file must be named explicitly in the rule.  If you want
21150 to find the prerequisite via a @code{VPATH} search, you have to code the
21151 whole thing manually.  @xref{Build Directories}.
21153 @node Automatic Rule Rewriting
21154 @subsection Automatic Rule Rewriting
21155 @cindex @code{VPATH} and automatic rule rewriting
21156 @cindex automatic rule rewriting and @code{VPATH}
21158 Some @command{make} implementations, such as Solaris and Tru64,
21159 search for prerequisites in @code{VPATH} and
21160 then rewrite each occurrence as a plain word in the rule.
21161 For instance:
21163 @example
21164 # This isn't portable to GNU make.
21165 VPATH = ../pkg/src
21166 f.c: if.c
21167         cp if.c f.c
21168 @end example
21170 @noindent
21171 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
21172 found in @file{../pkg/src}.
21174 However, this rule leads to real problems in practice.  For example, if
21175 the source directory contains an ordinary file named @file{test} that is
21176 used in a dependency, Solaris @command{make} rewrites commands like
21177 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
21178 @dots{}}, which is typically undesirable.  In fact, @command{make} is
21179 completely unaware of shell syntax used in the rules, so the VPATH
21180 rewrite can potentially apply to @emph{any} whitespace-separated word
21181 in a rule, including shell variables, functions, and keywords.
21183 @example
21184 $ @kbd{mkdir build}
21185 $ @kbd{cd build}
21186 $ @kbd{cat > Makefile <<'END'}
21187 VPATH = ..
21188 all: arg func for echo
21189         func () @{ for arg in "$$@@"; do echo $$arg; done; @}; \
21190         func "hello world"
21192 $ @kbd{touch ../arg ../func ../for ../echo}
21193 $ @kbd{make}
21194 ../func () @{ ../for ../arg in "$@@"; do ../echo $arg; done; @}; \
21195 ../func "hello world"
21196 sh: syntax error at line 1: `do' unexpected
21197 *** Error code 2
21198 @end example
21200 @noindent
21201 To avoid this problem, portable makefiles should never mention a source
21202 file or dependency whose name is that of a shell keyword like @file{for}
21203 or @file{until}, a shell command like @command{cat} or @command{gcc} or
21204 @command{test}, or a shell function or variable used in the corresponding
21205 @command{Makefile} recipe.
21207 Because of these problems GNU @command{make} and many other @command{make}
21208 implementations do not rewrite commands, so portable makefiles should
21209 search @code{VPATH} manually.  It is tempting to write this:
21211 @smallexample
21212 # This isn't portable to Solaris make.
21213 VPATH = ../pkg/src
21214 f.c: if.c
21215         cp `test -f if.c || echo $(VPATH)/`if.c f.c
21216 @end smallexample
21218 @noindent
21219 However, the ``prerequisite rewriting'' still applies here.  So if
21220 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
21221 execute
21223 @smallexample
21224 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
21225 @end smallexample
21227 @noindent
21228 which reduces to
21230 @example
21231 cp if.c f.c
21232 @end example
21234 @noindent
21235 and thus fails.  Oops.
21237 A simple workaround, and good practice anyway, is to use @samp{$?} and
21238 @samp{$@@} when possible:
21240 @smallexample
21241 VPATH = ../pkg/src
21242 f.c: if.c
21243         cp $? $@@
21244 @end smallexample
21246 @noindent
21247 but this does not generalize well to commands with multiple
21248 prerequisites.  A more general workaround is to rewrite the rule so that
21249 the prerequisite @file{if.c} never appears as a plain word.  For
21250 example, these three rules would be safe, assuming @file{if.c} is in
21251 @file{../pkg/src} and the other files are in the working directory:
21253 @smallexample
21254 VPATH = ../pkg/src
21255 f.c: if.c f1.c
21256         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
21257 g.c: if.c g1.c
21258         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
21259 h.c: if.c h1.c
21260         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
21261 @end smallexample
21263 Things get worse when your prerequisites are in a macro.
21265 @example
21266 VPATH = ../pkg/src
21267 HEADERS = f.h g.h h.h
21268 install-HEADERS: $(HEADERS)
21269         for i in $(HEADERS); do \
21270           $(INSTALL) -m 644 \
21271             `test -f $$i || echo $(VPATH)/`$$i \
21272             $(DESTDIR)$(includedir)/$$i; \
21273 @c $$ restore font-lock
21274         done
21275 @end example
21277 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
21278 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
21279 where @code{f.h} and @code{g.h} are plain words and are hence
21280 subject to @code{VPATH} adjustments.
21282 If the three files are in @file{../pkg/src}, the rule is run as:
21284 @example
21285 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
21286   install -m 644 \
21287      `test -f $i || echo ../pkg/src/`$i \
21288      /usr/local/include/$i; \
21289 done
21290 @end example
21292 where the two first @command{install} calls fail.  For instance,
21293 consider the @code{f.h} installation:
21295 @example
21296 install -m 644 \
21297   `test -f ../pkg/src/f.h || \
21298     echo ../pkg/src/ \
21299   `../pkg/src/f.h \
21300   /usr/local/include/../pkg/src/f.h;
21301 @end example
21303 @noindent
21304 It reduces to:
21306 @example
21307 install -m 644 \
21308   ../pkg/src/f.h \
21309   /usr/local/include/../pkg/src/f.h;
21310 @end example
21312 Note that the manual @code{VPATH} search did not cause any problems here;
21313 however this command installs @file{f.h} in an incorrect directory.
21315 Trying to quote @code{$(HEADERS)} in some way, as we did for
21316 @code{foo.c} a few makefiles ago, does not help:
21318 @example
21319 install-HEADERS: $(HEADERS)
21320         headers='$(HEADERS)'; \
21321         for i in $$headers; do \
21322           $(INSTALL) -m 644 \
21323             `test -f $$i || echo $(VPATH)/`$$i \
21324             $(DESTDIR)$(includedir)/$$i; \
21325         done
21326 @end example
21328 Now, @code{headers='$(HEADERS)'} macro-expands to:
21330 @example
21331 headers='f.h g.h h.h'
21332 @end example
21334 @noindent
21335 but @code{g.h} is still a plain word.  (As an aside, the idiom
21336 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
21337 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
21338 syntax error on @code{for i in;}.)
21340 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
21342 @example
21343 VPATH = ../pkg/src
21344 HEADERS = f.h g.h h.h
21345 install-HEADERS: $(HEADERS)
21346         headers='$(HEADERS)'; \
21347         for i in $$headers; do \
21348           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
21349           $(INSTALL) -m 644 \
21350             `test -f $$i || echo $(VPATH)/`$$i \
21351             $(DESTDIR)$(includedir)/$$i; \
21352 @c $$ restore font-lock
21353         done
21354 @end example
21356 Automake does something similar.  However the above hack works only if
21357 the files listed in @code{HEADERS} are in the current directory or a
21358 subdirectory; they should not be in an enclosing directory.  If we had
21359 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
21360 build with Tru64 @command{make}.  The reason is that not only does
21361 Tru64 @command{make} rewrite dependencies, but it also simplifies
21362 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
21363 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
21364 a leading @file{../pkg/src/} component.
21366 The following example makes the behavior of Tru64 @command{make}
21367 more apparent.
21369 @example
21370 $ @kbd{cat Makefile}
21371 VPATH = sub
21372 all: ../foo
21373         echo ../foo
21374 $ @kbd{ls}
21375 Makefile foo
21376 $ @kbd{make}
21377 echo foo
21379 @end example
21381 @noindent
21382 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
21383 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
21384 directory does not even exist, this just means that the simplification
21385 occurred before the file was checked for.)
21387 For the record here is how SunOS 4 @command{make} behaves on this
21388 example.
21390 @smallexample
21391 $ @kbd{make}
21392 make: Fatal error: Don't know how to make target `../foo'
21393 $ @kbd{mkdir sub}
21394 $ @kbd{make}
21395 echo sub/../foo
21396 sub/../foo
21397 @end smallexample
21400 @node Tru64 Directory Magic
21401 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
21402 @cindex @code{VPATH} and prerequisite directories
21403 @cindex prerequisite directories and @code{VPATH}
21405 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
21406 @command{make} creates it in the current directory.
21408 @example
21409 $ @kbd{mkdir -p foo/bar build}
21410 $ @kbd{cd build}
21411 $ @kbd{cat >Makefile <<END
21412 VPATH = ..
21413 all: foo/bar
21414 END}
21415 $ @kbd{make}
21416 mkdir foo
21417 mkdir foo/bar
21418 @end example
21420 This can yield unexpected results if a rule uses a manual @code{VPATH}
21421 search as presented before.
21423 @example
21424 VPATH = ..
21425 all : foo/bar
21426         command `test -d foo/bar || echo ../`foo/bar
21427 @end example
21429 The above @command{command} is run on the empty @file{foo/bar}
21430 directory that was created in the current directory.
21432 @node Make Target Lookup
21433 @subsection Make Target Lookup
21434 @cindex @code{VPATH}, resolving target pathnames
21436 GNU @command{make} uses a complex algorithm to decide when it
21437 should use files found via a @code{VPATH} search.  @xref{Search
21438 Algorithm, , How Directory Searches are Performed, make, The GNU Make
21439 Manual}.
21441 If a target needs to be rebuilt, GNU @command{make} discards the
21442 file name found during the @code{VPATH} search for this target, and
21443 builds the file locally using the file name given in the makefile.
21444 If a target does not need to be rebuilt, GNU @command{make} uses the
21445 file name found during the @code{VPATH} search.
21447 Other @command{make} implementations, like NetBSD @command{make}, are
21448 easier to describe: the file name found during the @code{VPATH} search
21449 is used whether the target needs to be rebuilt or not.  Therefore
21450 new files are created locally, but existing files are updated at their
21451 @code{VPATH} location.
21453 OpenBSD and FreeBSD @command{make}, however,
21454 never perform a
21455 @code{VPATH} search for a dependency that has an explicit rule.
21456 This is extremely annoying.
21458 When attempting a @code{VPATH} build for an autoconfiscated package
21459 (e.g., @code{mkdir build && cd build && ../configure}), this means
21461 @command{make} builds everything locally in the @file{build}
21462 directory, while BSD @command{make} builds new files locally and
21463 updates existing files in the source directory.
21465 @example
21466 $ @kbd{cat Makefile}
21467 VPATH = ..
21468 all: foo.x bar.x
21469 foo.x bar.x: newer.x
21470         @@echo Building $@@
21471 $ @kbd{touch ../bar.x}
21472 $ @kbd{touch ../newer.x}
21473 $ @kbd{make}        # GNU make
21474 Building foo.x
21475 Building bar.x
21476 $ @kbd{pmake}       # NetBSD make
21477 Building foo.x
21478 Building ../bar.x
21479 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21480 Building foo.x
21481 Building bar.x
21482 $ @kbd{tmake}       # Tru64 make
21483 Building foo.x
21484 Building bar.x
21485 $ @kbd{touch ../bar.x}
21486 $ @kbd{make}        # GNU make
21487 Building foo.x
21488 $ @kbd{pmake}       # NetBSD make
21489 Building foo.x
21490 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21491 Building foo.x
21492 Building bar.x
21493 $ @kbd{tmake}       # Tru64 make
21494 Building foo.x
21495 Building bar.x
21496 @end example
21498 Note how NetBSD @command{make} updates @file{../bar.x} in its
21499 VPATH location, and how FreeBSD, OpenBSD, and Tru64
21500 @command{make} always
21501 update @file{bar.x}, even when @file{../bar.x} is up to date.
21503 Another point worth mentioning is that once GNU @command{make} has
21504 decided to ignore a @code{VPATH} file name (e.g., it ignored
21505 @file{../bar.x} in the above example) it continues to ignore it when
21506 the target occurs as a prerequisite of another rule.
21508 The following example shows that GNU @command{make} does not look up
21509 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
21510 because it ignored the @code{VPATH} result of @file{bar.x} while running
21511 the @code{bar.x: newer.x} rule.
21513 @example
21514 $ @kbd{cat Makefile}
21515 VPATH = ..
21516 all: bar.y
21517 bar.x: newer.x
21518         @@echo Building $@@
21519 .SUFFIXES: .x .y
21520 .x.y:
21521         cp $< $@@
21522 $ @kbd{touch ../bar.x}
21523 $ @kbd{touch ../newer.x}
21524 $ @kbd{make}        # GNU make
21525 Building bar.x
21526 cp bar.x bar.y
21527 cp: cannot stat 'bar.x': No such file or directory
21528 make: *** [bar.y] Error 1
21529 $ @kbd{pmake}       # NetBSD make
21530 Building ../bar.x
21531 cp ../bar.x bar.y
21532 $ @kbd{rm bar.y}
21533 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21534 echo Building bar.x
21535 cp bar.x bar.y
21536 cp: cannot stat 'bar.x': No such file or directory
21537 *** Error code 1
21538 $ @kbd{tmake}       # Tru64 make
21539 Building bar.x
21540 cp: bar.x: No such file or directory
21541 *** Exit 1
21542 @end example
21544 Note that if you drop away the command from the @code{bar.x: newer.x}
21545 rule, GNU @command{make} magically starts to work: it
21546 knows that @code{bar.x} hasn't been updated, therefore it doesn't
21547 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
21548 uses.  Tru64 also works, but FreeBSD and OpenBSD
21549 still don't.
21551 @example
21552 $ @kbd{cat Makefile}
21553 VPATH = ..
21554 all: bar.y
21555 bar.x: newer.x
21556 .SUFFIXES: .x .y
21557 .x.y:
21558         cp $< $@@
21559 $ @kbd{touch ../bar.x}
21560 $ @kbd{touch ../newer.x}
21561 $ @kbd{make}        # GNU make
21562 cp ../bar.x bar.y
21563 $ @kbd{rm bar.y}
21564 $ @kbd{pmake}       # NetBSD make
21565 cp ../bar.x bar.y
21566 $ @kbd{rm bar.y}
21567 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21568 cp bar.x bar.y
21569 cp: cannot stat 'bar.x': No such file or directory
21570 *** Error code 1
21571 $ @kbd{tmake}       # Tru64 make
21572 cp ../bar.x bar.y
21573 @end example
21575 It seems the sole solution that would please every @command{make}
21576 implementation is to never rely on @code{VPATH} searches for targets.
21577 In other words, @code{VPATH} should be reserved to sources that are not built.
21580 @node Single Suffix Rules
21581 @section Single Suffix Rules and Separated Dependencies
21582 @cindex Single Suffix Inference Rule
21583 @cindex Rule, Single Suffix Inference
21584 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
21585 (@samp{.from.to:}), but which @emph{destination} suffix is empty
21586 (@samp{.from:}).
21588 @cindex Separated Dependencies
21589 @dfn{Separated dependencies} simply refers to listing the prerequisite
21590 of a target, without defining a rule.  Usually one can list on the one
21591 hand side, the rules, and on the other hand side, the dependencies.
21593 Solaris @command{make} does not support separated dependencies for
21594 targets defined by single suffix rules:
21596 @example
21597 $ @kbd{cat Makefile}
21598 .SUFFIXES: .in
21599 foo: foo.in
21600 .in:
21601         cp $< $@@
21602 $ @kbd{touch foo.in}
21603 $ @kbd{make}
21604 $ @kbd{ls}
21605 Makefile  foo.in
21606 @end example
21608 @noindent
21609 while GNU Make does:
21611 @example
21612 $ @kbd{gmake}
21613 cp foo.in foo
21614 $ @kbd{ls}
21615 Makefile  foo       foo.in
21616 @end example
21618 Note it works without the @samp{foo: foo.in} dependency.
21620 @example
21621 $ @kbd{cat Makefile}
21622 .SUFFIXES: .in
21623 .in:
21624         cp $< $@@
21625 $ @kbd{make foo}
21626 cp foo.in foo
21627 @end example
21629 @noindent
21630 and it works with double suffix inference rules:
21632 @example
21633 $ @kbd{cat Makefile}
21634 foo.out: foo.in
21635 .SUFFIXES: .in .out
21636 .in.out:
21637         cp $< $@@
21638 $ @kbd{make}
21639 cp foo.in foo.out
21640 @end example
21642 As a result, in such a case, you have to write target rules.
21644 @node Timestamps and Make
21645 @section Timestamp Resolution and Make
21646 @cindex timestamp resolution
21647 Traditionally, file timestamps had 1-second resolution, and
21648 @command{make} used those timestamps to determine whether one file was
21649 newer than the other.  However, many modern file systems have
21650 timestamps with 1-nanosecond resolution.  Some @command{make}
21651 implementations look at the entire timestamp; others ignore the
21652 fractional part, which can lead to incorrect results.  Normally this
21653 is not a problem, but in some extreme cases you may need to use tricks
21654 like @samp{sleep 1} to work around timestamp truncation bugs.
21656 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
21657 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
21658 Tools}).  Hence you should be wary of rules like this:
21660 @example
21661 dest: src
21662         cp -p src dest
21663 @end example
21665 as @file{dest} often appears to be older than @file{src} after the
21666 timestamp is truncated, and this can cause @command{make} to do
21667 needless rework the next time it is invoked.  To work around this
21668 problem, you can use a timestamp file, e.g.:
21670 @example
21671 dest-stamp: src
21672         cp -p src dest
21673         date >dest-stamp
21674 @end example
21676 Apart from timestamp resolution, there are also differences in handling
21677 equal timestamps.  HP-UX @command{make} updates targets if it has the
21678 same timestamp as one of its prerequisites, in violation of Posix rules.
21680 This can cause spurious rebuilds for repeated runs of @command{make}.
21681 This in turn can cause @command{make} to fail if it tries to rebuild
21682 generated files in a possibly read-only source tree with tools not
21683 present on the end-user machine.  Use GNU @command{make} instead.
21687 @c ======================================== Portable C and C++ Programming
21689 @node Portable C and C++
21690 @chapter Portable C and C++ Programming
21691 @cindex Portable C and C++ programming
21693 C and C++ programs often use low-level features of the underlying
21694 system, and therefore are often more difficult to make portable to other
21695 platforms.
21697 Several standards have been developed to help make your programs more
21698 portable.  If you write programs with these standards in mind, you can
21699 have greater confidence that your programs work on a wide variety
21700 of systems.
21701 @ifhtml
21702 @uref{https://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
21703 Standards Supported by GCC}
21704 @end ifhtml
21705 @ifnothtml
21706 @xref{Standards, , Language Standards Supported by
21707 GCC, gcc, Using the GNU Compiler Collection
21708 (GCC)},
21709 @end ifnothtml
21710 for a list of C-related standards.  Many programs also assume the
21711 @uref{https://@/en.wikipedia.org/@/wiki/@/POSIX, Posix standard}.
21713 Some old code is written to be portable to K&R C, which predates any C
21714 standard.  K&R C compilers are no longer of practical interest, though,
21715 and the rest of section assumes at least C89, the first C standard.
21717 Program portability is a huge topic, and this section can only briefly
21718 introduce common pitfalls.  @xref{System Portability, , Portability
21719 between System Types, standards, The GNU Coding Standards}, for
21720 more information.
21722 @menu
21723 * Varieties of Unportability::  How to make your programs unportable
21724 * Integer Overflow::            When integers get too large
21725 * Preprocessor Arithmetic::     @code{#if} expression problems
21726 * Null Pointers::               Properties of null pointers
21727 * Buffer Overruns::             Subscript errors and the like
21728 * Volatile Objects::            @code{volatile} and signals
21729 * Floating Point Portability::  Portable floating-point arithmetic
21730 * Exiting Portably::            Exiting and the exit status
21731 @end menu
21733 @node Varieties of Unportability
21734 @section Varieties of Unportability
21735 @cindex portability
21737 Autoconf tests and ordinary programs often need to test what is allowed
21738 on a system, and therefore they may need to deliberately exceed the
21739 boundaries of what the standards allow, if only to see whether an
21740 optional feature is present.  When you write such a program, you should
21741 keep in mind the difference between constraints, unspecified behavior,
21742 and undefined behavior.
21744 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
21745 example constraint is that C programs must not declare a bit-field with
21746 negative width.  Tests can therefore reliably assume that programs with
21747 negative-width bit-fields are rejected by a compiler that conforms
21748 to the standard.
21750 @dfn{Unspecified behavior} is valid behavior, where the standard allows
21751 multiple possibilities.  For example, the order of evaluation of
21752 function arguments is unspecified.  Some unspecified behavior is
21753 @dfn{implementation-defined}, i.e., documented by the implementation,
21754 but since Autoconf tests cannot read the documentation they cannot
21755 distinguish between implementation-defined and other unspecified
21756 behavior.  It is common for Autoconf tests to probe implementations to
21757 determine otherwise-unspecified behavior.
21759 @dfn{Undefined behavior} is invalid behavior, where the standard allows
21760 the implementation to do anything it pleases.  For example,
21761 dereferencing a null pointer leads to undefined behavior.  If possible,
21762 test programs should avoid undefined behavior, since a program with
21763 undefined behavior might succeed on a test that should fail.
21765 The above rules apply to programs that are intended to conform to the
21766 standard.  However, strictly-conforming programs are quite rare, since
21767 the standards are so limiting.  A major goal of Autoconf is to support
21768 programs that use implementation features not described by the standard,
21769 and it is fairly common for test programs to violate the above rules, if
21770 the programs work well enough in practice.
21772 @node Integer Overflow
21773 @section Integer Overflow
21774 @cindex integer overflow
21775 @cindex overflow, signed integer
21776 @cindex signed integer overflow
21777 @cindex wraparound arithmetic
21779 Although some traditional C programs assume that signed integer overflow
21780 wraps around reliably using two's complement arithmetic, the C standard
21781 says that program behavior is undefined on overflow, and these C
21782 programs may not work on many modern implementations.
21784 @menu
21785 * Integer Overflow Basics::     Why integer overflow is a problem
21786 * Signed Overflow Examples::    Examples of code assuming wraparound
21787 * Optimization and Wraparound::  Optimizations that break uses of wraparound
21788 * Signed Overflow Advice::      Practical advice for signed overflow issues
21789 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
21790 @end menu
21792 @node Integer Overflow Basics
21793 @subsection Basics of Integer Overflow
21794 @cindex integer overflow
21795 @cindex overflow, signed integer
21796 @cindex signed integer overflow
21797 @cindex wraparound arithmetic
21799 In languages like C, integer overflow wraps around for unsigned
21800 integer types that are at least as wide as @code{unsigned int};
21801 e.g., @code{UINT_MAX + 1} yields zero.
21802 This is guaranteed by the C standard and is
21803 portable in practice, unless you specify aggressive,
21804 nonstandard optimization options
21805 suitable only for special applications.
21807 In contrast, the C standard says that signed integer overflow leads to
21808 undefined behavior where a program can do anything, including dumping
21809 core or overrunning a buffer.  The misbehavior can even precede the
21810 overflow.  Such an overflow can occur during addition, subtraction,
21811 multiplication, division, and left shift.  It can even occur for
21812 unsigned types like @code{unsigned short int} that are narrower
21813 than @code{int}, as values of these types are widened to @code{int}
21814 before computation.
21816 Despite this requirement of the standard, some C programs assume that
21817 signed integer overflow silently wraps around modulo a power of two,
21818 using two's complement arithmetic, so long as you convert the resulting
21819 value to a signed integer type.  These programs can have problems,
21820 especially when optimization is enabled.  If you assume a GCC-like
21821 compiler, you can work around the problems by compiling with GCC's
21822 @code{-fwrapv} option; however, this is not portable.
21824 For historical reasons the C standard also allows implementations with
21825 ones' complement or signed magnitude arithmetic, but it is safe to
21826 assume two's complement nowadays.
21828 Also, overflow can occur when converting an out-of-range value to a
21829 signed integer type.  Here a standard implementation must define what
21830 happens, and this can include raising an exception.  Although practical
21831 implementations typically wrap around silently in this case, a few
21832 debugging implementations trap instead.
21834 @node Signed Overflow Examples
21835 @subsection Examples of Code Assuming Wraparound Overflow
21836 @cindex integer overflow
21837 @cindex overflow, signed integer
21838 @cindex signed integer overflow
21839 @cindex wraparound arithmetic
21841 There was long a tension between what the C standard requires for signed
21842 integer overflow, and what traditional C programs commonly assumed.  The
21843 standard allows aggressive optimizations based on assumptions that
21844 overflow never occurs, but traditionally many C programs relied on overflow
21845 wrapping around.  Although these programs did not conform to the standard,
21846 they formerly worked in practice because traditionally compilers did not
21847 optimize in such a way that would break the programs.  Nowadays, though,
21848 compilers do perform these optimizations, so portable programs can no
21849 longer assume reliable wraparound on signed integer overflow.
21851 The C Standard says that if a program has signed integer overflow its
21852 behavior is undefined, and the undefined behavior can even precede the
21853 overflow.  To take an extreme example:
21855 @c Inspired by Robert Dewar's example in
21856 @c <https://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
21857 @example
21858 if (password == expected_password)
21859   allow_superuser_privileges ();
21860 else if (counter++ == INT_MAX)
21861   abort ();
21862 else
21863   printf ("%d password mismatches\n", counter);
21864 @end example
21866 @noindent
21867 If the @code{int} variable @code{counter} equals @code{INT_MAX},
21868 @code{counter++} must overflow and the behavior is undefined, so the C
21869 standard allows the compiler to optimize away the test against
21870 @code{INT_MAX} and the @code{abort} call.
21871 Worse, if an earlier bug in the program lets the compiler deduce that
21872 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
21873 the C standard allows the compiler to optimize away the password test
21874 and generate code that allows superuser privileges unconditionally.
21876 Here is an example derived from the 7th Edition Unix implementation of
21877 @code{atoi} (1979-01-10):
21879 @example
21880 char *p;
21881 int f, n;
21882 @dots{}
21883 while (*p >= '0' && *p <= '9')
21884   n = n * 10 + *p++ - '0';
21885 return (f ? -n : n);
21886 @end example
21888 @noindent
21889 Even if the input string is in range, on most modern machines this has
21890 signed overflow when computing the most negative integer (the @code{-n}
21891 overflows) or a value near an extreme integer (the @code{+}
21892 overflows).
21894 Here is another example, derived from the 7th Edition implementation of
21895 @code{rand} (1979-01-10).  Here the programmer expects both
21896 multiplication and addition to wrap on overflow:
21898 @example
21899 static long int randx = 1;
21900 @dots{}
21901 randx = randx * 1103515245 + 12345;
21902 return (randx >> 16) & 077777;
21903 @end example
21905 In the following example, derived from the GNU C Library 2.15
21906 implementation of @code{mktime} (2012-03-21), the code assumes
21907 wraparound arithmetic in @code{+} to detect signed overflow:
21909 @example
21910 time_t t, t1, t2;
21911 int sec_requested, sec_adjustment;
21912 @dots{}
21913 t1 = t + sec_requested;
21914 t2 = t1 + sec_adjustment;
21915 if (((t1 < t) != (sec_requested < 0))
21916     | ((t2 < t1) != (sec_adjustment < 0)))
21917   return -1;
21918 @end example
21920 Although some of these examples will likely behave as if signed integer
21921 overflow wraps around reliably, other examples are likely to misbehave
21922 when optimization is enabled.  All these examples should be avoided in
21923 portable code because signed integer overflow is not reliable on modern
21924 systems, and it's not worth worrying about which of these examples
21925 happen to work on most platforms and which do not.
21927 @node Optimization and Wraparound
21928 @subsection Optimizations That Break Wraparound Arithmetic
21929 @cindex loop induction
21931 Compilers sometimes generate code that is incompatible with wraparound
21932 integer arithmetic.  A simple example is an algebraic simplification: a
21933 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
21934 because it assumes that @code{i * 2000} does not overflow.  The
21935 translation is not equivalent to the original when overflow occurs:
21936 e.g., in the typical case of 32-bit signed two's complement wraparound
21937 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
21938 the original expression returns @minus{}2147483 but the optimized
21939 version returns the mathematically correct value 2147484.
21941 More subtly, loop induction optimizations often exploit the undefined
21942 behavior of signed overflow.  Consider the following contrived function
21943 @code{sumc}:
21945 @example
21947 sumc (int lo, int hi)
21949   int sum = 0;
21950   for (int i = lo; i <= hi; i++)
21951     sum ^= i * 53;
21952   return sum;
21954 @end example
21956 @noindent
21957 To avoid multiplying by 53 each time through the loop, an optimizing
21958 compiler might internally transform @code{sumc} to the equivalent of the
21959 following:
21961 @example
21963 transformed_sumc (int lo, int hi)
21965   int sum = 0;
21966   int hic = hi * 53;
21967   for (int ic = lo * 53; ic <= hic; ic += 53)
21968     sum ^= ic;
21969   return sum;
21971 @end example
21973 @noindent
21974 This transformation is allowed by the C standard, but it is invalid for
21975 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
21976 overflow in computing expressions like @code{hi * 53} can cause the
21977 expression @code{i <= hi} to yield a different value from the
21978 transformed expression @code{ic <= hic}.
21980 For this reason, compilers that use loop induction and similar
21981 techniques often do not support reliable wraparound arithmetic when a
21982 loop induction variable like @code{ic} is involved.  Since loop
21983 induction variables are generated by the compiler, and are not visible
21984 in the source code, it is not always trivial to say whether the problem
21985 affects your code.
21987 Hardly any code actually depends on wraparound arithmetic in cases like
21988 these, so in practice these loop induction optimizations are almost
21989 always useful.  However, edge cases in this area can cause problems.
21990 For example:
21992 @example
21993 for (int j = 1; 0 < j; j *= 2)
21994   test (j);
21995 @end example
21997 @noindent
21998 Here, the loop attempts to iterate through all powers of 2 that
21999 @code{int} can represent, but the C standard allows a compiler to
22000 optimize away the comparison and generate an infinite loop,
22001 under the argument that behavior is undefined on overflow.  As of this
22002 writing this optimization is done on some platforms by
22003 GCC with @option{-O2}, so this code is not portable in practice.
22005 @node Signed Overflow Advice
22006 @subsection Practical Advice for Signed Overflow Issues
22007 @cindex integer overflow
22008 @cindex overflow, signed integer
22009 @cindex signed integer overflow
22010 @cindex wraparound arithmetic
22012 Ideally the safest approach is to avoid signed integer overflow
22013 entirely.  For example, instead of multiplying two signed integers, you
22014 can convert them to double-width integers, multiply the wider values,
22015 then test whether the result is in the narrower range.  Or you can use
22016 more-complicated code employing unsigned integers of the same width.
22018 Rewriting code in this way will be inconvenient, though, especially if
22019 the signed values might be negative and no wider type is available.
22020 Using unsigned arithmetic to check for overflow is
22021 particularly painful to do portably and efficiently when dealing with an
22022 integer type like @code{uid_t} whose width and signedness vary from
22023 platform to platform.  Also, this approach may hurt performance.
22025 Hence it is often useful to maintain code that needs
22026 wraparound on overflow, instead of rewriting the code.  The rest of this
22027 section attempts to give practical advice for this situation.
22029 To detect integer overflow portably when attempting operations like
22030 @code{sum = a + b}, you can use the @code{intprops} module of Gnulib.
22031 @xref{Gnulib}.  For example:
22033 @example
22034 #include <intprops.h>
22036 /* Set sum = a + b, diagnosing overflow.  */
22037 if (!INT_ADD_OK (a, b, &sum))
22038   return "integer overflow detected";
22039 /* Now the code can use 'sum'.  */
22040 @end example
22042 To add two integers with overflow wrapping around reliably in the sum,
22043 you can use @code{INT_ADD_WRAPV (a, b, &sum)} instead:
22045 @example
22046 #include <intprops.h>
22048 /* Set sum = a + b, with wraparound.  */
22049 if (INT_ADD_WRAPV (a, b, &sum))
22050   /* 'sum' has just the low order bits.  */;
22051 else
22052   /* 'sum' is the correct answer.  */;
22053 @end example
22055 The @code{intprops} module supports similar macros for other arithmetic
22056 operations, e.g., @code{INT_SUBTRACT_OK} and @code{INT_MULTIPLY_WRAPV}.
22057 If your code is intended to run only on GCC 7 or later, you can instead
22058 use the GNU C primitives @code{__builtin_add_overflow},
22059 @code{__builtin_sub_overflow}, and @code{__builtin_mul_overflow}.
22060 The @code{intprops} module uses these GCC 7 primitives if available,
22061 so that the cost of invoking these macros is typically just one machine
22062 instruction for the arithmetic and another instruction for the rare
22063 branch on overflow.
22065 If your code uses a signed loop index, make sure that the index cannot
22066 overflow, along with all signed expressions derived from the index.
22067 Here is a contrived example of problematic code with two instances of
22068 overflow.
22070 @example
22071 for (int i = INT_MAX - 10; i <= INT_MAX; i++)
22072   if (i + 1 < 0)
22073     @{
22074       report_overflow ();
22075       break;
22076     @}
22077 @end example
22079 @noindent
22080 Because of the two overflows, a compiler might optimize away or
22081 transform the two comparisons in a way that is incompatible with the
22082 wraparound assumption.
22084 If your code is intended to be compiled only by GCC and
22085 assumes wraparound behavior, and you want to insulate it
22086 against any GCC optimizations that would fail to support that
22087 behavior, you should use GCC's @option{-fwrapv} option, which
22088 causes signed overflow to wrap around reliably (except for division and
22089 remainder, as discussed in the next section).
22091 If you need to write portable code and therefore cannot assume that
22092 signed integer overflow wraps around reliably, you should consider
22093 debugging with a GCC option that causes signed overflow to raise an
22094 exception.  These options include @option{-fsanitize=undefined} and
22095 @option{-ftrapv}.
22097 @node Signed Integer Division
22098 @subsection Signed Integer Division and Integer Overflow
22099 @cindex division, integer
22101 Overflow in signed
22102 integer division is not always harmless: for example, on CPUs of the
22103 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
22104 which by default terminates the program.  Worse, taking the remainder
22105 of these two values typically yields the same signal on these CPUs,
22106 behavior that the C standard allows.
22108 @node Preprocessor Arithmetic
22109 @section Preprocessor Arithmetic
22110 @cindex preprocessor arithmetic
22112 In C99 and later, preprocessor arithmetic, used for @code{#if}
22113 expressions, must
22114 be evaluated as if all signed values are of type @code{intmax_t} and all
22115 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
22116 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
22117 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
22118 @code{long long int}.  Also, some older preprocessors mishandle
22119 constants ending in @code{LL}.  To work around these problems, you can
22120 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
22121 @code{configure}-time rather than at @code{#if}-time.
22123 @node Null Pointers
22124 @section Properties of Null Pointers
22125 @cindex null pointers
22127 Most modern hosts reliably fail when you attempt to dereference a null
22128 pointer.
22130 On almost all modern hosts, null pointers use an all-bits-zero internal
22131 representation, so you can reliably use @code{memset} with 0 to set all
22132 the pointers in an array to null values.
22134 If @code{p} is a null pointer to an object type, the C expression
22135 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
22136 the standard says that it has undefined behavior.
22138 @node Buffer Overruns
22139 @section Buffer Overruns and Subscript Errors
22140 @cindex buffer overruns
22142 Buffer overruns and subscript errors are the most common dangerous
22143 errors in C programs.  They result in undefined behavior because storing
22144 outside an array typically modifies storage that is used by some other
22145 object, and most modern systems lack runtime checks to catch these
22146 errors.  Programs should not rely on buffer overruns being caught.
22148 There is one exception to the usual rule that a portable program cannot
22149 address outside an array.  In C, it is valid to compute the address just
22150 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
22151 so long as you do not dereference the resulting pointer.  But it is not
22152 valid to compute the address just before an object, e.g., @code{&a[-1]};
22153 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
22154 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
22155 reliable in general, and it is usually easy enough to avoid the
22156 potential portability problem, e.g., by allocating an extra unused array
22157 element at the start or end.
22159 @uref{https://@/www.valgrind.org/, Valgrind} can catch many overruns.
22160 GCC users might also consider using the @option{-fsanitize=} options
22161 to catch overruns.
22162 @xref{Instrumentation Options, , Program Instrumentation Options,
22163       gcc, Using the GNU Compiler Collection (GCC)}.
22165 Buffer overruns are usually caused by off-by-one errors, but there are
22166 more subtle ways to get them.
22168 Using @code{int} values to index into an array or compute array sizes
22169 causes problems on typical 64-bit hosts where an array index might
22170 be @math{2^{31}} or larger.  Index values of type @code{size_t} avoid this
22171 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
22172 are signed, and are wide enough in practice.
22174 If you add or multiply two numbers to calculate an array size, e.g.,
22175 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
22176 multiplication overflows.
22178 Many implementations of the @code{alloca} function silently misbehave
22179 and can generate buffer overflows if given sizes that are too large.
22180 The size limits are implementation dependent, but are at least 4000
22181 bytes on all platforms that we know about.
22183 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
22184 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
22185 portable code should not use them unless the inputs are known to be
22186 within certain limits.  The time-related functions can overflow their
22187 buffers if given timestamps out of range (e.g., a year less than -999
22188 or greater than 9999).  Time-related buffer overflows cannot happen with
22189 recent-enough versions of the GNU C library, but are possible
22190 with other
22191 implementations.  The @code{gets} function is the worst, since it almost
22192 invariably overflows its buffer when presented with an input line larger
22193 than the buffer.
22195 @node Volatile Objects
22196 @section Volatile Objects
22197 @cindex volatile objects
22199 The keyword @code{volatile} is often misunderstood in portable code.
22200 Its use inhibits some memory-access optimizations, but programmers often
22201 wish that it had a different meaning than it actually does.
22203 @code{volatile} was designed for code that accesses special objects like
22204 memory-mapped device registers whose contents spontaneously change.
22205 Such code is inherently low-level, and it is difficult to specify
22206 portably what @code{volatile} means in these cases.  The C standard
22207 says, ``What constitutes an access to an object that has
22208 volatile-qualified type is implementation-defined,'' so in theory each
22209 implementation is supposed to fill in the gap by documenting what
22210 @code{volatile} means for that implementation.  In practice, though,
22211 this documentation is usually absent or incomplete.
22213 One area of confusion is the distinction between objects defined with
22214 volatile types, and volatile lvalues.  From the C standard's point of
22215 view, an object defined with a volatile type has externally visible
22216 behavior.  You can think of such objects as having little oscilloscope
22217 probes attached to them, so that the user can observe some properties of
22218 accesses to them, just as the user can observe data written to output
22219 files.  However, the standard does not make it clear whether users can
22220 observe accesses by volatile lvalues to ordinary objects.  For example:
22222 @example
22223 /* Declare and access a volatile object.
22224    Accesses to X are "visible" to users.  */
22225 static int volatile x;
22226 x = 1;
22228 /* Access two ordinary objects via a volatile lvalue.
22229    It's not clear whether accesses to *P are "visible".  */
22230 int y;
22231 int *z = malloc (sizeof (int));
22232 int volatile *p;
22233 p = &y;
22234 *p = 1;
22235 p = z;
22236 *p = 1;
22237 @end example
22239 Programmers often wish that @code{volatile} meant ``Perform the memory
22240 access here and now, without merging several memory accesses, without
22241 changing the memory word size, and without reordering.''  But the C
22242 standard does not require this.  For objects defined with a volatile
22243 type, accesses must be done before the next sequence point; but
22244 otherwise merging, reordering, and word-size change is allowed.  Worse,
22245 it is not clear from the standard whether volatile lvalues provide more
22246 guarantees in general than nonvolatile lvalues, if the underlying
22247 objects are ordinary.
22249 Even when accessing objects defined with a volatile type,
22250 the C standard allows only
22251 extremely limited signal handlers: in C99 the behavior is undefined if a signal
22252 handler reads any non-local object, or writes to any non-local object
22253 whose type is not @code{sig_atomic_t volatile}, or calls any standard
22254 library function other than @code{abort}, @code{signal}, and
22255 @code{_Exit}.  Hence C compilers need not worry about a signal handler
22256 disturbing ordinary computation.  C11 and Posix allow some additional
22257 behavior in a portable signal handler, but are still quite restrictive.
22259 Some C implementations allow memory-access optimizations within each
22260 translation unit, such that actual behavior agrees with the behavior
22261 required by the standard only when calling a function in some other
22262 translation unit, and a signal handler acts like it was called from a
22263 different translation unit.  The C99 standard hints that in these
22264 implementations, objects referred to by signal handlers ``would require
22265 explicit specification of @code{volatile} storage, as well as other
22266 implementation-defined restrictions.''  But unfortunately even for this
22267 special case these other restrictions are often not documented well.
22268 This area was significantly changed in C11, and eventually implementations
22269 will probably head in the C11 direction, but this will take some time.
22270 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
22271 GNU Compiler Collection (GCC)}, for some
22272 restrictions imposed by GCC.  @xref{Defining Handlers, ,
22273 Defining Signal Handlers, libc, The GNU C Library}, for some
22274 restrictions imposed by the GNU C library.  Restrictions
22275 differ on other platforms.
22277 If possible, it is best to use a signal handler that fits within the
22278 limits imposed by the C and Posix standards.
22280 If this is not practical, you can try the following rules of thumb.  A
22281 signal handler should access only volatile lvalues, preferably lvalues
22282 that refer to objects defined with a volatile type, and should not
22283 assume that the accessed objects have an internally consistent state
22284 if they are larger than a machine word.  Furthermore, installers
22285 should employ compilers and compiler options that are commonly used
22286 for building operating system kernels, because kernels often need more
22287 from @code{volatile} than the C Standard requires, and installers who
22288 compile an application in a similar environment can sometimes benefit
22289 from the extra constraints imposed by kernels on compilers.
22290 Admittedly we are hand-waving somewhat here, as there are few
22291 guarantees in this area; the rules of thumb may help to fix some bugs
22292 but there is a good chance that they will not fix them all.
22294 For @code{volatile}, C++ has the same problems that C does.
22295 Multithreaded applications have even more problems with @code{volatile},
22296 but they are beyond the scope of this section.
22298 The bottom line is that using @code{volatile} typically hurts
22299 performance but should not hurt correctness.  In some cases its use
22300 does help correctness, but these cases are often so poorly understood
22301 that all too often adding @code{volatile} to a data structure merely
22302 alleviates some symptoms of a bug while not fixing the bug in general.
22304 @node Floating Point Portability
22305 @section Floating Point Portability
22306 @cindex floating point
22308 Almost all modern systems use IEEE-754 floating point, and it is safe to
22309 assume IEEE-754 in most portable code these days.  For more information,
22310 please see David Goldberg's classic paper
22311 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
22312 Scientist Should Know About Floating-Point Arithmetic}.
22314 @node Exiting Portably
22315 @section Exiting Portably
22316 @cindex exiting portably
22318 A C or C++ program can exit with status @var{N} by returning
22319 @var{N} from the @code{main} function.  Portable programs are supposed
22320 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
22321 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
22322 fail by exiting with status 1, and test programs that assume Posix can
22323 fail by exiting with status values from 1 through 255.  Programs on
22324 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
22325 status when @code{main} returned nonzero, but ancient systems like these
22326 are no longer of practical concern.
22328 A program can also exit with status @var{N} by passing @var{N} to the
22329 @code{exit} function, and a program can fail by calling the @code{abort}
22330 function.  If a program is specialized to just some platforms, it can fail
22331 by calling functions specific to those platforms, e.g., @code{_exit}
22332 (Posix).  However, like other functions, an exit
22333 function should be declared, typically by including a header.  For
22334 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
22335 either directly or via the default includes (@pxref{Default Includes}).
22337 A program can fail due to undefined behavior such as dereferencing a null
22338 pointer, but this is not recommended as undefined behavior allows an
22339 implementation to do whatever it pleases and this includes exiting
22340 successfully.
22343 @c ================================================== Manual Configuration
22345 @node Manual Configuration
22346 @chapter Manual Configuration
22348 A few kinds of features can't be guessed automatically by running test
22349 programs.  For example, the details of the object-file format, or
22350 special options that need to be passed to the compiler or linker.
22351 Autoconf provides a uniform method for handling unguessable features,
22352 by giving each operating system a @dfn{canonical system type}, also
22353 known as a @dfn{canonical name} or @dfn{target triplet}.
22355 @prindex @command{config.guess}
22356 @prindex @command{config.sub}
22358 If you use any of the macros described in this chapter, you must
22359 distribute the helper scripts @command{config.guess} and
22360 @command{config.sub} along with your source code.  Some Autoconf macros
22361 use these macros internally, so you may need to distribute these scripts
22362 even if you do not use any of these macros yourself.  @xref{Input}, for
22363 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
22364 to control in which directory @command{configure} looks for helper
22365 scripts, and where to get the scripts from.
22367 @menu
22368 * Specifying Target Triplets::  Specifying target triplets
22369 * Canonicalizing::              Getting the canonical system type
22370 * Using System Type::           What to do with the system type
22371 @end menu
22373 @node Specifying Target Triplets
22374 @section Specifying target triplets
22375 @cindex System type
22376 @cindex Target triplet
22377 @c This node used to be named Specifying Names.  The @anchor allows old
22378 @c links to still work.
22379 @anchor{Specifying Names}
22381 Autoconf-generated
22382 @command{configure} scripts can make decisions based on a canonical name
22383 for the system type, or @dfn{target triplet}, which has the form:
22384 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
22385 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
22387 @command{configure} can usually guess the canonical name for the type of
22388 system it's running on.  To do so it runs a script called
22389 @command{config.guess}, which infers the name using the @code{uname}
22390 command or symbols predefined by the C preprocessor.
22392 Alternately, the user can specify the system type with command line
22393 arguments to @command{configure} (@pxref{System Type}.  Doing so is
22394 necessary when
22395 cross-compiling.  In the most complex case of cross-compiling, three
22396 system types are involved.  The options to specify them are:
22398 @table @option
22399 @item --build=@var{build-type}
22400 the type of system on which the package is being configured and
22401 compiled.  It defaults to the result of running @command{config.guess}.
22402 Specifying a @var{build-type} that differs from @var{host-type} enables
22403 cross-compilation mode.
22405 @item --host=@var{host-type}
22406 the type of system on which the package runs.  By default it is the
22407 same as the build machine.  The tools that get used to build and
22408 manipulate binaries will, by default, all be prefixed with
22409 @code{@var{host-type}-}, such as @code{@var{host-type}-gcc},
22410 @code{@var{host-type}-g++}, @code{@var{host-type}-ar}, and
22411 @code{@var{host-type}-nm}.  If the binaries produced by these tools can
22412 be executed by the build system, the configure script will make use of
22413 it in @code{AC_RUN_IFELSE} invocations; otherwise, cross-compilation
22414 mode is enabled.  Specifying a @var{host-type} that differs
22415 from @var{build-type}, when @var{build-type} was also explicitly
22416 specified, equally enables cross-compilation mode.
22418 @item --target=@var{target-type}
22419 the type of system for which any compiler tools in the package
22420 produce code (rarely needed).  By default, it is the same as host.
22421 @end table
22423 If you mean to override the result of @command{config.guess} but
22424 still produce binaries for the build machine, use @option{--build},
22425 not @option{--host}.
22427 So, for example, to produce binaries for 64-bit MinGW, use a command
22428 like this:
22430 @example
22431 ./configure --host=x86_64-w64-mingw64
22432 @end example
22434 If your system has the ability to execute MinGW binaries but you don't
22435 want to make use of this feature and instead prefer cross-compilation
22436 guesses, use a command like this:
22438 @example
22439 ./configure --build=x86_64-pc-linux-gnu --host=x86_64-w64-mingw64
22440 @end example
22442 @noindent
22443 Note that if you do not specify @option{--host}, @command{configure}
22444 fails if it can't run the code generated by the specified compiler.  For
22445 example, configuring as follows fails:
22447 @example
22448 ./configure CC=x86_64-w64-mingw64-gcc
22449 @end example
22451 When cross-compiling, @command{configure} will warn about any tools
22452 (compilers, linkers, assemblers) whose name is not prefixed with the
22453 host type.  This is an aid to users performing cross-compilation.
22454 Continuing the example above, if a cross-compiler named @command{cc} is
22455 used with a native @command{pkg-config}, then libraries found by
22456 @command{pkg-config} will likely cause subtle build failures; but using
22457 the names @command{x86_64-w64-mingw64-gcc} and
22458 @command{x86_64-w64-mingw64-pkg-config}
22459 avoids any confusion.  Avoiding the warning is as simple as creating the
22460 correct symlinks naming the cross tools.
22462 @cindex @command{config.sub}
22463 @command{configure} recognizes short aliases for many system types; for
22464 example, @samp{decstation} can be used instead of
22465 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
22466 @command{config.sub} to canonicalize system type aliases.
22468 This section deliberately omits the description of the obsolete
22469 interface; see @ref{Hosts and Cross-Compilation}.
22472 @node Canonicalizing
22473 @section Getting the Canonical System Type
22474 @cindex System type
22475 @cindex Canonical system type
22477 The following macros make the system type available to @command{configure}
22478 scripts.
22480 @ovindex build_alias
22481 @ovindex host_alias
22482 @ovindex target_alias
22484 The variables @samp{build_alias}, @samp{host_alias}, and
22485 @samp{target_alias} are always exactly the arguments of @option{--build},
22486 @option{--host}, and @option{--target}; in particular, they are left empty
22487 if the user did not use them, even if the corresponding
22488 @code{AC_CANONICAL} macro was run.  Any configure script may use these
22489 variables anywhere.  These are the variables that should be used when in
22490 interaction with the user.
22492 If you need to recognize some special environments based on their system
22493 type, run the following macros to get canonical system names.  These
22494 variables are not set before the macro call.
22496 @defmac AC_CANONICAL_BUILD
22497 @acindex{CANONICAL_BUILD}
22498 @ovindex build
22499 @ovindex build_cpu
22500 @ovindex build_vendor
22501 @ovindex build_os
22502 Compute the canonical build-system type variable, @code{build}, and its
22503 three individual parts @code{build_cpu}, @code{build_vendor}, and
22504 @code{build_os}.
22506 If @option{--build} was specified, then @code{build} is the
22507 canonicalization of @code{build_alias} by @command{config.sub},
22508 otherwise it is determined by the shell script @command{config.guess}.
22509 @end defmac
22511 @defmac AC_CANONICAL_HOST
22512 @acindex{CANONICAL_HOST}
22513 @ovindex host
22514 @ovindex host_cpu
22515 @ovindex host_vendor
22516 @ovindex host_os
22517 Compute the canonical host-system type variable, @code{host}, and its
22518 three individual parts @code{host_cpu}, @code{host_vendor}, and
22519 @code{host_os}.
22521 If @option{--host} was specified, then @code{host} is the
22522 canonicalization of @code{host_alias} by @command{config.sub},
22523 otherwise it defaults to @code{build}.
22524 @end defmac
22526 @defmac AC_CANONICAL_TARGET
22527 @acindex{CANONICAL_TARGET}
22528 @ovindex target
22529 @ovindex target_cpu
22530 @ovindex target_vendor
22531 @ovindex target_os
22532 Compute the canonical target-system type variable, @code{target}, and its
22533 three individual parts @code{target_cpu}, @code{target_vendor}, and
22534 @code{target_os}.
22536 If @option{--target} was specified, then @code{target} is the
22537 canonicalization of @code{target_alias} by @command{config.sub},
22538 otherwise it defaults to @code{host}.
22539 @end defmac
22541 Note that there can be artifacts due to the backward compatibility
22542 code.  @xref{Hosts and Cross-Compilation}, for more.
22544 @node Using System Type
22545 @section Using the System Type
22547 In @file{configure.ac} the system type is generally used by one or more
22548 @code{case} statements to select system-specifics.  Shell wildcards can
22549 be used to match a group of system types.
22551 For example, an extra assembler code object file could be chosen, giving
22552 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
22553 following would be used in a makefile to add the object to a
22554 program or library.
22556 @example
22557 AS_CASE([$host],
22558   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
22559   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
22560   [CYCLE_OBJ=""]
22562 AC_SUBST([CYCLE_OBJ])
22563 @end example
22565 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
22566 to select variant source files, for example optimized code for some
22567 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
22568 so some runtime capability checks may be necessary too.
22570 @example
22571 case $host in
22572   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
22573   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
22574   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
22575 esac
22576 @end example
22578 The host system type can also be used to find cross-compilation tools
22579 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
22581 The above examples all show @samp{$host}, since this is where the code
22582 is going to run.  Only rarely is it necessary to test @samp{$build}
22583 (which is where the build is being done).
22585 Whenever you're tempted to use @samp{$host} it's worth considering
22586 whether some sort of probe would be better.  New system types come along
22587 periodically or previously missing features are added.  Well-written
22588 probes can adapt themselves to such things, but hard-coded lists of
22589 names can't.  Here are some guidelines,
22591 @itemize @bullet
22592 @item
22593 Availability of libraries and library functions should always be checked
22594 by probing.
22595 @item
22596 Variant behavior of system calls is best identified with runtime tests
22597 if possible, but bug workarounds or obscure difficulties might have to
22598 be driven from @samp{$host}.
22599 @item
22600 Assembler code is inevitably highly CPU-specific and is best selected
22601 according to @samp{$host_cpu}.
22602 @item
22603 Assembler variations like underscore prefix on globals or ELF versus
22604 COFF type directives are however best determined by probing, perhaps
22605 even examining the compiler output.
22606 @end itemize
22608 @samp{$target} is for use by a package creating a compiler or similar.
22609 For ordinary packages it's meaningless and should not be used.  It
22610 indicates what the created compiler should generate code for, if it can
22611 cross-compile.  @samp{$target} generally selects various hard-coded CPU
22612 and system conventions, since usually the compiler or tools under
22613 construction themselves determine how the target works.
22616 @c ===================================================== Site Configuration.
22618 @node Site Configuration
22619 @chapter Site Configuration
22621 @command{configure} scripts support several kinds of local configuration
22622 decisions.  There are ways for users to specify where external software
22623 packages are, include or exclude optional features, install programs
22624 under modified names, and set default values for @command{configure}
22625 options.
22627 @menu
22628 * Help Formatting::             Customizing @samp{configure --help}
22629 * External Software::           Working with other optional software
22630 * Package Options::             Selecting optional features
22631 * Pretty Help Strings::         Formatting help string
22632 * Option Checking::             Controlling checking of @command{configure} options
22633 * Site Details::                Configuring site details
22634 * Transforming Names::          Changing program names when installing
22635 * Site Defaults::               Giving @command{configure} local defaults
22636 @end menu
22638 @node Help Formatting
22639 @section Controlling Help Output
22641 Users consult @samp{configure --help} to learn of configuration
22642 decisions specific to your package.  By default, @command{configure}
22643 breaks this output into sections for each type of option; within each
22644 section, help strings appear in the order @file{configure.ac} defines
22645 them:
22647 @example
22648 Optional Features:
22649   @dots{}
22650   --enable-bar            include bar
22652 Optional Packages:
22653   @dots{}
22654   --with-foo              use foo
22655 @end example
22657 @defmac AC_PRESERVE_HELP_ORDER
22658 @acindex{PRESERVE_HELP_ORDER}
22660 Request an alternate @option{--help} format, in which options of all
22661 types appear together, in the order defined.  Call this macro before any
22662 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
22664 @example
22665 Optional Features and Packages:
22666   @dots{}
22667   --enable-bar            include bar
22668   --with-foo              use foo
22669 @end example
22671 @end defmac
22673 @node External Software
22674 @section Working With External Software
22675 @cindex External software
22677 Some packages require, or can optionally use, other software packages
22678 that are already installed.  The user can give @command{configure}
22679 command line options to specify which such external software to use.
22680 The options have one of these forms:
22682 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22683 @c awful.
22684 @example
22685 --with-@var{package}@r{[}=@var{arg}@r{]}
22686 --without-@var{package}
22687 @end example
22689 For example, @option{--with-gnu-ld} means work with the GNU linker
22690 instead of some other linker.  @option{--with-x} means work with The X
22691 Window System.
22693 The user can give an argument by following the package name with
22694 @samp{=} and the argument.  Giving an argument of @samp{no} is for
22695 packages that are used by default; it says to @emph{not} use the
22696 package.  An argument that is neither @samp{yes} nor @samp{no} could
22697 include a name or number of a version of the other package, to specify
22698 more precisely which other package this program is supposed to work
22699 with.  If no argument is given, it defaults to @samp{yes}.
22700 @option{--without-@var{package}} is equivalent to
22701 @option{--with-@var{package}=no}.
22703 Normally @command{configure} scripts complain about
22704 @option{--with-@var{package}} options that they do not support.
22705 @xref{Option Checking}, for details, and for how to override the
22706 defaults.
22708 For each external software package that may be used, @file{configure.ac}
22709 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
22710 user asked to use it.  Whether each package is used or not by default,
22711 and which arguments are valid, is up to you.
22713 @anchor{AC_ARG_WITH}
22714 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
22715   @ovar{action-if-given}, @ovar{action-if-not-given})
22716 @acindex{ARG_WITH}
22717 If the user gave @command{configure} the option @option{--with-@var{package}}
22718 or @option{--without-@var{package}}, run shell commands
22719 @var{action-if-given}.  If neither option was given, run shell commands
22720 @var{action-if-not-given}.  The name @var{package} indicates another
22721 software package that this program should work with.  It should consist
22722 only of alphanumeric characters, dashes, plus signs, and dots.
22724 The option's argument is available to the shell commands
22725 @var{action-if-given} in the shell variable @code{withval}, which is
22726 actually just the value of the shell variable named
22727 @code{with_@var{package}}, with any non-alphanumeric characters in
22728 @var{package} changed into @samp{_}.  You may use that variable instead,
22729 if you wish.
22731 Note that @var{action-if-not-given} is not expanded until the point that
22732 @code{AC_ARG_WITH} was expanded.  If you need the value of
22733 @code{with_@var{package}} set to a default value by the time argument
22734 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22735 diversion (@pxref{m4_divert_text}) (if done as an argument to
22736 @code{AC_ARG_WITH}, also provide non-diverted text to avoid a shell
22737 syntax error).
22739 The argument @var{help-string} is a description of the option that
22740 looks like this:
22741 @example
22742   --with-readline         support fancy command line editing
22743 @end example
22745 @noindent
22746 @var{help-string} may be more than one line long, if more detail is
22747 needed.  Just make sure the columns line up in @samp{configure
22748 --help}.  Avoid tabs in the help string.  The easiest way to provide the
22749 proper leading whitespace is to format your @var{help-string} with the macro
22750 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22752 The following example shows how to use the @code{AC_ARG_WITH} macro in
22753 a common situation.  You want to let the user decide whether to enable
22754 support for an external library (e.g., the readline library); if the user
22755 specified neither @option{--with-readline} nor @option{--without-readline},
22756 you want to enable support for readline only if the library is available
22757 on the system.
22759 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22760 @example
22761 AC_ARG_WITH([readline],
22762   [AS_HELP_STRING([--with-readline],
22763     [support fancy command line editing @@<:@@default=check@@:>@@])],
22764   [],
22765   [: m4_divert_text([DEFAULTS], [with_readline=check])])
22767 LIBREADLINE=
22768 AS_IF([test "x$with_readline" != xno],
22769   [AC_CHECK_LIB([readline], [main],
22770     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22771      AC_DEFINE([HAVE_LIBREADLINE], [1],
22772                [Define if you have libreadline])
22773     ],
22774     [if test "x$with_readline" != xcheck; then
22775        AC_MSG_FAILURE(
22776          [--with-readline was given, but test for readline failed])
22777      fi
22778     ], -lncurses)])
22779 @end example
22781 The next example shows how to use @code{AC_ARG_WITH} to give the user the
22782 possibility to enable support for the readline library, in case it is still
22783 experimental and not well tested, and is therefore disabled by default.
22785 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22786 @example
22787 AC_ARG_WITH([readline],
22788   [AS_HELP_STRING([--with-readline],
22789     [enable experimental support for readline])],
22790   [],
22791   [with_readline=no])
22793 LIBREADLINE=
22794 AS_IF([test "x$with_readline" != xno],
22795   [AC_CHECK_LIB([readline], [main],
22796     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22797      AC_DEFINE([HAVE_LIBREADLINE], [1],
22798                [Define if you have libreadline])
22799     ],
22800     [AC_MSG_FAILURE(
22801        [--with-readline was given, but test for readline failed])],
22802     [-lncurses])])
22803 @end example
22805 The last example shows how to use @code{AC_ARG_WITH} to give the user the
22806 possibility to disable support for the readline library, given that it is
22807 an important feature and that it should be enabled by default.
22809 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within 'if' is solved.
22810 @example
22811 AC_ARG_WITH([readline],
22812   [AS_HELP_STRING([--without-readline],
22813     [disable support for readline])],
22814   [],
22815   [with_readline=yes])
22817 LIBREADLINE=
22818 AS_IF([test "x$with_readline" != xno],
22819   [AC_CHECK_LIB([readline], [main],
22820     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22821      AC_DEFINE([HAVE_LIBREADLINE], [1],
22822                [Define if you have libreadline])
22823     ],
22824     [AC_MSG_FAILURE(
22825        [readline test failed (--without-readline to disable)])],
22826     [-lncurses])])
22827 @end example
22829 These three examples can be easily adapted to the case where
22830 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
22831 @ref{Package Options}).
22832 @end defmac
22834 @node Package Options
22835 @section Choosing Package Options
22836 @cindex Package options
22837 @cindex Options, package
22839 If a software package has optional compile-time features, the user can
22840 give @command{configure} command line options to specify whether to
22841 compile them.  The options have one of these forms:
22843 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22844 @c awful.
22845 @example
22846 --enable-@var{feature}@r{[}=@var{arg}@r{]}
22847 --disable-@var{feature}
22848 @end example
22850 These options allow users to choose which optional features to build and
22851 install.  @option{--enable-@var{feature}} options should never make a
22852 feature behave differently or cause one feature to replace another.
22853 They should only cause parts of the program to be built rather than left
22854 out.
22856 The user can give an argument by following the feature name with
22857 @samp{=} and the argument.  Giving an argument of @samp{no} requests
22858 that the feature @emph{not} be made available.  A feature with an
22859 argument looks like @option{--enable-debug=stabs}.  If no argument is
22860 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
22861 equivalent to @option{--enable-@var{feature}=no}.
22863 Normally @command{configure} scripts complain about
22864 @option{--enable-@var{package}} options that they do not support.
22865 @xref{Option Checking}, for details, and for how to override the
22866 defaults.
22868 For each optional feature, @file{configure.ac} should call
22869 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
22870 to include it.  Whether each feature is included or not by default, and
22871 which arguments are valid, is up to you.
22873 @anchor{AC_ARG_ENABLE}
22874 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
22875   @ovar{action-if-given}, @ovar{action-if-not-given})
22876 @acindex{ARG_ENABLE}
22877 If the user gave @command{configure} the option
22878 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
22879 shell commands @var{action-if-given}.  If neither option was given, run
22880 shell commands @var{action-if-not-given}.  The name @var{feature}
22881 indicates an optional user-level facility.  It should consist only of
22882 alphanumeric characters, dashes, plus signs, and dots.
22884 The option's argument is available to the shell commands
22885 @var{action-if-given} in the shell variable @code{enableval}, which is
22886 actually just the value of the shell variable named
22887 @code{enable_@var{feature}}, with any non-alphanumeric characters in
22888 @var{feature} changed into @samp{_}.  You may use that variable instead,
22889 if you wish.  The @var{help-string} argument is like that of
22890 @code{AC_ARG_WITH} (@pxref{External Software}).
22892 Note that @var{action-if-not-given} is not expanded until the point that
22893 @code{AC_ARG_ENABLE} was expanded.  If you need the value of
22894 @code{enable_@var{feature}} set to a default value by the time argument
22895 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22896 diversion (@pxref{m4_divert_text}) (if done as an argument to
22897 @code{AC_ARG_ENABLE}, also provide non-diverted text to avoid a shell
22898 syntax error).
22900 You should format your @var{help-string} with the macro
22901 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22903 See the examples suggested with the definition of @code{AC_ARG_WITH}
22904 (@pxref{External Software}) to get an idea of possible applications of
22905 @code{AC_ARG_ENABLE}.
22906 @end defmac
22908 @node Pretty Help Strings
22909 @section Making Your Help Strings Look Pretty
22910 @cindex Help strings
22912 Properly formatting the @samp{help strings} which are used in
22913 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
22914 (@pxref{Package Options}) can be challenging.  Specifically, you want
22915 your own @samp{help strings} to line up in the appropriate columns of
22916 @samp{configure --help} just like the standard Autoconf @samp{help
22917 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
22919 @anchor{AS_HELP_STRING}
22920 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
22921   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
22922 @asindex{HELP_STRING}
22924 Expands into a help string that looks pretty when the user executes
22925 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
22926 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
22927 Options}).  The following example makes this clearer.
22929 @example
22930 AC_ARG_WITH([foo],
22931   [AS_HELP_STRING([--with-foo],
22932      [use foo (default is no)])],
22933   [use_foo=$withval],
22934   [use_foo=no])
22935 @end example
22937 Then the last few lines of @samp{configure --help} appear like
22938 this:
22940 @example
22941 --enable and --with options recognized:
22942   --with-foo              use foo (default is no)
22943 @end example
22945 Macro expansion is performed on the first argument.  However, the second
22946 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
22947 list of text to be reformatted, and is not subject to macro expansion.
22948 Since it is not expanded, it should not be double quoted.
22949 @xref{Autoconf Language}, for a more detailed explanation.
22951 The @code{AS_HELP_STRING} macro is particularly helpful when the
22952 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
22953 arguments, as shown in the following example.  Be aware that
22954 @var{left-hand-side} may not expand to unbalanced quotes,
22955 although quadrigraphs can be used.
22957 @example
22958 AC_DEFUN([MY_ARG_WITH],
22959   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
22960      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
22961                      [use $1 (default is $2)])],
22962      [use_[]$1=$withval],
22963      [use_[]$1=$2])])
22964 MY_ARG_WITH([a_b], [no])
22965 @end example
22966 @noindent
22967 Here, the last few lines of @samp{configure --help} will include:
22969 @example
22970 --enable and --with options recognized:
22971   --with-a-b              use a_b (default is no)
22972 @end example
22974 The parameters @var{indent-column} and @var{wrap-column} were introduced
22975 in Autoconf 2.62.  Generally, they should not be specified; they exist
22976 for fine-tuning of the wrapping.
22977 @example
22978 AS_HELP_STRING([--option], [description of option])
22979 @result{}  --option                description of option
22980 AS_HELP_STRING([--option], [description of option], [15], [30])
22981 @result{}  --option     description of
22982 @result{}               option
22983 @end example
22984 @end defmac
22987 @node Option Checking
22988 @section Controlling Checking of @command{configure} Options
22989 @cindex Options, Package
22991 The @command{configure} script checks its command-line options against a
22992 list of known options, like @option{--help} or @option{--config-cache}.
22993 An unknown option ordinarily indicates a mistake by the user and
22994 @command{configure} halts with an error.  However, by default unknown
22995 @option{--with-@var{package}} and @option{--enable-@var{feature}}
22996 options elicit only a warning, to support configuring entire source
22997 trees.
22999 Source trees often contain multiple packages with a top-level
23000 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
23001 (@pxref{Subdirectories}).  Because the packages generally support
23002 different @option{--with-@var{package}} and
23003 @option{--enable-@var{feature}} options, the GNU Coding
23004 Standards say they must accept unrecognized options without halting.
23005 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
23006 automatically disables the warnings.
23008 This default behavior may be modified in two ways.  First, the installer
23009 can invoke @code{configure --disable-option-checking} to disable
23010 these warnings, or invoke @code{configure --enable-option-checking=fatal}
23011 options to turn them into fatal errors, respectively.  Second, the
23012 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
23014 @defmac AC_DISABLE_OPTION_CHECKING
23015 @acindex{DISABLE_OPTION_CHECKING}
23017 By default, disable warnings related to any unrecognized
23018 @option{--with-@var{package}} or @option{--enable-@var{feature}}
23019 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
23021 The installer can override this behavior by passing
23022 @option{--enable-option-checking} (enable warnings) or
23023 @option{--enable-option-checking=fatal} (enable errors) to
23024 @command{configure}.
23025 @end defmac
23028 @node Site Details
23029 @section Configuring Site Details
23030 @cindex Site details
23032 Some software packages require complex site-specific information.  Some
23033 examples are host names to use for certain services, company names, and
23034 email addresses to contact.  Since some configuration scripts generated
23035 by Metaconfig ask for such information interactively, people sometimes
23036 wonder how to get that information in Autoconf-generated configuration
23037 scripts, which aren't interactive.
23039 Such site configuration information should be put in a file that is
23040 edited @emph{only by users}, not by programs.  The location of the file
23041 can either be based on the @code{prefix} variable, or be a standard
23042 location such as the user's home directory.  It could even be specified
23043 by an environment variable.  The programs should examine that file at
23044 runtime, rather than at compile time.  Runtime configuration is more
23045 convenient for users and makes the configuration process simpler than
23046 getting the information while configuring.  @xref{Directory Variables, ,
23047 Variables for Installation Directories, standards, The GNU Coding
23048 Standards}, for more information on where to put data files.
23050 @node Transforming Names
23051 @section Transforming Program Names When Installing
23052 @cindex Transforming program names
23053 @cindex Program names, transforming
23055 Autoconf supports changing the names of programs when installing them.
23056 In order to use these transformations, @file{configure.ac} must call the
23057 macro @code{AC_ARG_PROGRAM}.
23059 @defmac AC_ARG_PROGRAM
23060 @acindex{ARG_PROGRAM}
23061 @ovindex program_transform_name
23062 Place in output variable @code{program_transform_name} a sequence of
23063 @code{sed} commands for changing the names of installed programs.
23065 If any of the options described below are given to @command{configure},
23066 program names are transformed accordingly.  Otherwise, if
23067 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
23068 is given, the target type followed by a dash is used as a prefix.
23069 Otherwise, no program name transformation is done.
23070 @end defmac
23072 @menu
23073 * Transformation Options::      @command{configure} options to transform names
23074 * Transformation Examples::     Sample uses of transforming names
23075 * Transformation Rules::        Makefile uses of transforming names
23076 @end menu
23078 @node Transformation Options
23079 @subsection Transformation Options
23081 You can specify name transformations by giving @command{configure} these
23082 command line options:
23084 @table @option
23085 @item --program-prefix=@var{prefix}
23086 prepend @var{prefix} to the names;
23088 @item --program-suffix=@var{suffix}
23089 append @var{suffix} to the names;
23091 @item --program-transform-name=@var{expression}
23092 perform @code{sed} substitution @var{expression} on the names.
23093 @end table
23095 @node Transformation Examples
23096 @subsection Transformation Examples
23098 These transformations are useful with programs that can be part of a
23099 cross-compilation development environment.  For example, a
23100 cross-assembler running on x86-64 configured with
23101 @option{--target=aarch64-linux-gnu} is normally installed as
23102 @file{aarch64-linux-gnu-as}, rather than @file{as}, which could be confused
23103 with a native x86-64 assembler.
23105 You can force a program name to begin with @file{g}, if you don't want
23106 GNU programs installed on your system to shadow other programs with
23107 the same name.  For example, if you configure GNU @code{diff} with
23108 @option{--program-prefix=g}, then when you run @samp{make install} it is
23109 installed as @file{/usr/local/bin/gdiff}.
23111 As a more sophisticated example, you could use
23113 @example
23114 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
23115 @end example
23116 @noindent
23118 to prepend @samp{g} to most of the program names in a source tree,
23119 excepting those like @code{gdb} that already have one and those like
23120 @code{less} and @code{lesskey} that aren't GNU programs.  (That is
23121 assuming that you have a source tree containing those programs that is
23122 set up to use this feature.)
23124 One way to install multiple versions of some programs simultaneously is
23125 to append a version number to the name of one or both.  For example, if
23126 you want to keep Autoconf version 1 around for awhile, you can configure
23127 Autoconf version 2 using @option{--program-suffix=2} to install the
23128 programs as @file{/usr/local/bin/autoconf2},
23129 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
23130 that only the binaries are renamed, therefore you'd have problems with
23131 the library files which might overlap.
23133 @node Transformation Rules
23134 @subsection Transformation Rules
23136 Here is how to use the variable @code{program_transform_name} in a
23137 @file{Makefile.in}:
23139 @example
23140 PROGRAMS = cp ls rm
23141 transform = @@program_transform_name@@
23142 install:
23143         for p in $(PROGRAMS); do \
23144           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
23145                                               sed '$(transform)'`; \
23146         done
23148 uninstall:
23149         for p in $(PROGRAMS); do \
23150           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
23151 @c $$ restore font-lock
23152         done
23153 @end example
23155 It is guaranteed that @code{program_transform_name} is never empty, and
23156 that there are no useless separators.  Therefore you may safely embed
23157 @code{program_transform_name} within a sed program using @samp{;}:
23159 @example
23160 transform = @@program_transform_name@@
23161 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
23162 @end example
23164 Whether to do the transformations on documentation files (Texinfo or
23165 @code{man}) is a tricky question; there seems to be no perfect answer,
23166 due to the several reasons for name transforming.  Documentation is not
23167 usually particular to a specific architecture, and Texinfo files do not
23168 conflict with system documentation.  But they might conflict with
23169 earlier versions of the same files, and @code{man} pages sometimes do
23170 conflict with system documentation.  As a compromise, it is probably
23171 best to do name transformations on @code{man} pages but not on Texinfo
23172 manuals.
23174 @node Site Defaults
23175 @section Setting Site Defaults
23176 @cindex Site defaults
23177 @cindex config.site
23179 Autoconf-generated @command{configure} scripts allow your site to provide
23180 default values for some configuration values.  You do this by creating
23181 site- and system-wide initialization files.
23183 @evindex CONFIG_SITE
23184 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
23185 uses its value as a space-separated list of shell scripts to read;
23186 it is recommended that these be absolute file names.  Otherwise, it
23187 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
23188 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
23189 settings in machine-specific files override those in machine-independent
23190 ones in case of conflict.
23192 Site files can be arbitrary shell scripts, but only certain kinds of
23193 code are really appropriate to be in them.  Because @command{configure}
23194 reads any cache file after it has read any site files, a site file can
23195 define a default cache file to be shared between all Autoconf-generated
23196 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
23197 you set a default cache file in a site file, it is a good idea to also
23198 set the output variable @code{CC} in that site file, because the cache
23199 file is only valid for a particular compiler, but many systems have
23200 several available.
23202 You can examine or override the value set by a command line option to
23203 @command{configure} in a site file; options set shell variables that have
23204 the same names as the options, with any dashes turned into underscores.
23205 The exceptions are that @option{--without-} and @option{--disable-} options
23206 are like giving the corresponding @option{--with-} or @option{--enable-}
23207 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
23208 sets the variable @code{cache_file} to the value @samp{localcache};
23209 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
23210 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
23211 variable @code{prefix} to the value @samp{/usr}; etc.
23213 Site files are also good places to set default values for other output
23214 variables, such as @code{CFLAGS}, if you need to give them non-default
23215 values: anything you would normally do, repetitively, on the command
23216 line.  If you use non-default values for @var{prefix} or
23217 @var{exec_prefix} (wherever you locate the site file), you can set them
23218 in the site file if you specify it with the @code{CONFIG_SITE}
23219 environment variable.
23221 You can set some cache values in the site file itself.  Doing this is
23222 useful if you are cross-compiling, where it is impossible to check features
23223 that require running a test program.  You could ``prime the cache'' by
23224 setting those values correctly for that system in
23225 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
23226 variables you need to set, see the documentation of the respective
23227 Autoconf macro.  If the variables or their semantics are undocumented,
23228 you may need to look for shell variables with @samp{_cv_} in their names
23229 in the affected @command{configure} scripts, or in the Autoconf M4
23230 source code for those macros; but in that case, their name or semantics
23231 may change in a future Autoconf version.
23233 The cache file is careful to not override any variables set in the site
23234 files.  Similarly, you should not override command-line options in the
23235 site files.  Your code should check that variables such as @code{prefix}
23236 and @code{cache_file} have their default values (as set near the top of
23237 @command{configure}) before changing them.
23239 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
23240 command @samp{configure --prefix=/usr/share/local/gnu} would read this
23241 file (if @code{CONFIG_SITE} is not set to a different file).
23243 @example
23244 # /usr/share/local/gnu/share/config.site for configure
23246 # Change some defaults.
23247 test "$prefix" = NONE && prefix=/usr/share/local/gnu
23248 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
23249 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
23250 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
23251 test "$runstatedir" = '$@{localstatedir@}/run' && runstatedir=/run
23253 # Give Autoconf 2.x generated configure scripts a shared default
23254 # cache file for feature test results, architecture-specific.
23255 if test "$cache_file" = /dev/null; then
23256   cache_file="$prefix/var/config.cache"
23257   # A cache file is only valid for one C compiler.
23258   CC=gcc
23260 @end example
23262 @c Leave this use of "File system" rendered as one word, but
23263 @c slightly obfuscated so as not to trigger the syntax-check prohibition.
23264 @cindex File@/system Hierarchy Standard
23265 @cindex FHS
23267 Another use of @file{config.site} is for priming the directory variables
23268 @c "File system", but slightly obfuscated, as above.
23269 in a manner consistent with the File@/system Hierarchy Standard
23270 (FHS).  Once the following file is installed at
23271 @file{/usr/share/config.site}, a user can execute simply
23272 @code{./configure --prefix=/usr} to get all the directories chosen in
23273 the locations recommended by FHS.
23275 @example
23276 # /usr/share/config.site for FHS defaults when installing below /usr,
23277 # and the respective settings were not changed on the command line.
23278 if test "$prefix" = /usr; then
23279   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
23280   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
23281   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
23283 @end example
23285 @cindex @file{lib64}
23286 @cindex 64-bit libraries
23287 Likewise, on platforms where 64-bit libraries are built by default, then
23288 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
23289 it is appropriate to install @file{/usr/local/@/share/config.site}:
23291 @example
23292 # /usr/local/share/config.site for platforms that prefer
23293 # the directory /usr/local/lib64 over /usr/local/lib.
23294 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
23295 @end example
23298 @c ============================================== Running configure Scripts.
23300 @node Running configure Scripts
23301 @chapter Running @command{configure} Scripts
23302 @cindex @command{configure}
23304 Below are instructions on how to configure a package that uses a
23305 @command{configure} script, suitable for inclusion as an @file{INSTALL}
23306 file in the package.  A plain-text version of @file{INSTALL} which you
23307 may use comes with Autoconf.
23309 @menu
23310 * Basic Installation::          Instructions for typical cases
23311 * Compilers and Options::       Selecting compilers and optimization
23312 * Multiple Architectures::      Compiling for multiple architectures at once
23313 * Installation Names::          Installing in different directories
23314 * Optional Features::           Selecting optional features
23315 * Particular Systems::          Particular systems
23316 * System Type::                 Specifying the system type
23317 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
23318 * Defining Variables::          Specifying the compiler etc.
23319 * configure Invocation::        Changing how @command{configure} runs
23320 @end menu
23322 @set autoconf
23323 @include install.texi
23326 @c ============================================== config.status Invocation
23328 @node config.status Invocation
23329 @chapter config.status Invocation
23330 @cindex @command{config.status}
23332 The @command{configure} script creates a file named @file{config.status},
23333 which actually configures, @dfn{instantiates}, the template files.  It
23334 also records the configuration options that were specified when the
23335 package was last configured in case reconfiguring is needed.
23337 Synopsis:
23338 @example
23339 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
23340 @end example
23342 It configures each @var{tag}; if none are specified, all the templates
23343 are instantiated.  A @var{tag} refers to a file or other tag associated
23344 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
23345 macro (@pxref{Configuration Actions}).  The files must be specified
23346 without their dependencies, as in
23348 @example
23349 ./config.status foobar
23350 @end example
23352 @noindent
23355 @example
23356 ./config.status foobar:foo.in:bar.in
23357 @end example
23359 The supported options are:
23361 @table @option
23362 @item --help
23363 @itemx -h
23364 Print a summary of the command line options, the list of the template
23365 files, and exit.
23367 @item --version
23368 @itemx -V
23369 Print the version number of Autoconf and the configuration settings,
23370 and exit.
23372 @item --config
23373 Print the configuration settings in reusable way, quoted for the shell,
23374 and exit.  For example, for a debugging build that otherwise reuses the
23375 configuration from a different build directory @var{build-dir} of a
23376 package in @var{src-dir}, you could use the following:
23378 @example
23379 args=`@var{build-dir}/config.status --config`
23380 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
23381 @end example
23383 @noindent
23384 Note that it may be necessary to override a @option{--srcdir} setting
23385 that was saved in the configuration, if the arguments are used in a
23386 different build directory.
23388 @item --silent
23389 @itemx --quiet
23390 @itemx -q
23391 Do not print progress messages.
23393 @item --debug
23394 @itemx -d
23395 Don't remove the temporary files.
23397 @item --file=@var{file}[:@var{template}]
23398 Require that @var{file} be instantiated as if
23399 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
23400 @var{file} and @var{template} may be @samp{-} in which case the standard
23401 output and/or standard input, respectively, is used.  If a
23402 @var{template} file name is relative, it is first looked for in the build
23403 tree, and then in the source tree.  @xref{Configuration Actions}, for
23404 more details.
23406 This option and the following ones provide one way for separately
23407 distributed packages to share the values computed by @command{configure}.
23408 Doing so can be useful if some of the packages need a superset of the
23409 features that one of them, perhaps a common library, does.  These
23410 options allow a @file{config.status} file to create files other than the
23411 ones that its @file{configure.ac} specifies, so it can be used for a
23412 different package, or for extracting a subset of values.  For example,
23414 @example
23415 echo '@@CC@@' | ./config.status --file=-
23416 @end example
23418 @noindent
23419 provides the value of @code{@@CC@@} on standard output.
23421 @item --header=@var{file}[:@var{template}]
23422 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
23424 @item --recheck
23425 Ask @file{config.status} to update itself and exit (no instantiation).
23426 This option is useful if you change @command{configure}, so that the
23427 results of some tests might be different from the previous run.  The
23428 @option{--recheck} option reruns @command{configure} with the same arguments
23429 you used before, plus the @option{--no-create} option, which prevents
23430 @command{configure} from running @file{config.status} and creating
23431 @file{Makefile} and other files, and the @option{--no-recursion} option,
23432 which prevents @command{configure} from running other @command{configure}
23433 scripts in subdirectories.  (This is so other Make rules can
23434 run @file{config.status} when it changes; @pxref{Automatic Remaking},
23435 for an example).
23436 @end table
23438 @file{config.status} checks several optional environment variables that
23439 can alter its behavior:
23441 @anchor{CONFIG_SHELL}
23442 @defvar CONFIG_SHELL
23443 @evindex CONFIG_SHELL
23444 The shell with which to run @command{configure}.  It must be
23445 Bourne-compatible, and the absolute name of the shell should be passed.
23446 The default is a shell that supports @code{LINENO} if available, and
23447 @file{/bin/sh} otherwise.
23448 @end defvar
23450 @defvar CONFIG_STATUS
23451 @evindex CONFIG_STATUS
23452 The file name to use for the shell script that records the
23453 configuration.  The default is @file{./config.status}.  This variable is
23454 useful when one package uses parts of another and the @command{configure}
23455 scripts shouldn't be merged because they are maintained separately.
23456 @end defvar
23458 You can use @file{./config.status} in your makefiles.  For example, in
23459 the dependencies given above (@pxref{Automatic Remaking}),
23460 @file{config.status} is run twice when @file{configure.ac} has changed.
23461 If that bothers you, you can make each run only regenerate the files for
23462 that rule:
23463 @example
23464 @group
23465 config.h: stamp-h
23466 stamp-h: config.h.in config.status
23467         ./config.status config.h
23468         echo > stamp-h
23470 Makefile: Makefile.in config.status
23471         ./config.status Makefile
23472 @end group
23473 @end example
23475 The calling convention of @file{config.status} has changed; see
23476 @ref{Obsolete config.status Use}, for details.
23479 @c =================================================== Obsolete Constructs
23481 @node Obsolete Constructs
23482 @chapter Obsolete Constructs
23483 @cindex Obsolete constructs
23485 Autoconf changes, and throughout the years some constructs have been
23486 obsoleted.  Most of the changes involve the macros, but in some cases
23487 the tools themselves, or even some concepts, are now considered
23488 obsolete.
23490 You may completely skip this chapter if you are new to Autoconf.  Its
23491 intention is mainly to help maintainers updating their packages by
23492 understanding how to move to more modern constructs.
23494 @menu
23495 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
23496 * acconfig Header::             Additional entries in @file{config.h.in}
23497 * autoupdate Invocation::       Automatic update of @file{configure.ac}
23498 * Obsolete Macros::             Backward compatibility macros
23499 * Autoconf 1::                  Tips for upgrading your files
23500 * Autoconf 2.13::               Some fresher tips
23501 @end menu
23503 @node Obsolete config.status Use
23504 @section Obsolete @file{config.status} Invocation
23506 @file{config.status} now supports arguments to specify the files to
23507 instantiate; see @ref{config.status Invocation}, for more details.
23508 Before, environment variables had to be used.
23510 @defvar CONFIG_COMMANDS
23511 @evindex CONFIG_COMMANDS
23512 The tags of the commands to execute.  The default is the arguments given
23513 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
23514 @file{configure.ac}.
23515 @end defvar
23517 @defvar CONFIG_FILES
23518 @evindex CONFIG_FILES
23519 The files in which to perform @samp{@@@var{variable}@@} substitutions.
23520 The default is the arguments given to @code{AC_OUTPUT} and
23521 @code{AC_CONFIG_FILES} in @file{configure.ac}.
23522 @end defvar
23524 @defvar CONFIG_HEADERS
23525 @evindex CONFIG_HEADERS
23526 The files in which to substitute C @code{#define} statements.  The
23527 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
23528 macro was not called, @file{config.status} ignores this variable.
23529 @end defvar
23531 @defvar CONFIG_LINKS
23532 @evindex CONFIG_LINKS
23533 The symbolic links to establish.  The default is the arguments given to
23534 @code{AC_CONFIG_LINKS}; if that macro was not called,
23535 @file{config.status} ignores this variable.
23536 @end defvar
23538 In @ref{config.status Invocation}, using this old interface, the example
23539 would be:
23541 @example
23542 @group
23543 config.h: stamp-h
23544 stamp-h: config.h.in config.status
23545         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
23546           CONFIG_HEADERS=config.h ./config.status
23547         echo > stamp-h
23549 Makefile: Makefile.in config.status
23550         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
23551           CONFIG_FILES=Makefile ./config.status
23552 @end group
23553 @end example
23555 @noindent
23556 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
23557 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
23558 for @code{CONFIG_COMMANDS}, etc.)
23561 @node acconfig Header
23562 @section @file{acconfig.h}
23564 @cindex @file{acconfig.h}
23565 @cindex @file{config.h.top}
23566 @cindex @file{config.h.bot}
23568 In order to produce @file{config.h.in}, @command{autoheader} needs to
23569 build or to find templates for each symbol.  Modern releases of Autoconf
23570 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
23571 Macros}), but in older releases a file, @file{acconfig.h}, contained the
23572 list of needed templates.  @command{autoheader} copied comments and
23573 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
23574 the current directory, if present.  This file used to be mandatory if
23575 you @code{AC_DEFINE} any additional symbols.
23577 Modern releases of Autoconf also provide @code{AH_TOP} and
23578 @code{AH_BOTTOM} if you need to prepend/append some information to
23579 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
23580 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
23581 @command{autoheader} copies the lines before the line containing
23582 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
23583 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
23584 @command{autoheader} copies the lines after that line to the end of the
23585 file it generates.  Either or both of those strings may be omitted.  An
23586 even older alternate way to produce the same effect in ancient versions
23587 of Autoconf is to create the files @file{@var{file}.top} (typically
23588 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
23589 directory.  If they exist, @command{autoheader} copies them to the
23590 beginning and end, respectively, of its output.
23592 In former versions of Autoconf, the files used in preparing a software
23593 package for distribution were:
23594 @example
23595 @group
23596 configure.ac --.   .------> autoconf* -----> configure
23597                +---+
23598 [aclocal.m4] --+   `---.
23599 [acsite.m4] ---'       |
23600                        +--> [autoheader*] -> [config.h.in]
23601 [acconfig.h] ----.     |
23602                  +-----'
23603 [config.h.top] --+
23604 [config.h.bot] --'
23605 @end group
23606 @end example
23608 Using only the @code{AH_} macros, @file{configure.ac} should be
23609 self-contained, and should not depend upon @file{acconfig.h} etc.
23612 @node autoupdate Invocation
23613 @section Using @command{autoupdate} to Modernize @file{configure.ac}
23614 @cindex @command{autoupdate}
23616 The @command{autoupdate} program updates a @file{configure.ac} file that
23617 calls Autoconf macros by their old names to use the current macro names.
23618 In version 2 of Autoconf, most of the macros were renamed to use a more
23619 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
23620 description of the new scheme.  Although the old names still work
23621 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
23622 new names), you can make your @file{configure.ac} files more readable
23623 and make it easier to use the current Autoconf documentation if you
23624 update them to use the new macro names.
23626 @evindex SIMPLE_BACKUP_SUFFIX
23627 If given no arguments, @command{autoupdate} updates @file{configure.ac},
23628 backing up the original version with the suffix @file{~} (or the value
23629 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
23630 set).  If you give @command{autoupdate} an argument, it reads that file
23631 instead of @file{configure.ac} and writes the updated file to the
23632 standard output.
23634 @noindent
23635 @command{autoupdate} accepts the following options:
23637 @table @option
23638 @item --help
23639 @itemx -h
23640 Print a summary of the command line options and exit.
23642 @item --version
23643 @itemx -V
23644 Print the version number of Autoconf and exit.
23646 @item --verbose
23647 @itemx -v
23648 Report processing steps.
23650 @item --debug
23651 @itemx -d
23652 Don't remove the temporary files.
23654 @item --force
23655 @itemx -f
23656 Force the update even if the file has not changed.  Disregard the cache.
23658 @item --include=@var{dir}
23659 @itemx -I @var{dir}
23660 Also look for input files in @var{dir}.  Multiple invocations accumulate.
23661 Directories are browsed from last to first.
23663 @item --prepend-include=@var{dir}
23664 @itemx -B @var{dir}
23665 Prepend directory @var{dir} to the search path.  This is used to include
23666 the language-specific files before any third-party macros.
23667 @end table
23669 @node Obsolete Macros
23670 @section Obsolete Macros
23672 Several macros are obsoleted in Autoconf, for various reasons (typically
23673 they failed to quote properly, couldn't be extended for more recent
23674 issues, etc.).  They are still supported, but deprecated: their use
23675 should be avoided.
23677 During the jump from Autoconf version 1 to version 2, most of the
23678 macros were renamed to use a more uniform and descriptive naming scheme,
23679 but their signature did not change.  @xref{Macro Names}, for a
23680 description of the new naming scheme.  Below, if there is just the mapping
23681 from old names to new names for these macros, the reader is invited to
23682 refer to the definition of the new macro for the signature and the
23683 description.
23685 @defmac AC_AIX
23686 @acindex{AIX}
23687 @cvindex _ALL_SOURCE
23688 This macro is a platform-specific subset of
23689 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23690 @end defmac
23692 @defmac AC_ALLOCA
23693 @acindex{ALLOCA}
23694 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
23695 @end defmac
23697 @defmac AC_ARG_ARRAY
23698 @acindex{ARG_ARRAY}
23699 Removed because of limited usefulness.
23700 @end defmac
23702 @defmac AC_C_CROSS
23703 @acindex{C_CROSS}
23704 This macro is obsolete; it does nothing.
23705 @end defmac
23707 @defmac AC_C_LONG_DOUBLE
23708 @acindex{C_LONG_DOUBLE}
23709 @cvindex HAVE_LONG_DOUBLE
23710 If the C compiler supports a working @code{long double} type with more
23711 range or precision than the @code{double} type, define
23712 @code{HAVE_LONG_DOUBLE}.
23714 You should use @code{AC_TYPE_LONG_DOUBLE} or
23715 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23716 @end defmac
23718 @defmac AC_CANONICAL_SYSTEM
23719 @acindex{CANONICAL_SYSTEM}
23720 Determine the system type and set output variables to the names of the
23721 canonical system types.  @xref{Canonicalizing}, for details about the
23722 variables this macro sets.
23724 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
23725 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
23726 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
23727 other macros (@pxref{Canonicalizing}).
23728 @end defmac
23730 @defmac AC_CHAR_UNSIGNED
23731 @acindex{CHAR_UNSIGNED}
23732 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
23733 @end defmac
23735 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
23736 @acindex{CHECK_TYPE}
23737 Autoconf, up to 2.13, used to provide this version of
23738 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
23739 it is a member of the @code{CHECK} clan, it does
23740 more than just checking.  Secondly, missing types are defined
23741 using @code{#define}, not @code{typedef}, and this can lead to
23742 problems in the case of pointer types.
23744 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
23745 @ref{Generic Types}, for the description of the current macro.
23747 If the type @var{type} is not defined, define it to be the C (or C++)
23748 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
23750 This macro is equivalent to:
23752 @example
23753 AC_CHECK_TYPE([@var{type}], [],
23754   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
23755      [Define to '@var{default}'
23756       if <sys/types.h> does not define.])])
23757 @end example
23759 In order to keep backward compatibility, the two versions of
23760 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
23762 @enumerate
23763 @item
23764 If there are three or four arguments, the modern version is used.
23766 @item
23767 If the second argument appears to be a C or C++ type, then the
23768 obsolete version is used.  This happens if the argument is a C or C++
23769 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
23770 followed by one of @samp{[(* } and then by a string of zero or more
23771 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
23773 @item
23774 If the second argument is spelled with the alphabet of valid C and C++
23775 types, the user is warned and the modern version is used.
23777 @item
23778 Otherwise, the modern version is used.
23779 @end enumerate
23781 @noindent
23782 You are encouraged either to use a valid builtin type, or to use the
23783 equivalent modern code (see above), or better yet, to use
23784 @code{AC_CHECK_TYPES} together with
23786 @example
23787 #ifndef HAVE_LOFF_T
23788 typedef loff_t off_t;
23789 #endif
23790 @end example
23791 @end defmac
23792 @c end of AC_CHECK_TYPE
23794 @defmac AC_CHECKING (@var{feature-description})
23795 @acindex{CHECKING}
23796 Same as
23798 @example
23799 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
23800 @end example
23802 @noindent
23803 @xref{AC_MSG_NOTICE}.
23804 @end defmac
23806 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
23807   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
23808 @acindex{COMPILE_CHECK}
23809 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
23810 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
23811 addition that it prints @samp{checking for @var{echo-text}} to the
23812 standard output first, if @var{echo-text} is non-empty.  Use
23813 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
23814 messages (@pxref{Printing Messages}).
23815 @end defmac
23817 @defmac AC_CONST
23818 @acindex{CONST}
23819 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
23820 @end defmac
23822 @defmac AC_CROSS_CHECK
23823 @acindex{CROSS_CHECK}
23824 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
23825 @code{:-)}.
23826 @end defmac
23828 @defmac AC_CYGWIN
23829 @acindex{CYGWIN}
23830 @evindex CYGWIN
23831 Check for the Cygwin environment in which case the shell variable
23832 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
23833 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
23834 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
23836 @example
23837 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
23838 case $host_os in
23839   *cygwin* ) CYGWIN=yes;;
23840          * ) CYGWIN=no;;
23841 esac
23842 @end example
23844 Beware that the variable @env{CYGWIN} has a special meaning when
23845 running Cygwin, and should not be changed.  That's yet another reason
23846 not to use this macro.
23847 @end defmac
23849 @defmac AC_DECL_SYS_SIGLIST
23850 @acindex{DECL_SYS_SIGLIST}
23851 @cvindex SYS_SIGLIST_DECLARED
23852 Same as:
23854 @example
23855 AC_CHECK_DECLS([sys_siglist], [], [],
23856 [#include <signal.h>
23857 /* NetBSD declares sys_siglist in unistd.h.  */
23858 #ifdef HAVE_UNISTD_H
23859 # include <unistd.h>
23860 #endif
23862 @end example
23864 @noindent
23865 @xref{AC_CHECK_DECLS}.
23866 @end defmac
23868 @defmac AC_DECL_YYTEXT
23869 @acindex{DECL_YYTEXT}
23870 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23871 @end defmac
23873 @defmac AC_DIAGNOSE (@var{category}, @var{message})
23874 @acindex{DIAGNOSE}
23875 Replaced by @code{m4_warn} (@pxref{m4_warn}).
23876 @end defmac
23878 @defmac AC_DIR_HEADER
23879 @acindex{DIR_HEADER}
23880 @cvindex DIRENT
23881 @cvindex SYSNDIR
23882 @cvindex SYSDIR
23883 @cvindex NDIR
23884 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
23885 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
23886 (@pxref{AC_HEADER_DIRENT}),
23887 but defines a different set of C preprocessor macros to indicate which
23888 header file is found:
23890 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
23891 @item Header            @tab Old Symbol     @tab New Symbol
23892 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
23893 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
23894 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
23895 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
23896 @end multitable
23897 @end defmac
23899 @defmac AC_DYNIX_SEQ
23900 @acindex{DYNIX_SEQ}
23901 If on DYNIX/ptx, add @option{-lseq} to output variable
23902 @code{LIBS}.  This macro used to be defined as
23904 @example
23905 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
23906 @end example
23908 @noindent
23909 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
23910 @end defmac
23912 @defmac AC_EXEEXT
23913 @acindex{EXEEXT}
23914 @ovindex EXEEXT
23915 Defined the output variable @code{EXEEXT} based on the output of the
23916 compiler, which is now done automatically.  Typically set to empty
23917 string if Posix and @samp{.exe} if a DOS variant.
23918 @end defmac
23920 @defmac AC_EMXOS2
23921 @acindex{EMXOS2}
23922 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
23923 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
23924 check the nature of the host is using @code{AC_CANONICAL_HOST}
23925 (@pxref{Canonicalizing}).
23926 @end defmac
23928 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
23929   @ovar{action-if-not-given})
23930 @acindex{ENABLE}
23931 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
23932 support providing a help string (@pxref{AC_ARG_ENABLE}).
23933 @end defmac
23935 @defmac AC_ERROR
23936 @acindex{ERROR}
23937 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
23938 @end defmac
23940 @defmac AC_FATAL (@var{message})
23941 @acindex{FATAL}
23942 Replaced by @code{m4_fatal} (@pxref{m4_fatal}).
23943 @end defmac
23945 @defmac AC_FIND_X
23946 @acindex{FIND_X}
23947 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
23948 @end defmac
23950 @defmac AC_FIND_XTRA
23951 @acindex{FIND_XTRA}
23952 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
23953 @end defmac
23955 @defmac AC_FOREACH
23956 @acindex{FOREACH}
23957 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
23958 @end defmac
23960 @defmac AC_FUNC_CHECK
23961 @acindex{FUNC_CHECK}
23962 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
23963 @end defmac
23965 @anchor{AC_FUNC_SETVBUF_REVERSED}
23966 @defmac AC_FUNC_SETVBUF_REVERSED
23967 @acindex{FUNC_SETVBUF_REVERSED}
23968 @cvindex SETVBUF_REVERSED
23969 @c @fuindex setvbuf
23970 @prindex @code{setvbuf}
23971 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
23972 the buffering type as its second argument and the buffer pointer as the
23973 third, instead of the other way around, and defined
23974 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
23975 were those based on SVR2, which became obsolete in 1987, and the macro
23976 is no longer needed.
23977 @end defmac
23979 @defmac AC_FUNC_WAIT3
23980 @acindex{FUNC_WAIT3}
23981 @cvindex HAVE_WAIT3
23982 @c @fuindex wait3
23983 @prindex @code{wait3}
23984 If @code{wait3} is found and fills in the contents of its third argument
23985 (a @samp{struct rusage *}), which HP-UX does not do, define
23986 @code{HAVE_WAIT3}.
23988 These days portable programs should use @code{waitpid}, not
23989 @code{wait3}, as @code{wait3} has been removed from Posix.
23990 @end defmac
23992 @defmac AC_GCC_TRADITIONAL
23993 @acindex{GCC_TRADITIONAL}
23994 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
23995 @end defmac
23997 @defmac AC_GETGROUPS_T
23998 @acindex{GETGROUPS_T}
23999 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
24000 @end defmac
24002 @defmac AC_GETLOADAVG
24003 @acindex{GETLOADAVG}
24004 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
24005 @end defmac
24007 @defmac AC_GNU_SOURCE
24008 @acindex{GNU_SOURCE}
24009 @cvindex _GNU_SOURCE
24010 This macro is a platform-specific subset of
24011 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
24012 @end defmac
24014 @defmac AC_HAVE_FUNCS
24015 @acindex{HAVE_FUNCS}
24016 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
24017 @end defmac
24019 @defmac AC_HAVE_HEADERS
24020 @acindex{HAVE_HEADERS}
24021 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
24022 @end defmac
24024 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
24025   @ovar{action-if-not-found}, @ovar{other-libraries})
24026 @acindex{HAVE_LIBRARY}
24027 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
24028 @var{function} argument of @code{main}.  In addition, @var{library} can
24029 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
24030 all of those cases, the compiler is passed @option{-lfoo}.  However,
24031 @var{library} cannot be a shell variable; it must be a literal name.
24032 @xref{AC_CHECK_LIB}.
24033 @end defmac
24035 @defmac AC_HAVE_POUNDBANG
24036 @acindex{HAVE_POUNDBANG}
24037 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
24038 @end defmac
24040 @defmac AC_HEADER_CHECK
24041 @acindex{HEADER_CHECK}
24042 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
24043 @end defmac
24045 @defmac AC_HEADER_EGREP
24046 @acindex{HEADER_EGREP}
24047 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
24048 @end defmac
24050 @anchor{AC_HEADER_TIME}
24051 @defmac AC_HEADER_TIME
24052 @acindex{HEADER_TIME}
24053 @cvindex TIME_WITH_SYS_TIME
24054 @hdrindex{time.h}
24055 @hdrindex{sys/time.h}
24056 @caindex header_time
24057 This macro used to check whether it was possible to include
24058 @file{time.h} and @file{sys/time.h} in the same source file,
24059 defining @code{TIME_WITH_SYS_TIME} if so.
24061 Nowadays, it is equivalent to @samp{AC_CHECK_HEADERS([sys/time.h])},
24062 although it does still define @code{TIME_WITH_SYS_TIME} for
24063 compatibility's sake.  @file{time.h} is universally present, and the
24064 systems on which @file{sys/time.h} conflicted with @file{time.h} are
24065 obsolete.
24066 @end defmac
24068 @defmac AC_HELP_STRING
24069 @acindex{HELP_STRING}
24070 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
24071 @end defmac
24073 @defmac AC_INIT (@var{unique-file-in-source-dir})
24074 @acindex{INIT}
24075 Formerly @code{AC_INIT} used to have a single argument, and was
24076 equivalent to:
24078 @example
24079 AC_INIT
24080 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
24081 @end example
24082 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
24083 @end defmac
24085 @defmac AC_INLINE
24086 @acindex{INLINE}
24087 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
24088 @end defmac
24090 @defmac AC_INT_16_BITS
24091 @acindex{INT_16_BITS}
24092 @cvindex INT_16_BITS
24093 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
24094 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
24095 @end defmac
24097 @defmac AC_IRIX_SUN
24098 @acindex{IRIX_SUN}
24099 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
24100 @code{LIBS}.  If you were using it to get @code{getmntent}, use
24101 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
24102 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
24103 getpwnam)}.  Up to Autoconf 2.13, it used to be
24105 @example
24106 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
24107 @end example
24109 @noindent
24110 now it is defined as
24112 @example
24113 AC_FUNC_GETMNTENT
24114 AC_CHECK_LIB([sun], [getpwnam])
24115 @end example
24117 @noindent
24118 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
24119 @end defmac
24121 @defmac AC_ISC_POSIX
24122 @acindex{ISC_POSIX}
24123 @ovindex LIBS
24124 This macro adds @option{-lcposix} to output variable @code{LIBS} if
24125 necessary for Posix facilities.  Sun dropped support for the obsolete
24126 INTERACTIVE Systems Corporation Unix on 2006-07-23.  New programs
24127 need not use this macro.  It is implemented as
24128 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
24129 @end defmac
24131 @defmac AC_LANG_C
24132 @acindex{LANG_C}
24133 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
24134 @end defmac
24136 @defmac AC_LANG_CPLUSPLUS
24137 @acindex{LANG_CPLUSPLUS}
24138 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
24139 @end defmac
24141 @defmac AC_LANG_FORTRAN77
24142 @acindex{LANG_FORTRAN77}
24143 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
24144 @end defmac
24146 @defmac AC_LANG_RESTORE
24147 @acindex{LANG_RESTORE}
24148 Select the @var{language} that is saved on the top of the stack, as set
24149 by @code{AC_LANG_SAVE}, remove it from the stack, and call
24150 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
24151 preferred way to change languages.
24152 @end defmac
24154 @defmac AC_LANG_SAVE
24155 @acindex{LANG_SAVE}
24156 Remember the current language (as set by @code{AC_LANG}) on a stack.
24157 The current language does not change.  @code{AC_LANG_PUSH} is preferred
24158 (@pxref{AC_LANG_PUSH}).
24159 @end defmac
24161 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
24162 @acindex{LINK_FILES}
24163 This is an obsolete version of @code{AC_CONFIG_LINKS}
24164 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
24166 @example
24167 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
24168               host.h            object.h)
24169 @end example
24171 @noindent
24174 @example
24175 AC_CONFIG_LINKS([host.h:config/$machine.h
24176                 object.h:config/$obj_format.h])
24177 @end example
24178 @end defmac
24180 @defmac AC_LN_S
24181 @acindex{LN_S}
24182 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
24183 @end defmac
24185 @defmac AC_LONG_64_BITS
24186 @acindex{LONG_64_BITS}
24187 @cvindex LONG_64_BITS
24188 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
24189 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
24190 (@pxref{AC_CHECK_SIZEOF}).
24191 @end defmac
24193 @defmac AC_LONG_DOUBLE
24194 @acindex{LONG_DOUBLE}
24195 If the C compiler supports a working @code{long double} type with more
24196 range or precision than the @code{double} type, define
24197 @code{HAVE_LONG_DOUBLE}.
24199 You should use @code{AC_TYPE_LONG_DOUBLE} or
24200 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
24201 @end defmac
24203 @defmac AC_LONG_FILE_NAMES
24204 @acindex{LONG_FILE_NAMES}
24205 Replaced by
24206 @example
24207 AC_SYS_LONG_FILE_NAMES
24208 @end example
24209 @noindent
24210 @xref{AC_SYS_LONG_FILE_NAMES}.
24211 @end defmac
24213 @defmac AC_MAJOR_HEADER
24214 @acindex{MAJOR_HEADER}
24215 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
24216 @end defmac
24218 @defmac AC_MEMORY_H
24219 @acindex{MEMORY_H}
24220 @cvindex NEED_MEMORY_H
24221 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
24222 defined in @file{memory.h}.  Today it is equivalent to
24223 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
24224 your code to get the @code{mem} functions from @file{string.h} instead.
24225 @end defmac
24227 @defmac AC_MINGW32
24228 @acindex{MINGW32}
24229 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
24230 environment and sets @code{MINGW32}.  Don't use this macro, the
24231 dignified means to check the nature of the host is using
24232 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24233 @end defmac
24235 @defmac AC_MINIX
24236 @acindex{MINIX}
24237 @cvindex _MINIX
24238 @cvindex _POSIX_SOURCE
24239 @cvindex _POSIX_1_SOURCE
24240 This macro is a platform-specific subset of
24241 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
24242 @end defmac
24244 @defmac AC_MINUS_C_MINUS_O
24245 @acindex{MINUS_C_MINUS_O}
24246 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
24247 @end defmac
24249 @defmac AC_MMAP
24250 @acindex{MMAP}
24251 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
24252 @end defmac
24254 @defmac AC_MODE_T
24255 @acindex{MODE_T}
24256 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
24257 @end defmac
24259 @defmac AC_OBJEXT
24260 @acindex{OBJEXT}
24261 @ovindex OBJEXT
24262 Defined the output variable @code{OBJEXT} based on the output of the
24263 compiler, after .c files have been excluded.  Typically set to @samp{o}
24264 if Posix, @samp{obj} if a DOS variant.
24265 Now the compiler checking macros handle
24266 this automatically.
24267 @end defmac
24269 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
24270 @acindex{OBSOLETE}
24271 Make M4 print a message to the standard error output warning that
24272 @var{this-macro-name} is obsolete, and giving the file and line number
24273 where it was called.  @var{this-macro-name} should be the name of the
24274 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
24275 it is printed at the end of the warning message; for example, it can be
24276 a suggestion for what to use instead of @var{this-macro-name}.
24278 For instance
24280 @example
24281 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
24282 @end example
24284 @noindent
24285 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
24286 services to the user (@pxref{AU_DEFUN}).
24287 @end defmac
24289 @defmac AC_OFF_T
24290 @acindex{OFF_T}
24291 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
24292 @end defmac
24294 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
24295 @acindex{OUTPUT}
24296 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
24297 interface is equivalent to:
24299 @example
24300 @group
24301 AC_CONFIG_FILES(@var{file}@dots{})
24302 AC_CONFIG_COMMANDS([default],
24303                    @var{extra-cmds}, @var{init-cmds})
24304 AC_OUTPUT
24305 @end group
24306 @end example
24308 @noindent
24309 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
24310 @end defmac
24312 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
24313 @acindex{OUTPUT_COMMANDS}
24314 Specify additional shell commands to run at the end of
24315 @file{config.status}, and shell commands to initialize any variables
24316 from @command{configure}.  This macro may be called multiple times.  It is
24317 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
24319 Here is an unrealistic example:
24321 @example
24322 fubar=27
24323 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
24324                    [fubar=$fubar])
24325 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
24326                    [echo init bit])
24327 @end example
24329 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
24330 additional key, an important difference is that
24331 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
24332 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
24333 can safely be given macro calls as arguments:
24335 @example
24336 AC_CONFIG_COMMANDS(foo, [my_FOO()])
24337 @end example
24339 @noindent
24340 Conversely, where one level of quoting was enough for literal strings
24341 with @code{AC_OUTPUT_COMMANDS}, you need two with
24342 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
24344 @example
24345 @group
24346 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
24347 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
24348 @end group
24349 @end example
24350 @end defmac
24352 @defmac AC_PID_T
24353 @acindex{PID_T}
24354 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
24355 @end defmac
24357 @defmac AC_PREFIX
24358 @acindex{PREFIX}
24359 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
24360 @end defmac
24362 @defmac AC_PROG_CC_C89
24363 @acindex{PROG_CC_C89}
24364 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
24365 @end defmac
24367 @defmac AC_PROG_CC_C99
24368 @acindex{PROG_CC_C99}
24369 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
24370 @end defmac
24372 @defmac AC_PROG_CC_STDC
24373 @acindex{PROG_CC_STDC}
24374 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
24375 @end defmac
24377 @defmac AC_PROGRAMS_CHECK
24378 @acindex{PROGRAMS_CHECK}
24379 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
24380 @end defmac
24382 @defmac AC_PROGRAMS_PATH
24383 @acindex{PROGRAMS_PATH}
24384 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
24385 @end defmac
24387 @defmac AC_PROGRAM_CHECK
24388 @acindex{PROGRAM_CHECK}
24389 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
24390 @end defmac
24392 @defmac AC_PROGRAM_EGREP
24393 @acindex{PROGRAM_EGREP}
24394 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
24395 @end defmac
24397 @defmac AC_PROGRAM_PATH
24398 @acindex{PROGRAM_PATH}
24399 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
24400 @end defmac
24402 @defmac AC_REMOTE_TAPE
24403 @acindex{REMOTE_TAPE}
24404 Removed because of limited usefulness.
24405 @end defmac
24407 @defmac AC_RESTARTABLE_SYSCALLS
24408 @acindex{RESTARTABLE_SYSCALLS}
24409 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
24410 these days portable programs should use @code{sigaction} with
24411 @code{SA_RESTART} if they want restartable system calls.  They should
24412 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
24413 system call is restartable is a dynamic issue, not a configuration-time
24414 issue.
24415 @end defmac
24417 @defmac AC_RETSIGTYPE
24418 @acindex{RETSIGTYPE}
24419 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
24420 is obsolete when assuming C89 or better.
24421 @end defmac
24423 @defmac AC_RSH
24424 @acindex{RSH}
24425 Removed because of limited usefulness.
24426 @end defmac
24428 @defmac AC_SCO_INTL
24429 @acindex{SCO_INTL}
24430 @ovindex LIBS
24431 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
24432 macro used to do this:
24434 @example
24435 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
24436 @end example
24438 @noindent
24439 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
24440 @end defmac
24442 @defmac AC_SETVBUF_REVERSED
24443 @acindex{SETVBUF_REVERSED}
24444 Replaced by
24445 @example
24446 AC_FUNC_SETVBUF_REVERSED
24447 @end example
24448 @noindent
24449 @xref{AC_FUNC_SETVBUF_REVERSED}.
24450 @end defmac
24452 @defmac AC_SET_MAKE
24453 @acindex{SET_MAKE}
24454 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
24455 @end defmac
24457 @defmac AC_SIZEOF_TYPE
24458 @acindex{SIZEOF_TYPE}
24459 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
24460 @end defmac
24462 @defmac AC_SIZE_T
24463 @acindex{SIZE_T}
24464 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
24465 @end defmac
24467 @defmac AC_STAT_MACROS_BROKEN
24468 @acindex{STAT_MACROS_BROKEN}
24469 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
24470 @end defmac
24472 @defmac AC_STDC_HEADERS
24473 @acindex{STDC_HEADERS}
24474 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}), which
24475 is itself obsolete.  Nowadays it is safe to assume the facilities of C90
24476 exist.
24477 @end defmac
24479 @defmac AC_STRCOLL
24480 @acindex{STRCOLL}
24481 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
24482 @end defmac
24484 @defmac AC_STRUCT_ST_BLKSIZE
24485 @acindex{STRUCT_ST_BLKSIZE}
24486 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
24487 @cvindex HAVE_ST_BLKSIZE
24488 If @code{struct stat} contains an @code{st_blksize} member, define
24489 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
24490 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
24491 the future.  This macro is obsoleted, and should be replaced by
24493 @example
24494 AC_CHECK_MEMBERS([struct stat.st_blksize])
24495 @end example
24496 @noindent
24497 @xref{AC_CHECK_MEMBERS}.
24498 @end defmac
24500 @defmac AC_STRUCT_ST_RDEV
24501 @acindex{STRUCT_ST_RDEV}
24502 @cvindex HAVE_ST_RDEV
24503 @cvindex HAVE_STRUCT_STAT_ST_RDEV
24504 If @code{struct stat} contains an @code{st_rdev} member, define
24505 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
24506 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
24507 in the future.  Actually, even the new macro is obsolete and should be
24508 replaced by:
24509 @example
24510 AC_CHECK_MEMBERS([struct stat.st_rdev])
24511 @end example
24512 @noindent
24513 @xref{AC_CHECK_MEMBERS}.
24514 @end defmac
24516 @defmac AC_ST_BLKSIZE
24517 @acindex{ST_BLKSIZE}
24518 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24519 @end defmac
24521 @defmac AC_ST_BLOCKS
24522 @acindex{ST_BLOCKS}
24523 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
24524 @end defmac
24526 @defmac AC_ST_RDEV
24527 @acindex{ST_RDEV}
24528 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24529 @end defmac
24531 @defmac AC_SYS_RESTARTABLE_SYSCALLS
24532 @acindex{SYS_RESTARTABLE_SYSCALLS}
24533 @cvindex HAVE_RESTARTABLE_SYSCALLS
24534 If the system automatically restarts a system call that is interrupted
24535 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
24536 not check whether system calls are restarted in general---it checks whether a
24537 signal handler installed with @code{signal} (but not @code{sigaction})
24538 causes system calls to be restarted.  It does not check whether system calls
24539 can be restarted when interrupted by signals that have no handler.
24541 These days portable programs should use @code{sigaction} with
24542 @code{SA_RESTART} if they want restartable system calls.  They should
24543 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
24544 system call is restartable is a dynamic issue, not a configuration-time
24545 issue.
24546 @end defmac
24548 @defmac AC_SYS_SIGLIST_DECLARED
24549 @acindex{SYS_SIGLIST_DECLARED}
24550 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
24551 name is obsolete, as the same functionality is now achieved via
24552 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
24553 @end defmac
24555 @defmac AC_TEST_CPP
24556 @acindex{TEST_CPP}
24557 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
24558 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
24559 @end defmac
24561 @defmac AC_TEST_PROGRAM
24562 @acindex{TEST_PROGRAM}
24563 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
24564 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
24565 @end defmac
24567 @defmac AC_TIMEZONE
24568 @acindex{TIMEZONE}
24569 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
24570 @end defmac
24572 @defmac AC_TIME_WITH_SYS_TIME
24573 @acindex{TIME_WITH_SYS_TIME}
24574 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}), which is
24575 itself obsolete; nowadays one need only do
24576 @samp{AC_CHECK_HEADERS([sys/time.h])}.
24577 @end defmac
24579 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
24580   @ovar{action-if-true}, @ovar{action-if-false})
24581 @acindex{TRY_COMPILE}
24582 Same as:
24584 @example
24585 AC_COMPILE_IFELSE(
24586   [AC_LANG_PROGRAM([[@var{includes}]],
24587      [[@var{function-body}]])],
24588   [@var{action-if-true}],
24589   [@var{action-if-false}])
24590 @end example
24592 @noindent
24593 @xref{Running the Compiler}.
24595 This macro double quotes both @var{includes} and @var{function-body}.
24597 For C and C++, @var{includes} is any @code{#include} statements needed
24598 by the code in @var{function-body} (@var{includes} is ignored if
24599 the currently selected language is Fortran or Fortran 77).  The compiler
24600 and compilation flags are determined by the current language
24601 (@pxref{Language Choice}).
24602 @end defmac
24604 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
24605 @acindex{TRY_CPP}
24606 Same as:
24608 @example
24609 AC_PREPROC_IFELSE(
24610   [AC_LANG_SOURCE([[@var{input}]])],
24611   [@var{action-if-true}],
24612   [@var{action-if-false}])
24613 @end example
24615 @noindent
24616 @xref{Running the Preprocessor}.
24618 This macro double quotes the @var{input}.
24619 @end defmac
24621 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
24622   @ovar{action-if-true}, @ovar{action-if-false})
24623 @acindex{TRY_LINK}
24624 Same as:
24626 @example
24627 AC_LINK_IFELSE(
24628   [AC_LANG_PROGRAM([[@var{includes}]],
24629      [[@var{function-body}]])],
24630   [@var{action-if-true}],
24631   [@var{action-if-false}])
24632 @end example
24634 @noindent
24635 @xref{Running the Linker}.
24637 This macro double quotes both @var{includes} and @var{function-body}.
24639 Depending on the current language (@pxref{Language Choice}), create a
24640 test program to see whether a function whose body consists of
24641 @var{function-body} can be compiled and linked.  If the file compiles
24642 and links successfully, run shell commands @var{action-if-found},
24643 otherwise run @var{action-if-not-found}.
24645 This macro double quotes both @var{includes} and @var{function-body}.
24647 For C and C++, @var{includes} is any @code{#include} statements needed
24648 by the code in @var{function-body} (@var{includes} is ignored if
24649 the currently selected language is Fortran or Fortran 77).  The compiler
24650 and compilation flags are determined by the current language
24651 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
24652 @code{LIBS} are used for linking.
24653 @end defmac
24655 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
24656   @ovar{action-if-not-found})
24657 @acindex{TRY_LINK_FUNC}
24658 This macro is equivalent to
24659 @example
24660 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
24661   [@var{action-if-found}], [@var{action-if-not-found}])
24662 @end example
24663 @noindent
24664 @xref{Running the Linker}.
24665 @end defmac
24667 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
24668   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
24669 @acindex{TRY_RUN}
24670 Same as:
24672 @example
24673 AC_RUN_IFELSE(
24674   [AC_LANG_SOURCE([[@var{program}]])],
24675   [@var{action-if-true}],
24676   [@var{action-if-false}],
24677   [@var{action-if-cross-compiling}])
24678 @end example
24680 @noindent
24681 @xref{Runtime}.
24682 @end defmac
24684 @anchor{AC_TYPE_SIGNAL}
24685 @defmac AC_TYPE_SIGNAL
24686 @acindex{TYPE_SIGNAL}
24687 @cvindex RETSIGTYPE
24688 @hdrindex{signal.h}
24689 If @file{signal.h} declares @code{signal} as returning a pointer to a
24690 function returning @code{void}, define @code{RETSIGTYPE} to be
24691 @code{void}; otherwise, define it to be @code{int}.  These days, it is
24692 portable to assume C89, and that signal handlers return @code{void},
24693 without needing to use this macro or @code{RETSIGTYPE}.
24695 When targeting older K&R C, it is possible to define signal handlers as
24696 returning type @code{RETSIGTYPE}, and omit a return statement:
24698 @example
24699 @group
24700 RETSIGTYPE
24701 hup_handler ()
24703 @dots{}
24705 @end group
24706 @end example
24707 @end defmac
24709 @defmac AC_UID_T
24710 @acindex{UID_T}
24711 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
24712 @end defmac
24714 @defmac AC_UNISTD_H
24715 @acindex{UNISTD_H}
24716 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}),
24717 which is one of the tests done as a side effect by
24718 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), so usually
24719 unnecessary to write explicitly.
24720 @end defmac
24722 @defmac AC_USG
24723 @acindex{USG}
24724 @cvindex USG
24725 Define @code{USG} if the BSD string functions (@code{bcopy},
24726 @code{bzero}, @code{index}, @code{rindex}, etc) are @emph{not} defined
24727 in @file{strings.h}.  Modern code should assume @file{string.h} exists
24728 and should use the ISO C string functions (@code{memmove}, @code{memset},
24729 @code{strchr}, @code{strrchr}, etc) unconditionally.
24731 @file{strings.h} may be the only header that declares @code{strcasecmp},
24732 @code{strncasecmp}, and @code{ffs}.  @code{AC_INCLUDES_DEFAULT} checks
24733 for it (@pxref{Default Includes}); test @code{HAVE_STRINGS_H}.
24734 @end defmac
24736 @defmac AC_UTIME_NULL
24737 @acindex{UTIME_NULL}
24738 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
24739 @end defmac
24741 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
24742 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
24743 If the cache file is inconsistent with the current host, target and
24744 build system types, it used to execute @var{cmd} or print a default
24745 error message.  This is now handled by default.
24746 @end defmac
24748 @defmac AC_VERBOSE (@var{result-description})
24749 @acindex{VERBOSE}
24750 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
24751 @end defmac
24753 @defmac AC_VFORK
24754 @acindex{VFORK}
24755 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
24756 @end defmac
24758 @defmac AC_VPRINTF
24759 @acindex{VPRINTF}
24760 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
24761 @end defmac
24763 @defmac AC_WAIT3
24764 @acindex{WAIT3}
24765 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
24766 portable programs should use @code{waitpid}, not @code{wait3}, as
24767 @code{wait3} has been removed from Posix.
24768 @end defmac
24770 @defmac AC_WARN
24771 @acindex{WARN}
24772 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
24773 @end defmac
24775 @defmac AC_WARNING (@var{message})
24776 @acindex{WARNING}
24777 Replaced by @code{m4_warn} (@pxref{m4_warn}).
24778 @end defmac
24780 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
24781   @ovar{action-if-not-given})
24782 @acindex{WITH}
24783 This is an obsolete version of @code{AC_ARG_WITH} that does not
24784 support providing a help string (@pxref{AC_ARG_WITH}).
24785 @end defmac
24787 @defmac AC_WORDS_BIGENDIAN
24788 @acindex{WORDS_BIGENDIAN}
24789 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
24790 @end defmac
24792 @defmac AC_XENIX_DIR
24793 @acindex{XENIX_DIR}
24794 @ovindex LIBS
24795 This macro used to add @option{-lx} to output variable @code{LIBS} if on
24796 Xenix.  Also, if @file{dirent.h} is being checked for, added
24797 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
24798 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
24799 running XENIX on which you should not depend:
24801 @example
24802 AC_MSG_CHECKING([for Xenix])
24803 AC_EGREP_CPP([yes],
24804 [#if defined M_XENIX && !defined M_UNIX
24805   yes
24806 #endif],
24807              [AC_MSG_RESULT([yes]); XENIX=yes],
24808              [AC_MSG_RESULT([no]); XENIX=])
24809 @end example
24810 @noindent
24811 Don't use this macro, the dignified means to check the nature of the
24812 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24813 @end defmac
24815 @defmac AC_YYTEXT_POINTER
24816 @acindex{YYTEXT_POINTER}
24817 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
24818 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
24819 @end defmac
24821 @node Autoconf 1
24822 @section Upgrading From Version 1
24823 @cindex Upgrading autoconf
24824 @cindex Autoconf upgrading
24826 Autoconf version 2 is mostly backward compatible with version 1.
24827 However, it introduces better ways to do some things, and doesn't
24828 support some of the ugly things in version 1.  So, depending on how
24829 sophisticated your @file{configure.ac} files are, you might have to do
24830 some manual work in order to upgrade to version 2.  This chapter points
24831 out some problems to watch for when upgrading.  Also, perhaps your
24832 @command{configure} scripts could benefit from some of the new features in
24833 version 2; the changes are summarized in the file @file{NEWS} in the
24834 Autoconf distribution.
24836 @menu
24837 * Changed File Names::          Files you might rename
24838 * Changed Makefiles::           New things to put in @file{Makefile.in}
24839 * Changed Macros::              Macro calls you might replace
24840 * Changed Results::             Changes in how to check test results
24841 * Changed Macro Writing::       Better ways to write your own macros
24842 @end menu
24844 @node Changed File Names
24845 @subsection Changed File Names
24847 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
24848 in a particular package's source directory), you must rename it to
24849 @file{acsite.m4}.  @xref{autoconf Invocation}.
24851 If you distribute @file{install.sh} with your package, rename it to
24852 @file{install-sh} so @command{make} builtin rules don't inadvertently
24853 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
24854 looks for the script under both names, but it is best to use the new name.
24856 If you were using @file{config.h.top}, @file{config.h.bot}, or
24857 @file{acconfig.h}, you still can, but you have less clutter if you
24858 use the @code{AH_} macros.  @xref{Autoheader Macros}.
24860 @node Changed Makefiles
24861 @subsection Changed Makefiles
24863 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
24864 your @file{Makefile.in} files, so they can take advantage of the values
24865 of those variables in the environment when @command{configure} is run.
24866 Doing this isn't necessary, but it's a convenience for users.
24868 Also add @samp{@@configure_input@@} in a comment to each input file for
24869 @code{AC_OUTPUT}, so that the output files contain a comment saying
24870 they were produced by @command{configure}.  Automatically selecting the
24871 right comment syntax for all the kinds of files that people call
24872 @code{AC_OUTPUT} on became too much work.
24874 Add @file{config.log} and @file{config.cache} to the list of files you
24875 remove in @code{distclean} targets.
24877 If you have the following in @file{Makefile.in}:
24879 @example
24880 prefix = /usr/local
24881 exec_prefix = $(prefix)
24882 @end example
24884 @noindent
24885 you must change it to:
24887 @example
24888 prefix = @@prefix@@
24889 exec_prefix = @@exec_prefix@@
24890 @end example
24892 @noindent
24893 The old behavior of replacing those variables without @samp{@@}
24894 characters around them has been removed.
24896 @node Changed Macros
24897 @subsection Changed Macros
24899 Many of the macros were renamed in Autoconf version 2.  You can still
24900 use the old names, but the new ones are clearer, and it's easier to find
24901 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
24902 new names for the old macros.  Use the @command{autoupdate} program to
24903 convert your @file{configure.ac} to using the new macro names.
24904 @xref{autoupdate Invocation}.
24906 Some macros have been superseded by similar ones that do the job better,
24907 but are not call-compatible.  If you get warnings about calling obsolete
24908 macros while running @command{autoconf}, you may safely ignore them, but
24909 your @command{configure} script generally works better if you follow
24910 the advice that is printed about what to replace the obsolete macros with.  In
24911 particular, the mechanism for reporting the results of tests has
24912 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
24913 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
24914 looks better if you switch to @code{AC_MSG_CHECKING} and
24915 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
24916 in conjunction with cache variables.  @xref{Caching Results}.
24920 @node Changed Results
24921 @subsection Changed Results
24923 If you were checking the results of previous tests by examining the
24924 shell variable @code{DEFS}, you need to switch to checking the values of
24925 the cache variables for those tests.  @code{DEFS} no longer exists while
24926 @command{configure} is running; it is only created when generating output
24927 files.  This difference from version 1 is because properly quoting the
24928 contents of that variable turned out to be too cumbersome and
24929 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
24930 Variable Names}.
24932 For example, here is a @file{configure.ac} fragment written for Autoconf
24933 version 1:
24935 @example
24936 AC_HAVE_FUNCS(syslog)
24937 case "$DEFS" in
24938 *-DHAVE_SYSLOG*) ;;
24939 *) # syslog is not in the default libraries.  See if it's in some other.
24940   saved_LIBS="$LIBS"
24941   for lib in bsd socket inet; do
24942     AC_CHECKING(for syslog in -l$lib)
24943     LIBS="-l$lib $saved_LIBS"
24944     AC_HAVE_FUNCS(syslog)
24945     case "$DEFS" in
24946     *-DHAVE_SYSLOG*) break ;;
24947     *) ;;
24948     esac
24949     LIBS="$saved_LIBS"
24950   done ;;
24951 esac
24952 @end example
24954 Here is a way to write it for version 2:
24956 @example
24957 AC_CHECK_FUNCS([syslog])
24958 if test "x$ac_cv_func_syslog" = xno; then
24959   # syslog is not in the default libraries.  See if it's in some other.
24960   for lib in bsd socket inet; do
24961     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
24962       LIBS="-l$lib $LIBS"; break])
24963   done
24965 @end example
24967 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
24968 backslashes before quotes, you need to remove them.  It now works
24969 predictably, and does not treat quotes (except back quotes) specially.
24970 @xref{Setting Output Variables}.
24972 All of the Boolean shell variables set by Autoconf macros now use
24973 @samp{yes} for the true value.  Most of them use @samp{no} for false,
24974 though for backward compatibility some use the empty string instead.  If
24975 you were relying on a shell variable being set to something like 1 or
24976 @samp{t} for true, you need to change your tests.
24978 @node Changed Macro Writing
24979 @subsection Changed Macro Writing
24981 When defining your own macros, you should now use @code{AC_DEFUN}
24982 instead of @code{define}.  @code{AC_DEFUN} automatically calls
24983 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
24984 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
24985 messages on the screen.  There's no actual harm in continuing to use the
24986 older way, but it's less convenient and attractive.  @xref{Macro
24987 Definitions}.
24989 You probably looked at the macros that came with Autoconf as a guide for
24990 how to do things.  It would be a good idea to take a look at the new
24991 versions of them, as the style is somewhat improved and they take
24992 advantage of some new features.
24994 If you were doing tricky things with undocumented Autoconf internals
24995 (macros, variables, diversions), check whether you need to change
24996 anything to account for changes that have been made.  Perhaps you can
24997 even use an officially supported technique in version 2 instead of
24998 kludging.  Or perhaps not.
25000 To speed up your locally written feature tests, add caching to them.
25001 See whether any of your tests are of general enough usefulness to
25002 encapsulate them into macros that you can share.
25005 @node Autoconf 2.13
25006 @section Upgrading From Version 2.13
25007 @cindex Upgrading autoconf
25008 @cindex Autoconf upgrading
25010 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
25011 suits this section@enddots{}
25013 @quotation
25014 Autoconf version 2.50 is mostly backward compatible with version 2.13.
25015 However, it introduces better ways to do some things, and doesn't
25016 support some of the ugly things in version 2.13.  So, depending on how
25017 sophisticated your @file{configure.ac} files are, you might have to do
25018 some manual work in order to upgrade to version 2.50.  This chapter
25019 points out some problems to watch for when upgrading.  Also, perhaps
25020 your @command{configure} scripts could benefit from some of the new
25021 features in version 2.50; the changes are summarized in the file
25022 @file{NEWS} in the Autoconf distribution.
25023 @end quotation
25025 @menu
25026 * Changed Quotation::           Broken code which used to work
25027 * New Macros::                  Interaction with foreign macros
25028 * Hosts and Cross-Compilation::  Bugward compatibility kludges
25029 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
25030 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
25031 @end menu
25033 @node Changed Quotation
25034 @subsection Changed Quotation
25036 The most important changes are invisible to you: the implementation of
25037 most macros have completely changed.  This allowed more factorization of
25038 the code, better error messages, a higher uniformity of the user's
25039 interface etc.  Unfortunately, as a side effect, some construct which
25040 used to (miraculously) work might break starting with Autoconf 2.50.
25041 The most common culprit is bad quotation.
25043 For instance, in the following example, the message is not properly
25044 quoted:
25046 @example
25047 AC_INIT
25048 AC_CHECK_HEADERS(foo.h, ,
25049   AC_MSG_ERROR(cannot find foo.h, bailing out))
25050 AC_OUTPUT
25051 @end example
25053 @noindent
25054 Autoconf 2.13 simply ignores it:
25056 @example
25057 $ @kbd{autoconf-2.13; ./configure --silent}
25058 creating cache ./config.cache
25059 configure: error: cannot find foo.h
25061 @end example
25063 @noindent
25064 while Autoconf 2.50 produces a broken @file{configure}:
25066 @example
25067 $ @kbd{autoconf-2.50; ./configure --silent}
25068 configure: error: cannot find foo.h
25069 ./configure: exit: bad non-numeric arg `bailing'
25070 ./configure: exit: bad non-numeric arg `bailing'
25072 @end example
25074 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
25075 too!
25077 @example
25078 AC_INIT([Example], [1.0], [bug-example@@example.org])
25079 AC_CHECK_HEADERS([foo.h], [],
25080   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
25081 AC_OUTPUT
25082 @end example
25084 Many many (and many more) Autoconf macros were lacking proper quotation,
25085 including no less than@dots{} @code{AC_DEFUN} itself!
25087 @example
25088 $ @kbd{cat configure.in}
25089 AC_DEFUN([AC_PROG_INSTALL],
25090 [# My own much better version
25092 AC_INIT
25093 AC_PROG_INSTALL
25094 AC_OUTPUT
25095 $ @kbd{autoconf-2.13}
25096 autoconf: Undefined macros:
25097 ***BUG in Autoconf--please report*** AC_FD_MSG
25098 ***BUG in Autoconf--please report*** AC_EPI
25099 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
25100 configure.in:5:AC_PROG_INSTALL
25101 $ @kbd{autoconf-2.50}
25103 @end example
25106 @node New Macros
25107 @subsection New Macros
25109 @cindex undefined macro
25110 @cindex @code{_m4_divert_diversion}
25112 While Autoconf was relatively dormant in the late 1990s, Automake
25113 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
25114 in 2001, Autoconf provided
25115 versions of these macros, integrated in the @code{AC_} namespace,
25116 instead of @code{AM_}.  But in order to ease the upgrading via
25117 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
25119 Unfortunately older versions of Automake (e.g., Automake 1.4)
25120 did not quote the names of these macros.
25121 Therefore, when @command{m4} finds something like
25122 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
25123 @code{AM_TYPE_PTRDIFF_T} is
25124 expanded, replaced with its Autoconf definition.
25126 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
25127 complains, in its own words:
25129 @example
25130 $ @kbd{cat configure.ac}
25131 AC_INIT([Example], [1.0], [bug-example@@example.org])
25132 AM_TYPE_PTRDIFF_T
25133 $ @kbd{aclocal-1.4}
25134 $ @kbd{autoconf}
25135 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
25136 aclocal.m4:17: the top level
25137 autom4te: m4 failed with exit status: 1
25139 @end example
25141 Modern versions of Automake no longer define most of these
25142 macros, and properly quote the names of the remaining macros.
25143 If you must use an old Automake, do not depend upon macros from Automake
25144 as it is simply not its job
25145 to provide macros (but the one it requires itself):
25147 @example
25148 $ @kbd{cat configure.ac}
25149 AC_INIT([Example], [1.0], [bug-example@@example.org])
25150 AM_TYPE_PTRDIFF_T
25151 $ @kbd{rm aclocal.m4}
25152 $ @kbd{autoupdate}
25153 autoupdate: 'configure.ac' is updated
25154 $ @kbd{cat configure.ac}
25155 AC_INIT([Example], [1.0], [bug-example@@example.org])
25156 AC_CHECK_TYPES([ptrdiff_t])
25157 $ @kbd{aclocal-1.4}
25158 $ @kbd{autoconf}
25160 @end example
25163 @node Hosts and Cross-Compilation
25164 @subsection Hosts and Cross-Compilation
25165 @cindex Cross compilation
25167 Based on the experience of compiler writers, and after long public
25168 debates, many aspects of the cross-compilation chain have changed:
25170 @itemize @minus
25171 @item
25172 the relationship between the build, host, and target architecture types,
25174 @item
25175 the command line interface for specifying them to @command{configure},
25177 @item
25178 the variables defined in @command{configure},
25180 @item
25181 the enabling of cross-compilation mode.
25182 @end itemize
25184 @sp 1
25186 The relationship between build, host, and target have been cleaned up:
25187 the chain of default is now simply: target defaults to host, host to
25188 build, and build to the result of @command{config.guess}.  Nevertheless,
25189 in order to ease the transition from 2.13 to 2.50, the following
25190 transition scheme is implemented.  @emph{Do not rely on it}, as it will
25191 be completely disabled in a couple of releases (we cannot keep it, as it
25192 proves to cause more problems than it cures).
25194 They all default to the result of running @command{config.guess}, unless
25195 you specify either @option{--build} or @option{--host}.  In this case,
25196 the default becomes the system type you specified.  If you specify both,
25197 and they're different, @command{configure} enters cross compilation
25198 mode, so it doesn't run any tests that require execution.
25200 Hint: if you mean to override the result of @command{config.guess},
25201 prefer @option{--build} over @option{--host}.
25203 @sp 1
25205 For backward compatibility, @command{configure} accepts a system
25206 type as an option by itself.  Such an option overrides the
25207 defaults for build, host, and target system types.  The following
25208 configure statement configures a cross toolchain that runs on
25209 NetBSD/alpha but generates code for GNU Hurd/sparc,
25210 which is also the build platform.
25212 @example
25213 ./configure --host=alpha-netbsd sparc-gnu
25214 @end example
25216 @sp 1
25218 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
25219 and @code{target} had a different semantics before and after the
25220 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
25221 @option{--build} is strictly copied into @code{build_alias}, and is left
25222 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
25223 set to the canonicalized build type.  To ease the transition, before,
25224 its contents is the same as that of @code{build_alias}.  Do @emph{not}
25225 rely on this broken feature.
25227 For consistency with the backward compatibility scheme exposed above,
25228 when @option{--host} is specified but @option{--build} isn't, the build
25229 system is assumed to be the same as @option{--host}, and
25230 @samp{build_alias} is set to that value.  Eventually, this
25231 historically incorrect behavior will go away.
25233 @sp 1
25235 The former scheme to enable cross-compilation proved to cause more harm
25236 than good, in particular, it used to be triggered too easily, leaving
25237 regular end users puzzled in front of cryptic error messages.
25238 @command{configure} could even enter cross-compilation mode only
25239 because the compiler was not functional.  This is mainly because
25240 @command{configure} used to try to detect cross-compilation, instead of
25241 waiting for an explicit flag from the user.
25243 Now, @command{configure} enters cross-compilation mode if and only if
25244 @option{--host} is passed.
25246 That's the short documentation.  To ease the transition between 2.13 and
25247 its successors, a more complicated scheme is implemented.  @emph{Do not
25248 rely on the following}, as it will be removed in the near future.
25250 If you specify @option{--host}, but not @option{--build}, when
25251 @command{configure} performs the first compiler test it tries to run
25252 an executable produced by the compiler.  If the execution fails, it
25253 enters cross-compilation mode.  This is fragile.  Moreover, by the time
25254 the compiler test is performed, it may be too late to modify the
25255 build-system type: other tests may have already been performed.
25256 Therefore, whenever you specify @option{--host}, be sure to specify
25257 @option{--build} too.
25259 @example
25260 ./configure --build=x86_64-pc-linux-gnu --host=x86_64-w64-mingw64
25261 @end example
25263 @noindent
25264 enters cross-compilation mode.  The former interface, which
25265 consisted in setting the compiler to a cross-compiler without informing
25266 @command{configure} is obsolete.  For instance, @command{configure}
25267 fails if it can't run the code generated by the specified compiler if you
25268 configure as follows:
25270 @example
25271 ./configure CC=x86_64-w64-mingw64-gcc
25272 @end example
25275 @node AC_LIBOBJ vs LIBOBJS
25276 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
25278 Up to Autoconf 2.13, the replacement of functions was triggered via the
25279 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
25280 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
25281 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
25283 This change is mandated by the unification of the GNU Build System
25284 components.  In particular, the various fragile techniques used to parse
25285 a @file{configure.ac} are all replaced with the use of traces.  As a
25286 consequence, any action must be traceable, which obsoletes critical
25287 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
25288 and it can even be handled gracefully (read, ``without your having to
25289 change something'').
25291 There were two typical uses of @code{LIBOBJS}: asking for a replacement
25292 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
25294 @sp 1
25296 As for function replacement, the fix is immediate: use
25297 @code{AC_LIBOBJ}.  For instance:
25299 @example
25300 LIBOBJS="$LIBOBJS fnmatch.o"
25301 LIBOBJS="$LIBOBJS malloc.$ac_objext"
25302 @end example
25304 @noindent
25305 should be replaced with:
25307 @example
25308 AC_LIBOBJ([fnmatch])
25309 AC_LIBOBJ([malloc])
25310 @end example
25312 @sp 1
25314 @ovindex LIBOBJDIR
25315 When used with Automake 1.10 or newer, a suitable value for
25316 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
25317 can be referenced from any @file{Makefile.am}.  Even without Automake,
25318 arranging for @code{LIBOBJDIR} to be set correctly enables
25319 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
25320 The @code{LIBOBJDIR} feature is experimental.
25323 @node AC_ACT_IFELSE vs AC_TRY_ACT
25324 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
25325 @c the anchor keeps the old node name, to try to avoid breaking links
25326 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
25328 @acindex{@var{ACT}_IFELSE}
25329 @acindex{TRY_@var{ACT}}
25330 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
25331 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
25332 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
25333 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
25334 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
25335 @code{AC_TRY_RUN}.  The motivations where:
25336 @itemize @minus
25337 @item
25338 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
25339 quoting their arguments;
25341 @item
25342 the combinatorial explosion is solved by decomposing on the one hand the
25343 generation of sources, and on the other hand executing the program;
25345 @item
25346 this scheme helps supporting more languages than plain C and C++.
25347 @end itemize
25349 In addition to the change of syntax, the philosophy has changed too:
25350 while emphasis was put on speed at the expense of accuracy, today's
25351 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
25352 expense of speed.
25355 As a perfect example of what is @emph{not} to be done, here is how to
25356 find out whether a header file contains a particular declaration, such
25357 as a typedef, a structure, a structure member, or a function.  Use
25358 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
25359 header file; on some systems the symbol might be defined in another
25360 header file that the file you are checking includes.
25362 As a (bad) example, here is how you should not check for C preprocessor
25363 symbols, either defined by header files or predefined by the C
25364 preprocessor: using @code{AC_EGREP_CPP}:
25366 @example
25367 @group
25368 AC_EGREP_CPP(yes,
25369 [#ifdef _AIX
25370   yes
25371 #endif
25372 ], is_aix=yes, is_aix=no)
25373 @end group
25374 @end example
25376 The above example, properly written would (i) use
25377 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
25379 @example
25380 @group
25381 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
25382 [[#ifndef _AIX
25383  error: This isn't AIX!
25384 #endif
25385 ]])],
25386                    [is_aix=yes],
25387                    [is_aix=no])
25388 @end group
25389 @end example
25392 @c ============================= Generating Test Suites with Autotest
25394 @node Using Autotest
25395 @chapter Generating Test Suites with Autotest
25397 @cindex Autotest
25399 @display
25400 @strong{N.B.: This section describes a feature which is still
25401 stabilizing.  Although we believe that Autotest is useful as-is, this
25402 documentation describes an interface which might change in the future:
25403 do not depend upon Autotest without subscribing to the Autoconf mailing
25404 lists.}
25405 @end display
25407 It is paradoxical that portable projects depend on nonportable tools
25408 to run their test suite.  Autoconf by itself is the paragon of this
25409 problem: although it aims at perfectly portability, up to 2.13 its
25410 test suite was using DejaGNU, a rich and complex testing
25411 framework, but which is far from being standard on Posix systems.
25412 Worse yet, it was likely to be missing on the most fragile platforms,
25413 the very platforms that are most likely to torture Autoconf and
25414 exhibit deficiencies.
25416 To circumvent this problem, many package maintainers have developed their
25417 own testing framework, based on simple shell scripts whose sole outputs
25418 are exit status values describing whether the test succeeded.  Most of
25419 these tests share common patterns, and this can result in lots of
25420 duplicated code and tedious maintenance.
25422 Following exactly the same reasoning that yielded to the inception of
25423 Autoconf, Autotest provides a test suite generation framework, based on
25424 M4 macros building a portable shell script.  The suite itself is
25425 equipped with automatic logging and tracing facilities which greatly
25426 diminish the interaction with bug reporters, and simple timing reports.
25428 Autoconf itself has been using Autotest for years, and we do attest that
25429 it has considerably improved the strength of the test suite and the
25430 quality of bug reports.  Other projects are known to use some generation
25431 of Autotest, such as Bison, GNU Wdiff, GNU Tar, each of
25432 them with different needs, and this usage has validated Autotest as a general
25433 testing framework.
25435 Nonetheless, compared to DejaGNU, Autotest is inadequate for
25436 interactive tool testing, which is probably its main limitation.
25438 @menu
25439 * Using an Autotest Test Suite::  Autotest and the user
25440 * Writing Testsuites::          Autotest macros
25441 * testsuite Invocation::        Running @command{testsuite} scripts
25442 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
25443 @end menu
25445 @node Using an Autotest Test Suite
25446 @section Using an Autotest Test Suite
25448 @menu
25449 * testsuite Scripts::           The concepts of Autotest
25450 * Autotest Logs::               Their contents
25451 @end menu
25453 @node testsuite Scripts
25454 @subsection @command{testsuite} Scripts
25456 @cindex @command{testsuite}
25458 Generating testing or validation suites using Autotest is rather easy.
25459 The whole validation suite is held in a file to be processed through
25460 @command{autom4te}, itself using GNU M4 under the hood, to
25461 produce a stand-alone Bourne shell script which then gets distributed.
25462 Neither @command{autom4te} nor GNU M4 are needed at
25463 the installer's end.
25465 @cindex test group
25466 Each test of the validation suite should be part of some test group.  A
25467 @dfn{test group} is a sequence of interwoven tests that ought to be
25468 executed together, usually because one test in the group creates data
25469 files that a later test in the same group needs to read.  Complex test
25470 groups make later debugging more tedious.  It is much better to
25471 keep only a few tests per test group.  Ideally there is only one test
25472 per test group.
25474 For all but the simplest packages, some file such as @file{testsuite.at}
25475 does not fully hold all test sources, as these are often easier to
25476 maintain in separate files.  Each of these separate files holds a single
25477 test group, or a sequence of test groups all addressing some common
25478 functionality in the package.  In such cases, @file{testsuite.at}
25479 merely initializes the validation suite, and sometimes does elementary
25480 health checking, before listing include statements for all other test
25481 files.  The special file @file{package.m4}, containing the
25482 identification of the package, is automatically included if found.
25484 A convenient alternative consists in moving all the global issues
25485 (local Autotest macros, elementary health checking, and @code{AT_INIT}
25486 invocation) into the file @code{local.at}, and making
25487 @file{testsuite.at} be a simple list of @code{m4_include}s of sub test
25488 suites.  In such case, generating the whole test suite or pieces of it
25489 is only a matter of choosing the @command{autom4te} command line
25490 arguments.
25492 The validation scripts that Autotest produces are by convention called
25493 @command{testsuite}.  When run, @command{testsuite} executes each test
25494 group in turn, producing only one summary line per test to say if that
25495 particular test succeeded or failed.  At end of all tests, summarizing
25496 counters get printed.  One debugging directory is left for each test
25497 group which failed, if any: such directories are named
25498 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
25499 the test group, and they include:
25501 @itemize @bullet
25502 @item a debugging script named @file{run} which reruns the test in
25503 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
25504 of debugging scripts has the purpose of easing the chase for bugs.
25506 @item all the files created with @code{AT_DATA}
25508 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
25510 @item a log of the run, named @file{testsuite.log}
25511 @end itemize
25513 In the ideal situation, none of the tests fail, and consequently no
25514 debugging directory is left behind for validation.
25516 It often happens in practice that individual tests in the validation
25517 suite need to get information coming out of the configuration process.
25518 Some of this information, common for all validation suites, is provided
25519 through the file @file{atconfig}, automatically created by
25520 @code{AC_CONFIG_TESTDIR}.  For configuration information which your
25521 testing environment specifically needs, you might prepare an optional
25522 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
25523 The configuration process produces @file{atconfig} and @file{atlocal}
25524 out of these two input files, and these two produced files are
25525 automatically read by the @file{testsuite} script.
25527 Here is a diagram showing the relationship between files.
25529 @noindent
25530 Files used in preparing a software package for distribution:
25532 @example
25533                 [package.m4] -->.
25534                                  \
25535 subfile-1.at ->.  [local.at] ---->+
25536     ...         \                  \
25537 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
25538     ...         /
25539 subfile-n.at ->'
25540 @end example
25542 @noindent
25543 Files used in configuring a software package:
25545 @example
25546                                      .--> atconfig
25547                                     /
25548 [atlocal.in] -->  config.status* --<
25549                                     \
25550                                      `--> [atlocal]
25551 @end example
25553 @noindent
25554 Files created during test suite execution:
25556 @example
25557 atconfig -->.                    .--> testsuite.log
25558              \                  /
25559               >-- testsuite* --<
25560              /                  \
25561 [atlocal] ->'                    `--> [testsuite.dir]
25562 @end example
25565 @node Autotest Logs
25566 @subsection Autotest Logs
25568 When run, the test suite creates a log file named after itself, e.g., a
25569 test suite named @command{testsuite} creates @file{testsuite.log}.  It
25570 contains a lot of information, usually more than maintainers actually
25571 need, but therefore most of the time it contains all that is needed:
25573 @table @asis
25574 @item command line arguments
25575 A bad but unfortunately widespread habit consists of
25576 setting environment variables before the command, such as in
25577 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
25578 know this change, hence (i) it cannot report it to you, and (ii)
25579 it cannot preserve the value of @code{CC} for subsequent runs.
25580 Autoconf faced exactly the same problem, and solved it by asking
25581 users to pass the variable definitions as command line arguments.
25582 Autotest requires this rule, too, but has no means to enforce it; the log
25583 then contains a trace of the variables that were changed by the user.
25585 @item @file{ChangeLog} excerpts
25586 The topmost lines of all the @file{ChangeLog} files found in the source
25587 hierarchy.  This is especially useful when bugs are reported against
25588 development versions of the package, since the version string does not
25589 provide sufficient information to know the exact state of the sources
25590 the user compiled.  Of course, this relies on the use of a
25591 @file{ChangeLog}.
25593 @item build machine
25594 Running a test suite in a cross-compile environment is not an easy task,
25595 since it would mean having the test suite run on a machine @var{build},
25596 while running programs on a machine @var{host}.  It is much simpler to
25597 run both the test suite and the programs on @var{host}, but then, from
25598 the point of view of the test suite, there remains a single environment,
25599 @var{host} = @var{build}.  The log contains relevant information on the
25600 state of the @var{build} machine, including some important environment
25601 variables.
25602 @c FIXME: How about having an M4sh macro to say "hey, log the value
25603 @c of '@dots{}'"?  This would help both Autoconf and Autotest.
25605 @item tested programs
25606 The absolute file name and answers to @option{--version} of the tested
25607 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
25609 @item configuration log
25610 The contents of @file{config.log}, as created by @command{configure},
25611 are appended.  It contains the configuration flags and a detailed report
25612 on the configuration itself.
25613 @end table
25616 @node Writing Testsuites
25617 @section Writing @file{testsuite.at}
25619 The @file{testsuite.at} is a Bourne shell script making use of special
25620 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
25621 its beginning followed by one call to @code{m4_include} per source file
25622 for tests.  Each such included file, or the remainder of
25623 @file{testsuite.at} if include files are not used, contain a sequence of
25624 test groups.  Each test group begins with a call to @code{AT_SETUP},
25625 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
25626 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
25627 groups can be categorized by a call to @code{AT_BANNER}.
25629 All of the public Autotest macros have all-uppercase names in the
25630 namespace @samp{^AT_} to prevent them from accidentally conflicting with
25631 other text; Autoconf also reserves the namespace @samp{^_AT_} for
25632 internal macros.  All shell variables used in the testsuite for internal
25633 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
25634 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
25635 makes use of the file system namespace @samp{^at-}.
25637 Since Autoconf is built on top of M4sugar (@pxref{Programming in
25638 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
25639 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
25640 @emph{should not use} the namespace of a package that does not own the
25641 macro or shell code you are writing.
25643 @defmac AT_INIT (@ovar{name})
25644 @atindex{INIT}
25645 @c FIXME: Not clear, plus duplication of the information.
25646 Initialize Autotest.  Giving a @var{name} to the test suite is
25647 encouraged if your package includes several test suites.  Before this
25648 macro is called, @code{AT_PACKAGE_STRING} and
25649 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
25650 information about the testsuite to the user.  Typically, these macros
25651 are provided by a file @file{package.m4} built by @command{make}
25652 (@pxref{Making testsuite Scripts}), in order to inherit the package
25653 name, version, and bug reporting address from @file{configure.ac}.
25654 @end defmac
25656 @defmac AT_COPYRIGHT (@var{copyright-notice})
25657 @atindex{COPYRIGHT}
25658 @cindex Copyright Notice
25659 State that, in addition to the Free Software Foundation's copyright on
25660 the Autotest macros, parts of your test suite are covered by
25661 @var{copyright-notice}.
25663 The @var{copyright-notice} shows up in both the head of
25664 @command{testsuite} and in @samp{testsuite --version}.
25665 @end defmac
25667 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
25668   @ovar{action-if-given}, @ovar{action-if-not-given})
25669 @atindex{ARG_OPTION}
25670 @vrindex at_arg_@var{option}
25671 Accept options from the space-separated list @var{options}, a list that
25672 has leading dashes removed from the options.  Long options will be
25673 prefixed with @samp{--}, single-character options with @samp{-}.  The
25674 first word in this list is the primary @var{option}, any others are
25675 assumed to be short-hand aliases.  The variable associated with it
25676 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
25677 with underscores.
25679 If the user passes @option{--@var{option}} to the @command{testsuite},
25680 the variable will be set to @samp{:}.  If the user does not pass the
25681 option, or passes @option{--no-@var{option}}, then the variable will be
25682 set to @samp{false}.
25684 @vrindex at_optarg
25685 @vrindex at_optarg_@var{option}
25686 @var{action-if-given} is run each time the option is encountered; here,
25687 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
25688 appropriate.  @code{at_optarg} is actually just a copy of
25689 @code{at_arg_@var{option}}.
25691 @var{action-if-not-given} will be run once after option parsing is
25692 complete and if no option from @var{options} was used.
25694 @var{help-text} is added to the end of the list of options shown in
25695 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25697 It is recommended that you use a package-specific prefix to @var{options}
25698 names in order to avoid clashes with future Autotest built-in options.
25699 @end defmac
25701 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
25702   @ovar{action-if-given}, @ovar{action-if-not-given})
25703 @atindex{ARG_OPTION_ARG}
25704 @vrindex at_arg_@var{option}
25705 Accept options with arguments from the space-separated list
25706 @var{options}, a list that has leading dashes removed from the options.
25707 Long options will be prefixed with @samp{--}, single-character options
25708 with @samp{-}.  The first word in this list is the primary @var{option},
25709 any others are assumed to be short-hand aliases.  The variable associated
25710 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
25711 replaced with underscores.
25713 If the user passes @option{--@var{option}=@var{arg}} or
25714 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
25715 variable will be set to @samp{@var{arg}}.
25717 @vrindex at_optarg
25718 @var{action-if-given} is run each time the option is encountered; here,
25719 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
25720 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
25722 @var{action-if-not-given} will be run once after option parsing is
25723 complete and if no option from @var{options} was used.
25725 @var{help-text} is added to the end of the list of options shown in
25726 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25728 It is recommended that you use a package-specific prefix to @var{options}
25729 names in order to avoid clashes with future Autotest built-in options.
25730 @end defmac
25732 @defmac AT_COLOR_TESTS
25733 @atindex{COLOR_TESTS}
25734 Enable colored test results by default when the output is connected to
25735 a terminal.
25736 @end defmac
25738 @defmac AT_TESTED (@var{executables})
25739 @atindex{TESTED}
25740 Log the file name and answer to @option{--version} of each program in
25741 space-separated list @var{executables}.  Several invocations register
25742 new executables, in other words, don't fear registering one program
25743 several times.
25745 Autotest test suites rely on @env{PATH} to find the tested program.
25746 This avoids the need to generate absolute names of the various tools, and
25747 makes it possible to test installed programs.  Therefore, knowing which
25748 programs are being exercised is crucial to understanding problems in
25749 the test suite itself, or its occasional misuses.  It is a good idea to
25750 also subscribe foreign programs you depend upon, to avoid incompatible
25751 diagnostics.
25753 @var{executables} is implicitly wrapped in shell double quotes, but it
25754 will still use shell variable expansion (@samp{$}), command substitution
25755 (@samp{`}), and backslash escaping (@samp{\}).  In particular, the
25756 @env{EXEEXT} variable is available if it is passed to the testsuite
25757 via @file{atlocal} or @file{atconfig}.
25758 @end defmac
25760 @defmac AT_PREPARE_TESTS (@var{shell-code})
25761 @atindex{PREPARE_TESTS}
25762 Execute @var{shell-code} in the main testsuite process,
25763 after initializing the test suite and processing command-line options,
25764 but before running any tests.  If this macro is used several times,
25765 all of the @var{shell-code}s will be executed,
25766 in the order they appeared in @file{testsuite.at}.
25768 One reason to use @code{AT_PREPARE_TESTS} is when the programs under
25769 test are sensitive to environment variables: you can unset all these
25770 variables or reset them to safe values in @var{shell-code}.
25772 @var{shell-code} is only executed if at least one test is going to be
25773 run.  In particular, it will not be executed if any of the @option{--help},
25774 @option{--version}, @option{--list}, or @option{--clean} options are
25775 given to @command{testsuite} (@pxref{testsuite Invocation}).
25776 @end defmac
25778 @defmac AT_PREPARE_EACH_TEST (@var{shell-code})
25779 @atindex{AT_PREPARE_EACH_TEST}
25780 Execute @var{shell-code} in each test group's subshell, at the point of
25781 the @code{AT_SETUP} that starts the test group.
25782 @end defmac
25784 @defmac AT_TEST_HELPER_FN (@var{name}, @var{args}, @var{description}, @var{code})
25785 Define a shell function that will be available to the code for each test
25786 group.  Its name will be @code{ath_fn_@var{name}}, and its body will be
25787 @var{code}.  (The prefix prevents name conflicts with shell functions
25788 defined by M4sh and Autotest.)
25790 @var{args} should describe the function's arguments and @var{description}
25791 what it does; these are used only for documentation comments in the
25792 generated testsuite script.
25793 @end defmac
25795 @sp 1
25797 @defmac AT_BANNER (@var{test-category-name})
25798 @atindex{BANNER}
25799 This macro identifies the start of a category of related test groups.
25800 When the resulting @file{testsuite} is invoked with more than one test
25801 group to run, its output will include a banner containing
25802 @var{test-category-name} prior to any tests run from that category.  The
25803 banner should be no more than about 40 or 50 characters.  A blank banner
25804 indicates uncategorized tests; an empty line will be inserted after
25805 tests from an earlier category, effectively ending that category.
25806 @end defmac
25808 @defmac AT_SETUP (@var{test-group-name})
25809 @atindex{SETUP}
25810 This macro starts a group of related tests, all to be executed in the
25811 same subshell.  It accepts a single argument, which holds a few words
25812 (no more than about 30 or 40 characters) quickly describing the purpose
25813 of the test group being started.  @var{test-group-name} must not expand
25814 to unbalanced quotes, although quadrigraphs can be used.
25815 @end defmac
25817 @defmac AT_KEYWORDS (@var{keywords})
25818 @atindex{KEYWORDS}
25819 Associate the space-separated list of @var{keywords} to the enclosing
25820 test group.  This makes it possible to run ``slices'' of the test suite.
25821 For instance, if some of your test groups exercise some @samp{foo}
25822 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
25823 @samp{./testsuite -k foo} to run exclusively these test groups.  The
25824 @var{test-group-name} of the test group is automatically recorded to
25825 @code{AT_KEYWORDS}.
25827 Several invocations within a test group accumulate new keywords.  In
25828 other words, don't fear registering the same keyword several times in a
25829 test group.
25830 @end defmac
25832 @defmac AT_CAPTURE_FILE (@var{file})
25833 @atindex{CAPTURE_FILE}
25834 If the current test group fails, log the contents of @var{file}.
25835 Several identical calls within one test group have no additional effect.
25836 @end defmac
25838 @defmac AT_FAIL_IF (@var{shell-condition})
25839 @atindex{FAIL_IF}
25840 Make the test group fail and skip the rest of its execution, if
25841 @var{shell-condition} is true.  @var{shell-condition} is a shell expression
25842 such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
25843 will be executed and may still cause the test group to be skipped.
25844 You can instantiate this macro many times from within the same test group.
25846 You should use this macro only for very simple failure conditions.  If the
25847 @var{shell-condition} could emit any kind of output you should instead
25848 use @command{AT_CHECK} like
25849 @example
25850 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
25851 @end example
25852 @noindent
25853 so that such output is properly recorded in the @file{testsuite.log}
25854 file.
25855 @end defmac
25857 @defmac AT_SKIP_IF (@var{shell-condition})
25858 @atindex{SKIP_IF}
25859 Determine whether the test should be skipped because it requires
25860 features that are unsupported on the machine under test.
25861 @var{shell-condition} is a shell expression such as a @code{test}
25862 command.  Tests before @command{AT_SKIP_IF} will be executed
25863 and may still cause the test group to fail.  You can instantiate this
25864 macro many times from within the same test group.
25866 You should use this macro only for very simple skip conditions.  If the
25867 @var{shell-condition} could emit any kind of output you should instead
25868 use @command{AT_CHECK} like
25869 @example
25870 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
25871 @end example
25872 @noindent
25873 so that such output is properly recorded in the @file{testsuite.log}
25874 file.
25875 @end defmac
25877 @defmac AT_XFAIL_IF (@var{shell-condition})
25878 @atindex{XFAIL_IF}
25879 Determine whether the test is expected to fail because it is a known
25880 bug (for unsupported features, you should skip the test).
25881 @var{shell-condition} is a shell expression such as a @code{test}
25882 command; you can instantiate this macro many times from within the
25883 same test group, and one of the conditions is enough to turn
25884 the test into an expected failure.
25885 @end defmac
25887 @defmac AT_CLEANUP
25888 @atindex{CLEANUP}
25889 End the current test group.
25890 @end defmac
25892 @sp 1
25894 @defmac AT_DATA (@var{file}, @var{contents})
25895 @defmacx AT_DATA_UNQUOTED (@var{file}, @var{contents})
25896 @atindex{DATA}
25897 Initialize an input data @var{file} with given @var{contents}.  Of
25898 course, the @var{contents} have to be properly quoted between square
25899 brackets to protect against included commas or spurious M4
25900 expansion.  @var{contents} must be empty or end with a newline.
25901 @var{file} must
25902 be a single shell word that expands into a single file name.
25904 The difference between @code{AT_DATA} and @code{AT_DATA_UNQUOTED} is
25905 that only the latter performs shell variable expansion (@samp{$}),
25906 command substitution (@samp{`}), and backslash escaping (@samp{\})
25907 on @var{contents}.
25908 @end defmac
25910 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25911   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25912 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25913   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25914 @atindex{CHECK}
25915 @atindex{CHECK_UNQUOTED}
25916 @vrindex at_status
25917 Perform a test, by running the shell @var{commands} in a subshell.
25918 @var{commands} is output as-is, so shell expansions are honored.
25919 These commands are expected to have a final exit status of @var{status},
25920 and to produce output as described by @var{stdout} and @var{stderr}
25921 (see below).
25923 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25925 If @var{commands} exit with unexpected status 77, then the rest of the
25926 test group is skipped.  If @var{commands} exit with unexpected status
25927 99, then the test group is immediately failed; this is called a
25928 @emph{hard failure}.  Otherwise, the test is considered to have
25929 succeeeded if all of the status, stdout, and stderr expectations were
25930 met.
25932 If @var{run-if-fail} is nonempty, it provides extra shell commands to
25933 run when the test fails; if @var{run-if-pass} is nonempty, it provides
25934 extra shell commands to run when the test succeeds.  These commands are
25935 @emph{not} run in a subshell, and they are not run when the test group
25936 is skipped (exit code 77) or hard-failed (exit code 99).  They may
25937 change whether the test group is considered to have succeeded, by
25938 modifying the shell variable @code{at_failed}; set it to @code{:} to
25939 indicate that the test group has failed, or @code{false} to indicate
25940 that it has succeeded.
25942 The exit status of @var{commands} is available to @var{run-if-fail} and
25943 @var{run-if-pass} commands in the @code{at_status} shell variable.  The
25944 output from @var{commands} is also available, in the files named by the
25945 @code{at_stdout} and @code{at_stderr} variables.
25947 If @var{status} is the literal @samp{ignore}, then the exit status of
25948 @var{commands} is not checked, except for the special cases of 77 (skip)
25949 and 99 (hard failure).  The existence of hard failures allows one to
25950 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
25951 feature has not yet been implemented, but to still distinguish between
25952 gracefully handling the missing feature and dumping core.
25954 If the value of the @var{stdout} or @var{stderr} parameter is one of the
25955 literals in the following table, then the test treats the output
25956 according to the rules of that literal.
25958 @table @samp
25959 @item ignore
25960 The content of the output is ignored, but still captured in the test
25961 group log (if the testsuite is run with the @option{-v} option, the test
25962 group log is displayed as the test is run; if the test group later
25963 fails, the test group log is also copied into the overall testsuite
25964 log).  This action is valid for both @var{stdout} and @var{stderr}.
25966 @item ignore-nolog
25967 The content of the output is ignored, and nothing is captured in the log
25968 files.  If @var{commands} are likely to produce binary output (including
25969 long lines) or large amounts of output, then logging the output can make
25970 it harder to locate details related to subsequent tests within the
25971 group, and could potentially corrupt terminal display of a user running
25972 @command{testsuite -v}.  This action is valid for both @var{stdout} and
25973 @var{stderr}.
25975 @item stdout
25976 Only valid as the @var{stdout} parameter.  Capture the content of
25977 standard output in both a file named @file{stdout} and the test group log.
25978 Subsequent commands in the test group can then post-process the file.
25979 This action is often used when it is desired to use @command{grep} to
25980 look for a substring in the output, or when the output must be
25981 post-processed to normalize error messages into a common form.
25983 @item stderr
25984 Only valid as the @var{stderr} parameter.  Capture the content of
25985 standard error in both a file named @file{stderr} and the test group log.
25987 @item stdout-nolog
25988 @itemx stderr-nolog
25989 Like @samp{stdout} or @samp{stderr}, except that the captured output is
25990 not duplicated into the test group log.  This action is particularly
25991 useful for an intermediate check that produces large amounts of data,
25992 which will be followed by another check that filters down to the
25993 relevant data, as it makes it easier to locate details in the log.
25995 @item expout
25996 Only valid as the @var{stdout} parameter.  Compare standard output with
25997 the previously created file @file{expout}, and list any differences in
25998 the testsuite log.
26000 @item experr
26001 Only valid as the @var{stderr} parameter.  Compare standard error with
26002 the previously created file @file{experr}, and list any differences in
26003 the testsuite log.
26004 @end table
26006 Otherwise, the values of the @var{stdout} and @var{stderr} parameters
26007 are treated as text that must exactly match the output given by
26008 @var{commands} on standard output and standard error (including an empty
26009 parameter for no output); any differences are captured in the testsuite
26010 log and the test is failed (unless an unexpected exit status of 77
26011 skipped the test instead).
26013 @code{AT_CHECK_UNQUOTED} performs shell variable expansion (@samp{$}),
26014 command substitution (@samp{`}), and backslash escaping (@samp{\}) on
26015 comparison text given in the @var{stdout} and @var{stderr} parameters;
26016 @code{AT_CHECK} does not.  There is no difference in the interpretation
26017 of @var{commands}.
26018 @end defmac
26020 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
26021   @ovar{run-if-fail}, @ovar{run-if-pass})
26022 @atindex{CHECK_EUNIT}
26023 Initialize and execute an Erlang module named @var{module} that performs
26024 tests following the @var{test-spec} EUnit test specification.
26025 @var{test-spec} must be a valid EUnit test specification, as defined in
26026 the @uref{https://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
26027 Reference Manual}.  @var{erlflags} are optional command-line options
26028 passed to the Erlang interpreter to execute the test Erlang module.
26029 Typically, @var{erlflags} defines at least the paths to directories
26030 containing the compiled Erlang modules under test, as @samp{-pa path1
26031 path2 ...}.
26033 For example, the unit tests associated with Erlang module @samp{testme},
26034 which compiled code is in subdirectory @file{src}, can be performed
26035 with:
26037 @example
26038 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
26039                [-pa "$@{abs_top_builddir@}/src"])
26040 @end example
26042 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
26044 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
26045 must be defined as the path of the Erlang interpreter, the path of the
26046 Erlang compiler, and the command-line flags to pass to the compiler,
26047 respectively.  Those variables should be configured in
26048 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
26049 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
26050 variables are automatically defined in the testsuite.  If @code{ERL} or
26051 @code{ERLC} is not defined, the test group is skipped.
26053 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
26054 be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
26055 an invalid EUnit test specification, the test group fails.  Otherwise,
26056 if the EUnit test passes, shell commands @var{run-if-pass} are executed
26057 or, if the EUnit test fails, shell commands @var{run-if-fail} are
26058 executed and the test group fails.
26060 Only the generated test Erlang module is automatically compiled and
26061 executed.  If @var{test-spec} involves testing other Erlang modules,
26062 e.g. module @samp{testme} in the example above, those modules must be
26063 already compiled.
26065 If the testsuite is run in verbose mode and with the @option{--verbose} option,
26066 EUnit is also run in verbose mode to output more details about
26067 individual unit tests.
26068 @end defmac
26071 @node testsuite Invocation
26072 @section Running @command{testsuite} Scripts
26073 @cindex @command{testsuite}
26075 Autotest test suites support the following options:
26077 @table @option
26078 @item --help
26079 @itemx -h
26080 Display the list of options and exit successfully.
26082 @item --version
26083 @itemx -V
26084 Display the version of the test suite and exit successfully.
26086 @item --directory=@var{dir}
26087 @itemx -C @var{dir}
26088 Change the current directory to @var{dir} before creating any files.
26089 Useful for running the testsuite in a subdirectory from a top-level
26090 Makefile.
26092 @item --jobs@r{[}=@var{n}@r{]}
26093 @itemx -j@ovar{n}
26094 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
26095 run all given tests in parallel.  Note that there should be no space
26096 before the argument to @option{-j}, as @option{-j @var{number}} denotes
26097 the separate arguments @option{-j} and @option{@var{number}}, see below.
26099 In parallel mode, the standard input device of the testsuite script is
26100 not available to commands inside a test group.  Furthermore, banner
26101 lines are not printed, and the summary line for each test group is
26102 output after the test group completes.  Summary lines may appear
26103 unordered.  If verbose and trace output are enabled (see below), they
26104 may appear intermixed from concurrently running tests.
26106 Parallel mode requires the @command{mkfifo} command to work, and will be
26107 silently disabled otherwise.
26109 @item --clean
26110 @itemx -c
26111 Remove all the files the test suite might have created and exit.  Meant
26112 for @code{clean} Make targets.
26114 @item --list
26115 @itemx -l
26116 List all the tests (or only the selection), including their possible
26117 keywords.
26118 @end table
26120 @sp 1
26122 By default all tests are performed (or described with @option{--list})
26123 silently in the default environment, but the environment, set of tests,
26124 and verbosity level can be tuned:
26126 @table @samp
26127 @item @var{variable}=@var{value}
26128 Set the environment @var{variable} to @var{value}.  Use this rather
26129 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
26130 different environment.
26132 @cindex @code{AUTOTEST_PATH}
26133 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
26134 to @env{PATH}.  Relative directory names (not starting with
26135 @samp{/}) are considered to be relative to the top level of the
26136 package being built.  All directories are made absolute, first
26137 starting from the top level @emph{build} tree, then from the
26138 @emph{source} tree.  For instance @samp{./testsuite
26139 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
26140 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
26141 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
26142 @env{PATH}.
26144 @item @var{number}
26145 @itemx @var{number}-@var{number}
26146 @itemx @var{number}-
26147 @itemx -@var{number}
26148 Add the corresponding test groups, with obvious semantics, to the
26149 selection.
26151 @item --keywords=@var{keywords}
26152 @itemx -k @var{keywords}
26153 Add to the selection the test groups with title or keywords (arguments
26154 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
26155 of the comma separated list @var{keywords}, case-insensitively.  Use
26156 @samp{!} immediately before the keyword to invert the selection for this
26157 keyword.  By default, the keywords match whole words; enclose them in
26158 @samp{.*} to also match parts of words.
26160 For example, running
26162 @example
26163 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
26164 @end example
26166 @noindent
26167 selects all tests tagged @samp{autoupdate} @emph{and} with tags
26168 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
26169 etc.), while
26171 @example
26172 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
26173 @end example
26175 @noindent
26176 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
26177 containing @samp{FUNC}.
26179 @item --errexit
26180 @itemx -e
26181 If any test fails, immediately abort testing.  This implies
26182 @option{--debug}: post test group clean up, and top-level logging
26183 are inhibited.  This option is meant for the full test
26184 suite, it is not really useful for generated debugging scripts.
26185 If the testsuite is run in parallel mode using @option{--jobs},
26186 then concurrently running tests will finish before exiting.
26188 @item --verbose
26189 @itemx -v
26190 Force more verbosity in the detailed output of what is being done.  This
26191 is the default for debugging scripts.
26193 @item --color
26194 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
26195 Enable colored test results.  Without an argument, or with @samp{always},
26196 test results will be colored.  With @samp{never}, color mode is turned
26197 off.  Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
26198 the testsuite author, or the argument @samp{auto} is given, then test
26199 results are colored if standard output is connected to a terminal.
26201 @item --debug
26202 @itemx -d
26203 Do not remove the files after a test group was performed---but they are
26204 still removed @emph{before}, therefore using this option is sane when
26205 running several test groups.  Create debugging scripts.  Do not
26206 overwrite the top-level
26207 log (in order to preserve a supposedly existing full log file).  This is
26208 the default for debugging scripts, but it can also be useful to debug
26209 the testsuite itself.
26211 @item --recheck
26212 Add to the selection all test groups that failed or passed unexpectedly
26213 during the last non-debugging test run.
26215 @item --trace
26216 @itemx -x
26217 Trigger shell tracing of the test groups.
26218 @end table
26220 Besides these options accepted by every Autotest testsuite, the
26221 testsuite author might have added package-specific options
26222 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
26223 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
26224 the package documentation for details.
26227 @node Making testsuite Scripts
26228 @section Making @command{testsuite} Scripts
26230 For putting Autotest into movement, you need some configuration and
26231 makefile machinery.  We recommend, at least if your package uses deep or
26232 shallow hierarchies, that you use @file{tests/} as the name of the
26233 directory holding all your tests and their makefile.  Here is a
26234 check list of things to do, followed by an example, taking into
26235 consideration whether you are also using Automake.
26237 @itemize @minus
26239 @item
26240 @cindex @file{package.m4}
26241 @atindex{PACKAGE_STRING}
26242 @atindex{PACKAGE_BUGREPORT}
26243 @atindex{PACKAGE_NAME}
26244 @atindex{PACKAGE_TARNAME}
26245 @atindex{PACKAGE_VERSION}
26246 @atindex{PACKAGE_URL}
26247 Make sure to create the file @file{package.m4}, which defines the
26248 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
26249 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
26250 address to which bug reports should be sent.  For sake of completeness,
26251 we suggest that you also define @code{AT_PACKAGE_NAME},
26252 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
26253 @code{AT_PACKAGE_URL}.
26254 @xref{Initializing configure}, for a description of these variables.
26255 Be sure to distribute @file{package.m4} and to put it into the source
26256 hierarchy: the test suite ought to be shipped!  See below for an example.
26258 @item
26259 Invoke @code{AC_CONFIG_TESTDIR} in your @file{configure.ac}.
26261 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvarv{test-path, directory})
26262 @acindex{CONFIG_TESTDIR}
26263 An Autotest test suite is to be configured in @var{directory}.  This
26264 macro causes @file{@var{directory}/atconfig} to be created by
26265 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
26266 @var{test-path} (@pxref{testsuite Invocation}).
26267 @end defmac
26269 @item
26270 Still within @file{configure.ac}, as appropriate, ensure that some
26271 @code{AC_CONFIG_FILES} command includes substitution for
26272 @file{tests/atlocal}.
26274 @item
26275 Also within your @file{configure.ac}, arrange for the @code{AUTOM4TE}
26276 variable to be set.
26278 @item
26279 The appropriate @file{Makefile} should be modified so the validation in
26280 your package is triggered by @samp{make check}.
26281 @end itemize
26283 The following example demonstrates the above checklist, first by
26284 assuming that you are using Automake (see below for tweaks to make to
26285 get the same results without Automake).  Begin by adding the following
26286 lines to your @file{configure.ac}:
26288 @example
26289 # Initialize the test suite.
26290 AC_CONFIG_TESTDIR([tests])
26291 AC_CONFIG_FILES([tests/Makefile tests/atlocal])
26292 AM_MISSING_PROG([AUTOM4TE], [autom4te])
26293 @end example
26295 Next, add the following lines to your @file{tests/Makefile.am}, in order
26296 to link @samp{make check} with a validation suite.
26298 @example
26299 # The ':;' works around a Bash 3.2 bug when the output is not writable.
26300 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
26301         :;@{ \
26302           echo '# Signature of the current package.' && \
26303           echo 'm4_define([AT_PACKAGE_NAME],' && \
26304           echo '  [$(PACKAGE_NAME)])' && \
26305           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
26306           echo '  [$(PACKAGE_TARNAME)])' && \
26307           echo 'm4_define([AT_PACKAGE_VERSION],' && \
26308           echo '  [$(PACKAGE_VERSION)])' && \
26309           echo 'm4_define([AT_PACKAGE_STRING],' && \
26310           echo '  [$(PACKAGE_STRING)])' && \
26311           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
26312           echo '  [$(PACKAGE_BUGREPORT)])'; \
26313           echo 'm4_define([AT_PACKAGE_URL],' && \
26314           echo '  [$(PACKAGE_URL)])'; \
26315         @} >'$(srcdir)/package.m4'
26317 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
26318 TESTSUITE = $(srcdir)/testsuite
26320 check-local: atconfig atlocal $(TESTSUITE)
26321         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
26323 installcheck-local: atconfig atlocal $(TESTSUITE)
26324         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
26325           $(TESTSUITEFLAGS)
26327 clean-local:
26328         test ! -f '$(TESTSUITE)' || \
26329          $(SHELL) '$(TESTSUITE)' --clean
26331 AUTOTEST = $(AUTOM4TE) --language=autotest
26332 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
26333         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
26334         mv $@@.tmp $@@
26335 @end example
26337 Note that the built testsuite is distributed; this is necessary because
26338 users might not have Autoconf installed, and thus would not be able to
26339 rebuild it.  Likewise, the use of Automake's @code{AM_MISSING_PROG} will
26340 arrange for the definition of @code{$AUTOM4TE} within the Makefile to
26341 provide the user with
26342 a nicer error message if they modify a source file to the testsuite, and
26343 accidentally trigger the rebuild rules.
26345 You might want to list explicitly the dependencies, i.e., the list of
26346 the files @file{testsuite.at} includes.
26348 If you don't use Automake, you should make the following tweaks.  In
26349 your @file{configure.ac}, replace the @code{AM_MISSING_PROG} line above
26350 with @code{AC_PATH_PROG([AUTOM4TE], [autom4te], [false])}.  You are
26351 welcome to also try using the @command{missing} script from the Automake
26352 project instead of @command{false}, to try to get a nicer error message
26353 when the user modifies prerequisites but did not have Autoconf
26354 installed, but at that point you may be better off using Automake.
26355 Then, take the code suggested above for @file{tests/@/Makefile.am} and
26356 place it in your @file{tests/@/Makefile.in} instead.  Add code to your
26357 @file{tests/@/Makefile.in} to ensure that @code{$(EXTRA_DIST)} files are
26358 distributed, as well as adding the following additional lines to prepare
26359 the set of needed Makefile variables:
26361 @example
26362 subdir = tests
26363 PACKAGE_NAME = @@PACKAGE_NAME@@
26364 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
26365 PACKAGE_VERSION = @@PACKAGE_VERSION@@
26366 PACKAGE_STRING = @@PACKAGE_STRING@@
26367 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
26368 PACKAGE_URL = @@PACKAGE_URL@@
26369 AUTOM4TE = @@AUTOM4TE@@
26371 atconfig: $(top_builddir)/config.status
26372         cd $(top_builddir) && \
26373            $(SHELL) ./config.status $(subdir)/$@@
26375 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
26376         cd $(top_builddir) && \
26377            $(SHELL) ./config.status $(subdir)/$@@
26378 @end example
26380 Using the above example (with or without Automake), and assuming you
26381 were careful to not initialize @samp{TESTSUITEFLAGS} within your
26382 makefile, you can now fine-tune test suite execution at runtime by
26383 altering this variable, for example:
26385 @example
26386 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
26387 @end example
26391 @c =============================== Frequent Autoconf Questions, with answers
26393 @node FAQ
26394 @chapter Frequent Autoconf Questions, with answers
26396 Several questions about Autoconf come up occasionally.  Here some of them
26397 are addressed.
26399 @menu
26400 * Distributing::                Distributing @command{configure} scripts
26401 * Why GNU M4::                  Why not use the standard M4?
26402 * Bootstrapping::               Autoconf and GNU M4 require each other?
26403 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
26404 * Defining Directories::        Passing @code{datadir} to program
26405 * Autom4te Cache::              What is it?  Can I remove it?
26406 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
26407 * Expanded Before Required::    Expanded Before Required
26408 * Debugging::                   Debugging @command{configure} scripts
26409 @end menu
26411 @node Distributing
26412 @section Distributing @command{configure} Scripts
26413 @cindex License
26415 @display
26416 What are the restrictions on distributing @command{configure}
26417 scripts that Autoconf generates?  How does that affect my
26418 programs that use them?
26419 @end display
26421 There are no restrictions on how the configuration scripts that Autoconf
26422 produces may be distributed or used.  In Autoconf version 1, they were
26423 covered by the GNU General Public License.  We still encourage
26424 software authors to distribute their work under terms like those of the
26425 GPL, but doing so is not required to use Autoconf.
26427 Of the other files that might be used with @command{configure},
26428 @file{config.h.in} is under whatever copyright you use for your
26429 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
26430 exception to the GPL when they are used with an Autoconf-generated
26431 @command{configure} script, which permits you to distribute them under the
26432 same terms as the rest of your package.  @file{install-sh} is from the X
26433 Consortium and is not copyrighted.
26435 @node Why GNU M4
26436 @section Why Require GNU M4?
26438 @display
26439 Why does Autoconf require GNU M4?
26440 @end display
26442 Many M4 implementations have hard-coded limitations on the size and
26443 number of macros that Autoconf exceeds.  They also lack several
26444 builtin macros that it would be difficult to get along without in a
26445 sophisticated application like Autoconf, including:
26447 @example
26448 m4_builtin
26449 m4_indir
26450 m4_bpatsubst
26451 __file__
26452 __line__
26453 @end example
26455 Autoconf requires version 1.4.6 or later of GNU M4.
26457 Since only software maintainers need to use Autoconf, and since GNU
26458 M4 is simple to configure and install, it seems reasonable to require
26459 GNU M4 to be installed also.  Many maintainers of GNU and
26460 other free software already have most of the GNU utilities
26461 installed, since they prefer them.
26463 @node Bootstrapping
26464 @section How Can I Bootstrap?
26465 @cindex Bootstrap
26467 @display
26468 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
26469 @command{configure} script, how do I bootstrap?  It seems like a chicken
26470 and egg problem!
26471 @end display
26473 This is a misunderstanding.  Although GNU M4 does come with a
26474 @command{configure} script produced by Autoconf, Autoconf is not required
26475 in order to run the script and install GNU M4.  Autoconf is only
26476 required if you want to change the M4 @command{configure} script, which few
26477 people have to do (mainly its maintainer).
26479 @node Why Not Imake
26480 @section Why Not Imake?
26481 @cindex Imake
26483 @display
26484 Why not use Imake instead of @command{configure} scripts?
26485 @end display
26487 Several people have written addressing this question, so
26488 adaptations of their explanations are included here.
26490 The following answer is based on one written by Richard Pixley:
26492 @quotation
26493 Autoconf generated scripts frequently work on machines that it has
26494 never been set up to handle before.  That is, it does a good job of
26495 inferring a configuration for a new system.  Imake cannot do this.
26497 Imake uses a common database of host specific data.  For X11, this makes
26498 sense because the distribution is made as a collection of tools, by one
26499 central authority who has control over the database.
26501 GNU tools are not released this way.  Each GNU tool has a
26502 maintainer; these maintainers are scattered across the world.  Using a
26503 common database would be a maintenance nightmare.  Autoconf may appear
26504 to be this kind of database, but in fact it is not.  Instead of listing
26505 host dependencies, it lists program requirements.
26507 If you view the GNU suite as a collection of native tools, then the
26508 problems are similar.  But the GNU development tools can be
26509 configured as cross tools in almost any host+target permutation.  All of
26510 these configurations can be installed concurrently.  They can even be
26511 configured to share host independent files across hosts.  Imake doesn't
26512 address these issues.
26514 Imake templates are a form of standardization.  The GNU coding
26515 standards address the same issues without necessarily imposing the same
26516 restrictions.
26517 @end quotation
26520 Here is some further explanation, written by Per Bothner:
26522 @quotation
26523 One of the advantages of Imake is that it is easy to generate large
26524 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
26525 However, @code{cpp} is not programmable: it has limited conditional
26526 facilities, and no looping.  And @code{cpp} cannot inspect its
26527 environment.
26529 All of these problems are solved by using @code{sh} instead of
26530 @code{cpp}.  The shell is fully programmable, has macro substitution,
26531 can execute (or source) other shell scripts, and can inspect its
26532 environment.
26533 @end quotation
26536 Paul Eggert elaborates more:
26538 @quotation
26539 With Autoconf, installers need not assume that Imake itself is already
26540 installed and working well.  This may not seem like much of an advantage
26541 to people who are accustomed to Imake.  But on many hosts Imake is not
26542 installed or the default installation is not working well, and requiring
26543 Imake to install a package hinders the acceptance of that package on
26544 those hosts.  For example, the Imake template and configuration files
26545 might not be installed properly on a host, or the Imake build procedure
26546 might wrongly assume that all source files are in one big directory
26547 tree, or the Imake configuration might assume one compiler whereas the
26548 package or the installer needs to use another, or there might be a
26549 version mismatch between the Imake expected by the package and the Imake
26550 supported by the host.  These problems are much rarer with Autoconf,
26551 where each package comes with its own independent configuration
26552 processor.
26554 Also, Imake often suffers from unexpected interactions between
26555 @command{make} and the installer's C preprocessor.  The fundamental problem
26556 here is that the C preprocessor was designed to preprocess C programs,
26557 not makefiles.  This is much less of a problem with Autoconf,
26558 which uses the general-purpose preprocessor M4, and where the
26559 package's author (rather than the installer) does the preprocessing in a
26560 standard way.
26561 @end quotation
26564 Finally, Mark Eichin notes:
26566 @quotation
26567 Imake isn't all that extensible, either.  In order to add new features to
26568 Imake, you need to provide your own project template, and duplicate most
26569 of the features of the existing one.  This means that for a sophisticated
26570 project, using the vendor-provided Imake templates fails to provide any
26571 leverage---since they don't cover anything that your own project needs
26572 (unless it is an X11 program).
26574 On the other side, though:
26576 The one advantage that Imake has over @command{configure}:
26577 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
26578 than @file{Makefile.in} files.  There is a fix to this, however---at least
26579 for the Kerberos V5 tree, we've modified things to call in common
26580 @file{post.in} and @file{pre.in} makefile fragments for the
26581 entire tree.  This means that a lot of common things don't have to be
26582 duplicated, even though they normally are in @command{configure} setups.
26583 @end quotation
26586 @node Defining Directories
26587 @section How Do I @code{#define} Installation Directories?
26589 @display
26590 My program needs library files, installed in @code{datadir} and
26591 similar.  If I use
26593 @example
26594 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
26595   [Define to the read-only architecture-independent
26596    data directory.])
26597 @end example
26599 @noindent
26600 I get
26602 @example
26603 #define DATADIR "$@{prefix@}/share"
26604 @end example
26605 @end display
26607 As already explained, this behavior is on purpose, mandated by the
26608 GNU Coding Standards, see @ref{Installation Directory
26609 Variables}.  There are several means to achieve a similar goal:
26611 @itemize @minus
26612 @item
26613 Do not use @code{AC_DEFINE} but use your makefile to pass the
26614 actual value of @code{datadir} via compilation flags.
26615 @xref{Installation Directory Variables}, for the details.
26617 @item
26618 This solution can be simplified when compiling a program: you may either
26619 extend the @code{CPPFLAGS}:
26621 @example
26622 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
26623 @end example
26625 @noindent
26626 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
26628 @example
26629 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
26630 @end example
26632 @noindent
26633 Alternatively, create a dedicated header file:
26635 @example
26636 DISTCLEANFILES = myprog-paths.h
26637 myprog-paths.h: Makefile
26638         echo '#define DATADIR "$(datadir)"' >$@@
26639 @end example
26641 @noindent
26642 The Gnulib module @samp{configmake} provides such a header with all the
26643 standard directory variables defined, @pxref{configmake,,, gnulib, GNU
26644 Gnulib}.
26646 @item
26647 Use @code{AC_DEFINE} but have @command{configure} compute the literal
26648 value of @code{datadir} and others.  Many people have wrapped macros to
26649 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
26650 the @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
26651 Archive}.
26653 This solution does not conform to the GNU Coding Standards.
26655 @item
26656 Note that all the previous solutions hard wire the absolute name of
26657 these directories in the executables, which is not a good property.  You
26658 may try to compute the names relative to @code{prefix}, and try to
26659 find @code{prefix} at runtime, this way your package is relocatable.
26660 @end itemize
26663 @node Autom4te Cache
26664 @section What is @file{autom4te.cache}?
26666 @display
26667 What is this directory @file{autom4te.cache}?  Can I safely remove it?
26668 @end display
26670 In the GNU Build System, @file{configure.ac} plays a central
26671 role and is read by many tools: @command{autoconf} to create
26672 @file{configure}, @command{autoheader} to create @file{config.h.in},
26673 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
26674 check the completeness of @file{configure.ac}, @command{autoreconf} to
26675 check the GNU Build System components that are used.  To
26676 ``read @file{configure.ac}'' actually means to compile it with M4,
26677 which can be a long process for complex @file{configure.ac}.
26679 This is why all these tools, instead of running directly M4, invoke
26680 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
26681 a specific demand, stores additional information in
26682 @file{autom4te.cache} for future runs.  For instance, if you run
26683 @command{autoconf}, behind the scenes, @command{autom4te} also
26684 stores information for the other tools, so that when you invoke
26685 @command{autoheader} or @command{automake} etc., reprocessing
26686 @file{configure.ac} is not needed.  The speed up is frequently 30%,
26687 and is increasing with the size of @file{configure.ac}.
26689 But it is and remains being simply a cache: you can safely remove it.
26691 @sp 1
26693 @display
26694 Can I permanently get rid of it?
26695 @end display
26697 The creation of this cache can be disabled from
26698 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
26699 details.  You should be aware that disabling the cache slows down the
26700 Autoconf test suite by 40%.  The more GNU Build System
26701 components are used, the more the cache is useful; for instance
26702 running @samp{autoreconf -f} on the Core Utilities is twice slower without
26703 the cache @emph{although @option{--force} implies that the cache is
26704 not fully exploited}, and eight times slower than without
26705 @option{--force}.
26708 @node Present But Cannot Be Compiled
26709 @section Header Present But Cannot Be Compiled
26711 The most important guideline to bear in mind when checking for
26712 features is to mimic as much as possible the intended use.
26713 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
26714 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
26715 the preprocessor, instead of the compiler, to check for headers.  As a
26716 result, incompatibilities between headers went unnoticed during
26717 configuration, and maintainers finally had to deal with this issue
26718 elsewhere.
26720 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
26721 checks are performed, and @command{configure} complains loudly if the
26722 compiler and the preprocessor do not agree.  However, only the compiler
26723 result is considered.  As of Autoconf 2.70, only the compiler check is
26724 performed.
26726 Consider the following example:
26728 @smallexample
26729 $ @kbd{cat number.h}
26730 typedef int number;
26731 $ @kbd{cat pi.h}
26732 const number pi = 3;
26733 $ @kbd{cat configure.ac}
26734 AC_INIT([Example], [1.0], [bug-example@@example.org])
26735 AC_CHECK_HEADERS([pi.h])
26736 $ @kbd{autoconf -Wall}
26737 $ @kbd{./configure CPPFLAGS='-I.'}
26738 checking for gcc... gcc
26739 checking whether the C compiler works... yes
26740 checking for C compiler default output file name... a.out
26741 checking for suffix of executables...
26742 checking whether we are cross compiling... no
26743 checking for suffix of object files... o
26744 checking whether the compiler supports GNU C... yes
26745 checking whether gcc accepts -g... yes
26746 checking for gcc option to enable C11 features... -std=gnu11
26747 checking for sys/types.h... yes
26748 checking for sys/stat.h... yes
26749 checking for strings.h... yes
26750 checking for inttypes.h... yes
26751 checking for stdint.h... yes
26752 checking for unistd.h... yes
26753 checking for pi.h... no
26754 @end smallexample
26756 @noindent
26757 The proper way to handle this case is using the fourth argument
26758 (@pxref{Generic Headers}):
26760 @example
26761 $ @kbd{cat configure.ac}
26762 AC_INIT([Example], [1.0], [bug-example@@example.org])
26763 AC_CHECK_HEADERS([number.h pi.h], [], [],
26764 [[#ifdef HAVE_NUMBER_H
26765 # include <number.h>
26766 #endif
26768 $ @kbd{autoconf -Wall}
26769 $ @kbd{./configure CPPFLAGS='-I.'}
26770 checking for gcc... gcc
26771 checking whether the C compiler works... yes
26772 checking for C compiler default output file name... a.out
26773 checking for suffix of executables...
26774 checking whether we are cross compiling... no
26775 checking for suffix of object files... o
26776 checking whether the compiler supports GNU C... yes
26777 checking whether gcc accepts -g... yes
26778 checking for gcc option to enable C11 features... -std=gnu11
26779 checking for number.h... yes
26780 checking for pi.h... yes
26781 @end example
26783 See @ref{Particular Headers}, for a list of headers with their
26784 prerequisites.
26786 @node Expanded Before Required
26787 @section Expanded Before Required
26789 @cindex expanded before required
26790 Older versions of Autoconf silently built files with incorrect ordering
26791 between dependent macros if an outer macro first expanded, then later
26792 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
26793 situation no longer generates out-of-order code, but results in
26794 duplicate output and a syntax warning:
26796 @example
26797 $ @kbd{cat configure.ac}
26798 @result{}AC_DEFUN([TESTA], [[echo in A
26799 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
26800 @result{}SEEN_A=:]])
26801 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
26802 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
26803 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
26804 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
26805 @result{}TESTA
26806 @result{}TESTC])
26807 @result{}AC_INIT
26808 @result{}OUTER
26809 @result{}AC_OUTPUT
26810 $ @kbd{autoconf}
26811 @result{}configure.ac:11: warning: AC_REQUIRE:
26812 @result{} 'TESTA' was expanded before it was required
26813 @result{}configure.ac:4: TESTB is expanded from...
26814 @result{}configure.ac:6: TESTC is expanded from...
26815 @result{}configure.ac:7: OUTER is expanded from...
26816 @result{}configure.ac:11: the top level
26817 @end example
26819 @noindent
26820 To avoid this warning, decide what purpose the macro in question serves.
26821 If it only needs to be expanded once (for example, if it provides
26822 initialization text used by later macros), then the simplest fix is to
26823 change the macro to be declared with @code{AC_DEFUN_ONCE}
26824 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
26825 newer.  A more portable fix is to change all
26826 instances of direct calls to instead go through @code{AC_REQUIRE}
26827 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
26828 by arguments or by the current definition of other macros in the m4
26829 environment, then the macro should always be directly expanded instead
26830 of required.
26832 For another case study, consider this example trimmed down from an
26833 actual package.  Originally, the package contained shell code and
26834 multiple macro invocations at the top level of @file{configure.ac}:
26836 @example
26837 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26838 foobar=
26839 AC_PROG_CC
26841 @end example
26843 @noindent
26844 but that was getting complex, so the author wanted to offload some of
26845 the text into a new macro in another file included via
26846 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
26847 macro:
26849 @example
26850 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26851 AC_DEFUN([BAR], [
26852 foobar=
26853 AC_PROG_CC
26857 @end example
26859 @noindent
26860 With older versions of Autoconf, the setting of @samp{foobar=} occurs
26861 before the single compiler check, as the author intended.  But with
26862 Autoconf 2.64, this issues the ``expanded before it was required''
26863 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
26864 check, one before @samp{foobar=}, and one after.  To understand why this
26865 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
26866 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
26867 the documented semantics of @code{AC_REQUIRE}, this means that
26868 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
26869 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceding the
26870 use of @samp{foobar=}.  The older versions of Autoconf were broken with
26871 regards to the rules of @code{AC_REQUIRE}, which explains why the code
26872 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
26873 autoconf.  In other words, the author was unknowingly relying on a bug
26874 exploit to get the desired results, and that exploit broke once the bug
26875 was fixed.
26877 So, what recourse does the author have, to restore their intended
26878 semantics of setting @samp{foobar=} prior to a single compiler check,
26879 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
26880 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
26881 there is always the possibility of using the lower-level
26882 @code{m4_define}:
26884 @example
26885 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26886 m4_define([BAR], [
26887 foobar=
26888 AC_PROG_CC
26892 @end example
26894 @noindent
26895 This works great if everything is in the same file.  However, it does
26896 not help in the case where the author wants to have @command{aclocal}
26897 find the definition of @code{BAR} from its own file, since
26898 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
26899 better fix is to recognize that if @code{BAR} also uses
26900 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
26901 to a subsequent require.  Then, by creating yet another helper macro,
26902 the author can once again guarantee a single invocation of
26903 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
26904 author can also use @code{AC_BEFORE} to make sure no other macro
26905 appearing before @code{BAR} has triggered an unwanted expansion of
26906 @code{AC_PROG_CC}.
26908 @example
26909 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26910 AC_DEFUN([BEFORE_CC], [
26911 foobar=
26913 AC_DEFUN([BAR], [
26914 AC_BEFORE([$0], [AC_PROG_CC])dnl
26915 AC_REQUIRE([BEFORE_CC])dnl
26916 AC_REQUIRE([AC_PROG_CC])dnl
26920 @end example
26923 @node Debugging
26924 @section Debugging @command{configure} scripts
26926 While in general, @command{configure} scripts generated by Autoconf
26927 strive to be fairly portable to various systems, compilers, shells, and
26928 other tools, it may still be necessary to debug a failing test, broken
26929 script or makefile, or fix or override an incomplete, faulty, or erroneous
26930 test, especially during macro development.  Failures can occur at all levels,
26931 in M4 syntax or semantics, shell script issues, or due to bugs in the
26932 test or the tools invoked by @command{configure}.  Together with the
26933 rather arcane error message that @command{m4} and @command{make} may
26934 produce when their input contains syntax errors, this can make debugging
26935 rather painful.
26937 Nevertheless, here is a list of hints and strategies that may help:
26939 @itemize
26940 @item
26941 When @command{autoconf} fails, common causes for error include:
26943 @itemize
26944 @item
26945 mismatched or unbalanced parentheses or braces (@pxref{Balancing
26946 Parentheses}),
26948 @item under- or over-quoted macro arguments (@pxref{Autoconf
26949 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
26950 Macros}),
26952 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
26953 Language}).
26954 @end itemize
26956 Typically, it helps to go back to the last working version of the input
26957 and compare the differences for each of these errors.  Another
26958 possibility is to sprinkle pairs of @code{m4_traceon} and
26959 @code{m4_traceoff} judiciously in the code, either without a parameter
26960 or listing some macro names and watch @command{m4} expand its input
26961 verbosely (@pxref{Debugging via autom4te}).
26963 @item
26964 Sometimes @command{autoconf} succeeds but the generated
26965 @command{configure} script has invalid shell syntax.  You can detect this
26966 case by running @samp{bash -n configure} or @samp{sh -n configure}.
26967 If this command fails, the same tips apply, as if @command{autoconf} had
26968 failed.
26970 @item
26971 Debugging @command{configure} script execution may be done by sprinkling
26972 pairs of @code{set -x} and @code{set +x} into the shell script before
26973 and after the region that contains a bug.  Running the whole script with
26974 @samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
26975 @var{shell} may work, but produces lots of output.  Here, it can help to
26976 search for markers like @samp{checking for} a particular test in the
26977 @var{log-file}.
26979 @item
26980 Alternatively, you might use a shell with debugging capabilities like
26981 @uref{http://bashdb.sourceforge.net/, bashdb}.
26983 @item
26984 When @command{configure} tests produce invalid results for your system,
26985 it may be necessary to override them:
26987 @itemize
26988 @item
26989 For programs, tools or libraries variables, preprocessor, compiler, or
26990 linker flags, it is often sufficient to override them at @command{make}
26991 run time with some care (@pxref{Macros and Submakes}).  Since this
26992 normally won't cause @command{configure} to be run again with these
26993 changed settings, it may fail if the changed variable would have caused
26994 different test results from @command{configure}, so this may work only
26995 for simple differences.
26997 @item
26998 Most tests which produce their result in a substituted variable allow to
26999 override the test by setting the variable on the @command{configure}
27000 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
27001 @pxref{Particular Systems}).
27003 @item
27004 Many tests store their result in a cache variable (@pxref{Caching
27005 Results}).  This lets you override them either on the
27006 @command{configure} command line as above, or through a primed cache or
27007 site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
27008 cache variable is documented with a test macro or may be inferred from
27009 @ref{Cache Variable Names}; the precise semantics of undocumented
27010 variables are often internal details, subject to change.
27011 @end itemize
27013 @item
27014 Alternatively, @command{configure} may produce invalid results because
27015 of uncaught programming errors, in your package or in an upstream
27016 library package.  For example, when @code{AC_CHECK_LIB} fails to find a
27017 library with a specified function, always check @file{config.log}.  This
27018 will reveal the exact error that produced the failing result: the
27019 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
27020 @end itemize
27022 Conversely, as macro author, you can make it easier for users of your
27023 macro:
27025 @itemize
27026 @item
27027 by minimizing dependencies between tests and between test results as far
27028 as possible,
27030 @item
27031 by using @command{make} variables to factorize and allow
27032 override of settings at @command{make} run time,
27034 @item
27035 by honoring the GNU Coding Standards and not overriding flags
27036 reserved for the user except temporarily during @command{configure}
27037 tests,
27039 @item
27040 by not requiring users of your macro to use the cache variables.
27041 Instead, expose the result of the test via @var{run-if-true} and
27042 @var{run-if-false} parameters.  If the result is not a boolean,
27043 then provide it through documented shell variables.
27044 @end itemize
27047 @c ===================================================== History of Autoconf.
27049 @node History
27050 @chapter History of Autoconf
27051 @cindex History of autoconf
27053 @emph{This chapter was written by the original author, David MacKenzie.}
27055 You may be wondering, Why was Autoconf originally written?  How did it
27056 get into its present form?  (Why does it look like gorilla spit?)  If
27057 you're not wondering, then this chapter contains no information useful
27058 to you, and you might as well skip it.  If you @emph{are} wondering,
27059 then let there be light@enddots{}
27061 @menu
27062 * Genesis::                     Prehistory and naming of @command{configure}
27063 * Exodus::                      The plagues of M4 and Perl
27064 * Leviticus::                   The priestly code of portability arrives
27065 * Numbers::                     Growth and contributors
27066 * Deuteronomy::                 Approaching the promises of easy configuration
27067 @end menu
27069 @node Genesis
27070 @section Genesis
27072 In June 1991 I was maintaining many of the GNU utilities for the
27073 Free Software Foundation.  As they were ported to more platforms and
27074 more programs were added, the number of @option{-D} options that users
27075 had to select in the makefile (around 20) became burdensome.
27076 Especially for me---I had to test each new release on a bunch of
27077 different systems.  So I wrote a little shell script to guess some of
27078 the correct settings for the fileutils package, and released it as part
27079 of fileutils 2.0.  That @command{configure} script worked well enough that
27080 the next month I adapted it (by hand) to create similar @command{configure}
27081 scripts for several other GNU utilities packages.  Brian Berliner
27082 also adapted one of my scripts for his CVS revision control system.
27084 Later that summer, I learned that Richard Stallman and Richard Pixley
27085 were developing similar scripts to use in the GNU compiler tools;
27086 so I adapted my @command{configure} scripts to support their evolving
27087 interface: using the file name @file{Makefile.in} as the templates;
27088 adding @samp{+srcdir}, the first option (of many); and creating
27089 @file{config.status} files.
27091 @node Exodus
27092 @section Exodus
27094 As I got feedback from users, I incorporated many improvements, using
27095 Emacs to search and replace, cut and paste, similar changes in each of
27096 the scripts.  As I adapted more GNU utilities packages to use
27097 @command{configure} scripts, updating them all by hand became impractical.
27098 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
27099 mail saying that the @command{configure} scripts were great, and asking if
27100 I had a tool for generating them that I could send him.  No, I thought,
27101 but I should!  So I started to work out how to generate them.  And the
27102 journey from the slavery of hand-written @command{configure} scripts to the
27103 abundance and ease of Autoconf began.
27105 Cygnus @command{configure}, which was being developed at around that time,
27106 is table driven; it is meant to deal mainly with a discrete number of
27107 system types with a small number of mainly unguessable features (such as
27108 details of the object file format).  The automatic configuration system
27109 that Brian Fox had developed for Bash takes a similar approach.  For
27110 general use, it seems to me a hopeless cause to try to maintain an
27111 up-to-date database of which features each variant of each operating
27112 system has.  It's easier and more reliable to check for most features on
27113 the fly---especially on hybrid systems that people have hacked on
27114 locally or that have patches from vendors installed.
27116 I considered using an architecture similar to that of Cygnus
27117 @command{configure}, where there is a single @command{configure} script that
27118 reads pieces of @file{configure.in} when run.  But I didn't want to have
27119 to distribute all of the feature tests with every package, so I settled
27120 on having a different @command{configure} made from each
27121 @file{configure.in} by a preprocessor.  That approach also offered more
27122 control and flexibility.
27124 I looked briefly into using the Metaconfig package, by Larry Wall,
27125 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
27126 reasons.  The @command{Configure} scripts it produces are interactive,
27127 which I find quite inconvenient; I didn't like the ways it checked for
27128 some features (such as library functions); I didn't know that it was
27129 still being maintained, and the @command{Configure} scripts I had
27130 seen didn't work on many modern systems (such as System V R4 and NeXT);
27131 it wasn't flexible in what it could do in response to a feature's
27132 presence or absence; I found it confusing to learn; and it was too big
27133 and complex for my needs (I didn't realize then how much Autoconf would
27134 eventually have to grow).
27136 I considered using Perl to generate my style of @command{configure}
27137 scripts, but decided that M4 was better suited to the job of simple
27138 textual substitutions: it gets in the way less, because output is
27139 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
27140 the GNU extensions to M4.)  Also, some of my friends at the
27141 University of Maryland had recently been putting M4 front ends on
27142 several programs, including @code{tvtwm}, and I was interested in trying
27143 out a new language.
27145 @node Leviticus
27146 @section Leviticus
27148 Since my @command{configure} scripts determine the system's capabilities
27149 automatically, with no interactive user intervention, I decided to call
27150 the program that generates them Autoconfig.  But with a version number
27151 tacked on, that name would be too long for old Unix file systems,
27152 so I shortened it to Autoconf.
27154 In the fall of 1991 I called together a group of fellow questers after
27155 the Holy Grail of portability (er, that is, alpha testers) to give me
27156 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
27157 and continued to add features and improve the techniques used in the
27158 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
27159 with the idea of making an Autoconf shell script to run M4
27160 and check for unresolved macro calls; Richard Pixley, who suggested
27161 running the compiler instead of searching the file system to find
27162 include files and symbols, for more accurate results; Karl Berry, who
27163 got Autoconf to configure @TeX{} and added the macro index to the
27164 documentation; and Ian Lance Taylor, who added support for creating a C
27165 header file as an alternative to putting @option{-D} options in a
27166 makefile, so he could use Autoconf for his UUCP package.
27167 The alpha testers cheerfully adjusted their files again and again as the
27168 names and calling conventions of the Autoconf macros changed from
27169 release to release.  They all contributed many specific checks, great
27170 ideas, and bug fixes.
27172 @node Numbers
27173 @section Numbers
27175 In July 1992, after months of alpha testing, I released Autoconf 1.0,
27176 and converted many GNU packages to use it.  I was surprised by how
27177 positive the reaction to it was.  More people started using it than I
27178 could keep track of, including people working on software that wasn't
27179 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
27180 Autoconf continued to improve rapidly, as many people using the
27181 @command{configure} scripts reported problems they encountered.
27183 Autoconf turned out to be a good torture test for M4 implementations.
27184 Unix M4 started to dump core because of the length of the
27185 macros that Autoconf defined, and several bugs showed up in GNU
27186 M4 as well.  Eventually, we realized that we needed to use some
27187 features that only GNU M4 has.  4.3BSD M4, in
27188 particular, has an impoverished set of builtin macros; the System V
27189 version is better, but still doesn't provide everything we need.
27191 More development occurred as people put Autoconf under more stresses
27192 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
27193 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
27194 invalid arguments.  Jim Blandy bravely coerced it into configuring
27195 GNU Emacs, laying the groundwork for several later improvements.
27196 Roland McGrath got it to configure the GNU C Library, wrote the
27197 @command{autoheader} script to automate the creation of C header file
27198 templates, and added a @option{--verbose} option to @command{configure}.
27199 Noah Friedman added the @option{--autoconf-dir} option and
27200 @code{AC_MACRODIR} environment variable.  (He also coined the term
27201 @dfn{autoconfiscate} to mean ``adapt a software package to use
27202 Autoconf''.)  Roland and Noah improved the quoting protection in
27203 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
27204 dealing with portability problems from February through June, 1993.
27206 @node Deuteronomy
27207 @section Deuteronomy
27209 A long wish list for major features had accumulated, and the effect of
27210 several years of patching by various people had left some residual
27211 cruft.  In April 1994, while working for Cygnus Support, I began a major
27212 revision of Autoconf.  I added most of the features of the Cygnus
27213 @command{configure} that Autoconf had lacked, largely by adapting the
27214 relevant parts of Cygnus @command{configure} with the help of david zuhn
27215 and Ken Raeburn.  These features include support for using
27216 @file{config.sub}, @file{config.guess}, @option{--host}, and
27217 @option{--target}; making links to files; and running @command{configure}
27218 scripts in subdirectories.  Adding these features enabled Ken to convert
27219 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
27220 Autoconf.
27222 I added more features in response to other peoples' requests.  Many
27223 people had asked for @command{configure} scripts to share the results of
27224 the checks between runs, because (particularly when configuring a large
27225 source tree, like Cygnus does) they were frustratingly slow.  Mike
27226 Haertel suggested adding site-specific initialization scripts.  People
27227 distributing software that had to unpack on MS-DOS asked for a way to
27228 override the @file{.in} extension on the file names, which produced file
27229 names like @file{config.h.in} containing two dots.  Jim Avera did an
27230 extensive examination of the problems with quoting in @code{AC_DEFINE}
27231 and @code{AC_SUBST}; his insights led to significant improvements.
27232 Richard Stallman asked that compiler output be sent to @file{config.log}
27233 instead of @file{/dev/null}, to help people debug the Emacs
27234 @command{configure} script.
27236 I made some other changes because of my dissatisfaction with the quality
27237 of the program.  I made the messages showing results of the checks less
27238 ambiguous, always printing a result.  I regularized the names of the
27239 macros and cleaned up coding style inconsistencies.  I added some
27240 auxiliary utilities that I had developed to help convert source code
27241 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
27242 the macros not interrupt each others' messages.  (That feature revealed
27243 some performance bottlenecks in GNU M4, which he hastily
27244 corrected!)  I reorganized the documentation around problems people want
27245 to solve.  And I began a test suite, because experience had shown that
27246 Autoconf has a pronounced tendency to regress when we change it.
27248 Again, several alpha testers gave invaluable feedback, especially
27249 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
27250 and Mark Eichin.
27252 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
27253 have free time again.  I think.  Yeah, right.)
27256 @c ========================================================== Appendices
27259 @node GNU Free Documentation License
27260 @appendix GNU Free Documentation License
27262 @include fdl.texi
27264 @node Indices
27265 @appendix Indices
27267 @menu
27268 * Environment Variable Index::  Index of environment variables used
27269 * Output Variable Index::       Index of variables set in output files
27270 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
27271 * Cache Variable Index::        Index of documented cache variables
27272 * Autoconf Macro Index::        Index of Autoconf macros
27273 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
27274 * Autotest Macro Index::        Index of Autotest macros
27275 * Program & Function Index::    Index of those with portability problems
27276 * Concept Index::               General index
27277 @end menu
27279 @node Environment Variable Index
27280 @appendixsec Environment Variable Index
27282 This is an alphabetical list of the environment variables that might
27283 influence Autoconf checks.
27285 @printindex ev
27287 @node Output Variable Index
27288 @appendixsec Output Variable Index
27290 This is an alphabetical list of the variables that Autoconf can
27291 substitute into files that it creates, typically one or more
27292 makefiles.  @xref{Setting Output Variables}, for more information
27293 on how this is done.
27295 @printindex ov
27297 @node Preprocessor Symbol Index
27298 @appendixsec Preprocessor Symbol Index
27300 This is an alphabetical list of the C preprocessor symbols that the
27301 Autoconf macros define.  To work with Autoconf, C source code needs to
27302 use these names in @code{#if} or @code{#ifdef} directives.
27304 @printindex cv
27306 @node Cache Variable Index
27307 @appendixsec Cache Variable Index
27309 This is an alphabetical list of documented cache variables used
27310 by macros defined in Autoconf.  Autoconf macros may use additional cache
27311 variables internally.
27312 @ifset shortindexflag
27313 To make the list easier to use, the variables are listed without their
27314 preceding @samp{ac_cv_}.
27315 @end ifset
27317 @printindex CA
27319 @node Autoconf Macro Index
27320 @appendixsec Autoconf Macro Index
27322 This is an alphabetical list of the Autoconf macros.
27323 @ifset shortindexflag
27324 To make the list easier to use, the macros are listed without their
27325 preceding @samp{AC_}.
27326 @end ifset
27328 @printindex AC
27330 @node M4 Macro Index
27331 @appendixsec M4 Macro Index
27333 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
27334 @ifset shortindexflag
27335 To make the list easier to use, the macros are listed without their
27336 preceding @samp{m4_} or @samp{AS_}.  The prefix is @samp{m4_} for
27337 all-lowercase macro names and @samp{AS_} for all-uppercase macro
27338 names.
27339 @end ifset
27341 @printindex MS
27343 @node Autotest Macro Index
27344 @appendixsec Autotest Macro Index
27346 This is an alphabetical list of the Autotest macros.
27347 @ifset shortindexflag
27348 To make the list easier to use, the macros are listed without their
27349 preceding @samp{AT_}.
27350 @end ifset
27352 @printindex AT
27354 @node Program & Function Index
27355 @appendixsec Program and Function Index
27357 This is an alphabetical list of the programs and functions whose
27358 portability is discussed in this document.
27360 @printindex pr
27362 @node Concept Index
27363 @appendixsec Concept Index
27365 This is an alphabetical list of the files, tools, and concepts
27366 introduced in this document.
27368 @printindex cp
27370 @bye
27372 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
27373 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
27374 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
27375 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
27376 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
27377 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
27378 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
27379 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
27380 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
27381 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
27382 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
27383 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
27384 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir vr
27385 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
27386 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
27387 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
27388 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
27389 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
27390 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
27391 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
27392 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
27393 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
27394 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
27395 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
27396 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
27397 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
27398 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
27399 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
27400 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
27401 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
27402 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
27403 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
27404 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
27405 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
27406 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
27407 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix acxindex autom
27408 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
27409 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
27410 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
27411 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
27412 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
27413 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
27414 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
27415 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
27416 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
27417 @c  LocalWords:  STDBOOL BOOL stdbool cplusplus bool Bool stdarg tm te
27418 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
27419 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
27420 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
27421 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
27422 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
27423 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
27424 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
27425 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
27426 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
27427 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
27428 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
27429 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
27430 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
27431 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
27432 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
27433 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
27434 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
27435 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
27436 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
27437 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
27438 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
27439 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
27440 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp pR
27441 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM url fc
27442 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc ing FP
27443 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
27444 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped SUBST'ed
27445 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
27446 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
27447 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
27448 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
27449 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
27450 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
27451 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
27452 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
27453 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
27454 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
27455 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
27456 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
27457 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
27458 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
27459 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
27460 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
27461 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
27462 @c  LocalWords:  Dynix basename aname cname macroexpands xno xcheck iso
27463 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline vrindex SYS
27464 @c  LocalWords:  syncodeindex define'd caindex CAindex MacKenzie DIRS
27465 @c  LocalWords:  Runtime runtime Submakes submakes MAKEFLAGS whitespace
27466 @c  LocalWords:  Timestamps Unportability Canonicalizing stdalign dirN
27467 @c  LocalWords:  acinclude AMFLAGS LIBS OBJCXXFLAGS GOFLAGS runstatedir
27468 @c  LocalWords:  metacharacter EXPENSIVEP errno setjmp wctype sys mawk
27469 @c  LocalWords:  nawk ggrep egrep gegrep fgrep gfgrep LEX lex yytext nm
27470 @c  LocalWords:  yywrap xflex lexyy YFLAGS yacc divnum libs fuindex ffs
27471 @c  LocalWords:  environ sigaction extern ftello nonnull STRTOLD LLONG
27472 @c  LocalWords:  strtold vfprintf ULLONG strcasecmp strncasecmp MSVC th
27473 @c  LocalWords:  NDEBUG Xenix INO libc ISDIR ISREG Tektronix Amdahl ino
27474 @c  LocalWords:  typedef pxref fileblocks submembers INTMAX intmax UINT
27475 @c  LocalWords:  INTPTR intptr SSIZE ssize uint UINTPTR uintptr OPENMP
27476 @c  LocalWords:  openmp OpenMP omp Alignas Alignof Noreturn UTF vals gl
27477 @c  LocalWords:  offsetof VARARRAYS VLA CCC stdcxx nullptr
27478 @c  LocalWords:  constexpr decltype unicode fstreams iostreams iomanip
27479 @c  LocalWords:  stringstreams GXX OBJCPP OBJCXX objcxx GOBJCXX erlc tx
27480 @c  LocalWords:  OBJCXXCPP FIXEDFORM GFC argc argv shellvar fpp MODEXT
27481 @c  LocalWords:  freeform fixedform MODINC MODOUT gccgo GOC xmkmf fseek
27482 @c  LocalWords:  interpval ftell Interix macOS PTHREAD NonStop XOPEN xc
27483 @c  LocalWords:  IEC ATTRIBS BFP DFP O'Donell Sebor ERTS Erlang's erts
27484 @c  LocalWords:  erlang Wundef scalable USG NOTMAKE DOUCH
27485 @c  LocalWords:  IVE changesyntax ifnotinfo oline num cfg debugfile cdr
27486 @c  LocalWords:  debugmode traceoff traceon patsubst dumpdefs ifelse aa
27487 @c  LocalWords:  mkstemp undivert lifo errprintn BINSH sanitization bcd
27488 @c  LocalWords:  cleardivert bmatch bpatsubsts subst cond nblank ifval
27489 @c  LocalWords:  ifblank ifnblank ifvaln fputc fgetc argn mapall dvarv
27490 @c  LocalWords:  shiftn abcd elt noquote mkargs joinall SHA prereq dup
27491 @c  LocalWords:  listc setb seta ARITH HNUM xcurly xoccupied
27492 @c  LocalWords:  TESTA TESTB TESTC hoc xpg xxyzzyz dtksh nosuch fifos
27493 @c  LocalWords:  fifo Stardent sig WIF WIFSIGNALED SIGQUIT tty perl ret
27494 @c  LocalWords:  SIGINT NUL SFN PRN aeiou MSYS SIGTERM xhi arith UWIN
27495 @c  LocalWords:  CLICOLOR FPATH POSIXLY Shellshock CVE OSF doit ec ci
27496 @c  LocalWords:  notreached cim nc ACL faccessat Alexandre getline sqrt
27497 @c  LocalWords:  CONVFMT FS OFMT CDS chgrp futimens utimensat oo esc od
27498 @c  LocalWords:  ownerships mape readdir mkfifo mknod testsuites XSI rf
27499 @c  LocalWords:  bcdox hexdump filelist rmdir flushleft busybox nl HAZy
27500 @c  LocalWords:  ABCDEFGHIJKLMNOPQRSTUVWXYZ Fantazy FAntAZy adc unix xb
27501 @c  LocalWords:  SUBMAKEFLAGS ehBc ehB hBc hvB dmake hostname nlinit xf
27502 @c  LocalWords:  DCOMMENT bart pathnames ifhtml randx
27503 @c  LocalWords:  sumc hic ic fwrapv ftrapv SIGFPE memset fmudflap ctime
27504 @c  LocalWords:  asctime lvalues lvalue Multithreaded decstation gdb na
27505 @c  LocalWords:  enableval lesskey FHS superset waitpid libfoo cposix
27506 @c  LocalWords:  mem RESTARTABLE bzero DejaGNU EUNIT subfile optarg ive
27507 @c  LocalWords:  nolog expout experr erlflags EUnit testme eunit myprog
27508 @c  LocalWords:  configmake vx bashdb tvtwm questers UUCP McGrath
27509 @c  LocalWords:  ispell
27510 @c Local Variables:
27511 @c fill-column: 72
27512 @c ispell-local-dictionary: "american"
27513 @c indent-tabs-mode: nil
27514 @c whitespace-check-buffer-indent: nil
27515 @c End: