Fix more bugs in specific tests under AC_LANG(C++).
[autoconf.git] / doc / autoconf.texi
blob69c52e49980223d916e9ae6937fb194c6209b8db
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
214 Free Software 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.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
801 repository}.  Anonymous CVS access is also available, see
802 @file{README} for more details.  Patches relative to the
803 current @command{git} version can be sent for review to the
804 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
805 discussion on prior patches
806 @uref{https://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
807 archived}; and all commits are posted in the read-only
808 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
809 also @uref{https://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
810 archived}.
812 Because of its mission, the Autoconf package itself
813 includes only a set of often-used
814 macros that have already demonstrated their usefulness.  Nevertheless,
815 if you wish to share your macros, or find existing ones, see the
816 @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
817 Archive}, which is kindly run by @email{simons@@cryp.to,
818 Peter Simons}.
821 @c ================================================= The GNU Build System
823 @node The GNU Build System
824 @chapter The GNU Build System
825 @cindex GNU build system
827 Autoconf solves an important problem---reliable discovery of
828 system-specific build and runtime information---but this is only one
829 piece of the puzzle for the development of portable software.  To this
830 end, the GNU project has developed a suite of integrated
831 utilities to finish the job Autoconf started: the GNU build
832 system, whose most important components are Autoconf, Automake, and
833 Libtool.  In this chapter, we introduce you to those tools, point you
834 to sources of more information, and try to convince you to use the
835 entire GNU build system for your software.
837 @menu
838 * Automake::                    Escaping makefile hell
839 * Gnulib::                      The GNU portability library
840 * Libtool::                     Building libraries portably
841 * Pointers::                    More info on the GNU build system
842 @end menu
844 @node Automake
845 @section Automake
847 The ubiquity of @command{make} means that a makefile is almost the
848 only viable way to distribute automatic build rules for software, but
849 one quickly runs into its numerous limitations.  Its lack of
850 support for automatic dependency tracking, recursive builds in
851 subdirectories, reliable timestamps (e.g., for network file systems), and
852 so on, mean that developers must painfully (and often incorrectly)
853 reinvent the wheel for each project.  Portability is non-trivial, thanks
854 to the quirks of @command{make} on many systems.  On top of all this is the
855 manual labor required to implement the many standard targets that users
856 have come to expect (@code{make install}, @code{make distclean},
857 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
858 you also have to insert repetitive code in your @file{Makefile.in} to
859 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
860 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
861 @cindex Automake
863 Automake allows you to specify your build needs in a @file{Makefile.am}
864 file with a vastly simpler and more powerful syntax than that of a plain
865 makefile, and then generates a portable @file{Makefile.in} for
866 use with Autoconf.  For example, the @file{Makefile.am} to build and
867 install a simple ``Hello world'' program might look like:
869 @example
870 bin_PROGRAMS = hello
871 hello_SOURCES = hello.c
872 @end example
874 @noindent
875 The resulting @file{Makefile.in} (~400 lines) automatically supports all
876 the standard targets, the substitutions provided by Autoconf, automatic
877 dependency tracking, @code{VPATH} building, and so on.  @command{make}
878 builds the @code{hello} program, and @code{make install} installs it
879 in @file{/usr/local/bin} (or whatever prefix was given to
880 @command{configure}, if not @file{/usr/local}).
882 The benefits of Automake increase for larger packages (especially ones
883 with subdirectories), but even for small programs the added convenience
884 and portability can be substantial.  And that's not all@enddots{}
886 @node Gnulib
887 @section Gnulib
889 GNU software has a well-deserved reputation for running on
890 many different types of systems.  While our primary goal is to write
891 software for the GNU system, many users and developers have
892 been introduced to us through the systems that they were already using.
894 @cindex Gnulib
895 Gnulib is a central location for common GNU code, intended to
896 be shared among free software packages.  Its components are typically
897 shared at the source level, rather than being a library that gets built,
898 installed, and linked against.  The idea is to copy files from Gnulib
899 into your own source tree.  There is no distribution tarball; developers
900 should just grab source modules from the repository.  The source files
901 are available online, under various licenses, mostly GNU
902 GPL or GNU LGPL.
904 Gnulib modules typically contain C source code along with Autoconf
905 macros used to configure the source code.  For example, the Gnulib
906 @code{stdalign} module implements a @file{stdalign.h} header that nearly
907 conforms to C11, even on old-fashioned hosts that lack @file{stdalign.h}.
908 This module contains a source file for the replacement header, along
909 with an Autoconf macro that arranges to use the replacement header on
910 old-fashioned systems.
912 @node Libtool
913 @section Libtool
915 Often, one wants to build not only programs, but libraries, so that
916 other programs can benefit from the fruits of your labor.  Ideally, one
917 would like to produce @emph{shared} (dynamically linked) libraries,
918 which can be used by multiple programs without duplication on disk or in
919 memory and can be updated independently of the linked programs.
920 Producing shared libraries portably, however, is the stuff of
921 nightmares---each system has its own incompatible tools, compiler flags,
922 and magic incantations.  Fortunately, GNU provides a solution:
923 @dfn{Libtool}.
924 @cindex Libtool
926 Libtool handles all the requirements of building shared libraries for
927 you, and at this time seems to be the @emph{only} way to do so with any
928 portability.  It also handles many other headaches, such as: the
929 interaction of Make rules with the variable suffixes of
930 shared libraries, linking reliably with shared libraries before they are
931 installed by the superuser, and supplying a consistent versioning system
932 (so that different versions of a library can be installed or upgraded
933 without breaking binary compatibility).  Although Libtool, like
934 Autoconf, can be used without Automake, it is most simply utilized in
935 conjunction with Automake---there, Libtool is used automatically
936 whenever shared libraries are needed, and you need not know its syntax.
938 @node Pointers
939 @section Pointers
941 Developers who are used to the simplicity of @command{make} for small
942 projects on a single system might be daunted at the prospect of
943 learning to use Automake and Autoconf.  As your software is
944 distributed to more and more users, however, you otherwise
945 quickly find yourself putting lots of effort into reinventing the
946 services that the GNU build tools provide, and making the
947 same mistakes that they once made and overcame.  (Besides, since
948 you're already learning Autoconf, Automake is a piece of cake.)
950 There are a number of places that you can go to for more information on
951 the GNU build tools.
953 @itemize @minus
955 @item Web
957 The project home pages for
958 @uref{https://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
959 @uref{https://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
960 @uref{https://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
961 @uref{https://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
963 @item Automake Manual
965 @xref{Top, , Automake, automake, GNU Automake}, for more
966 information on Automake.
968 @item Books
970 The book @cite{GNU Autoconf, Automake and
971 Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
972 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
973 New Riders), 2000, ISBN 1578701902.} describes the complete GNU
974 build environment.  You can also find
975 @uref{https://@/www.sourceware.org/@/autobook/, the entire book on-line}.
977 @end itemize
979 @c ================================================= Making configure Scripts.
981 @node Making configure Scripts
982 @chapter Making @command{configure} Scripts
983 @cindex @file{aclocal.m4}
984 @cindex @command{configure}
986 The configuration scripts that Autoconf produces are by convention
987 called @command{configure}.  When run, @command{configure} creates several
988 files, replacing configuration parameters in them with appropriate
989 values.  The files that @command{configure} creates are:
991 @itemize @minus
992 @item
993 one or more @file{Makefile} files, usually one in each subdirectory of the
994 package (@pxref{Makefile Substitutions});
996 @item
997 optionally, a C header file, the name of which is configurable,
998 containing @code{#define} directives (@pxref{Configuration Headers});
1000 @item
1001 a shell script called @file{config.status} that, when run, recreates
1002 the files listed above (@pxref{config.status Invocation});
1004 @item
1005 an optional shell script normally called @file{config.cache}
1006 (created when using @samp{configure --config-cache}) that
1007 saves the results of running many of the tests (@pxref{Cache Files});
1009 @item
1010 a file called @file{config.log} containing any messages produced by
1011 compilers, to help debugging if @command{configure} makes a mistake.
1012 @end itemize
1014 @cindex @file{configure.ac}
1015 To create a @command{configure} script with Autoconf, you need
1016 to write an Autoconf input file @file{configure.ac} and run
1017 @command{autoconf} on it.  If you write your own feature tests to
1018 supplement those that come with Autoconf, you might also write files
1019 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
1020 file to contain @code{#define} directives, you might also run
1021 @command{autoheader}, and you can distribute the generated file
1022 @file{config.h.in} with the package.
1024 Here is a diagram showing how the files that can be used in
1025 configuration are produced.  Programs that are executed are suffixed by
1026 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
1027 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1028 macro files (by reading @file{autoconf.m4}).
1030 @noindent
1031 Files used in preparing a software package for distribution, when using
1032 just Autoconf:
1033 @example
1034 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1036 @group
1037 configure.ac --.
1038                |   .------> autoconf* -----> configure
1039 [aclocal.m4] --+---+
1040                |   `-----> [autoheader*] --> [config.h.in]
1041 [acsite.m4] ---'
1042 @end group
1044 Makefile.in
1045 @end example
1047 @noindent
1048 Additionally, if you use Automake, the following additional productions
1049 come into play:
1051 @example
1052 @group
1053 [acinclude.m4] --.
1054                  |
1055 [local macros] --+--> aclocal* --> aclocal.m4
1056                  |
1057 configure.ac ----'
1058 @end group
1060 @group
1061 configure.ac --.
1062                +--> automake* --> Makefile.in
1063 Makefile.am ---'
1064 @end group
1065 @end example
1067 @noindent
1068 Files used in configuring a software package:
1069 @example
1070 @group
1071                        .-------------> [config.cache]
1072 configure* ------------+-------------> config.log
1073                        |
1074 [config.h.in] -.       v            .-> [config.h] -.
1075                +--> config.status* -+               +--> make*
1076 Makefile.in ---'                    `-> Makefile ---'
1077 @end group
1078 @end example
1080 @menu
1081 * Writing Autoconf Input::      What to put in an Autoconf input file
1082 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1083 * ifnames Invocation::          Listing the conditionals in source code
1084 * autoconf Invocation::         How to create configuration scripts
1085 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1086 @end menu
1088 @node Writing Autoconf Input
1089 @section Writing @file{configure.ac}
1091 To produce a @command{configure} script for a software package, create a
1092 file called @file{configure.ac} that contains invocations of the
1093 Autoconf macros that test the system features your package needs or can
1094 use.  Autoconf macros already exist to check for many features; see
1095 @ref{Existing Tests}, for their descriptions.  For most other features,
1096 you can use Autoconf template macros to produce custom checks; see
1097 @ref{Writing Tests}, for information about them.  For especially tricky
1098 or specialized features, @file{configure.ac} might need to contain some
1099 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1100 Programming}.  The @command{autoscan} program can give you a good start
1101 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1102 information).
1104 @cindex @file{configure.in}
1105 Previous versions of Autoconf promoted the name @file{configure.in},
1106 which is somewhat ambiguous (the tool needed to process this file is not
1107 described by its extension), and introduces a slight confusion with
1108 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1109 processed by @command{configure}'').  Using @file{configure.ac} is now
1110 preferred, while the use of @file{configure.in} will cause warnings
1111 from @command{autoconf}.
1113 @menu
1114 * Shell Script Compiler::       Autoconf as solution of a problem
1115 * Autoconf Language::           Programming in Autoconf
1116 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1117 @end menu
1119 @node Shell Script Compiler
1120 @subsection A Shell Script Compiler
1122 Just as for any other computer language, in order to properly program
1123 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1124 the language tries to address and @emph{how} it does so.
1126 The problem Autoconf addresses is that the world is a mess.  After all,
1127 you are using Autoconf in order to have your package compile easily on
1128 all sorts of different systems, some of them being extremely hostile.
1129 Autoconf itself bears the price for these differences: @command{configure}
1130 must run on all those systems, and thus @command{configure} must limit itself
1131 to their lowest common denominator of features.
1133 Naturally, you might then think of shell scripts; who needs
1134 @command{autoconf}?  A set of properly written shell functions is enough to
1135 make it easy to write @command{configure} scripts by hand.  Sigh!
1136 Unfortunately, even in 2008, where shells without any function support are
1137 far and few between, there are pitfalls to avoid when making use of them.
1138 Also, finding a Bourne shell that accepts shell functions is not trivial,
1139 even though there is almost always one on interesting porting targets.
1141 So, what is really needed is some kind of compiler, @command{autoconf},
1142 that takes an Autoconf program, @file{configure.ac}, and transforms it
1143 into a portable shell script, @command{configure}.
1145 How does @command{autoconf} perform this task?
1147 There are two obvious possibilities: creating a brand new language or
1148 extending an existing one.  The former option is attractive: all
1149 sorts of optimizations could easily be implemented in the compiler and
1150 many rigorous checks could be performed on the Autoconf program
1151 (e.g., rejecting any non-portable construct).  Alternatively, you can
1152 extend an existing language, such as the @code{sh} (Bourne shell)
1153 language.
1155 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1156 therefore most convenient to implement @command{autoconf} as a macro
1157 expander: a program that repeatedly performs @dfn{macro expansions} on
1158 text input, replacing macro calls with macro bodies and producing a pure
1159 @code{sh} script in the end.  Instead of implementing a dedicated
1160 Autoconf macro expander, it is natural to use an existing
1161 general-purpose macro language, such as M4, and implement the extensions
1162 as a set of M4 macros.
1165 @node Autoconf Language
1166 @subsection The Autoconf Language
1167 @cindex quotation
1169 The Autoconf language differs from many other computer
1170 languages because it treats actual code the same as plain text.  Whereas
1171 in C, for instance, data and instructions have different syntactic
1172 status, in Autoconf their status is rigorously the same.  Therefore, we
1173 need a means to distinguish literal strings from text to be expanded:
1174 quotation.
1176 When calling macros that take arguments, there must not be any white
1177 space between the macro name and the open parenthesis.
1179 @example
1180 AC_INIT ([oops], [1.0]) # incorrect
1181 AC_INIT([hello], [1.0]) # good
1182 @end example
1184 Arguments should
1185 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1186 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1187 unless they are quoted.  You should always quote an argument that
1188 might contain a macro name, comma, parenthesis, or a leading blank or
1189 newline.  This rule applies recursively for every macro
1190 call, including macros called from other macros.  For more details on
1191 quoting rules, see @ref{Programming in M4}.
1193 For instance:
1195 @example
1196 AC_CHECK_HEADER([stdio.h],
1197                 [AC_DEFINE([HAVE_STDIO_H], [1],
1198                    [Define to 1 if you have <stdio.h>.])],
1199                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1200 @end example
1202 @noindent
1203 is quoted properly.  You may safely simplify its quotation to:
1205 @example
1206 AC_CHECK_HEADER([stdio.h],
1207                 [AC_DEFINE([HAVE_STDIO_H], 1,
1208                    [Define to 1 if you have <stdio.h>.])],
1209                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1210 @end example
1212 @noindent
1213 because @samp{1} cannot contain a macro call.  Here, the argument of
1214 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1215 interpreted as an argument separator.  Also, the second and third arguments
1216 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1217 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1218 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1219 if you unwisely defined a macro with a name like @samp{Define} or
1220 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1221 would keep the quotes, but many Autoconf users find such precautions
1222 annoying, and would rewrite the example as follows:
1224 @example
1225 AC_CHECK_HEADER(stdio.h,
1226                 [AC_DEFINE(HAVE_STDIO_H, 1,
1227                    [Define to 1 if you have <stdio.h>.])],
1228                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1229 @end example
1231 @noindent
1232 This is safe, so long as you adopt good naming conventions and do not
1233 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1234 @samp{h}.  Though it is also safe here to omit the quotes around
1235 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1236 message strings are more likely to inadvertently contain commas.
1238 The following example is wrong and dangerous, as it is underquoted:
1240 @example
1241 AC_CHECK_HEADER(stdio.h,
1242                 AC_DEFINE(HAVE_STDIO_H, 1,
1243                    Define to 1 if you have <stdio.h>.),
1244                 AC_MSG_ERROR([sorry, can't do anything for you]))
1245 @end example
1247 In other cases, you may want to use text that also resembles a macro
1248 call.  You must quote that text (whether just the potential problem, or
1249 the entire line) even when it is not passed as a macro argument; and you
1250 may also have to use @code{m4_pattern_allow} (@pxref{Forbidden
1251 Patterns}), to declare your intention that the resulting configure file
1252 will have a literal that resembles what would otherwise be reserved for
1253 a macro name.  For example:
1255 @example
1256 dnl Simulate a possible future autoconf macro
1257 m4_define([AC_DC], [oops])
1258 dnl Underquoted:
1259 echo "Hard rock was here!  --AC_DC"
1260 dnl Correctly quoted:
1261 m4_pattern_allow([AC_DC])
1262 echo "Hard rock was here!  --[AC_DC]"
1263 [echo "Hard rock was here!  --AC_DC"]
1264 @end example
1266 @noindent
1267 which results in this text in @file{configure}:
1269 @example
1270 echo "Hard rock was here!  --oops"
1271 echo "Hard rock was here!  --AC_DC"
1272 echo "Hard rock was here!  --AC_DC"
1273 @end example
1275 @noindent
1276 When you use the same text in a macro argument, you must therefore have
1277 an extra quotation level (since one is stripped away by the macro
1278 substitution).  In general, then, it is a good idea to @emph{use double
1279 quoting for all literal string arguments}, either around just the
1280 problematic portions, or over the entire argument:
1282 @example
1283 m4_pattern_allow([AC_DC])
1284 AC_MSG_WARN([[AC_DC] stinks  --Iron Maiden])
1285 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1286 @end example
1288 It is also possible to avoid the problematic patterns in the first
1289 place, by the use of additional escaping (either a quadrigraph, or
1290 creative shell constructs), in which case it is no longer necessary to
1291 use @code{m4_pattern_allow}:
1293 @example
1294 echo "Hard rock was here!  --AC""_DC"
1295 AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1296 @end example
1298 You are now able to understand one of the constructs of Autoconf that
1299 has been continually misunderstood@enddots{}  The rule of thumb is that
1300 @emph{whenever you expect macro expansion, expect quote expansion};
1301 i.e., expect one level of quotes to be lost.  For instance:
1303 @example
1304 AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [],
1305  [AC_MSG_ERROR([you lose])])
1306 @end example
1308 @noindent
1309 is incorrect: here, the first argument of @code{AC_LANG_SOURCE} is
1310 @samp{char b[10];} and is expanded once, which results in
1311 @samp{char b10;}; and the @code{AC_LANG_SOURCE} is also expanded prior
1312 to being passed to @code{AC_COMPILE_IFELSE}.  (There was an idiom common
1313 in Autoconf's past to
1314 address this issue via the M4 @code{changequote} primitive, but do not
1315 use it!)  Let's take a closer look: the author meant the first argument
1316 to be understood as a literal, and therefore it must be quoted twice;
1317 likewise, the intermediate @code{AC_LANG_SOURCE} macro should be quoted
1318 once so that it is only expanded after the rest of the body of
1319 @code{AC_COMPILE_IFELSE} is in place:
1321 @example
1322 AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [],
1323   [AC_MSG_ERROR([you lose])])
1324 @end example
1326 @noindent
1327 Voil@`a, you actually produce @samp{char b[10];} this time!
1329 On the other hand, descriptions (e.g., the last parameter of
1330 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1331 are subject to line breaking, for example---and should not be double quoted.
1332 Even if these descriptions are short and are not actually broken, double
1333 quoting them yields weird results.
1335 Some macros take optional arguments, which this documentation represents
1336 as @ovar{arg} (not to be confused with the quote characters).  You may
1337 just leave them empty, or use @samp{[]} to make the emptiness of the
1338 argument explicit, or you may simply omit the trailing commas.  The
1339 three lines below are equivalent:
1341 @example
1342 AC_CHECK_HEADERS([stdio.h], [], [], [])
1343 AC_CHECK_HEADERS([stdio.h],,,)
1344 AC_CHECK_HEADERS([stdio.h])
1345 @end example
1347 It is best to put each macro call on its own line in
1348 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1349 rely on the newline after the macro call to terminate the commands.
1350 This approach makes the generated @command{configure} script a little
1351 easier to read by not inserting lots of blank lines.  It is generally
1352 safe to set shell variables on the same line as a macro call, because
1353 the shell allows assignments without intervening newlines.
1355 You can include comments in @file{configure.ac} files by starting them
1356 with the @samp{#}.  For example, it is helpful to begin
1357 @file{configure.ac} files with a line like this:
1359 @example
1360 # Process this file with autoconf to produce a configure script.
1361 @end example
1363 @node Autoconf Input Layout
1364 @subsection Standard @file{configure.ac} Layout
1366 The order in which @file{configure.ac} calls the Autoconf macros is not
1367 important, with a few exceptions.  Every @file{configure.ac} must
1368 contain a call to @code{AC_INIT} before the checks, and a call to
1369 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1370 rely on other macros having been called first, because they check
1371 previously set values of some variables to decide what to do.  These
1372 macros are noted in the individual descriptions (@pxref{Existing
1373 Tests}), and they also warn you when @command{configure} is created if they
1374 are called out of order.
1376 To encourage consistency, here is a suggested order for calling the
1377 Autoconf macros.  Generally speaking, the things near the end of this
1378 list are those that could depend on things earlier in it.  For example,
1379 library functions could be affected by types and libraries.
1381 @display
1382 @group
1383 Autoconf requirements
1384 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1385 information on the package
1386 checks for programs
1387 checks for libraries
1388 checks for header files
1389 checks for types
1390 checks for structures
1391 checks for compiler characteristics
1392 checks for library functions
1393 checks for system services
1394 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1395 @code{AC_OUTPUT}
1396 @end group
1397 @end display
1400 @node autoscan Invocation
1401 @section Using @command{autoscan} to Create @file{configure.ac}
1402 @cindex @command{autoscan}
1404 The @command{autoscan} program can help you create and/or maintain a
1405 @file{configure.ac} file for a software package.  @command{autoscan}
1406 examines source files in the directory tree rooted at a directory given
1407 as a command line argument, or the current directory if none is given.
1408 It searches the source files for common portability problems and creates
1409 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1410 for that package, and checks a possibly existing @file{configure.ac} for
1411 completeness.
1413 When using @command{autoscan} to create a @file{configure.ac}, you
1414 should manually examine @file{configure.scan} before renaming it to
1415 @file{configure.ac}; it probably needs some adjustments.
1416 Occasionally, @command{autoscan} outputs a macro in the wrong order
1417 relative to another macro, so that @command{autoconf} produces a warning;
1418 you need to move such macros manually.  Also, if you want the package to
1419 use a configuration header file, you must add a call to
1420 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1421 also have to change or add some @code{#if} directives to your program in
1422 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1423 information about a program that can help with that job).
1425 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1426 consider adding its suggestions.  The file @file{autoscan.log}
1427 contains detailed information on why a macro is requested.
1429 @command{autoscan} uses several data files (installed along with Autoconf)
1430 to determine which macros to output when it finds particular symbols in
1431 a package's source files.  These data files all have the same format:
1432 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1433 output if that symbol is encountered.  Lines starting with @samp{#} are
1434 comments.
1436 @command{autoscan} accepts the following options:
1438 @table @option
1439 @item --help
1440 @itemx -h
1441 Print a summary of the command line options and exit.
1443 @item --version
1444 @itemx -V
1445 Print the version number of Autoconf and exit.
1447 @item --verbose
1448 @itemx -v
1449 Print the names of the files it examines and the potentially interesting
1450 symbols it finds in them.  This output can be voluminous.
1452 @item --debug
1453 @itemx -d
1454 Don't remove temporary files.
1456 @item --include=@var{dir}
1457 @itemx -I @var{dir}
1458 Append @var{dir} to the include path.  Multiple invocations accumulate.
1460 @item --prepend-include=@var{dir}
1461 @itemx -B @var{dir}
1462 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1463 @end table
1465 @node ifnames Invocation
1466 @section Using @command{ifnames} to List Conditionals
1467 @cindex @command{ifnames}
1469 @command{ifnames} can help you write @file{configure.ac} for a software
1470 package.  It prints the identifiers that the package already uses in C
1471 preprocessor conditionals.  If a package has already been set up to have
1472 some portability, @command{ifnames} can thus help you figure out what its
1473 @command{configure} needs to check for.  It may help fill in some gaps in a
1474 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1475 Invocation}).
1477 @command{ifnames} scans all of the C source files named on the command line
1478 (or the standard input, if none are given) and writes to the standard
1479 output a sorted list of all the identifiers that appear in those files
1480 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1481 directives.  It prints each identifier on a line, followed by a
1482 space-separated list of the files in which that identifier occurs.
1484 @noindent
1485 @command{ifnames} accepts the following options:
1487 @table @option
1488 @item --help
1489 @itemx -h
1490 Print a summary of the command line options and exit.
1492 @item --version
1493 @itemx -V
1494 Print the version number of Autoconf and exit.
1495 @end table
1497 @node autoconf Invocation
1498 @section Using @command{autoconf} to Create @command{configure}
1499 @cindex @command{autoconf}
1501 To create @command{configure} from @file{configure.ac}, run the
1502 @command{autoconf} program with no arguments.  @command{autoconf} processes
1503 @file{configure.ac} with the M4 macro processor, using the
1504 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1505 file instead of @file{configure.ac} and writes the configuration script
1506 to the standard output instead of to @command{configure}.  If you give
1507 @command{autoconf} the argument @option{-}, it reads from the standard
1508 input instead of @file{configure.ac} and writes the configuration script
1509 to the standard output.
1511 The Autoconf macros are defined in several files.  Some of the files are
1512 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1513 looks for the optional file @file{acsite.m4} in the directory that
1514 contains the distributed Autoconf macro files, and for the optional file
1515 @file{aclocal.m4} in the current directory.  Those files can contain
1516 your site's or the package's own Autoconf macro definitions
1517 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1518 defined in more than one of the files that @command{autoconf} reads, the
1519 last definition it reads overrides the earlier ones.
1521 @command{autoconf} accepts the following options:
1523 @table @option
1524 @item --help
1525 @itemx -h
1526 Print a summary of the command line options and exit.
1528 @item --version
1529 @itemx -V
1530 Print the version number of Autoconf and exit.
1532 @item --verbose
1533 @itemx -v
1534 Report processing steps.
1536 @item --debug
1537 @itemx -d
1538 Don't remove the temporary files.
1540 @item --force
1541 @itemx -f
1542 Remake @file{configure} even if newer than its input files.
1544 @item --include=@var{dir}
1545 @itemx -I @var{dir}
1546 Append @var{dir} to the include path.  Multiple invocations accumulate.
1548 @item --prepend-include=@var{dir}
1549 @itemx -B @var{dir}
1550 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1552 @item --output=@var{file}
1553 @itemx -o @var{file}
1554 Save output (script or trace) to @var{file}.  The file @option{-} stands
1555 for the standard output.
1557 @item --warnings=@var{category}[,@var{category}...]
1558 @itemx -W@var{category}[,@var{category}...]
1559 @evindex WARNINGS
1560 Enable or disable warnings related to each @var{category}.
1561 @xref{m4_warn}, for a comprehensive list of categories.
1562 Special values include:
1564 @table @samp
1565 @item all
1566 Enable all categories of warnings.
1568 @item none
1569 Disable all categories of warnings.
1571 @item error
1572 Treat all warnings as errors.
1574 @item no-@var{category}
1575 Disable warnings falling into @var{category}.
1576 @end table
1578 The enviroment variable @env{WARNINGS} may also be set to a
1579 comma-separated list of warning categories to enable or disable.
1580 It is interpreted exactly the same way as the argument of
1581 @option{--warnings}, but unknown categories are silently ignored.
1582 The command line takes precedence; for instance, if @env{WARNINGS}
1583 is set to @code{obsolete}, but @option{-Wnone} is given on the
1584 command line, no warnings will be issued.
1586 Some categories of warnings are on by default.
1587 Again, for details see @ref{m4_warn}.
1589 @item --trace=@var{macro}[:@var{format}]
1590 @itemx -t @var{macro}[:@var{format}]
1591 Do not create the @command{configure} script, but list the calls to
1592 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1593 arguments can be used to list several macros.  Multiple @option{--trace}
1594 arguments for a single macro are not cumulative; instead, you should
1595 just make @var{format} as long as needed.
1597 The @var{format} is a regular string, with newlines if desired, and
1598 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1599 @ref{autom4te Invocation}, for details on the @var{format}.
1601 @item --initialization
1602 @itemx -i
1603 By default, @option{--trace} does not trace the initialization of the
1604 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1605 results in a noticeable speedup, but can be disabled by this option.
1606 @end table
1609 It is often necessary to check the content of a @file{configure.ac}
1610 file, but parsing it yourself is extremely fragile and error-prone.  It
1611 is suggested that you rely upon @option{--trace} to scan
1612 @file{configure.ac}.  For instance, to find the list of variables that
1613 are substituted, use:
1615 @example
1616 @group
1617 $ @kbd{autoconf -t AC_SUBST}
1618 configure.ac:2:AC_SUBST:ECHO_C
1619 configure.ac:2:AC_SUBST:ECHO_N
1620 configure.ac:2:AC_SUBST:ECHO_T
1621 @i{More traces deleted}
1622 @end group
1623 @end example
1625 @noindent
1626 The example below highlights the difference between @samp{$@@},
1627 @samp{$*}, and @samp{$%}.
1629 @example
1630 @group
1631 $ @kbd{cat configure.ac}
1632 AC_DEFINE(This, is, [an
1633 [example]])
1634 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1635 *: $*
1636 %: $%'
1637 @@: [This],[is],[an
1638 [example]]
1639 *: This,is,an
1640 [example]
1641 %: This:is:an [example]
1642 @end group
1643 @end example
1645 @noindent
1646 The @var{format} gives you a lot of freedom:
1648 @example
1649 @group
1650 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1651 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1652 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1653 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1654 @i{More traces deleted}
1655 @end group
1656 @end example
1658 @noindent
1659 A long @var{separator} can be used to improve the readability of complex
1660 structures, and to ease their parsing (for instance when no single
1661 character is suitable as a separator):
1663 @example
1664 @group
1665 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1666 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1667 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1668 AUTOMAKE|:::::|automake|:::::|$missing_dir
1669 @i{More traces deleted}
1670 @end group
1671 @end example
1673 @node autoreconf Invocation
1674 @section Using @command{autoreconf} to Update @command{configure} Scripts
1675 @cindex @command{autoreconf}
1677 Installing the various components of the GNU Build System can be
1678 tedious: running @command{autopoint} for Gettext, @command{automake} for
1679 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1680 because some tools such as @command{automake} have been updated on your
1681 system, or because some of the sources such as @file{configure.ac} have
1682 been updated, or finally, simply in order to install the GNU Build
1683 System in a fresh tree.
1685 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1686 @command{aclocal}, @command{automake}, @command{libtoolize}, @command{intltoolize},
1687 @command{gtkdocize}, and @command{autopoint} (when appropriate) repeatedly
1688 to update the GNU Build System in the specified directories and their
1689 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1690 those files that are older than their sources.  The environment variables
1691 @env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL},
1692 @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{INTLTOOLIZE}, @env{GTKDOCIZE}, @env{M4},
1693 and @env{MAKE} may be used to override the invocation of the respective tools.
1695 If you install a new version of some tool, you can make
1696 @command{autoreconf} remake @emph{all} of the files by giving it the
1697 @option{--force} option.
1699 @xref{Automatic Remaking}, for Make rules to automatically
1700 rebuild @command{configure} scripts when their source files change.  That
1701 method handles the timestamps of configuration header templates
1702 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1703 @option{--localdir=@var{dir}}.
1705 @cindex Gettext
1706 @cindex @command{autopoint}
1707 Gettext supplies the @command{autopoint} command to add translation
1708 infrastructure to a source package.  If you use @command{autopoint},
1709 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1710 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1711 Invocation, , Invoking the @code{autopoint} Program, gettext,
1712 GNU @code{gettext} utilities}, for further details.
1714 @noindent
1715 @command{autoreconf} accepts the following options:
1717 @table @option
1718 @item --help
1719 @itemx -h
1720 Print a summary of the command line options and exit.
1722 @item --version
1723 @itemx -V
1724 Print the version number of Autoconf and exit.
1726 @item --verbose
1727 @itemx -v
1728 Print the name of each directory @command{autoreconf} examines and the
1729 commands it runs.  If given two or more times, pass @option{--verbose}
1730 to subordinate tools that support it.
1732 @item --debug
1733 @itemx -d
1734 Don't remove the temporary files.
1736 @item --force
1737 @itemx -f
1738 Consider all generated and standard auxiliary files to be obsolete.
1739 This remakes even @file{configure} scripts and configuration headers
1740 that are newer than their input files (@file{configure.ac} and, if
1741 present, @file{aclocal.m4}).
1743 If deemed appropriate, this option triggers calls to @samp{automake
1744 --force-missing}.  Passing both @option{--force} and @option{--install}
1745 to @command{autoreconf} will in turn undo any customizations to standard
1746 files.  Note that the macro @code{AM_INIT_AUTOMAKE} has some options
1747 which change the set of files considered to be standard.
1749 @item --install
1750 @itemx -i
1751 Install any missing standard auxiliary files in the package.  By
1752 default, files are copied; this can be changed with @option{--symlink}.
1754 If deemed appropriate, this option triggers calls to
1755 @samp{automake --add-missing},
1756 @samp{libtoolize}, @samp{autopoint}, etc.
1758 @item --no-recursive
1759 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1760 macro @code{AC_CONFIG_SUBDIRS}).
1762 @item --symlink
1763 @itemx -s
1764 When used with @option{--install}, install symbolic links to the missing
1765 auxiliary files instead of copying them.
1767 @item --make
1768 @itemx -m
1769 When the directories were configured, update the configuration by
1770 running @samp{./config.status --recheck && ./config.status}, and then
1771 run @samp{make}.
1773 @item --include=@var{dir}
1774 @itemx -I @var{dir}
1775 Append @var{dir} to the include path.  Multiple invocations accumulate.
1776 Passed on to @command{aclocal}, @command{autoconf} and
1777 @command{autoheader} internally.
1779 @item --prepend-include=@var{dir}
1780 @itemx -B @var{dir}
1781 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1782 Passed on to @command{autoconf} and @command{autoheader} internally.
1784 @item --warnings=@var{category}[,@var{category}...]
1785 @itemx -W@var{category}[,@var{category}...]
1786 @evindex WARNINGS
1787 Enable or disable warnings related to each @var{category}.
1788 @xref{m4_warn}, for a comprehensive list of categories.
1789 Special values include:
1791 @table @samp
1792 @item all
1793 Enable all categories of warnings.
1795 @item none
1796 Disable all categories of warnings.
1798 @item error
1799 Treat all warnings as errors.
1801 @item no-@var{category}
1802 Disable warnings falling into @var{category}.
1803 @end table
1805 The enviroment variable @env{WARNINGS} may also be set to a
1806 comma-separated list of warning categories to enable or disable.
1807 It is interpreted exactly the same way as the argument of
1808 @option{--warnings}, but unknown categories are silently ignored.
1809 The command line takes precedence; for instance, if @env{WARNINGS}
1810 is set to @code{obsolete}, but @option{-Wnone} is given on the
1811 command line, no warnings will be issued.
1813 Some categories of warnings are on by default.
1814 Again, for details see @ref{m4_warn}.
1815 @end table
1817 If you want @command{autoreconf} to pass flags that are not listed here
1818 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1819 Due to a limitation in the Autoconf implementation these flags currently
1820 must be set on a single line in @file{Makefile.am}, without any
1821 backslash-newlines.  Also, be aware that future Automake releases might
1822 start flagging @code{ACLOCAL_AMFLAGS} as obsolescent, or even remove
1823 support for it.
1825 @c ========================================= Initialization and Output Files.
1827 @node Setup
1828 @chapter Initialization and Output Files
1830 Autoconf-generated @command{configure} scripts need some information about
1831 how to initialize, such as how to find the package's source files and
1832 about the output files to produce.  The following sections describe the
1833 initialization and the creation of output files.
1835 @menu
1836 * Initializing configure::      Option processing etc.
1837 * Versioning::                  Dealing with Autoconf versions
1838 * Notices::                     Copyright, version numbers in @command{configure}
1839 * Input::                       Where Autoconf should find files
1840 * Output::                      Outputting results from the configuration
1841 * Configuration Actions::       Preparing the output based on results
1842 * Configuration Files::         Creating output files
1843 * Makefile Substitutions::      Using output variables in makefiles
1844 * Configuration Headers::       Creating a configuration header file
1845 * Configuration Commands::      Running arbitrary instantiation commands
1846 * Configuration Links::         Links depending on the configuration
1847 * Subdirectories::              Configuring independent packages together
1848 * Default Prefix::              Changing the default installation prefix
1849 @end menu
1851 @node Initializing configure
1852 @section Initializing @command{configure}
1854 Every @command{configure} script must call @code{AC_INIT} before doing
1855 anything else that produces output.  Calls to silent macros, such as
1856 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1857 are generally used via @file{aclocal.m4}, since that is implicitly
1858 included before the start of @file{configure.ac}.  The only other
1859 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1861 @anchor{AC_INIT}
1862 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1863   @ovar{tarname}, @ovar{url})
1864 @acindex{INIT}
1865 Process any command-line arguments and perform initialization
1866 and verification.
1868 Set the name of the @var{package} and its @var{version}.  These are
1869 typically used in @option{--version} support, including that of
1870 @command{configure}.  The optional argument @var{bug-report} should be
1871 the email to which users should send bug reports.  The package
1872 @var{tarname} differs from @var{package}: the latter designates the full
1873 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1874 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1875 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1876 other than alphanumerics and underscores are changed to @samp{-}.  If
1877 provided, @var{url} should be the home page for the package.
1879 All the arguments of @code{AC_INIT} must be static, i.e., there should not
1880 be any shell computation, quotes, or newlines, but they can be computed
1881 by M4.  This is because the package information strings are expanded at
1882 M4 time into several contexts, and must give the same text at shell time
1883 whether used in single-quoted strings, double-quoted strings, quoted
1884 here-documents, or unquoted here-documents.  It is permissible to use
1885 @code{m4_esyscmd} or @code{m4_esyscmd_s} for computing a version string
1886 that changes with every commit to a version control system (in fact,
1887 Autoconf does just that, for all builds of the development tree made
1888 between releases).
1890 The @var{tarname} argument is used to construct filenames.
1891 In addition to being static, it should not contain wildcard
1892 characters, white space, or anything else that could be troublesome
1893 as part of a file or directory name.
1895 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1896 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1897 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1899 @table @asis
1900 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1901 @acindex{PACKAGE_NAME}
1902 @ovindex PACKAGE_NAME
1903 @cvindex PACKAGE_NAME
1904 Exactly @var{package}.
1906 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1907 @acindex{PACKAGE_TARNAME}
1908 @ovindex PACKAGE_TARNAME
1909 @cvindex PACKAGE_TARNAME
1910 Exactly @var{tarname}, possibly generated from @var{package}.
1912 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1913 @acindex{PACKAGE_VERSION}
1914 @ovindex PACKAGE_VERSION
1915 @cvindex PACKAGE_VERSION
1916 Exactly @var{version}.
1918 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1919 @acindex{PACKAGE_STRING}
1920 @ovindex PACKAGE_STRING
1921 @cvindex PACKAGE_STRING
1922 Exactly @samp{@var{package} @var{version}}.
1924 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1925 @acindex{PACKAGE_BUGREPORT}
1926 @ovindex PACKAGE_BUGREPORT
1927 @cvindex PACKAGE_BUGREPORT
1928 Exactly @var{bug-report}, if one was provided.  Typically an email
1929 address, or URL to a bug management web page.
1931 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1932 @acindex{PACKAGE_URL}
1933 @ovindex PACKAGE_URL
1934 @cvindex PACKAGE_URL
1935 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1936 @var{package} begins with @samp{GNU }, then this defaults to
1937 @samp{https://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1938 assumed.
1939 @end table
1940 @end defmac
1942 If your @command{configure} script does its own option processing, it
1943 should inspect @samp{$@@} or @samp{$*} immediately after calling
1944 @code{AC_INIT}, because other Autoconf macros liberally use the
1945 @command{set} command to process strings, and this has the side effect
1946 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1947 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1948 implement your own option processing.  @xref{Site Configuration}.
1950 @node Versioning
1951 @section Dealing with Autoconf versions
1952 @cindex Autoconf version
1953 @cindex version, Autoconf
1955 The following optional macros can be used to help choose the minimum
1956 version of Autoconf that can successfully compile a given
1957 @file{configure.ac}.
1959 @defmac AC_PREREQ (@var{version})
1960 @acindex{PREREQ}
1961 @cindex Version
1962 Ensure that a recent enough version of Autoconf is being used.  If the
1963 version of Autoconf being used to create @command{configure} is
1964 earlier than @var{version}, print an error message to the standard
1965 error output and exit with failure (exit status is 63).  For example:
1967 @example
1968 AC_PREREQ([@value{VERSION}])
1969 @end example
1971 This macro may be used before @code{AC_INIT}.
1972 @end defmac
1974 @defmac AC_AUTOCONF_VERSION
1975 @acindex{AUTOCONF_VERSION}
1976 This macro was introduced in Autoconf 2.62.  It identifies the version
1977 of Autoconf that is currently parsing the input file, in a format
1978 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1979 other words, for this release of Autoconf, its value is
1980 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1981 conditional fallbacks based on when a feature was added to Autoconf,
1982 rather than using @code{AC_PREREQ} to require the newer version of
1983 Autoconf.  However, remember that the Autoconf philosophy favors feature
1984 checks over version checks.
1986 You should not expand this macro directly; use
1987 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1988 users might
1989 have a beta version of Autoconf installed, with arbitrary letters
1990 included in its version string.  This means it is possible for the
1991 version string to contain the name of a defined macro, such that
1992 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1993 macro during rescanning, and change the version string to be different
1994 than what you intended to check.
1995 @end defmac
1997 @node Notices
1998 @section Notices in @command{configure}
1999 @cindex Notices in @command{configure}
2001 The following macros manage version numbers for @command{configure}
2002 scripts.  Using them is optional.
2004 @defmac AC_COPYRIGHT (@var{copyright-notice})
2005 @acindex{COPYRIGHT}
2006 @cindex Copyright Notice
2007 State that, in addition to the Free Software Foundation's copyright on
2008 the Autoconf macros, parts of your @command{configure} are covered by the
2009 @var{copyright-notice}.
2011 The @var{copyright-notice} shows up in both the head of
2012 @command{configure} and in @samp{configure --version}.
2013 @end defmac
2016 @defmac AC_REVISION (@var{revision-info})
2017 @acindex{REVISION}
2018 @cindex Revision
2019 Copy revision stamp @var{revision-info} into the @command{configure}
2020 script, with any dollar signs or double-quotes removed.  This macro lets
2021 you put a revision stamp from @file{configure.ac} into @command{configure}
2022 without RCS or CVS changing it when you check in
2023 @command{configure}.  That way, you can determine easily which revision of
2024 @file{configure.ac} a particular @command{configure} corresponds to.
2026 For example, this line in @file{configure.ac}:
2028 @c The @w prevents RCS from changing the example in the manual.
2029 @example
2030 AC_REVISION([@w{$}Revision: 1.30 $])
2031 @end example
2033 @noindent
2034 produces this in @command{configure}:
2036 @example
2037 #!/bin/sh
2038 # From configure.ac Revision: 1.30
2039 @end example
2040 @end defmac
2043 @node Input
2044 @section Configure Input: Source Code, Macros, and Auxiliary Files
2046 The following macros help you manage the contents of your source tree.
2048 @anchor{AC_CONFIG_SRCDIR}
2049 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2050 @acindex{CONFIG_SRCDIR}
2051 Distinguish this package's source directory from other source
2052 directories that might happen to exist in the file system.
2053 @var{unique-file-in-source-dir} should name a file that is unique to
2054 this package.  @command{configure} will verify that this file exists in
2055 @file{@var{srcdir}}, before it runs any other checks.
2057 Use of this macro is strongly recommended.  It protects against people
2058 accidentally specifying the wrong directory with @option{--srcdir}.
2059 @xref{configure Invocation}, for more information.
2060 @end defmac
2062 Packages that use @command{aclocal} to generate @file{aclocal.m4}
2063 should declare where local macros can be found using
2064 @code{AC_CONFIG_MACRO_DIRS}.
2066 @defmac AC_CONFIG_MACRO_DIRS (@var{dir1} [@var{dir2} ... @var{dirN}])
2067 @defmacx AC_CONFIG_MACRO_DIR (@var{dir})
2068 @acindex{CONFIG_MACRO_DIRS}
2069 @acindex{CONFIG_MACRO_DIR}
2070 @acindex{CONFIG_MACRO_DIR_TRACE}
2071 Specify the given directories as the location of additional local Autoconf
2072 macros.  These macros are intended for use by commands like
2073 @command{autoreconf} or @command{aclocal} that trace macro calls; they should
2074 be called directly from @file{configure.ac} so that tools that install
2075 macros for @command{aclocal} can find the macros' declarations.  Tools
2076 that want to learn which directories have been selected should trace
2077 @code{AC_CONFIG_MACRO_DIR_TRACE}, which will be called once per directory.
2079 AC_CONFIG_MACRO_DIRS is the preferred form, and can be called multiple
2080 times and with multiple arguments; in such cases, directories in earlier
2081 calls are expected to be searched before directories in later calls, and
2082 directories appearing in the same call are expected to be searched in
2083 the order in which they appear in the call.  For historical reasons, the
2084 macro AC_CONFIG_MACRO_DIR can also be used once, if it appears first,
2085 for tools such as older @command{libtool} that weren't prepared to
2086 handle multiple directories.  For example, a usage like
2088 @smallexample
2089 AC_CONFIG_MACRO_DIR([dir1])
2090 AC_CONFIG_MACRO_DIRS([dir2])
2091 AC_CONFIG_MACRO_DIRS([dir3 dir4])
2092 @end smallexample
2094 will cause the trace of AC_CONFIG_MACRO_DIR_TRACE to appear four times,
2095 and should cause the directories to be searched in this order:
2096 @samp{dir1 dir2 dir3 dir4}.
2098 Note that if you use @command{aclocal} from an Automake release prior to
2099 1.13 to generate @file{aclocal.m4}, you must also set
2100 @code{ACLOCAL_AMFLAGS = -I @var{dir1} [-I @var{dir2} ... -I @var{dirN}]}
2101 in your top-level @file{Makefile.am}.  Due to a limitation in
2102 the Autoconf implementation of @command{autoreconf}, these include
2103 directives currently must be set on a single line in @file{Makefile.am},
2104 without any backslash-newlines.
2105 @end defmac
2107 @prindex @command{config.guess}
2108 @prindex @command{config.sub}
2109 @prindex @command{install-sh}
2111 Some Autoconf macros require auxiliary scripts.  @code{AC_PROG_INSTALL}
2112 and @code{AC_PROG_@w{MKDIR_P}} (@pxref{Particular Programs}) require a
2113 fallback implementation of @command{install} called @file{install-sh},
2114 and the @code{AC_CANONICAL} macros (@pxref{Manual Configuration})
2115 require the system-identification scripts @file{config.sub} and
2116 @file{config.guess}.  Third-party tools, such as Automake and Libtool,
2117 may require additional auxiliary scripts.
2119 By default, @command{configure} looks for these scripts next to itself,
2120 in @file{@var{srcdir}}.  For convenience when working with subdirectories
2121 with their own configure scripts (@pxref{Subdirectories}), if the
2122 scripts are not in @file{@var{srcdir}} it will also look in
2123 @file{@var{srcdir}/..} and @file{@var{srcdir}/../..}.  All of the
2124 scripts must be found in the same directory.
2126 If these default locations are not adequate, or simply to reduce clutter
2127 at the top level of the source tree, packages can use
2128 @code{AC_CONFIG_AUX_DIR} to declare where to look for auxiliary scripts.
2130 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2131 @acindex{CONFIG_AUX_DIR}
2132 Look for auxiliary scripts in @var{dir}.  Normally, @var{dir} should be a
2133 relative path, which is taken as relative to @file{@var{srcdir}}.
2134 If @var{dir} is an absolute path or contains shell variables, however,
2135 it is used as-is.
2137 When the goal of using @code{AC_CONFIG_AUX_DIR} is to reduce clutter at
2138 the top level of the source tree, the conventional name for @var{dir} is
2139 @file{build-aux}.  If you need portability to DOS variants, do not name
2140 the auxiliary directory @file{aux}.  @xref{File System Conventions}.
2141 @end defmac
2143 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2144 @acindex{REQUIRE_AUX_FILE}
2145 @vrindex ac_aux_dir
2146 Declare that @var{file} is an auxiliary script needed by this configure
2147 script, and set the shell variable @code{ac_aux_dir} to the directory
2148 where it can be found.  The value of @code{ac_aux_dir} is guaranteed to
2149 end with a @samp{/}.
2151 Macros that need auxiliary scripts must use this macro to register each
2152 script they need.
2153 @end defmac
2155 @command{configure} checks for all the auxiliary scripts it needs on
2156 startup, and exits with an error if any are missing.
2158 @command{autoreconf} also detects missing auxiliary scripts.  When used
2159 with the @option{--install} option, @command{autoreconf} will try to add
2160 missing scripts to the directory specified by @code{AC_CONFIG_AUX_DIR},
2161 or to the top level of the source tree if @code{AC_CONFIG_AUX_DIR} was
2162 not used.  It can always do this for the scripts needed by Autoconf core
2163 macros: @file{install-sh}, @file{config.sub}, and @file{config.guess}.
2164 Many other commonly-needed scripts are installed by the third-party
2165 tools that @command{autoreconf} knows how to run, such as @file{missing}
2166 for Automake and @file{ltmain.sh} for Libtool.
2168 If you are using Automake, auxiliary scripts will automatically be
2169 included in the tarball created by @command{make dist}.  If you are
2170 not using Automake you will need to arrange for auxiliary scripts to
2171 be included in tarballs yourself.  Auxiliary scripts should normally
2172 @emph{not} be checked into a version control system, for the same
2173 reasons that @command{configure} shouldn't be.
2175 The scripts needed by Autoconf core macros can be found in
2176 @file{$(datadir)/autoconf/build-aux} of the Autoconf installation
2177 (@pxref{Installation Directory Variables}).
2178 @file{install-sh} can be downloaded from
2179 @url{https://git.savannah.gnu.org/cgit/automake.git/plain/lib/install-sh}.
2180 @file{config.sub} and @file{config.guess} can be downloaded from
2181 @url{https://git.savannah.gnu.org/cgit/config.git/tree/}.
2183 @node Output
2184 @section Outputting Files
2185 @cindex Outputting files
2187 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2188 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2189 @file{config.status}, which in turn creates the makefiles and any
2190 other files resulting from configuration.  This is the only required
2191 macro besides @code{AC_INIT} (@pxref{Input}).
2193 @anchor{AC_OUTPUT}
2194 @defmac AC_OUTPUT
2195 @acindex{OUTPUT}
2196 @cindex Instantiation
2197 Generate @file{config.status} and launch it.  Call this macro once, at
2198 the end of @file{configure.ac}.
2200 @file{config.status} performs all the configuration actions: all the
2201 output files (see @ref{Configuration Files}, macro
2202 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2203 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2204 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2205 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2206 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2207 are honored.
2209 The location of your @code{AC_OUTPUT} invocation is the exact point
2210 where configuration actions are taken: any code afterwards is
2211 executed by @command{configure} once @command{config.status} was run.  If
2212 you want to bind actions to @command{config.status} itself
2213 (independently of whether @command{configure} is being run), see
2214 @ref{Configuration Commands, , Running Arbitrary Configuration
2215 Commands}.
2216 @end defmac
2218 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2219 @xref{Obsolete Macros}, for a description of the arguments that
2220 @code{AC_OUTPUT} used to support.
2223 If you run @command{make} in subdirectories, you should run it using the
2224 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2225 @code{MAKE} to the name of the @command{make} program plus any options it
2226 was given.  (But many do not include in it the values of any variables
2227 set on the command line, so those are not passed on automatically.)
2228 Some old versions of @command{make} do not set this variable.  The
2229 following macro allows you to use it even with those versions.
2231 @anchor{AC_PROG_MAKE_SET}
2232 @defmac AC_PROG_MAKE_SET
2233 @acindex{PROG_MAKE_SET}
2234 @ovindex SET_MAKE
2235 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2236 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2237 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2238 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2239 @code{SET_MAKE}.
2240 @end defmac
2242 If you use this macro, place a line like this in each @file{Makefile.in}
2243 that runs @command{MAKE} on other directories:
2245 @example
2246 @@SET_MAKE@@
2247 @end example
2251 @node Configuration Actions
2252 @section Performing Configuration Actions
2253 @cindex Configuration actions
2255 @file{configure} is designed so that it appears to do everything itself,
2256 but there is actually a hidden slave: @file{config.status}.
2257 @file{configure} is in charge of examining your system, but it is
2258 @file{config.status} that actually takes the proper actions based on the
2259 results of @file{configure}.  The most typical task of
2260 @file{config.status} is to @emph{instantiate} files.
2262 @acindex{CONFIG_@var{ITEMS}}
2263 This section describes the common behavior of the four standard
2264 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2265 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2266 have this prototype:
2268 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2269 @c awful.
2270 @example
2271 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2272 @end example
2274 @noindent
2275 where the arguments are:
2277 @table @var
2278 @item tag@dots{}
2279 A blank-or-newline-separated list of tags, which are typically the names of
2280 the files to instantiate.
2282 You are encouraged to use literals as @var{tags}.  In particular, you
2283 should avoid
2285 @example
2286 @dots{} && my_foos="$my_foos fooo"
2287 @dots{} && my_foos="$my_foos foooo"
2288 AC_CONFIG_@var{ITEMS}([$my_foos])
2289 @end example
2291 @noindent
2292 and use this instead:
2294 @example
2295 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2296 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2297 @end example
2299 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2300 special @var{tag} values: they may have the form @samp{@var{output}} or
2301 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2302 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2304 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2305 for example, asks for
2306 the creation of the file @file{Makefile} that contains the expansion of the
2307 output variables in the concatenation of @file{boiler/top.mk} and
2308 @file{boiler/bot.mk}.
2310 The special value @samp{-} might be used to denote the standard output
2311 when used in @var{output}, or the standard input when used in the
2312 @var{inputs}.  You most probably don't need to use this in
2313 @file{configure.ac}, but it is convenient when using the command line
2314 interface of @file{./config.status}, see @ref{config.status Invocation},
2315 for more details.
2317 The @var{inputs} may be absolute or relative file names.  In the latter
2318 case they are first looked for in the build tree, and then in the source
2319 tree.  Input files should be text files, and a line length below 2000
2320 bytes should be safe.
2322 @item commands
2323 Shell commands output literally into @file{config.status}, and
2324 associated with a tag that the user can use to tell @file{config.status}
2325 which commands to run.  The commands are run each time a @var{tag}
2326 request is given to @file{config.status}, typically each time the file
2327 @file{@var{tag}} is created.
2329 The variables set during the execution of @command{configure} are
2330 @emph{not} available here: you first need to set them via the
2331 @var{init-cmds}.  Nonetheless the following variables are pre-computed:
2333 @table @code
2334 @item srcdir
2335 @vrindex srcdir
2336 The name of the top source directory, assuming that the working
2337 directory is the top build directory.  This
2338 is what @command{configure}'s @option{--srcdir} option sets.
2340 @item ac_top_srcdir
2341 @vrindex ac_top_srcdir
2342 The name of the top source directory, assuming that the working
2343 directory is the current build directory.
2345 @item ac_top_build_prefix
2346 @vrindex ac_top_build_prefix
2347 The name of the top build directory, assuming that the working
2348 directory is the current build directory.
2349 It can be empty, or else ends with a slash, so that you may concatenate
2352 @item ac_srcdir
2353 @vrindex ac_srcdir
2354 The name of the corresponding source directory, assuming that the
2355 working directory is the current build directory.
2357 @item tmp
2358 @vrindex tmp
2359 The name of a temporary directory within the build tree, which you
2360 can use if you need to create additional temporary files.  The
2361 directory is cleaned up when @command{config.status} is done or
2362 interrupted.  Please use package-specific file name prefixes to
2363 avoid clashing with files that @command{config.status} may use
2364 internally.
2365 @end table
2367 @noindent
2368 The @dfn{current} directory refers to the directory (or
2369 pseudo-directory) containing the input part of @var{tags}.  For
2370 instance, running
2372 @example
2373 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2374 @end example
2376 @noindent
2377  with @option{--srcdir=../package} produces the following values:
2379 @example
2380 # Argument of --srcdir
2381 srcdir='../package'
2382 # Reversing deep/dir
2383 ac_top_build_prefix='../../'
2384 # Concatenation of $ac_top_build_prefix and srcdir
2385 ac_top_srcdir='../../../package'
2386 # Concatenation of $ac_top_srcdir and deep/dir
2387 ac_srcdir='../../../package/deep/dir'
2388 @end example
2390 @noindent
2391 independently of @samp{in/in.in}.
2393 @item init-cmds
2394 Shell commands output @emph{unquoted} near the beginning of
2395 @file{config.status}, and executed each time @file{config.status} runs
2396 (regardless of the tag).  Because they are unquoted, for example,
2397 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2398 is typically used by @file{configure} to give @file{config.status} some
2399 variables it needs to run the @var{commands}.
2401 You should be extremely cautious in your variable names: all the
2402 @var{init-cmds} share the same name space and may overwrite each other
2403 in unpredictable ways.  Sorry@enddots{}
2404 @end table
2406 All these macros can be called multiple times, with different
2407 @var{tag} values, of course!
2410 @node Configuration Files
2411 @section Creating Configuration Files
2412 @cindex Creating configuration files
2413 @cindex Configuration file creation
2415 Be sure to read the previous section, @ref{Configuration Actions}.
2417 @anchor{AC_CONFIG_FILES}
2418 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2419 @acindex{CONFIG_FILES}
2420 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2421 file (by default @file{@var{file}.in}), substituting the output variable
2422 values.
2423 @c Before we used to have this feature, which was later rejected
2424 @c because it complicates the writing of makefiles:
2425 @c If the file would be unchanged, it is left untouched, to preserve
2426 @c timestamp.
2427 This macro is one of the instantiating macros; see @ref{Configuration
2428 Actions}.  @xref{Makefile Substitutions}, for more information on using
2429 output variables.  @xref{Setting Output Variables}, for more information
2430 on creating them.  This macro creates the directory that the file is in
2431 if it doesn't exist.  Usually, makefiles are created this way,
2432 but other files, such as @file{.gdbinit}, can be specified as well.
2434 Typical calls to @code{AC_CONFIG_FILES} look like this:
2436 @example
2437 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2438 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2439 @end example
2441 You can override an input file name by appending to @var{file} a
2442 colon-separated list of input files.  Examples:
2444 @example
2445 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2446                 [lib/Makefile:boiler/lib.mk])
2447 @end example
2449 @noindent
2450 Doing this allows you to keep your file names acceptable to
2451 DOS variants, or
2452 to prepend and/or append boilerplate to the file.
2454 The @var{file} names should not contain shell metacharacters.
2455 @xref{Special Chars in Variables}.
2456 @end defmac
2460 @node Makefile Substitutions
2461 @section Substitutions in Makefiles
2462 @cindex Substitutions in makefiles
2463 @cindex Makefile substitutions
2465 Each subdirectory in a distribution that contains something to be
2466 compiled or installed should come with a file @file{Makefile.in}, from
2467 which @command{configure} creates a file @file{Makefile} in that directory.
2468 To create @file{Makefile}, @command{configure} performs a simple variable
2469 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2470 @file{Makefile.in} with the value that @command{configure} has determined
2471 for that variable.  Variables that are substituted into output files in
2472 this way are called @dfn{output variables}.  They are ordinary shell
2473 variables that are set in @command{configure}.  To make @command{configure}
2474 substitute a particular variable into the output files, the macro
2475 @code{AC_SUBST} must be called with that variable name as an argument.
2476 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2477 left unchanged.  @xref{Setting Output Variables}, for more information
2478 on creating output variables with @code{AC_SUBST}.
2480 A software package that uses a @command{configure} script should be
2481 distributed with a file @file{Makefile.in}, but no makefile; that
2482 way, the user has to properly configure the package for the local system
2483 before compiling it.
2485 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2486 GNU Coding Standards}, for more information on what to put in
2487 makefiles.
2489 @menu
2490 * Preset Output Variables::     Output variables that are always set
2491 * Installation Directory Variables::  Other preset output variables
2492 * Changed Directory Variables::  Warnings about @file{datarootdir}
2493 * Build Directories::           Supporting multiple concurrent compiles
2494 * Automatic Remaking::          Makefile rules for configuring
2495 @end menu
2497 @node Preset Output Variables
2498 @subsection Preset Output Variables
2499 @cindex Output variables
2501 Some output variables are preset by the Autoconf macros.  Some of the
2502 Autoconf macros set additional output variables, which are mentioned in
2503 the descriptions for those macros.  @xref{Output Variable Index}, for a
2504 complete list of output variables.  @xref{Installation Directory
2505 Variables}, for the list of the preset ones related to installation
2506 directories.  Below are listed the other preset ones, many of which are
2507 precious variables (@pxref{Setting Output Variables},
2508 @code{AC_ARG_VAR}).
2510 The preset variables which are available during @file{config.status}
2511 (@pxref{Configuration Actions}) may also be used during
2512 @command{configure} tests.  For example, it is permissible to reference
2513 @samp{$srcdir} when constructing a list of directories to pass via
2514 the @option{-I} option during a compiler feature check.  When used in this
2515 manner, coupled with the fact that @command{configure} is always run
2516 from the top build directory, it is sufficient to use just
2517 @samp{$srcdir} instead of @samp{$top_srcdir}.
2519 @c Just say no to ASCII sorting!  We're humans, not computers.
2520 @c These variables are listed as they would be in a dictionary:
2521 @c actor
2522 @c Actress
2523 @c actress
2525 @defvar CFLAGS
2526 @evindex CFLAGS
2527 @ovindex CFLAGS
2528 Debugging and optimization options for the C compiler.  If it is not set
2529 in the environment when @command{configure} runs, the default value is set
2530 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2531 uses this variable when compiling or linking programs to test for C features.
2533 If a compiler option affects only the behavior of the preprocessor
2534 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2535 instead.  If it affects only the linker (e.g., @option{-L@var{directory}}),
2536 it should be put into @code{LDFLAGS} instead.  If it
2537 affects only the compiler proper, @code{CFLAGS} is the natural home for
2538 it.  If an option affects multiple phases of the compiler, though,
2539 matters get tricky.  One approach to put such options directly into
2540 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2541 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2543 However, remember that some @file{Makefile} variables are reserved by
2544 the GNU Coding Standards for the use of the ``user''---the person
2545 building the package.  For instance, @code{CFLAGS} is one such variable.
2547 Sometimes package developers are tempted to set user variables such as
2548 @code{CFLAGS} because it appears to make their job easier.  However, the
2549 package itself should never set a user variable, particularly not to
2550 include switches that are required for proper compilation of the
2551 package.  Since these variables are documented as being for the package
2552 builder, that person rightfully expects to be able to override any of
2553 these variables at build time.  If the package developer needs to add
2554 switches without interfering with the user, the proper way to do that is
2555 to introduce an additional variable.  Automake makes this easy by
2556 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2557 automake, GNU Automake}), but the concept is the same even if
2558 Automake is not used.
2559 @end defvar
2561 @defvar configure_input
2562 @ovindex configure_input
2563 A comment saying that the file was generated automatically by
2564 @command{configure} and giving the name of the input file.
2565 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2566 of every makefile it creates.  For other files, you should
2567 reference this variable in a comment at the top of each input file.  For
2568 example, an input shell script should begin like this:
2570 @example
2571 #!/bin/sh
2572 # @@configure_input@@
2573 @end example
2575 @noindent
2576 The presence of that line also reminds people editing the file that it
2577 needs to be processed by @command{configure} in order to be used.
2578 @end defvar
2580 @defvar CPPFLAGS
2581 @evindex CPPFLAGS
2582 @ovindex CPPFLAGS
2583 Preprocessor options for the C, C++, Objective C, and Objective C++
2584 preprocessors and compilers.  If
2585 it is not set in the environment when @command{configure} runs, the default
2586 value is empty.  @command{configure} uses this variable when preprocessing
2587 or compiling programs to test for C, C++, Objective C, and Objective C++
2588 features.
2590 This variable's contents should contain options like @option{-I},
2591 @option{-D}, and @option{-U} that affect only the behavior of the
2592 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2593 can do if an option affects other phases of the compiler as well.
2595 Currently, @command{configure} always links as part of a single
2596 invocation of the compiler that also preprocesses and compiles, so it
2597 uses this variable also when linking programs.  However, it is unwise to
2598 depend on this behavior because the GNU Coding Standards do
2599 not require it and many packages do not use @code{CPPFLAGS} when linking
2600 programs.
2602 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2603 might run into.
2604 @end defvar
2606 @defvar CXXFLAGS
2607 @evindex CXXFLAGS
2608 @ovindex CXXFLAGS
2609 Debugging and optimization options for the C++ compiler.  It acts like
2610 @code{CFLAGS}, but for C++ instead of C.
2611 @end defvar
2613 @defvar DEFS
2614 @ovindex DEFS
2615 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2616 is called, @command{configure} replaces @samp{@@DEFS@@} with
2617 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2618 variable is not defined while @command{configure} is performing its tests,
2619 only when creating the output files.  @xref{Setting Output Variables}, for
2620 how to check the results of previous tests.
2621 @end defvar
2623 @defvar ECHO_C
2624 @defvarx ECHO_N
2625 @defvarx ECHO_T
2626 @ovindex ECHO_C
2627 @ovindex ECHO_N
2628 @ovindex ECHO_T
2629 How does one suppress the trailing newline from @command{echo} for
2630 question-answer message pairs?  These variables provide a way:
2632 @example
2633 echo $ECHO_N "And the winner is... $ECHO_C"
2634 sleep 100000000000
2635 echo "$@{ECHO_T@}dead."
2636 @end example
2638 @noindent
2639 Some old and uncommon @command{echo} implementations offer no means to
2640 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2641 want to use it.
2642 @end defvar
2644 @defvar ERLCFLAGS
2645 @evindex ERLCFLAGS
2646 @ovindex ERLCFLAGS
2647 Debugging and optimization options for the Erlang compiler.  If it is not set
2648 in the environment when @command{configure} runs, the default value is empty.
2649 @command{configure} uses this variable when compiling
2650 programs to test for Erlang features.
2651 @end defvar
2653 @defvar FCFLAGS
2654 @evindex FCFLAGS
2655 @ovindex FCFLAGS
2656 Debugging and optimization options for the Fortran compiler.  If it
2657 is not set in the environment when @command{configure} runs, the default
2658 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2659 @command{configure} uses this variable when compiling or linking
2660 programs to test for Fortran features.
2661 @end defvar
2663 @defvar FFLAGS
2664 @evindex FFLAGS
2665 @ovindex FFLAGS
2666 Debugging and optimization options for the Fortran 77 compiler.  If it
2667 is not set in the environment when @command{configure} runs, the default
2668 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2669 @command{configure} uses this variable when compiling or linking
2670 programs to test for Fortran 77 features.
2671 @end defvar
2673 @defvar LDFLAGS
2674 @evindex LDFLAGS
2675 @ovindex LDFLAGS
2676 Options for the linker.  If it is not set
2677 in the environment when @command{configure} runs, the default value is empty.
2678 @command{configure} uses this variable when linking programs to test for
2679 C, C++, Objective C, Objective C++, Fortran, and Go features.
2681 This variable's contents should contain options like @option{-s} and
2682 @option{-L} that affect only the behavior of the linker.  Please see the
2683 explanation of @code{CFLAGS} for what you can do if an option also
2684 affects other phases of the compiler.
2686 Don't use this variable to pass library names
2687 (@option{-l}) to the linker; use @code{LIBS} instead.
2688 @end defvar
2690 @defvar LIBS
2691 @evindex LIBS
2692 @ovindex LIBS
2693 @option{-l} options to pass to the linker.  The default value is empty,
2694 but some Autoconf macros may prepend extra libraries to this variable if
2695 those libraries are found and provide necessary functions, see
2696 @ref{Libraries}.  @command{configure} uses this variable when linking
2697 programs to test for C, C++, Objective C, Objective C++, Fortran, and Go
2698 features.
2699 @end defvar
2701 @defvar OBJCFLAGS
2702 @evindex OBJCFLAGS
2703 @ovindex OBJCFLAGS
2704 Debugging and optimization options for the Objective C compiler.  It
2705 acts like @code{CFLAGS}, but for Objective C instead of C.
2706 @end defvar
2708 @defvar OBJCXXFLAGS
2709 @evindex OBJCXXFLAGS
2710 @ovindex OBJCXXFLAGS
2711 Debugging and optimization options for the Objective C++ compiler.  It
2712 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2713 @end defvar
2715 @defvar GOFLAGS
2716 @evindex GOFLAGS
2717 @ovindex GOFLAGS
2718 Debugging and optimization options for the Go compiler.  It acts like
2719 @code{CFLAGS}, but for Go instead of C.
2720 @end defvar
2722 @defvar builddir
2723 @ovindex builddir
2724 Rigorously equal to @samp{.}.  Added for symmetry only.
2725 @end defvar
2727 @defvar abs_builddir
2728 @ovindex abs_builddir
2729 Absolute name of @code{builddir}.
2730 @end defvar
2732 @defvar top_builddir
2733 @ovindex top_builddir
2734 The relative name of the top level of the current build tree.  In the
2735 top-level directory, this is the same as @code{builddir}.
2736 @end defvar
2738 @defvar top_build_prefix
2739 @ovindex top_build_prefix
2740 The relative name of the top level of the current build tree with final
2741 slash if nonempty.  This is the same as @code{top_builddir}, except that
2742 it contains zero or more runs of @code{../}, so it should not be
2743 appended with a slash for concatenation.  This helps for @command{make}
2744 implementations that otherwise do not treat @file{./file} and @file{file}
2745 as equal in the top-level build directory.
2746 @end defvar
2748 @defvar abs_top_builddir
2749 @ovindex abs_top_builddir
2750 Absolute name of @code{top_builddir}.
2751 @end defvar
2753 @defvar srcdir
2754 @ovindex srcdir
2755 The name of the directory that contains the source code for
2756 that makefile.
2757 @end defvar
2759 @defvar abs_srcdir
2760 @ovindex abs_srcdir
2761 Absolute name of @code{srcdir}.
2762 @end defvar
2764 @defvar top_srcdir
2765 @ovindex top_srcdir
2766 The name of the top-level source code directory for the
2767 package.  In the top-level directory, this is the same as @code{srcdir}.
2768 @end defvar
2770 @defvar abs_top_srcdir
2771 @ovindex abs_top_srcdir
2772 Absolute name of @code{top_srcdir}.
2773 @end defvar
2775 @node Installation Directory Variables
2776 @subsection Installation Directory Variables
2777 @cindex Installation directories
2778 @cindex Directories, installation
2780 The following variables specify the directories for
2781 package installation, see @ref{Directory Variables, , Variables for
2782 Installation Directories, standards, The GNU Coding
2783 Standards}, for more information.  Each variable corresponds to an
2784 argument of @command{configure}; trailing slashes are stripped so that
2785 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2786 between directory names.  See the end of this section for
2787 details on when and how to use these variables.
2789 @defvar bindir
2790 @ovindex bindir
2791 The directory for installing executables that users run.
2792 @end defvar
2794 @defvar datadir
2795 @ovindex datadir
2796 The directory for installing idiosyncratic read-only
2797 architecture-independent data.
2798 @end defvar
2800 @defvar datarootdir
2801 @ovindex datarootdir
2802 The root of the directory tree for read-only architecture-independent
2803 data files.
2804 @end defvar
2806 @defvar docdir
2807 @ovindex docdir
2808 The directory for installing documentation files (other than Info and
2809 man).
2810 @end defvar
2812 @defvar dvidir
2813 @ovindex dvidir
2814 The directory for installing documentation files in DVI format.
2815 @end defvar
2817 @defvar exec_prefix
2818 @ovindex exec_prefix
2819 The installation prefix for architecture-dependent files.  By default
2820 it's the same as @code{prefix}.  You should avoid installing anything
2821 directly to @code{exec_prefix}.  However, the default value for
2822 directories containing architecture-dependent files should be relative
2823 to @code{exec_prefix}.
2824 @end defvar
2826 @defvar htmldir
2827 @ovindex htmldir
2828 The directory for installing HTML documentation.
2829 @end defvar
2831 @defvar includedir
2832 @ovindex includedir
2833 The directory for installing C header files.
2834 @end defvar
2836 @defvar infodir
2837 @ovindex infodir
2838 The directory for installing documentation in Info format.
2839 @end defvar
2841 @defvar libdir
2842 @ovindex libdir
2843 The directory for installing object code libraries.
2844 @end defvar
2846 @defvar libexecdir
2847 @ovindex libexecdir
2848 The directory for installing executables that other programs run.
2849 @end defvar
2851 @defvar localedir
2852 @ovindex localedir
2853 The directory for installing locale-dependent but
2854 architecture-independent data, such as message catalogs.  This directory
2855 usually has a subdirectory per locale.
2856 @end defvar
2858 @defvar localstatedir
2859 @ovindex localstatedir
2860 The directory for installing modifiable single-machine data.  Content in
2861 this directory typically survives a reboot.
2862 @end defvar
2864 @defvar runstatedir
2865 @ovindex runstatedir
2866 The directory for installing temporary modifiable single-machine data.
2867 Content in this directory survives as long as the process is running
2868 (such as pid files), as contrasted with @file{/tmp} that may be
2869 periodically cleaned.  Conversely, this directory is typically cleaned
2870 on a reboot.  By default, this is a subdirectory of
2871 @code{localstatedir}.
2872 @end defvar
2874 @defvar mandir
2875 @ovindex mandir
2876 The top-level directory for installing documentation in man format.
2877 @end defvar
2879 @defvar oldincludedir
2880 @ovindex oldincludedir
2881 The directory for installing C header files for non-GCC compilers.
2882 @end defvar
2884 @defvar pdfdir
2885 @ovindex pdfdir
2886 The directory for installing PDF documentation.
2887 @end defvar
2889 @defvar prefix
2890 @ovindex prefix
2891 The common installation prefix for all files.  If @code{exec_prefix}
2892 is defined to a different value, @code{prefix} is used only for
2893 architecture-independent files.
2894 @end defvar
2896 @defvar psdir
2897 @ovindex psdir
2898 The directory for installing PostScript documentation.
2899 @end defvar
2901 @defvar sbindir
2902 @ovindex sbindir
2903 The directory for installing executables that system
2904 administrators run.
2905 @end defvar
2907 @defvar sharedstatedir
2908 @ovindex sharedstatedir
2909 The directory for installing modifiable architecture-independent data.
2910 @end defvar
2912 @defvar sysconfdir
2913 @ovindex sysconfdir
2914 The directory for installing read-only single-machine data.
2915 @end defvar
2918 Most of these variables have values that rely on @code{prefix} or
2919 @code{exec_prefix}.  It is deliberate that the directory output
2920 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2921 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2922 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2924 This behavior is mandated by the GNU Coding Standards, so that when
2925 the user runs:
2927 @table @samp
2928 @item make
2929 she can still specify a different prefix from the one specified to
2930 @command{configure}, in which case, if needed, the package should hard
2931 code dependencies corresponding to the make-specified prefix.
2933 @item make install
2934 she can specify a different installation location, in which case the
2935 package @emph{must} still depend on the location which was compiled in
2936 (i.e., never recompile when @samp{make install} is run).  This is an
2937 extremely important feature, as many people may decide to install all
2938 the files of a package grouped together, and then install links from
2939 the final locations to there.
2940 @end table
2942 In order to support these features, it is essential that
2943 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2944 so that its value can be expanded based
2945 on the current value of @code{prefix}.
2947 A corollary is that you should not use these variables except in
2948 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2949 in @file{configure} and hard-coding it in makefiles using
2950 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2951 you should add
2952 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2953 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2955 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2956 @code{bindir} and friends in your shell scripts and other files; instead,
2957 let @command{make} manage their replacement.  For instance Autoconf
2958 ships templates of its shell scripts ending with @samp{.in}, and uses a
2959 makefile snippet similar to the following to build scripts like
2960 @command{autoheader} and @command{autom4te}:
2962 @example
2963 @group
2964 edit = sed \
2965         -e 's|@@bindir[@@]|$(bindir)|g' \
2966         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2967         -e 's|@@prefix[@@]|$(prefix)|g'
2968 @end group
2970 @group
2971 autoheader autom4te: Makefile
2972         rm -f $@@ $@@.tmp
2973         srcdir=''; \
2974           test -f ./$@@.in || srcdir=$(srcdir)/; \
2975           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2976 @c $$ restore font-lock
2977         chmod +x $@@.tmp
2978         chmod a-w $@@.tmp
2979         mv $@@.tmp $@@
2980 @end group
2982 @group
2983 autoheader: $(srcdir)/autoheader.in
2984 autom4te: $(srcdir)/autom4te.in
2985 @end group
2986 @end example
2988 Some details are noteworthy:
2990 @table @asis
2991 @item @samp{@@bindir[@@]}
2992 The brackets prevent @command{configure} from replacing
2993 @samp{@@bindir@@} in the Sed expression itself.
2994 Brackets are preferable to a backslash here, since
2995 Posix says @samp{\@@} is not portable.
2997 @item @samp{$(bindir)}
2998 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2999 instead.
3001 @item @samp{$(pkgdatadir)}
3002 The example takes advantage of the variable @samp{$(pkgdatadir)}
3003 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
3005 @item @samp{/}
3006 Don't use @samp{/} in the Sed expressions that replace file names since
3007 most likely the
3008 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
3009 Use a shell metacharacter instead, such as @samp{|}.
3011 @item special characters
3012 File names, file name components, and the value of @code{VPATH} should
3013 not contain shell metacharacters or white
3014 space.  @xref{Special Chars in Variables}.
3016 @item dependency on @file{Makefile}
3017 Since @code{edit} uses values that depend on the configuration specific
3018 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
3019 the output depends on @file{Makefile}, not @file{configure.ac}.
3021 @item @samp{$@@}
3022 The main rule is generic, and uses @samp{$@@} extensively to
3023 avoid the need for multiple copies of the rule.
3025 @item Separated dependencies and single suffix rules
3026 You can't use them!  The above snippet cannot be (portably) rewritten
3029 @example
3030 autoconf autoheader: Makefile
3031 @group
3032 .in:
3033         rm -f $@@ $@@.tmp
3034         $(edit) $< >$@@.tmp
3035         chmod +x $@@.tmp
3036         mv $@@.tmp $@@
3037 @end group
3038 @end example
3040 @xref{Single Suffix Rules}, for details.
3042 @item @samp{$(srcdir)}
3043 Be sure to specify the name of the source directory,
3044 otherwise the package won't support separated builds.
3045 @end table
3047 For the more specific installation of Erlang libraries, the following variables
3048 are defined:
3050 @defvar ERLANG_INSTALL_LIB_DIR
3051 @ovindex ERLANG_INSTALL_LIB_DIR
3052 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
3053 The common parent directory of Erlang library installation directories.
3054 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
3055 macro in @file{configure.ac}.
3056 @end defvar
3058 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
3059 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
3060 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3061 The installation directory for Erlang library @var{library}.
3062 This variable is set by using the
3063 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3064 macro in @file{configure.ac}.
3065 @end defvar
3067 @xref{Erlang Libraries}, for details.
3070 @node Changed Directory Variables
3071 @subsection Changed Directory Variables
3072 @cindex @file{datarootdir}
3074 In Autoconf 2.60, the set of directory variables has changed, and the
3075 defaults of some variables have been adjusted
3076 (@pxref{Installation Directory Variables}) to changes in the
3077 GNU Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
3078 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
3079 upgrading from an earlier Autoconf version, you may need to adjust your files
3080 to ensure that the directory variables are substituted correctly
3081 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
3082 in place.  For example, in a @file{Makefile.in}, adding
3084 @example
3085 datarootdir = @@datarootdir@@
3086 @end example
3088 @noindent
3089 is usually sufficient.  If you use Automake to create @file{Makefile.in},
3090 it will add this for you.
3092 To help with the transition, Autoconf warns about files that seem to use
3093 @code{datarootdir} without defining it.  In some cases, it then expands
3094 the value of @code{$datarootdir} in substitutions of the directory
3095 variables.  The following example shows such a warning:
3097 @example
3098 $ @kbd{cat configure.ac}
3099 AC_INIT
3100 AC_CONFIG_FILES([Makefile])
3101 AC_OUTPUT
3102 $ @kbd{cat Makefile.in}
3103 prefix = @@prefix@@
3104 datadir = @@datadir@@
3105 $ @kbd{autoconf}
3106 $ @kbd{configure}
3107 configure: creating ./config.status
3108 config.status: creating Makefile
3109 config.status: WARNING:
3110                Makefile.in seems to ignore the --datarootdir setting
3111 $ @kbd{cat Makefile}
3112 prefix = /usr/local
3113 datadir = $@{prefix@}/share
3114 @end example
3116 Usually one can easily change the file to accommodate both older and newer
3117 Autoconf releases:
3119 @example
3120 $ @kbd{cat Makefile.in}
3121 prefix = @@prefix@@
3122 datarootdir = @@datarootdir@@
3123 datadir = @@datadir@@
3124 $ @kbd{configure}
3125 configure: creating ./config.status
3126 config.status: creating Makefile
3127 $ @kbd{cat Makefile}
3128 prefix = /usr/local
3129 datarootdir = $@{prefix@}/share
3130 datadir = $@{datarootdir@}
3131 @end example
3133 @acindex{DATAROOTDIR_CHECKED}
3134 In some cases, however, the checks may not be able to detect that a suitable
3135 initialization of @code{datarootdir} is in place, or they may fail to detect
3136 that such an initialization is necessary in the output file.  If, after
3137 auditing your package, there are still spurious @file{configure} warnings about
3138 @code{datarootdir}, you may add the line
3140 @example
3141 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3142 @end example
3144 @noindent
3145 to your @file{configure.ac} to disable the warnings.  This is an exception
3146 to the usual rule that you should not define a macro whose name begins with
3147 @code{AC_} (@pxref{Macro Names}).
3151 @node Build Directories
3152 @subsection Build Directories
3153 @cindex Build directories
3154 @cindex Directories, build
3156 You can support compiling a software package for several architectures
3157 simultaneously from the same copy of the source code.  The object files
3158 for each architecture are kept in their own directory.
3160 To support doing this, @command{make} uses the @code{VPATH} variable to
3161 find the files that are in the source directory.  GNU Make
3162 can do this.  Most other recent @command{make} programs can do this as
3163 well, though they may have difficulties and it is often simpler to
3164 recommend GNU @command{make} (@pxref{VPATH and Make}).  Older
3165 @command{make} programs do not support @code{VPATH}; when using them, the
3166 source code must be in the same directory as the object files.
3168 If you are using GNU Automake, the remaining details in this
3169 section are already covered for you, based on the contents of your
3170 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
3171 supporting @code{VPATH} requires the following in your
3172 @file{Makefile.in}:
3174 @example
3175 srcdir = @@srcdir@@
3176 VPATH = @@srcdir@@
3177 @end example
3179 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3180 listed in VPATH}.
3182 @command{configure} substitutes the correct value for @code{srcdir} when
3183 it produces @file{Makefile}.
3185 Do not use the @command{make} variable @code{$<}, which expands to the
3186 file name of the file in the source directory (found with @code{VPATH}),
3187 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3188 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3189 versions of @command{make} do not set @code{$<} in explicit rules; they
3190 expand it to an empty value.
3192 Instead, Make command lines should always refer to source
3193 files by prefixing them with @samp{$(srcdir)/}.  It's safer
3194 to quote the source directory name, in case it contains characters that
3195 are special to the shell.  Because @samp{$(srcdir)} is expanded by Make,
3196 single-quoting works and is safer than double-quoting.  For example:
3198 @example
3199 time.info: time.texinfo
3200         $(MAKEINFO) '$(srcdir)/time.texinfo'
3201 @end example
3203 @node Automatic Remaking
3204 @subsection Automatic Remaking
3205 @cindex Automatic remaking
3206 @cindex Remaking automatically
3208 You can put rules like the following in the top-level @file{Makefile.in}
3209 for a package to automatically update the configuration information when
3210 you change the configuration files.  This example includes all of the
3211 optional files, such as @file{aclocal.m4} and those related to
3212 configuration header files.  Omit from the @file{Makefile.in} rules for
3213 any of these files that your package does not use.
3215 The @samp{$(srcdir)/} prefix is included because of limitations in the
3216 @code{VPATH} mechanism.
3218 The @file{stamp-} files are necessary because the timestamps of
3219 @file{config.h.in} and @file{config.h} are not changed if remaking
3220 them does not change their contents.  This feature avoids unnecessary
3221 recompilation.  You should include the file @file{stamp-h.in} in your
3222 package's distribution, so that @command{make} considers
3223 @file{config.h.in} up to date.  Don't use @command{touch}
3224 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3225 @command{echo} (using
3226 @command{date} would cause needless differences, hence CVS
3227 conflicts, etc.).
3229 @example
3230 @group
3231 $(srcdir)/configure: configure.ac aclocal.m4
3232         cd '$(srcdir)' && autoconf
3234 # autoheader might not change config.h.in, so touch a stamp file.
3235 $(srcdir)/config.h.in: stamp-h.in ;
3236 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3237         cd '$(srcdir)' && autoheader
3238         echo timestamp > '$(srcdir)/stamp-h.in'
3240 config.h: stamp-h ;
3241 stamp-h: config.h.in config.status
3242         ./config.status
3244 Makefile: Makefile.in config.status
3245         ./config.status
3247 config.status: configure
3248         ./config.status --recheck
3249 @end group
3250 @end example
3252 @noindent
3253 (Be careful if you copy these lines directly into your makefile, as you
3254 need to convert the indented lines to start with the tab character.)
3256 In addition, you should use
3258 @example
3259 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3260 @end example
3262 @noindent
3263 so @file{config.status} ensures that @file{config.h} is considered up to
3264 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3266 @xref{config.status Invocation}, for more examples of handling
3267 configuration-related dependencies.
3269 @node Configuration Headers
3270 @section Configuration Header Files
3271 @cindex Configuration Header
3272 @cindex @file{config.h}
3274 When a package contains more than a few tests that define C preprocessor
3275 symbols, the command lines to pass @option{-D} options to the compiler
3276 can get quite long.  This causes two problems.  One is that the
3277 @command{make} output is hard to visually scan for errors.  More
3278 seriously, the command lines can exceed the length limits of some
3279 operating systems.  As an alternative to passing @option{-D} options to
3280 the compiler, @command{configure} scripts can create a C header file
3281 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3282 macro selects this kind of output.  Though it can be called anywhere
3283 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3284 it right after @code{AC_INIT}.
3286 The package should @samp{#include} the configuration header file before
3287 any other header files, to prevent inconsistencies in declarations (for
3288 example, if it redefines @code{const}, or if it defines a macro like
3289 @code{_FILE_OFFSET_BITS} that affects the behavior of system
3290 headers). Note that it is okay to only include @file{config.h} from
3291 @file{.c} files; the project's @file{.h} files can rely on
3292 @file{config.h} already being included first by the corresponding
3293 @file{.c} file.
3295 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3296 option (or @option{-I..}; whichever directory contains @file{config.h}).
3297 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3298 the directory of the currently read file, i.e., the source directory, not
3299 the build directory.
3301 With the appropriate @option{-I} option, you can use
3302 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3303 because in the rare case when the source directory contains another
3304 @file{config.h}, the build directory should be searched first.
3307 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3308 @acindex{CONFIG_HEADERS}
3309 @cvindex HAVE_CONFIG_H
3310 This macro is one of the instantiating macros; see @ref{Configuration
3311 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3312 blank-or-newline-separated list @var{header} containing C preprocessor
3313 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3314 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3315 The usual name for @var{header} is @file{config.h};
3316 @var{header} should not contain shell metacharacters.
3317 @xref{Special Chars in Variables}.
3319 If @var{header} already exists and its contents are identical to what
3320 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3321 making some changes in the configuration without needlessly causing
3322 object files that depend on the header file to be recompiled.
3324 Usually the input file is named @file{@var{header}.in}; however, you can
3325 override the input file name by appending to @var{header} a
3326 colon-separated list of input files.  For example, you might need to make
3327 the input file name acceptable to DOS variants:
3329 @example
3330 AC_CONFIG_HEADERS([config.h:config.hin])
3331 @end example
3333 @end defmac
3335 @defmac AH_HEADER
3336 @ahindex{HEADER}
3337 This macro is defined as the name of the first declared config header
3338 and undefined if no config headers have been declared up to this point.
3339 A third-party macro may, for example, require use of a config header
3340 without invoking AC_CONFIG_HEADERS twice, like this:
3342 @example
3343 AC_CONFIG_COMMANDS_PRE(
3344         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3345 @end example
3347 @end defmac
3349 @xref{Configuration Actions}, for more details on @var{header}.
3351 @menu
3352 * Header Templates::            Input for the configuration headers
3353 * autoheader Invocation::       How to create configuration templates
3354 * Autoheader Macros::           How to specify CPP templates
3355 @end menu
3357 @node Header Templates
3358 @subsection Configuration Header Templates
3359 @cindex Configuration Header Template
3360 @cindex Header templates
3361 @cindex @file{config.h.in}
3363 Your distribution should contain a template file that looks as you want
3364 the final header file to look, including comments, with @code{#undef}
3365 statements which are used as hooks.  For example, suppose your
3366 @file{configure.ac} makes these calls:
3368 @example
3369 AC_CONFIG_HEADERS([conf.h])
3370 AC_CHECK_HEADERS([unistd.h])
3371 @end example
3373 @noindent
3374 Then you could have code like the following in @file{conf.h.in}.
3375 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3376 to 1, if and only if the system has @file{unistd.h}.
3378 @example
3379 @group
3380 /* Define as 1 if you have unistd.h.  */
3381 #undef HAVE_UNISTD_H
3382 @end group
3383 @end example
3385 The format of the template file is stricter than what the C preprocessor
3386 is required to accept.  A directive line should contain only whitespace,
3387 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3388 instead of @samp{#undef}, or of comments on the same line as
3389 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3390 once.  Other preprocessor lines, such as @samp{#ifdef} or
3391 @samp{#include}, are copied verbatim from the template into the
3392 generated header.
3394 Since it is a tedious task to keep a template header up to date, you may
3395 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3397 During the instantiation of the header, each @samp{#undef} line in the
3398 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3399 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3400 been executed during the @command{configure} run, the @samp{#undef} line is
3401 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3402 on many systems, it can be implicitly defined by the compiler, and
3403 undefining it in the header would then break compilation of subsequent
3404 headers.)
3406 Currently, @emph{all} remaining @samp{#undef} lines in the header
3407 template are commented out, whether or not there was a corresponding
3408 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3409 for future releases of Autoconf.
3411 Generally speaking, since you should not use @samp{#define}, and you
3412 cannot guarantee whether a @samp{#undef} directive in the header
3413 template will be converted to a @samp{#define} or commented out in the
3414 generated header file, the template file cannot be used for conditional
3415 definition effects.  Consequently, if you need to use the construct
3417 @example
3418 @group
3419 #ifdef THIS
3420 # define THAT
3421 #endif
3422 @end group
3423 @end example
3425 @noindent
3426 you must place it outside of the template.
3427 If you absolutely need to hook it to the config header itself, please put
3428 the directives to a separate file, and @samp{#include} that file from the
3429 config header template.  If you are using @command{autoheader}, you would
3430 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3433 @node autoheader Invocation
3434 @subsection Using @command{autoheader} to Create @file{config.h.in}
3435 @cindex @command{autoheader}
3437 The @command{autoheader} program can create a template file of C
3438 @samp{#define} statements for @command{configure} to use.
3439 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3440 @file{configure} sources to determine the name of the template.
3441 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3442 input file name, @command{autoheader} uses the first one.)
3444 It is recommended that only one input file is used.  If you want to append
3445 a boilerplate code, it is preferable to use
3446 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3447 File @file{conf_post.h} is not processed during the configuration then,
3448 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3449 prepend a boilerplate code.
3451 In order to do its job, @command{autoheader} needs you to document all
3452 of the symbols that you might use.  Typically this is done via an
3453 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3454 is a literal symbol and whose third argument describes the symbol
3455 (@pxref{Defining Symbols}).  Alternatively, you can use
3456 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3457 suitable input file for a subsequent configuration header file.
3458 Symbols defined by Autoconf's builtin tests are already documented properly;
3459 you need to document only those that you
3460 define yourself.
3462 You might wonder why @command{autoheader} is needed: after all, why
3463 would @command{configure} need to ``patch'' a @file{config.h.in} to
3464 produce a @file{config.h} instead of just creating @file{config.h} from
3465 scratch?  Well, when everything rocks, the answer is just that we are
3466 wasting our time maintaining @command{autoheader}: generating
3467 @file{config.h} directly is all that is needed.  When things go wrong,
3468 however, you'll be thankful for the existence of @command{autoheader}.
3470 The fact that the symbols are documented is important in order to
3471 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3472 well-defined list of symbols that should be defined (or not) is
3473 also important for people who are porting packages to environments where
3474 @command{configure} cannot be run: they just have to @emph{fill in the
3475 blanks}.
3477 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3479 If you give @command{autoheader} an argument, it uses that file instead
3480 of @file{configure.ac} and writes the header file to the standard output
3481 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3482 argument of @option{-}, it reads the standard input instead of
3483 @file{configure.ac} and writes the header file to the standard output.
3485 @command{autoheader} accepts the following options:
3487 @table @option
3488 @item --help
3489 @itemx -h
3490 Print a summary of the command line options and exit.
3492 @item --version
3493 @itemx -V
3494 Print the version number of Autoconf and exit.
3496 @item --verbose
3497 @itemx -v
3498 Report processing steps.
3500 @item --debug
3501 @itemx -d
3502 Don't remove the temporary files.
3504 @item --force
3505 @itemx -f
3506 Remake the template file even if newer than its input files.
3508 @item --include=@var{dir}
3509 @itemx -I @var{dir}
3510 Append @var{dir} to the include path.  Multiple invocations accumulate.
3512 @item --prepend-include=@var{dir}
3513 @itemx -B @var{dir}
3514 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3516 @item --warnings=@var{category}[,@var{category}...]
3517 @itemx -W@var{category}[,@var{category}...]
3518 @evindex WARNINGS
3519 Enable or disable warnings related to each @var{category}.
3520 @xref{m4_warn}, for a comprehensive list of categories.
3521 Special values include:
3523 @table @samp
3524 @item all
3525 Enable all categories of warnings.
3527 @item none
3528 Disable all categories of warnings.
3530 @item error
3531 Treat all warnings as errors.
3533 @item no-@var{category}
3534 Disable warnings falling into @var{category}.
3535 @end table
3537 The enviroment variable @env{WARNINGS} may also be set to a
3538 comma-separated list of warning categories to enable or disable.
3539 It is interpreted exactly the same way as the argument of
3540 @option{--warnings}, but unknown categories are silently ignored.
3541 The command line takes precedence; for instance, if @env{WARNINGS}
3542 is set to @code{obsolete}, but @option{-Wnone} is given on the
3543 command line, no warnings will be issued.
3545 Some categories of warnings are on by default.
3546 Again, for details see @ref{m4_warn}.
3547 @end table
3551 @node Autoheader Macros
3552 @subsection Autoheader Macros
3553 @cindex Autoheader macros
3555 @command{autoheader} scans @file{configure.ac} and figures out which C
3556 preprocessor symbols it might define.  It knows how to generate
3557 templates for symbols defined by @code{AC_CHECK_HEADERS},
3558 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3559 symbol, you must define a template for it.  If there are missing
3560 templates, @command{autoheader} fails with an error message.
3562 The template for a @var{symbol} is created
3563 by @command{autoheader} from
3564 the @var{description} argument to an @code{AC_DEFINE};
3565 see @ref{Defining Symbols}.
3567 For special needs, you can use the following macros.
3570 @defmac AH_TEMPLATE (@var{key}, @var{description})
3571 @ahindex{TEMPLATE}
3572 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3573 generates standard templates just like @code{AC_DEFINE} when a
3574 @var{description} is given.
3576 For example:
3578 @example
3579 AH_TEMPLATE([NULL_DEVICE],
3580   [Name of the file to open to get
3581    a null file, or a data sink.])
3582 @end example
3584 @noindent
3585 generates the following template, with the description properly
3586 justified.
3588 @example
3589 /* Name of the file to open to get a null file, or a data sink. */
3590 #undef NULL_DEVICE
3591 @end example
3592 @end defmac
3595 @defmac AH_VERBATIM (@var{key}, @var{template})
3596 @ahindex{VERBATIM}
3597 Tell @command{autoheader} to include the @var{template} as-is in the header
3598 template file.  This @var{template} is associated with the @var{key},
3599 which is used to sort all the different templates and guarantee their
3600 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3601 @end defmac
3604 @defmac AH_TOP (@var{text})
3605 @ahindex{TOP}
3606 Include @var{text} at the top of the header template file.
3607 @end defmac
3610 @defmac AH_BOTTOM (@var{text})
3611 @ahindex{BOTTOM}
3612 Include @var{text} at the bottom of the header template file.
3613 @end defmac
3616 Please note that @var{text} gets included ``verbatim'' to the template file,
3617 not to the resulting config header, so it can easily get mangled when the
3618 template is processed.  There is rarely a need for something other than
3620 @example
3621 AH_BOTTOM([#include <custom.h>])
3622 @end example
3626 @node Configuration Commands
3627 @section Running Arbitrary Configuration Commands
3628 @cindex Configuration commands
3629 @cindex Commands for configuration
3631 You can execute arbitrary commands before, during, and after
3632 @file{config.status} is run.  The three following macros accumulate the
3633 commands to run when they are called multiple times.
3634 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3635 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3637 @anchor{AC_CONFIG_COMMANDS}
3638 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3639 @acindex{CONFIG_COMMANDS}
3640 Specify additional shell commands to run at the end of
3641 @file{config.status}, and shell commands to initialize any variables
3642 from @command{configure}.  Associate the commands with @var{tag}.
3643 Since typically the @var{cmds} create a file, @var{tag} should
3644 naturally be the name of that file.  If needed, the directory hosting
3645 @var{tag} is created.  The @var{tag} should not contain shell
3646 metacharacters.  @xref{Special Chars in Variables}.
3647 This macro is one of the instantiating macros;
3648 see @ref{Configuration Actions}.
3650 Here is an unrealistic example:
3651 @example
3652 fubar=42
3653 AC_CONFIG_COMMANDS([fubar],
3654                    [echo this is extra $fubar, and so on.],
3655                    [fubar=$fubar])
3656 @end example
3658 Here is a better one:
3659 @example
3660 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3661 @end example
3662 @end defmac
3664 The following two macros look similar, but in fact they are not of the same
3665 breed: they are executed directly by @file{configure}, so you cannot use
3666 @file{config.status} to rerun them.
3668 @c Yet it is good to leave them here.  The user sees them together and
3669 @c decides which best fits their needs.
3671 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3672 @acindex{CONFIG_COMMANDS_PRE}
3673 Execute the @var{cmds} right before creating @file{config.status}.
3675 This macro presents the last opportunity to call @code{AC_SUBST},
3676 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3677 @end defmac
3679 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3680 @acindex{CONFIG_COMMANDS_POST}
3681 Execute the @var{cmds} right after creating @file{config.status}.
3682 @end defmac
3687 @node Configuration Links
3688 @section Creating Configuration Links
3689 @cindex Configuration links
3690 @cindex Links for configuration
3692 You may find it convenient to create links whose destinations depend upon
3693 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3694 creation of relative symbolic links can be delicate when the package is
3695 built in a directory different from the source directory.
3697 @anchor{AC_CONFIG_LINKS}
3698 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3699   @ovar{init-cmds})
3700 @acindex{CONFIG_LINKS}
3701 @cindex Links
3702 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3703 the corresponding link name @var{dest}.  Makes a symbolic link if
3704 possible, otherwise a hard link if possible, otherwise a copy.  The
3705 @var{dest} and @var{source} names should be relative to the top level
3706 source or build directory, and should not contain shell metacharacters.
3707 @xref{Special Chars in Variables}.
3709 This macro is one of the instantiating
3710 macros; see @ref{Configuration Actions}.
3712 For example, this call:
3714 @example
3715 AC_CONFIG_LINKS([host.h:config/$machine.h
3716                 object.h:config/$obj_format.h])
3717 @end example
3719 @noindent
3720 creates in the current directory @file{host.h} as a link to
3721 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3722 link to @file{@var{srcdir}/config/$obj_format.h}.
3724 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3725 impossible for @samp{config.status} to guess the links to establish.
3727 One can then run:
3728 @example
3729 ./config.status host.h object.h
3730 @end example
3731 @noindent
3732 to create the links.
3733 @end defmac
3737 @node Subdirectories
3738 @section Configuring Other Packages in Subdirectories
3739 @cindex Configure subdirectories
3740 @cindex Subdirectory configure
3742 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3743 makefiles in subdirectories.  However, @command{configure} scripts
3744 that control more than one independent package can use
3745 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3746 packages in subdirectories.
3748 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3749 @acindex{CONFIG_SUBDIRS}
3750 @ovindex subdirs
3751 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3752 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3753 be a literal, i.e., please do not use:
3755 @example
3756 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3757 if test "x$package_foo_enabled" = xyes; then
3758   my_subdirs="$my_subdirs foo"
3760 AC_CONFIG_SUBDIRS([$my_subdirs])
3761 @end example
3763 @noindent
3764 because this prevents @samp{./configure --help=recursive} from
3765 displaying the options of the package @code{foo}.  Instead, you should
3766 write:
3768 @example
3769 if test "x$package_foo_enabled" = xyes; then
3770   AC_CONFIG_SUBDIRS([foo])
3772 @end example
3774 If a given @var{dir} is not found at @command{configure} run time, a
3775 warning is reported; if the subdirectory is optional, write:
3777 @example
3778 if test -d "$srcdir/foo"; then
3779   AC_CONFIG_SUBDIRS([foo])
3781 @end example
3783 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3784 of @command{configure}.  This is for packages that might use a
3785 non-Autoconf script @command{Configure}, which can't be called through a
3786 wrapper @command{configure} since it would be the same file on
3787 case-insensitive file systems.
3789 The subdirectory @command{configure} scripts are given the same command
3790 line options that were given to this @command{configure} script, with minor
3791 changes if needed, which include:
3793 @itemize @minus
3794 @item
3795 adjusting a relative name for the cache file;
3797 @item
3798 adjusting a relative name for the source directory;
3800 @item
3801 propagating the current value of @code{$prefix}, including if it was
3802 defaulted, and if the default values of the top level and of the subdirectory
3803 @file{configure} differ.
3804 @end itemize
3806 This macro also sets the output variable @code{subdirs} to the list of
3807 directories @samp{@var{dir} @dots{}}.  Make rules can use
3808 this variable to determine which subdirectories to recurse into.
3810 This macro may be called multiple times.
3811 @end defmac
3813 @node Default Prefix
3814 @section Default Prefix
3815 @cindex Install prefix
3816 @cindex Prefix for install
3818 By default, @command{configure} sets the prefix for files it installs to
3819 @file{/usr/local}.  The user of @command{configure} can select a different
3820 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3821 There are two ways to change the default: when creating
3822 @command{configure}, and when running it.
3824 Some software packages might want to install in a directory other than
3825 @file{/usr/local} by default.  To accomplish that, use the
3826 @code{AC_PREFIX_DEFAULT} macro.
3828 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3829 @acindex{PREFIX_DEFAULT}
3830 Set the default installation prefix to @var{prefix} instead of
3831 @file{/usr/local}.
3832 @end defmac
3834 It may be convenient for users to have @command{configure} guess the
3835 installation prefix from the location of a related program that they
3836 have already installed.  If you wish to do that, you can call
3837 @code{AC_PREFIX_PROGRAM}.
3839 @anchor{AC_PREFIX_PROGRAM}
3840 @defmac AC_PREFIX_PROGRAM (@var{program})
3841 @acindex{PREFIX_PROGRAM}
3842 If the user did not specify an installation prefix (using the
3843 @option{--prefix} option), guess a value for it by looking for
3844 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3845 is found, set the prefix to the parent of the directory containing
3846 @var{program}, else default the prefix as described above
3847 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3848 @var{program} is @code{gcc} and the @env{PATH} contains
3849 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3850 @end defmac
3854 @c ======================================================== Existing tests
3856 @node Existing Tests
3857 @chapter Existing Tests
3859 These macros test for particular system features that packages might
3860 need or want to use.  If you need to test for a kind of feature that
3861 none of these macros check for, you can probably do it by calling
3862 primitive test macros with appropriate arguments (@pxref{Writing
3863 Tests}).
3865 These tests print messages telling the user which feature they're
3866 checking for, and what they find.  They cache their results for future
3867 @command{configure} runs (@pxref{Caching Results}).
3869 Some of these macros set output variables.  @xref{Makefile
3870 Substitutions}, for how to get their values.  The phrase ``define
3871 @var{name}'' is used below as a shorthand to mean ``define the C
3872 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3873 Symbols}, for how to get those symbol definitions into your program.
3875 @menu
3876 * Common Behavior::             Macros' standard schemes
3877 * Alternative Programs::        Selecting between alternative programs
3878 * Files::                       Checking for the existence of files
3879 * Libraries::                   Library archives that might be missing
3880 * Library Functions::           C library functions that might be missing
3881 * Header Files::                Header files that might be missing
3882 * Declarations::                Declarations that may be missing
3883 * Structures::                  Structures or members that might be missing
3884 * Types::                       Types that might be missing
3885 * Compilers and Preprocessors::  Checking for compiling programs
3886 * System Services::             Operating system services
3887 * C and Posix Variants::        Kludges for C and Posix variants
3888 * Erlang Libraries::            Checking for the existence of Erlang libraries
3889 @end menu
3891 @node Common Behavior
3892 @section Common Behavior
3893 @cindex Common autoconf behavior
3895 Much effort has been expended to make Autoconf easy to learn.  The most
3896 obvious way to reach this goal is simply to enforce standard interfaces
3897 and behaviors, avoiding exceptions as much as possible.  Because of
3898 history and inertia, unfortunately, there are still too many exceptions
3899 in Autoconf; nevertheless, this section describes some of the common
3900 rules.
3902 @menu
3903 * Standard Symbols::            Symbols defined by the macros
3904 * Default Includes::            Includes used by the generic macros
3905 @end menu
3907 @node Standard Symbols
3908 @subsection Standard Symbols
3909 @cindex Standard symbols
3911 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3912 their test transform their @var{argument} values to a standard alphabet.
3913 First, @var{argument} is converted to upper case and any asterisks
3914 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3915 that are not alphanumeric are converted to underscores.
3917 For instance,
3919 @example
3920 AC_CHECK_TYPES([struct $Expensive*])
3921 @end example
3923 @noindent
3924 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3925 succeeds.
3928 @node Default Includes
3929 @subsection Default Includes
3930 @cindex Default includes
3931 @cindex Includes, default
3932 @hdrindex{assert.h}
3933 @hdrindex{ctype.h}
3934 @hdrindex{errno.h}
3935 @hdrindex{float.h}
3936 @hdrindex{iso646.h}
3937 @hdrindex{limits.h}
3938 @hdrindex{locale.h}
3939 @hdrindex{math.h}
3940 @hdrindex{setjmp.h}
3941 @hdrindex{signal.h}
3942 @hdrindex{stdarg.h}
3943 @hdrindex{stddef.h}
3944 @hdrindex{stdio.h}
3945 @hdrindex{stdlib.h}
3946 @hdrindex{string.h}
3947 @hdrindex{time.h}
3948 @hdrindex{wchar.h}
3949 @hdrindex{wctype.h}
3951 Test programs frequently need to include headers that may or may not be
3952 available on the system whose features are being tested.  Each test can
3953 use all the preprocessor macros that have been @code{AC_DEFINE}d by
3954 previous tests, so for example one may write
3956 @example
3957 @group
3958 #include <time.h>
3959 #ifdef HAVE_SYS_TIME_H
3960 # include <sys/time.h>
3961 #endif
3962 @end group
3963 @end example
3965 @noindent
3966 if @file{sys/time.h} has already been tested for.
3968 All hosted environments that are still of interest for portable code
3969 provide all of the headers specified in ISO C90 (as amended in 1995):
3970 @file{assert.h}, @file{ctype.h}, @file{errno.h}, @file{float.h},
3971 @file{iso646.h}, @file{limits.h}, @file{locale.h}, @file{math.h},
3972 @file{setjmp.h}, @file{signal.h}, @file{stdarg.h}, @file{stddef.h},
3973 @file{stdio.h}, @file{stdlib.h}, @file{string.h}, @file{time.h},
3974 @file{wchar.h}, and @file{wctype.h}.  Most programs can safely include
3975 these headers unconditionally.  All other headers, including all headers
3976 from later revisions of the C standard, need to be tested for
3977 (@pxref{Header Files}).
3979 If your program needs to be portable to a @emph{freestanding}
3980 environment, such as an embedded OS that doesn't provide all of the
3981 facilities of the C90 standard library, you may need to test for some of
3982 the above headers as well.  Note that many Autoconf macros internally
3983 assume that the complete set of C90 headers are available.
3985 Most generic macros use the following macro to provide a default set
3986 of includes:
3988 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3989 @acindex{INCLUDES_DEFAULT}
3990 Expand to @var{include-directives} if present and nonempty, otherwise to:
3992 @example
3993 @group
3994 #include <stddef.h>
3995 #include <stdio.h>
3996 #include <stdlib.h>
3997 #include <string.h>
3998 #ifdef HAVE_SYS_TYPES_H
3999 # include <sys/types.h>
4000 #endif
4001 #ifdef HAVE_SYS_STAT_H
4002 # include <sys/stat.h>
4003 #endif
4004 #ifdef HAVE_STRINGS_H
4005 # include <strings.h>
4006 #endif
4007 #ifdef HAVE_INTTYPES_H
4008 # include <inttypes.h>
4009 #endif
4010 #ifdef HAVE_STDINT_H
4011 # include <stdint.h>
4012 #endif
4013 #ifdef HAVE_UNISTD_H
4014 # include <unistd.h>
4015 #endif
4016 @end group
4017 @end example
4019 Using this macro without @var{include-directives} has the side effect of
4020 checking for @file{sys/types.h}, @file{sys/stat.h}, @file{strings.h},
4021 @file{inttypes.h}, @file{stdint.h}, and @file{unistd.h}, as if by
4022 @code{AC_CHECK_HEADERS}.  For backward compatibility's sake, it also
4023 unconditionally defines @code{HAVE_STRING_H}, @code{HAVE_STDLIB_H}, and
4024 @code{STDC_HEADERS}.  New code should not make use of these preprocessor
4025 macros.
4026 @end defmac
4028 @defmac AC_CHECK_INCLUDES_DEFAULT
4029 @acindex{CHECK_INCLUDES_DEFAULT}
4030 Check for all the headers that @code{AC_INCLUDES_DEFAULT} would check
4031 for as a side-effect, if this has not already happened.
4033 This macro mainly exists so that @code{autoupdate} can replace certain
4034 obsolete constructs with it. You should not need to use it yourself; in
4035 fact, it is likely to be safe to delete it from any script in which it
4036 appears.  (@code{autoupdate} does not know whether preprocessor macros
4037 such as @code{HAVE_STDINT_H} are used in the program, nor whether they
4038 would get defined as a side-effect of other checks.)
4039 @end defmac
4041 @node Alternative Programs
4042 @section Alternative Programs
4043 @cindex Programs, checking
4045 These macros check for the presence or behavior of particular programs.
4046 They are used to choose between several alternative programs and to
4047 decide what to do once one has been chosen.  If there is no macro
4048 specifically defined to check for a program you need, and you don't need
4049 to check for any special properties of it, then you can use one of the
4050 general program-check macros.
4052 @menu
4053 * Particular Programs::         Special handling to find certain programs
4054 * Generic Programs::            How to find other programs
4055 @end menu
4057 @node Particular Programs
4058 @subsection Particular Program Checks
4060 These macros check for particular programs---whether they exist, and
4061 in some cases whether they support certain features.
4063 @defmac AC_PROG_AWK
4064 @acindex{PROG_AWK}
4065 @ovindex AWK
4066 @caindex prog_AWK
4067 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
4068 order, and set output variable @code{AWK} to the first one that is found.
4069 It tries @code{gawk} first because that is reported to be the
4070 best implementation.  The result can be overridden by setting the
4071 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
4073 Using this macro is sufficient to avoid the pitfalls of traditional
4074 @command{awk} (@pxref{awk, , Limitations of Usual Tools}).
4075 @end defmac
4077 @defmac AC_PROG_GREP
4078 @acindex{PROG_GREP}
4079 @ovindex GREP
4080 @caindex prog_GREP
4081 Look for the best available @code{grep} or @code{ggrep} that accepts the
4082 longest input lines possible, and that supports multiple @option{-e} options.
4083 Set the output variable @code{GREP} to whatever is chosen.
4084 @xref{grep, , Limitations of Usual Tools}, for more information about
4085 portability problems with the @command{grep} command family.  The result
4086 can be overridden by setting the @code{GREP} variable and is cached in the
4087 @code{ac_cv_path_GREP} variable.
4088 @end defmac
4090 @defmac AC_PROG_EGREP
4091 @acindex{PROG_EGREP}
4092 @ovindex EGREP
4093 @caindex prog_EGREP
4094 Check whether @code{$GREP -E} works, or else look for the best available
4095 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
4096 Set the output variable @code{EGREP} to whatever is chosen.  The result
4097 can be overridden by setting the @code{EGREP} variable and is cached in the
4098 @code{ac_cv_path_EGREP} variable.
4099 @end defmac
4101 @defmac AC_PROG_FGREP
4102 @acindex{PROG_FGREP}
4103 @ovindex FGREP
4104 @caindex prog_FGREP
4105 Check whether @code{$GREP -F} works, or else look for the best available
4106 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
4107 Set the output variable @code{FGREP} to whatever is chosen.  The result
4108 can be overridden by setting the @code{FGREP} variable and is cached in the
4109 @code{ac_cv_path_FGREP} variable.
4110 @end defmac
4112 @defmac AC_PROG_INSTALL
4113 @acindex{PROG_INSTALL}
4114 @ovindex INSTALL
4115 @ovindex INSTALL_PROGRAM
4116 @ovindex INSTALL_DATA
4117 @ovindex INSTALL_SCRIPT
4118 @caindex path_install
4119 @prindex @command{install-sh}
4120 Set output variable @code{INSTALL} to the name of a BSD-compatible
4121 @command{install} program, if one is found in the current @env{PATH}.
4122 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
4123 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
4124 default directories) to determine @var{dir} (@pxref{Output}).  Also set
4125 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
4126 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
4128 @samp{@@INSTALL@@} is special, as its value may vary for different
4129 configuration files.
4131 This macro screens out various instances of @command{install} known not to
4132 work.  It prefers to find a C program rather than a shell script, for
4133 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
4134 but that name is obsolete because some @command{make} programs have a rule
4135 that creates @file{install} from it if there is no makefile.  Further, this
4136 macro requires @command{install} to be able to install multiple files into a
4137 target directory in a single invocation.
4139 Autoconf comes with a copy of @file{install-sh} that you can use.
4140 If you use @code{AC_PROG_INSTALL}, you must include @file{install-sh} in
4141 your distribution; otherwise @command{autoreconf} and @command{configure}
4142 will produce an error message saying they can't find it---even if the
4143 system you're on has a good @command{install} program.  This check is a
4144 safety measure to prevent you from accidentally leaving that file out,
4145 which would prevent your package from installing on systems that don't
4146 have a BSD-compatible @command{install} program.
4148 If you need to use your own installation program because it has features
4149 not found in standard @command{install} programs, there is no reason to use
4150 @code{AC_PROG_INSTALL}; just put the file name of your program into your
4151 @file{Makefile.in} files.
4153 The result of the test can be overridden by setting the variable
4154 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4155 @end defmac
4157 @defmac AC_PROG_MKDIR_P
4158 @acindex{PROG_MKDIR_P}
4159 @ovindex MKDIR_P
4160 @caindex path_mkdir
4161 @prindex @command{install-sh}
4162 Set output variable @code{MKDIR_P} to a program that ensures that for
4163 each argument, a directory named by this argument exists, creating it
4164 and its parent directories if needed, and without race conditions when
4165 two instances of the program attempt to make the same directory at
4166 nearly the same time.
4168 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
4169 falls back on invoking @command{install-sh} with the @option{-d} option,
4170 so your package should
4171 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4172 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4173 is vulnerable to race conditions, so if you want to support parallel
4174 installs from
4175 different packages into the same directory you need to make sure you
4176 have an up-to-date @file{install-sh}.  In particular, be careful about
4177 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4179 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4180 in M4sh}), but it sets an output variable intended for use in other
4181 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4182 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
4183 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4184 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4185 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4186 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4187 Finally, @code{AS_MKDIR_P} does not check for race condition
4188 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4190 @samp{@@MKDIR_P@@} is special, as its value may vary for different
4191 configuration files.
4193 The result of the test can be overridden by setting the variable
4194 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4195 @end defmac
4197 @anchor{AC_PROG_LEX}
4198 @defmac AC_PROG_LEX (@var{options})
4199 @acindex{PROG_LEX}
4200 @ovindex LEX
4201 @ovindex LEXLIB
4202 @cvindex YYTEXT_POINTER
4203 @ovindex LEX_OUTPUT_ROOT
4204 @caindex prog_LEX
4205 Search for a lexical analyzer generator, preferring @code{flex}
4206 to plain @code{lex}.  Output variable @code{LEX} is set to whichever
4207 program is available.  If neither program is available, @code{LEX}
4208 is set to @samp{:};
4209 for packages that ship the generated @file{file.yy.c}
4210 alongside the source @file{file.l}, this default allows users without a
4211 lexer generator to still build the package even if the timestamp for
4212 @file{file.l} is inadvertently changed.
4214 The name of the program to use can be overridden by setting the
4215 output variable @code{LEX} or the cache variable @code{ac_cv_prog_LEX}
4216 when running @command{configure}.
4218 If a lexical analyzer generator is found, this macro performs additional
4219 checks for common portability pitfalls.  If these additional checks
4220 fail, @code{LEX} is reset to @samp{:}; otherwise the following
4221 additional macros and variables are provided.
4223 Preprocessor macro @code{YYTEXT_POINTER} is defined if the lexer
4224 skeleton, by default, declares @code{yytext} as a @samp{@w{char *}}
4225 rather than a @samp{@w{char []}}.
4227 Output variable @code{LEX_OUTPUT_ROOT} is set to the base of the file
4228 name that the lexer generates; this is usually either @file{lex.yy} or
4229 @file{lexyy}.
4231 If generated lexers need a library to work, output variable
4232 @code{LEXLIB} is set to a link option for that library (e.g.,
4233 @option{-ll}), otherwise it is set to empty.
4235 The @var{options} argument modifies the behavior of @code{AC_PROG_LEX}.
4236 It should be a whitespace-separated list of options.  Currently there
4237 are only two options, and they are mutually exclusive:
4239 @table @code
4240 @item yywrap
4241 Indicate that the library in @code{LEXLIB} needs to define the function
4242 @code{yywrap}.  If a library that defines this function cannot be found,
4243 @code{LEX} will be reset to @samp{:}.
4245 @item noyywrap
4246 Indicate that the library in @code{LEXLIB} does not need to define the
4247 function @code{yywrap}.  @command{configure} will not search for it at
4248 all.
4249 @end table
4251 Prior to Autoconf 2.70, @code{AC_PROG_LEX} did not take any arguments,
4252 and its behavior was different from either of the above possibilities:
4253 it would search for a library that defines @code{yywrap}, and would set
4254 @code{LEXLIB} to that library if it finds one.  However, if a library
4255 that defines this function could not be found, @code{LEXLIB} would be
4256 left empty and @code{LEX} would @emph{not} be reset.  This behavior was
4257 due to a bug, but several packages came to depend on it, so
4258 @code{AC_PROG_LEX} still does this if neither the @code{yywrap} nor the
4259 @code{noyywrap} option is given.
4261 Usage of @code{AC_PROG_LEX} without choosing one of the @code{yywrap}
4262 or @code{noyywrap} options is deprecated.  It is usually better to
4263 use @code{noyywrap} and define the @code{yywrap} function yourself,
4264 as this almost always renders the @code{LEXLIB} unnecessary.
4266 @strong{Caution:} As a side-effect of the test, this macro may delete
4267 any file in the configure script's current working directory named
4268 @file{lex.yy.c} or @file{lexyy.c}.
4270 @strong{Caution:} Packages that ship a generated @file{lex.yy.c}
4271 cannot assume that the definition of @code{YYTEXT_POINTER} matches
4272 the code in that file.  They also cannot assume that @code{LEXLIB}
4273 provides the library routines required by the code in that file.
4275 If you use Flex to generate @file{lex.yy.c}, you can work around these
4276 limitations by defining @code{yywrap} and @code{main} yourself
4277 (rendering @code{-lfl} unnecessary), and by using either the
4278 @option{--array} or @option{--pointer} options to control how
4279 @code{yytext} is declared.  The code generated by Flex is also more
4280 portable than the code generated by historical versions of Lex.
4282 If you have used Flex to generate @file{lex.yy.c}, and especially if
4283 your scanner depends on Flex features, we recommend you use this
4284 Autoconf snippet to prevent the scanner being regenerated with
4285 historical Lex:
4287 @example
4288 AC_PROG_LEX
4289 if test "x$LEX" != xflex; then
4290   LEX="$SHELL $missing_dir/missing flex"
4291   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4292   AC_SUBST([LEXLIB], [''])
4294 @end example
4296 The shell script @command{missing} can be found in the Automake
4297 distribution.
4299 Remember that the user may have supplied an alternate location in
4300 @env{LEX}, so if Flex is required, it is better to check that the user
4301 provided something sufficient by parsing the output of @samp{$LEX
4302 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4303 @end defmac
4305 @anchor{AC_PROG_LN_S}
4306 @defmac AC_PROG_LN_S
4307 @acindex{PROG_LN_S}
4308 @ovindex LN_S
4309 If @samp{ln -s} works on the current file system (the operating system
4310 and file system support symbolic links), set the output variable
4311 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4312 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -pR}.
4314 If you make a link in a directory other than the current directory, its
4315 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4316 create links using @samp{$(LN_S)}, either find out which form is used
4317 and adjust the arguments, or always invoke @code{ln} in the directory
4318 where the link is to be created.
4320 In other words, it does not work to do:
4321 @example
4322 $(LN_S) foo /x/bar
4323 @end example
4325 Instead, do:
4327 @example
4328 (cd /x && $(LN_S) foo bar)
4329 @end example
4330 @end defmac
4332 @defmac AC_PROG_RANLIB
4333 @acindex{PROG_RANLIB}
4334 @ovindex RANLIB
4335 @c @caindex prog_RANLIB
4336 @c @caindex prog_ac_ct_RANLIB
4337 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4338 is found, and otherwise to @samp{:} (do nothing).
4339 @end defmac
4341 @defmac AC_PROG_SED
4342 @acindex{PROG_SED}
4343 @ovindex SED
4344 @caindex path_SED
4345 Set output variable @code{SED} to a Sed implementation that conforms to
4346 Posix and does not have arbitrary length limits.  Report an error if no
4347 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4348 information about portability problems with Sed.
4350 The result of this test can be overridden by setting the @code{SED} variable
4351 and is cached in the @code{ac_cv_path_SED} variable.
4352 @end defmac
4354 @defmac AC_PROG_YACC
4355 @acindex{PROG_YACC}
4356 @evindex YACC
4357 @evindex YFLAGS
4358 @ovindex YACC
4359 @caindex prog_YACC
4360 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4361 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4362 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4363 The result of this test can be influenced by setting the variable
4364 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4365 @end defmac
4367 @node Generic Programs
4368 @subsection Generic Program and File Checks
4370 These macros are used to find programs not covered by the ``particular''
4371 test macros.  If you need to check the behavior of a program as well as
4372 find out whether it is present, you have to write your own test for it
4373 (@pxref{Writing Tests}).  By default, these macros use the environment
4374 variable @env{PATH}.  If you need to check for a program that might not
4375 be in the user's @env{PATH}, you can pass a modified path to use
4376 instead, like this:
4378 @example
4379 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4380              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4381 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4382 @end example
4384 You are strongly encouraged to declare the @var{variable} passed to
4385 @code{AC_CHECK_PROG} etc.@: as precious.  @xref{Setting Output Variables},
4386 @code{AC_ARG_VAR}, for more details.
4388 @anchor{AC_CHECK_PROG}
4389 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4390   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4391   @ovar{reject})
4392 @acindex{CHECK_PROG}
4393 @caindex prog_@var{variable}
4394 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4395 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4396 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4397 absolute file name) even if it is the first found in the search path; in
4398 that case, set @var{variable} using the absolute file name of the
4399 @var{prog-to-check-for} found that is not @var{reject}.  If
4400 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4401 @var{variable}.  The result of this test can be overridden by setting the
4402 @var{variable} variable or the cache variable
4403 @code{ac_cv_prog_@var{variable}}.
4404 @end defmac
4406 @anchor{AC_CHECK_PROGS}
4407 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4408   @ovar{value-if-not-found}, @dvar{path, $PATH})
4409 @acindex{CHECK_PROGS}
4410 @caindex prog_@var{variable}
4411 Check for each program in the blank-separated list
4412 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4413 @var{variable} to the name of that program.  Otherwise, continue
4414 checking the next program in the list.  If none of the programs in the
4415 list are found, set @var{variable} to @var{value-if-not-found}; if
4416 @var{value-if-not-found} is not specified, the value of @var{variable}
4417 is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4418 this test can be overridden by setting the @var{variable} variable or the
4419 cache variable @code{ac_cv_prog_@var{variable}}.
4420 @end defmac
4422 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4423   @ovar{value-if-not-found}, @dvar{path, $PATH})
4424 @acindex{CHECK_TARGET_TOOL}
4425 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4426 with a prefix of the target type as determined by
4427 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4428 If the tool cannot be found with a prefix, and if the build and target
4429 types are equal, then it is also searched for without a prefix.
4431 As noted in @ref{Specifying Target Triplets}, the
4432 target is rarely specified, because most of the time it is the same
4433 as the host: it is the type of system for which any compiler tool in
4434 the package produces code.  What this macro looks for is,
4435 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4436 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4437 uses to produce objects, archives or executables}.
4438 @end defmac
4440 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4441   @ovar{value-if-not-found}, @dvar{path, $PATH})
4442 @acindex{CHECK_TOOL}
4443 @c @caindex prog_@var{VARIABLE}
4444 @c @caindex prog_ac_ct_@var{VARIABLE}
4445 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4446 with a prefix of the host type as specified by @option{--host}, followed by a
4447 dash.  For example, if the user runs
4448 @samp{configure --build=x86_64-gnu --host=aarch64-linux-gnu}, then this call:
4449 @example
4450 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4451 @end example
4452 @noindent
4453 sets @code{RANLIB} to @file{aarch64-linux-gnu-ranlib} if that program exists in
4454 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4455 @var{path}, or to @samp{:} if neither program exists.
4457 When cross-compiling, this macro will issue a warning if no program
4458 prefixed with the host type could be found.
4459 For more information, see @ref{Specifying Target Triplets}.
4460 @end defmac
4462 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4463   @ovar{value-if-not-found}, @dvar{path, $PATH})
4464 @acindex{CHECK_TARGET_TOOLS}
4465 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4466 @var{progs-to-check-for} are checked with a prefix of the target type as
4467 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4468 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4469 prefix, and if the build and target types are equal, then the first one
4470 without a prefix is used.  If a tool is found, set @var{variable} to
4471 the name of that program.  If none of the tools in the list are found,
4472 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4473 is not specified, the value of @var{variable} is not changed.  Calls
4474 @code{AC_SUBST} for @var{variable}.
4475 @end defmac
4477 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4478   @ovar{value-if-not-found}, @dvar{path, $PATH})
4479 @acindex{CHECK_TOOLS}
4480 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4481 @var{progs-to-check-for} are checked with a prefix of the host type as
4482 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4483 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4484 prefix, then the first one without a prefix is used.  If a tool is found,
4485 set @var{variable} to the name of that program.  If none of the tools in
4486 the list are found, set @var{variable} to @var{value-if-not-found}; if
4487 @var{value-if-not-found} is not specified, the value of @var{variable}
4488 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4490 When cross-compiling, this macro will issue a warning if no program
4491 prefixed with the host type could be found.
4492 For more information, see @ref{Specifying Target Triplets}.
4493 @end defmac
4495 @anchor{AC_PATH_PROG}
4496 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4497   @ovar{value-if-not-found}, @dvar{path, $PATH})
4498 @acindex{PATH_PROG}
4499 @caindex path_@var{variable}
4500 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4501 name of @var{prog-to-check-for} if found.  The result of this test
4502 can be overridden by setting the @var{variable} variable.  A positive
4503 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4504 variable.
4505 @end defmac
4507 @anchor{AC_PATH_PROGS}
4508 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4509   @ovar{value-if-not-found}, @dvar{path, $PATH})
4510 @acindex{PATH_PROGS}
4511 @caindex path_@var{variable}
4512 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4513 are found, set @var{variable} to the absolute name of the program
4514 found.  The result of this test can be overridden by setting the
4515 @var{variable} variable.  A positive result of this test is cached in
4516 the @code{ac_cv_path_@var{variable}} variable.
4517 @end defmac
4519 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4520   @var{progs-to-check-for}, @var{feature-test}, @
4521   @ovar{action-if-not-found}, @dvar{path, $PATH})
4522 @acindex{PATH_PROGS_FEATURE_CHECK}
4523 @caindex path_@var{variable}
4524 @vrindex ac_path_@var{variable}
4525 @vrindex ac_path_@var{variable}_found
4526 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4527 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4528 its value.  Otherwise, check for each program in the blank-separated
4529 list @var{progs-to-check-for} existing in @var{path}.  For each program
4530 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4531 set to the absolute name of the candidate program.  If no invocation of
4532 @var{feature-test} sets the shell variable
4533 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4534 executed.  @var{feature-test} will be run even when
4535 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4536 choose a better candidate found later in @var{path}; to accept the
4537 current setting and bypass all further checks, @var{feature-test} can
4538 execute @code{ac_path_@var{variable}_found=:}.
4540 Note that this macro has some subtle differences from
4541 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4542 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4543 particular, @var{variable} is not set to the final value of
4544 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4545 run.  Also, on failure, any action can be performed, whereas
4546 @code{AC_CHECK_PROGS} only performs
4547 @code{@var{variable}=@var{value-if-not-found}}.
4549 Here is an example, similar to what Autoconf uses in its own configure
4550 script.  It will search for an implementation of @command{m4} that
4551 supports the @code{indir} builtin, even if it goes by the name
4552 @command{gm4} or is not the first implementation on @env{PATH}.
4554 @example
4555 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4556   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4557     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4558       test "x$m4out" = x0 \
4559       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4560     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4561 AC_SUBST([M4], [$ac_cv_path_M4])
4562 @end example
4563 @end defmac
4565 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4566   @ovar{value-if-not-found}, @dvar{path, $PATH})
4567 @acindex{PATH_TARGET_TOOL}
4568 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4569 name of the program if it is found.
4570 @end defmac
4572 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4573   @ovar{value-if-not-found}, @dvar{path, $PATH})
4574 @acindex{PATH_TOOL}
4575 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4576 name of the program if it is found.
4578 When cross-compiling, this macro will issue a warning if no program
4579 prefixed with the host type could be found.
4580 For more information, see @ref{Specifying Target Triplets}.
4581 @end defmac
4584 @node Files
4585 @section Files
4586 @cindex File, checking
4588 You might also need to check for the existence of files.  Before using
4589 these macros, ask yourself whether a runtime test might not be a better
4590 solution.  Be aware that, like most Autoconf macros, they test a feature
4591 of the host machine, and therefore, they die when cross-compiling.
4593 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4594   @ovar{action-if-not-found})
4595 @acindex{CHECK_FILE}
4596 @caindex file_@var{file}
4597 Check whether file @var{file} exists on the native system.  If it is
4598 found, execute @var{action-if-found}, otherwise do
4599 @var{action-if-not-found}, if given.  Cache the result of this test
4600 in the @code{ac_cv_file_@var{file}} variable, with characters not
4601 suitable for a variable name mapped to underscores.
4602 @end defmac
4604 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4605   @ovar{action-if-not-found})
4606 @acindex{CHECK_FILES}
4607 @caindex file_@var{file}
4608 For each file listed in @var{files}, execute @code{AC_CHECK_FILE}
4609 and perform either @var{action-if-found} or @var{action-if-not-found}.
4610 Like @code{AC_CHECK_FILE}, this defines @samp{HAVE_@var{file}}
4611 (@pxref{Standard Symbols}) for each file found and caches the results of
4612 each test in the @code{ac_cv_file_@var{file}} variable, with characters
4613 not suitable for a variable name mapped to underscores.
4614 @end defmac
4617 @node Libraries
4618 @section Library Files
4619 @cindex Library, checking
4621 The following macros check for the presence of certain C, C++, Fortran,
4622 or Go library archive files.
4624 @anchor{AC_CHECK_LIB}
4625 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4626   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4627 @acindex{CHECK_LIB}
4628 @caindex lib_@var{library}_@var{function}
4629 Test whether the library @var{library} is available by trying to link
4630 a test program that calls function @var{function} with the library.
4631 @var{function} should be a function provided by the library.
4632 Use the base
4633 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4634 the @var{library} argument.
4636 @var{action-if-found} is a list of shell commands to run if the link
4637 with the library succeeds; @var{action-if-not-found} is a list of shell
4638 commands to run if the link fails.  If @var{action-if-found} is not
4639 specified, the default action prepends @option{-l@var{library}} to
4640 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4641 capitals).  This macro is intended to support building @code{LIBS} in
4642 a right-to-left (least-dependent to most-dependent) fashion such that
4643 library dependencies are satisfied as a natural side effect of
4644 consecutive tests.  Linkers are sensitive to library ordering
4645 so the order in which @code{LIBS} is generated is important to reliable
4646 detection of libraries.
4648 If linking with @var{library} results in unresolved symbols that would
4649 be resolved by linking with additional libraries, give those libraries
4650 as the @var{other-libraries} argument, separated by spaces:
4651 e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4652 that @var{library} is present, because linking the test program can
4653 fail with unresolved symbols.  The @var{other-libraries} argument
4654 should be limited to cases where it is desirable to test for one library
4655 in the presence of another that is not already in @code{LIBS}.
4657 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4658 in some common cases.  Many standard functions like @code{gethostbyname}
4659 appear in the standard C library on some hosts, and in special libraries
4660 like @code{nsl} on other hosts.  On some hosts the special libraries
4661 contain variant implementations that you may not want to use.  These
4662 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4663 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4665 The result of this test is cached in the
4666 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4667 @end defmac
4669 @anchor{AC_SEARCH_LIBS}
4670 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4671   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4672 @acindex{SEARCH_LIBS}
4673 @caindex search_@var{function}
4674 Search for a library defining @var{function} if it's not already
4675 available.  This equates to calling
4676 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4677 no libraries, then for each library listed in @var{search-libs}.
4679 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4680 to contain @var{function}, and run @var{action-if-found}.  If the
4681 function is not found, run @var{action-if-not-found}.
4683 If linking with @var{library} results in unresolved symbols that would
4684 be resolved by linking with additional libraries, give those libraries
4685 as the @var{other-libraries} argument, separated by spaces:
4686 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4687 that @var{function} is present, because linking the test program
4688 always fails with unresolved symbols.
4690 The result of this test is cached in the
4691 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4692 @var{function} is already available, as @samp{no} if no library
4693 containing @var{function} was found, otherwise as the
4694 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4695 @end defmac
4699 @node Library Functions
4700 @section Library Functions
4702 The following macros check for particular C library functions.
4703 If there is no macro specifically defined to check for a function you need,
4704 and you don't need to check for any special properties of
4705 it, then you can use one of the general function-check macros.
4707 @menu
4708 * Function Portability::        Pitfalls with usual functions
4709 * Particular Functions::        Special handling to find certain functions
4710 * Generic Functions::           How to find other functions
4711 @end menu
4713 @node Function Portability
4714 @subsection Portability of C Functions
4715 @cindex Portability of C functions
4716 @cindex C function portability
4718 Most usual functions can either be missing, or be buggy, or be limited
4719 on some architectures.  This section tries to make an inventory of these
4720 portability issues.  By definition, this list always requires
4721 additions.  A much more complete list is maintained by the Gnulib
4722 project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4723 Current Posix Functions, gnulib, Gnulib}, @ref{Legacy Function
4724 Substitutes, , Legacy Functions, gnulib, Gnulib}, and @ref{Glibc
4725 Function Substitutes, , Glibc Functions, gnulib, Gnulib}.  Please
4726 help us keep the Gnulib list as complete as possible.
4728 @table @asis
4729 @item @code{exit}
4730 @c @fuindex exit
4731 @prindex @code{exit}
4732 On ancient hosts, @code{exit} returned @code{int}.
4733 This is because @code{exit} predates @code{void}, and there was a long
4734 tradition of it returning @code{int}.
4736 On current hosts, the problem more likely is that @code{exit} is not
4737 declared, due to C++ problems of some sort or another.  For this reason
4738 we suggest that test programs not invoke @code{exit}, but return from
4739 @code{main} instead.
4741 @item @code{free}
4742 @c @fuindex free
4743 @prindex @code{free}
4744 The C standard says a call @code{free (NULL)} does nothing, but
4745 some old systems don't support this (e.g., NextStep).
4747 @item @code{isinf}
4748 @itemx @code{isnan}
4749 @c @fuindex isinf
4750 @c @fuindex isnan
4751 @prindex @code{isinf}
4752 @prindex @code{isnan}
4753 In C99 and later, @code{isinf} and @code{isnan} are
4754 macros.  On some systems just macros are available
4755 (e.g., HP-UX and Solaris 10), on
4756 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4757 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4758 these functions are declared in nonstandard headers like
4759 @code{<sunmath.h>} and defined in non-default libraries like
4760 @option{-lm} or @option{-lsunmath}.
4762 In C99 and later, @code{isinf} and @code{isnan} macros work correctly with
4763 @code{long double} arguments, but pre-C99 systems that use functions
4764 typically assume @code{double} arguments.  On such a system,
4765 @code{isinf} incorrectly returns true for a finite @code{long double}
4766 argument that is outside the range of @code{double}.
4768 The best workaround for these issues is to use Gnulib modules
4769 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4770 solution involves code like the following.
4772 @smallexample
4773 #include <math.h>
4775 #ifndef isnan
4776 # define isnan(x) \
4777     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4778      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4779      : isnan_f (x))
4780 static int isnan_f  (float       x) @{ return x != x; @}
4781 static int isnan_d  (double      x) @{ return x != x; @}
4782 static int isnan_ld (long double x) @{ return x != x; @}
4783 #endif
4785 #ifndef isinf
4786 # define isinf(x) \
4787     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4788      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4789      : isinf_f (x))
4790 static int isinf_f  (float       x)
4791 @{ return !isnan (x) && isnan (x - x); @}
4792 static int isinf_d  (double      x)
4793 @{ return !isnan (x) && isnan (x - x); @}
4794 static int isinf_ld (long double x)
4795 @{ return !isnan (x) && isnan (x - x); @}
4796 #endif
4797 @end smallexample
4799 Some optimizing compilers mishandle these definitions, but systems with that bug
4800 typically have many other floating point corner-case compliance problems
4801 anyway, so it's probably not worth worrying about.
4803 @item @code{malloc}
4804 @c @fuindex malloc
4805 @prindex @code{malloc}
4806 The C standard says a call @code{malloc (0)} is implementation
4807 dependent.  It can return either @code{NULL} or a new non-null pointer.
4808 The latter is more common (e.g., the GNU C Library) but is by
4809 no means universal.  @code{AC_FUNC_MALLOC}
4810 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4812 @item @code{putenv}
4813 @c @fuindex putenv
4814 @prindex @code{putenv}
4815 Posix prefers @code{setenv} to @code{putenv}; among other things,
4816 @code{putenv} is not required of all Posix implementations, but
4817 @code{setenv} is.
4819 Posix specifies that @code{putenv} puts the given string directly in
4820 @code{environ}, but some systems make a copy of it instead (e.g.,
4821 glibc 2.0, or BSD).  And when a copy is made, @code{unsetenv} might
4822 not free it, causing a memory leak (e.g., FreeBSD 4).
4824 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4825 environment, but this is not standard usage and it dumps core
4826 on some systems (e.g., AIX).
4828 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4829 environment, rather than inserting it with an empty value.
4831 @item @code{realloc}
4832 @c @fuindex realloc
4833 @prindex @code{realloc}
4834 The C standard says a call @code{realloc (NULL, size)} is equivalent
4835 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4836 NextStep).
4838 @item @code{signal} handler
4839 @c @fuindex signal
4840 @prindex @code{signal}
4841 @prindex @code{sigaction}
4842 Normally @code{signal} takes a handler function with a return type of
4843 @code{void}, but some old systems required @code{int} instead.  Any
4844 actual @code{int} value returned is not used; this is only a
4845 difference in the function prototype demanded.
4847 All systems we know of in current use return @code{void}.  The
4848 @code{int} was to support K&R C, where of course @code{void} is not
4849 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4850 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4851 all cases.
4853 In most cases, it is more robust to use @code{sigaction} when it is
4854 available, rather than @code{signal}.
4856 @item @code{snprintf}
4857 @c @fuindex snprintf
4858 @prindex @code{snprintf}
4859 @c @fuindex vsnprintf
4860 @prindex @code{vsnprintf}
4861 In C99 and later, if the output array isn't big enough
4862 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4863 truncate the output and return the number of bytes that ought to have
4864 been produced.  Some older systems return the truncated length (e.g.,
4865 GNU C Library 2.0.x or IRIX 6.5), some a negative value
4866 (e.g., earlier GNU C Library versions), and some the buffer
4867 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4868 older systems ignore the length and overrun the buffer (e.g., 64-bit
4869 Solaris 7).
4871 @item @code{sprintf}
4872 @c @fuindex sprintf
4873 @prindex @code{sprintf}
4874 @c @fuindex vsprintf
4875 @prindex @code{vsprintf}
4876 The C standard says @code{sprintf} and @code{vsprintf} return the
4877 number of bytes written.  On some ancient systems (SunOS 4 for
4878 instance) they return the buffer pointer instead, but these no
4879 longer need to be worried about.
4881 @item @code{sscanf}
4882 @c @fuindex sscanf
4883 @prindex @code{sscanf}
4884 On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4885 that its
4886 input string be writable (though it doesn't actually change it).  This
4887 can be a problem when using @command{gcc} since it normally puts
4888 constant strings in read-only memory (@pxref{Incompatibilities,
4889 Incompatibilities of GCC, , gcc, Using and
4890 Porting the GNU Compiler Collection}).  Apparently in some cases even
4891 having format strings read-only can be a problem.
4893 @item @code{strerror_r}
4894 @c @fuindex strerror_r
4895 @prindex @code{strerror_r}
4896 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4897 systems (e.g., GNU C Library version 2.2.4) provide a
4898 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4899 can detect which is in use (@pxref{Particular Functions}).
4901 @item @code{strnlen}
4902 @c @fuindex strnlen
4903 @prindex @code{strnlen}
4904 AIX 4.3 provides a broken version which produces the
4905 following results:
4907 @example
4908 strnlen ("foobar", 0) = 0
4909 strnlen ("foobar", 1) = 3
4910 strnlen ("foobar", 2) = 2
4911 strnlen ("foobar", 3) = 1
4912 strnlen ("foobar", 4) = 0
4913 strnlen ("foobar", 5) = 6
4914 strnlen ("foobar", 6) = 6
4915 strnlen ("foobar", 7) = 6
4916 strnlen ("foobar", 8) = 6
4917 strnlen ("foobar", 9) = 6
4918 @end example
4920 @item @code{sysconf}
4921 @c @fuindex sysconf
4922 @prindex @code{sysconf}
4923 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4924 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4925 @code{#ifdef}.
4927 @item @code{unlink}
4928 @c @fuindex unlink
4929 @prindex @code{unlink}
4930 The Posix spec says that @code{unlink} causes the given file to be
4931 removed only after there are no more open file handles for it.  Some
4932 non-Posix hosts have trouble with this requirement, though,
4933 and some DOS variants even corrupt the file system.
4935 @item @code{unsetenv}
4936 @c @fuindex unsetenv
4937 @prindex @code{unsetenv}
4938 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4939 can be removed with a call @code{putenv ("FOO=")}, as described under
4940 @code{putenv} above.
4942 @item @code{va_copy}
4943 @c @fuindex va_copy
4944 @prindex @code{va_copy}
4945 C99 and later provide @code{va_copy} for copying
4946 @code{va_list} variables.  It may be available in older environments
4947 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4948 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4949 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4950 portability.
4952 @item @code{va_list}
4953 @c @fuindex va_list
4954 @prindex @code{va_list}
4955 @code{va_list} is not necessarily just a pointer.  It can be a
4956 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4957 not portable.  Or it can be an array (e.g., @command{gcc} in some
4958 PowerPC configurations), which means as a function parameter it can be
4959 effectively call-by-reference and library routines might modify the
4960 value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
4961 2.1).
4963 @item Signed @code{>>}
4964 Normally the C @code{>>} right shift of a signed type replicates the
4965 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4966 taken since Standard C doesn't require that behavior.  On those
4967 few processors without a native arithmetic shift (for instance Cray
4968 vector systems) zero bits may be shifted in, the same as a shift of an
4969 unsigned type.
4971 @item Integer @code{/}
4972 C divides signed integers by truncating their quotient toward zero,
4973 yielding the same result as Fortran.  However, before C99 the standard
4974 allowed C implementations to take the floor or ceiling of the quotient
4975 in some cases.  Hardly any implementations took advantage of this
4976 freedom, though, and it's probably not worth worrying about this issue
4977 nowadays.
4978 @end table
4981 @node Particular Functions
4982 @subsection Particular Function Checks
4983 @cindex Function, checking
4985 These macros check for particular C functions---whether they exist, and
4986 in some cases how they respond when given certain arguments.
4988 @anchor{AC_FUNC_ALLOCA}
4989 @defmac AC_FUNC_ALLOCA
4990 @acindex{FUNC_ALLOCA}
4991 @cvindex C_ALLOCA
4992 @cvindex HAVE_ALLOCA_H
4993 @ovindex ALLOCA
4994 @c @fuindex alloca
4995 @prindex @code{alloca}
4996 @hdrindex{alloca.h}
4997 @c @caindex working_alloca_h
4998 Check for the @code{alloca} function.  Define @code{HAVE_ALLOCA_H} if
4999 @file{alloca.h} defines a working @code{alloca}.  If not, look for a
5000 builtin alternative.  If either method succeeds, define
5001 @code{HAVE_ALLOCA}.  Otherwise, set the output variable @code{ALLOCA} to
5002 @samp{$@{LIBOBJDIR@}alloca.o} and define
5003 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
5004 garbage collect).  This variable is separate from @code{LIBOBJS} so
5005 multiple programs can share the value of @code{ALLOCA} without needing
5006 to create an actual library, in case only some of them use the code in
5007 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
5008 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
5010 Source files that use @code{alloca} should start with a piece of code
5011 like the following, to declare it properly.
5013 @example
5014 @group
5015 #include <stdlib.h>
5016 #include <stddef.h>
5017 #ifdef HAVE_ALLOCA_H
5018 # include <alloca.h>
5019 #elif !defined alloca
5020 # ifdef __GNUC__
5021 #  define alloca __builtin_alloca
5022 # elif defined _MSC_VER
5023 #  include <malloc.h>
5024 #  define alloca _alloca
5025 # elif !defined HAVE_ALLOCA
5026 #  ifdef  __cplusplus
5027 extern "C"
5028 #  endif
5029 void *alloca (size_t);
5030 # endif
5031 #endif
5032 @end group
5033 @end example
5035 If you don't want to maintain this piece of code in your package manually,
5036 you can instead use the Gnulib module @code{alloca-opt} or @code{alloca}.
5037 @xref{Gnulib}.
5038 @end defmac
5040 @defmac AC_FUNC_CHOWN
5041 @acindex{FUNC_CHOWN}
5042 @cvindex HAVE_CHOWN
5043 @c @fuindex chown
5044 @prindex @code{chown}
5045 @caindex func_chown_works
5046 If the @code{chown} function is available and works (in particular, it
5047 should accept @option{-1} for @code{uid} and @code{gid}), define
5048 @code{HAVE_CHOWN}.  The result of this macro is cached in the
5049 @code{ac_cv_func_chown_works} variable.
5051 If you want a workaround, that is, a @code{chown} function that is
5052 available and works, you can use the Gnulib module @code{chown}.
5053 @xref{Gnulib}.
5054 @end defmac
5056 @anchor{AC_FUNC_CLOSEDIR_VOID}
5057 @defmac AC_FUNC_CLOSEDIR_VOID
5058 @acindex{FUNC_CLOSEDIR_VOID}
5059 @cvindex CLOSEDIR_VOID
5060 @c @fuindex closedir
5061 @prindex @code{closedir}
5062 @caindex func_closedir_void
5063 If the @code{closedir} function does not return a meaningful value,
5064 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
5065 return value for an error indicator.
5067 Currently this test is implemented by running a test program.  When
5068 cross compiling the pessimistic assumption that @code{closedir} does not
5069 return a meaningful value is made.
5071 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
5072 variable.
5074 This macro is obsolescent, as @code{closedir} returns a meaningful value
5075 on current systems.  New programs need not use this macro.
5076 @end defmac
5078 @defmac AC_FUNC_ERROR_AT_LINE
5079 @acindex{FUNC_ERROR_AT_LINE}
5080 @c @fuindex error_at_line
5081 @prindex @code{error_at_line}
5082 @caindex lib_error_at_line
5083 If the @code{error_at_line} function is not found, require an
5084 @code{AC_LIBOBJ} replacement of @samp{error}.
5086 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
5087 variable.
5089 The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent.  New programs
5090 should use Gnulib's @code{error} module.  @xref{Gnulib}.
5091 @end defmac
5093 @defmac AC_FUNC_FNMATCH
5094 @acindex{FUNC_FNMATCH}
5095 @c @fuindex fnmatch
5096 @prindex @code{fnmatch}
5097 @caindex func_fnmatch_works
5098 If the @code{fnmatch} function conforms to Posix, define
5099 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
5100 the bugs in Solaris 2.4.
5102 Unlike the other specific
5103 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
5104 broken/missing @code{fnmatch}.  This is for historical reasons.
5105 See @code{AC_REPLACE_FNMATCH} below.
5107 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
5108 variable.
5110 This macro is obsolescent.  New programs should use Gnulib's
5111 @code{fnmatch-posix} module.  @xref{Gnulib}.
5112 @end defmac
5114 @defmac AC_FUNC_FNMATCH_GNU
5115 @acindex{FUNC_FNMATCH_GNU}
5116 @c @fuindex fnmatch
5117 @prindex @code{fnmatch}
5118 @caindex func_fnmatch_gnu
5119 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
5120 whether @code{fnmatch} supports GNU extensions.  Detect common
5121 implementation bugs, for example, the bugs in the GNU C
5122 Library 2.1.
5124 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
5125 variable.
5127 This macro is obsolescent.  New programs should use Gnulib's
5128 @code{fnmatch-gnu} module.  @xref{Gnulib}.
5129 @end defmac
5131 @anchor{AC_FUNC_FORK}
5132 @defmac AC_FUNC_FORK
5133 @acindex{FUNC_FORK}
5134 @cvindex HAVE_VFORK_H
5135 @cvindex HAVE_WORKING_FORK
5136 @cvindex HAVE_WORKING_VFORK
5137 @cvindex vfork
5138 @c @fuindex fork
5139 @prindex @code{fork}
5140 @c @fuindex vfork
5141 @prindex @code{vfork}
5142 @hdrindex{vfork.h}
5143 @c @caindex func_fork
5144 @c @caindex func_fork_works
5145 This macro checks for the @code{fork} and @code{vfork} functions.  If a
5146 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
5147 checks whether @code{fork} is just a stub by trying to run it.
5149 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
5150 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
5151 define @code{vfork} to be @code{fork} for backward compatibility with
5152 previous versions of @command{autoconf}.  This macro checks for several known
5153 errors in implementations of @code{vfork} and considers the system to not
5154 have a working @code{vfork} if it detects any of them.
5156 Since this macro defines @code{vfork} only for backward compatibility with
5157 previous versions of @command{autoconf} you're encouraged to define it
5158 yourself in new code:
5159 @example
5160 @group
5161 #ifndef HAVE_WORKING_VFORK
5162 # define vfork fork
5163 #endif
5164 @end group
5165 @end example
5167 The results of this macro are cached in the @code{ac_cv_func_fork_works}
5168 and @code{ac_cv_func_vfork_works} variables.  In order to override the
5169 test, you also need to set the @code{ac_cv_func_fork} and
5170 @code{ac_cv_func_vfork} variables.
5171 @end defmac
5173 @defmac AC_FUNC_FSEEKO
5174 @acindex{FUNC_FSEEKO}
5175 @cvindex _LARGEFILE_SOURCE
5176 @cvindex HAVE_FSEEKO
5177 @c @fuindex fseeko
5178 @prindex @code{fseeko}
5179 @c @fuindex ftello
5180 @prindex @code{ftello}
5181 @c @caindex sys_largefile_source
5182 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
5183 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
5184 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
5185 may occur when compiling with @code{AC_SYS_LARGEFILE} on
5186 largefile-sensitive systems where @code{off_t} does not default to a
5187 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
5189 The Gnulib module @code{fseeko} invokes @code{AC_FUNC_FSEEKO}
5190 and also contains workarounds for other portability problems of
5191 @code{fseeko}.  @xref{Gnulib}.
5192 @end defmac
5194 @defmac AC_FUNC_GETGROUPS
5195 @acindex{FUNC_GETGROUPS}
5196 @cvindex HAVE_GETGROUPS
5197 @ovindex GETGROUPS_LIBS
5198 @c @fuindex getgroups
5199 @prindex @code{getgroups}
5200 @caindex func_getgroups_works
5201 If the @code{getgroups} function is available and works (unlike on
5202 Ultrix 4.3 and NeXTstep 3.2, where @samp{getgroups (0, 0)} always fails),
5203 define @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
5204 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
5206 This macro is obsolescent. New programs need not use this macro.  But
5207 they may want to use the Gnulib module @code{getgroups}, which provides
5208 workarounds to other portability problems of this function.
5209 @end defmac
5211 @anchor{AC_FUNC_GETLOADAVG}
5212 @defmac AC_FUNC_GETLOADAVG
5213 @acindex{FUNC_GETLOADAVG}
5214 @cvindex SVR4
5215 @cvindex DGUX
5216 @cvindex UMAX
5217 @cvindex UMAX4_3
5218 @cvindex HAVE_NLIST_H
5219 @cvindex NLIST_NAME_UNION
5220 @cvindex GETLOADAVG_PRIVILEGED
5221 @cvindex NEED_SETGID
5222 @cvindex C_GETLOADAVG
5223 @ovindex LIBOBJS
5224 @ovindex NEED_SETGID
5225 @ovindex KMEM_GROUP
5226 @ovindex GETLOADAVG_LIBS
5227 @c @fuindex getloadavg
5228 @prindex @code{getloadavg}
5229 Check how to get the system load averages.  To perform its tests
5230 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5231 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5232 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5234 If the system has the @code{getloadavg} function, define
5235 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5236 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
5237 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
5238 @samp{getloadavg} and possibly define several other C preprocessor
5239 macros and output variables:
5241 @enumerate
5242 @item
5243 Define @code{C_GETLOADAVG}.
5245 @item
5246 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5247 those systems.
5249 @item
5250 @hdrindex{nlist.h}
5251 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5253 @item
5254 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5255 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
5256 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5258 @item
5259 Programs may need to be installed set-group-ID (or set-user-ID) for
5260 @code{getloadavg} to work.  In this case, define
5261 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5262 to @samp{true} (and otherwise to @samp{false}), and set
5263 @code{KMEM_GROUP} to the name of the group that should own the installed
5264 program.
5265 @end enumerate
5267 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5268 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5269 @end defmac
5271 @anchor{AC_FUNC_GETMNTENT}
5272 @defmac AC_FUNC_GETMNTENT
5273 @acindex{FUNC_GETMNTENT}
5274 @cvindex HAVE_GETMNTENT
5275 @c @fuindex getmntent
5276 @prindex @code{getmntent}
5277 @caindex search_getmntent
5278 Check for @code{getmntent} in the standard C library, and then in the
5279 @file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5280 IRIX 4, PTX, and UnixWare, respectively.  Then, if
5281 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5282 @code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5283 @code{ac_cv_func_getmntent} to @code{no}.
5285 The result of this macro can be overridden by setting the cache variable
5286 @code{ac_cv_search_getmntent}.
5288 The @code{AC_FUNC_GETMNTENT} macro is obsolescent.  New programs should
5289 use Gnulib's @code{mountlist} module.  @xref{Gnulib}.
5290 @end defmac
5292 @defmac AC_FUNC_GETPGRP
5293 @acindex{FUNC_GETPGRP}
5294 @cvindex GETPGRP_VOID
5295 @c @fuindex getpgid
5296 @c @fuindex getpgrp
5297 @prindex @code{getpgid}
5298 @prindex @code{getpgrp}
5299 @caindex func_getpgrp_void
5300 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5301 @code{getpgrp}; this is the Posix behavior.  On older BSD
5302 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5303 behaves like Posix's @code{getpgid}.
5305 @example
5306 #ifdef GETPGRP_VOID
5307   pid = getpgrp ();
5308 #else
5309   pid = getpgrp (0);
5310 #endif
5311 @end example
5313 This macro does not check whether
5314 @code{getpgrp} exists at all; if you need to work in that situation,
5315 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5317 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5318 variable.
5320 This macro is obsolescent, as current systems have a @code{getpgrp}
5321 whose signature conforms to Posix.  New programs need not use this macro.
5322 @end defmac
5324 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5325 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5326 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5327 @c @fuindex lstat
5328 @prindex @code{lstat}
5329 @caindex func_lstat_dereferences_slashed_symlink
5330 If @file{link} is a symbolic link, then @code{lstat} should treat
5331 @file{link/} the same as @file{link/.}.  However, many older
5332 @code{lstat} implementations incorrectly ignore trailing slashes.
5334 It is safe to assume that if @code{lstat} incorrectly ignores
5335 trailing slashes, then other symbolic-link-aware functions like
5336 @code{unlink} also incorrectly ignore trailing slashes.
5338 If @code{lstat} behaves properly, define
5339 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5340 @code{AC_LIBOBJ} replacement of @code{lstat}.
5342 The result of this macro is cached in the
5343 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5345 The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5346 New programs should use Gnulib's @code{lstat} module.  @xref{Gnulib}.
5347 @end defmac
5349 @defmac AC_FUNC_MALLOC
5350 @acindex{FUNC_MALLOC}
5351 @cvindex HAVE_MALLOC
5352 @cvindex malloc
5353 @c @fuindex malloc
5354 @prindex @code{malloc}
5355 @caindex func_malloc_0_nonnull
5356 If the @code{malloc} function is compatible with the GNU C
5357 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5358 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5359 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5360 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5361 native @code{malloc} is not used in the main project.
5363 Typically, the replacement file @file{malloc.c} should look like (note
5364 the @samp{#undef malloc}):
5366 @verbatim
5367 #include <config.h>
5368 #undef malloc
5370 #include <sys/types.h>
5372 void *malloc ();
5374 /* Allocate an N-byte block of memory from the heap.
5375    If N is zero, allocate a 1-byte block.  */
5377 void *
5378 rpl_malloc (size_t n)
5380   if (n == 0)
5381     n = 1;
5382   return malloc (n);
5384 @end verbatim
5386 The result of this macro is cached in the
5387 @code{ac_cv_func_malloc_0_nonnull} variable.
5389 If you don't want to maintain a @code{malloc.c} file in your package
5390 manually, you can instead use the Gnulib module @code{malloc-gnu}.
5391 @end defmac
5393 @defmac AC_FUNC_MBRTOWC
5394 @acindex{FUNC_MBRTOWC}
5395 @cvindex HAVE_MBRTOWC
5396 @c @fuindex mbrtowc
5397 @prindex @code{mbrtowc}
5398 @caindex func_mbrtowc
5399 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5400 type @code{mbstate_t} are properly declared.
5402 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5403 variable.
5405 The Gnulib module @code{mbrtowc} not only ensures that the
5406 function is declared, but also works around other portability
5407 problems of this function.
5408 @end defmac
5410 @defmac AC_FUNC_MEMCMP
5411 @acindex{FUNC_MEMCMP}
5412 @ovindex LIBOBJS
5413 @c @fuindex memcmp
5414 @prindex @code{memcmp}
5415 @caindex func_memcmp_working
5416 If the @code{memcmp} function is not available, or does not work on
5417 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5418 bytes or more and with at least one buffer not starting on a 4-byte
5419 boundary (such as the one on NeXT x86 OpenStep), require an
5420 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5422 The result of this macro is cached in the
5423 @code{ac_cv_func_memcmp_working} variable.
5425 This macro is obsolescent, as current systems have a working
5426 @code{memcmp}.  New programs need not use this macro.
5427 @end defmac
5429 @defmac AC_FUNC_MKTIME
5430 @acindex{FUNC_MKTIME}
5431 @ovindex LIBOBJS
5432 @c @fuindex mktime
5433 @prindex @code{mktime}
5434 @caindex func_working_mktime
5435 If the @code{mktime} function is not available, or does not work
5436 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5437 For the purposes of this test, @code{mktime} should conform to the
5438 Posix standard and should be the inverse of
5439 @code{localtime}.
5441 The result of this macro is cached in the
5442 @code{ac_cv_func_working_mktime} variable.
5444 The @code{AC_FUNC_MKTIME} macro is obsolescent.  New programs should
5445 use Gnulib's @code{mktime} module.  @xref{Gnulib}.
5446 @end defmac
5448 @anchor{AC_FUNC_MMAP}
5449 @defmac AC_FUNC_MMAP
5450 @acindex{FUNC_MMAP}
5451 @cvindex HAVE_MMAP
5452 @c @fuindex mmap
5453 @prindex @code{mmap}
5454 @caindex func_mmap_fixed_mapped
5455 If the @code{mmap} function exists and works correctly, define
5456 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5457 memory.
5459 The result of this macro is cached in the
5460 @code{ac_cv_func_mmap_fixed_mapped} variable.
5462 Note: This macro asks for more than what an average program needs from
5463 @code{mmap}.  In particular, the use of @code{MAP_FIXED} fails on
5464 HP-UX 11, whereas @code{mmap} otherwise works fine on this platform.
5465 @end defmac
5467 @defmac AC_FUNC_OBSTACK
5468 @acindex{FUNC_OBSTACK}
5469 @cvindex HAVE_OBSTACK
5470 @cindex obstack
5471 @caindex func_obstack
5472 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5473 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5475 The result of this macro is cached in the @code{ac_cv_func_obstack}
5476 variable.
5478 The @code{AC_FUNC_OBSTACK} macro is obsolescent.  New programs should use
5479 Gnulib's @code{obstack} module.  @xref{Gnulib}.
5480 @end defmac
5482 @defmac AC_FUNC_REALLOC
5483 @acindex{FUNC_REALLOC}
5484 @cvindex HAVE_REALLOC
5485 @cvindex realloc
5486 @c @fuindex realloc
5487 @prindex @code{realloc}
5488 @caindex func_realloc_0_nonnull
5489 If the @code{realloc} function is compatible with the GNU C
5490 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5491 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5492 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5493 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5494 the native @code{realloc} is not used in the main project.  See
5495 @code{AC_FUNC_MALLOC} for details.
5497 The result of this macro is cached in the
5498 @code{ac_cv_func_realloc_0_nonnull} variable.
5500 If you don't want to maintain a @code{realloc.c} file in your package
5501 manually, you can instead use the Gnulib module @code{realloc-gnu}.
5502 @end defmac
5504 @defmac AC_FUNC_SELECT_ARGTYPES
5505 @acindex{FUNC_SELECT_ARGTYPES}
5506 @cvindex SELECT_TYPE_ARG1
5507 @cvindex SELECT_TYPE_ARG234
5508 @cvindex SELECT_TYPE_ARG5
5509 @c @fuindex select
5510 @prindex @code{select}
5511 @c @caindex func_select_args
5512 Determines the correct type to be passed for each of the
5513 @code{select} function's arguments, and defines those types
5514 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5515 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5516 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5517 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5519 This macro is obsolescent, as current systems have a @code{select} whose
5520 signature conforms to Posix.  New programs need not use this macro.
5521 @end defmac
5523 @defmac AC_FUNC_SETPGRP
5524 @acindex{FUNC_SETPGRP}
5525 @cvindex SETPGRP_VOID
5526 @c @fuindex setpgrp
5527 @prindex @code{setpgrp}
5528 @caindex func_setpgrp_void
5529 If @code{setpgrp} takes no argument (the Posix version), define
5530 @code{SETPGRP_VOID}.  Otherwise, it is the BSD version, which takes
5531 two process IDs as arguments.  This macro does not check whether
5532 @code{setpgrp} exists at all; if you need to work in that situation,
5533 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5535 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5536 variable.
5538 This macro is obsolescent, as current systems have a @code{setpgrp}
5539 whose signature conforms to Posix.  New programs need not use this macro.
5540 @end defmac
5542 @defmac AC_FUNC_STAT
5543 @defmacx AC_FUNC_LSTAT
5544 @acindex{FUNC_STAT}
5545 @acindex{FUNC_LSTAT}
5546 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5547 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5548 @c @fuindex stat
5549 @prindex @code{stat}
5550 @c @fuindex lstat
5551 @prindex @code{lstat}
5552 @caindex func_stat_empty_string_bug
5553 @caindex func_lstat_empty_string_bug
5554 Determine whether @code{stat} or @code{lstat} have the bug that it
5555 succeeds when given the zero-length file name as argument.  The @code{stat}
5556 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5557 this.
5559 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5560 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5561 replacement of it.
5563 The results of these macros are cached in the
5564 @code{ac_cv_func_stat_empty_string_bug} and the
5565 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5567 These macros are obsolescent, as no current systems have the bug.
5568 New programs need not use these macros.
5569 @end defmac
5571 @anchor{AC_FUNC_STRCOLL}
5572 @defmac AC_FUNC_STRCOLL
5573 @acindex{FUNC_STRCOLL}
5574 @cvindex HAVE_STRCOLL
5575 @c @fuindex strcoll
5576 @prindex @code{strcoll}
5577 @caindex func_strcoll_works
5578 If the @code{strcoll} function exists and works correctly, define
5579 @code{HAVE_STRCOLL}.  This does a bit more than
5580 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5581 definitions of @code{strcoll} that should not be used.  But it does
5582 not check against a known bug of this function on Solaris 10.
5584 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5585 variable.
5586 @end defmac
5588 @defmac AC_FUNC_STRERROR_R
5589 @acindex{FUNC_STRERROR_R}
5590 @cvindex HAVE_STRERROR_R
5591 @cvindex HAVE_DECL_STRERROR_R
5592 @cvindex STRERROR_R_CHAR_P
5593 @c @fuindex strerror_r
5594 @caindex func_strerror_r_char_p
5595 @prindex @code{strerror_r}
5596 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5597 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5598 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5599 returns an @code{int} error number.  The Thread-Safe Functions option of
5600 Posix requires @code{strerror_r} to return @code{int}, but
5601 many systems (including, for example, version 2.2.4 of the GNU C
5602 Library) return a @code{char *} value that is not necessarily equal to
5603 the buffer argument.
5605 The result of this macro is cached in the
5606 @code{ac_cv_func_strerror_r_char_p} variable.
5608 The Gnulib module @code{strerror_r} not only ensures that the function
5609 has the return type specified by Posix, but also works around other
5610 portability problems of this function.
5611 @end defmac
5613 @anchor{AC_FUNC_STRFTIME}
5614 @defmac AC_FUNC_STRFTIME
5615 @acindex{FUNC_STRFTIME}
5616 @cvindex HAVE_STRFTIME
5617 @c @fuindex strftime
5618 @prindex @code{strftime}
5619 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5620 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5622 This macro is obsolescent, as no current systems require the @file{intl}
5623 library for @code{strftime}.  New programs need not use this macro.
5624 @end defmac
5626 @defmac AC_FUNC_STRTOD
5627 @acindex{FUNC_STRTOD}
5628 @ovindex POW_LIB
5629 @c @fuindex strtod
5630 @prindex @code{strtod}
5631 @caindex func_strtod
5632 @caindex func_pow
5633 If the @code{strtod} function does not exist or doesn't work correctly,
5634 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5635 because @file{strtod.c} is likely to need @samp{pow}, set the output
5636 variable @code{POW_LIB} to the extra library needed.
5638 This macro caches its result in the @code{ac_cv_func_strtod} variable
5639 and depends upon the result in the @code{ac_cv_func_pow} variable.
5641 The @code{AC_FUNC_STRTOD} macro is obsolescent.  New programs should
5642 use Gnulib's @code{strtod} module.  @xref{Gnulib}.
5643 @end defmac
5645 @defmac AC_FUNC_STRTOLD
5646 @acindex{FUNC_STRTOLD}
5647 @cvindex HAVE_STRTOLD
5648 @prindex @code{strtold}
5649 @caindex func_strtold
5650 If the @code{strtold} function exists and conforms to C99 or later, define
5651 @code{HAVE_STRTOLD}.
5653 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5655 The Gnulib module @code{strtold} not only ensures that the
5656 function exists, but also works around other portability
5657 problems of this function.
5658 @end defmac
5660 @defmac AC_FUNC_STRNLEN
5661 @acindex{FUNC_STRNLEN}
5662 @cvindex HAVE_STRNLEN
5663 @c @fuindex strnlen
5664 @prindex @code{strnlen}
5665 @caindex func_strnlen_working
5666 If the @code{strnlen} function is not available, or is buggy (like the one
5667 from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5669 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5670 variable.
5672 The @code{AC_FUNC_STRNLEN} macro is obsolescent.  New programs should
5673 use Gnulib's @code{strnlen} module.  @xref{Gnulib}.
5674 @end defmac
5676 @anchor{AC_FUNC_UTIME_NULL}
5677 @defmac AC_FUNC_UTIME_NULL
5678 @acindex{FUNC_UTIME_NULL}
5679 @cvindex HAVE_UTIME_NULL
5680 @c @fuindex utime
5681 @prindex @code{utime}
5682 @caindex func_utime_null
5683 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5684 the present, define @code{HAVE_UTIME_NULL}.
5686 This macro caches its result in the @code{ac_cv_func_utime_null}
5687 variable.
5689 This macro is obsolescent, as all current systems have a @code{utime}
5690 that behaves this way.  New programs need not use this macro.
5691 @end defmac
5693 @anchor{AC_FUNC_VPRINTF}
5694 @defmac AC_FUNC_VPRINTF
5695 @acindex{FUNC_VPRINTF}
5696 @cvindex HAVE_VPRINTF
5697 @cvindex HAVE_DOPRNT
5698 @c @fuindex vprintf
5699 @prindex @code{vprintf}
5700 @c @fuindex vsprintf
5701 @prindex @code{vsprintf}
5702 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5703 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5704 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5705 are also available.)
5707 This macro is obsolescent, as all current systems have @code{vprintf}.
5708 New programs need not use this macro.
5709 @end defmac
5711 @defmac AC_REPLACE_FNMATCH
5712 @acindex{REPLACE_FNMATCH}
5713 @c @fuindex fnmatch
5714 @prindex @code{fnmatch}
5715 @hdrindex{fnmatch.h}
5716 @caindex func_fnmatch_works
5717 If the @code{fnmatch} function does not conform to Posix (see
5718 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5720 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5721 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5722 copy of the source code of GNU @code{fnmatch}.  If necessary,
5723 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5724 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5725 included in place of the system @code{<fnmatch.h>}.
5727 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5728 variable.
5730 This macro is obsolescent, as it assumes the use of particular source
5731 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5732 which provides this macro along with the source files.  @xref{Gnulib}.
5733 @end defmac
5737 @node Generic Functions
5738 @subsection Generic Function Checks
5740 These macros are used to find functions not covered by the ``particular''
5741 test macros.  If the functions might be in libraries other than the
5742 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5743 If you need to check the behavior of a function as well as find out
5744 whether it is present, you have to write your own test for
5745 it (@pxref{Writing Tests}).
5747 @anchor{AC_CHECK_FUNC}
5748 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5749   @ovar{action-if-not-found})
5750 @acindex{CHECK_FUNC}
5751 @caindex func_@var{function}
5752 If C function @var{function} is available, run shell commands
5753 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5754 want to define a symbol if the function is available, consider using
5755 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5756 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5757 standardized than C++.  (@pxref{Language Choice}, for more information
5758 about selecting the language for checks.)
5760 This macro caches its result in the @code{ac_cv_func_@var{function}}
5761 variable.
5762 @end defmac
5764 @anchor{AC_CHECK_FUNCS}
5765 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5766   @ovar{action-if-not-found})
5767 @acindex{CHECK_FUNCS}
5768 @cvindex HAVE_@var{function}
5769 For each @var{function} enumerated in the blank-or-newline-separated argument
5770 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5771 If @var{action-if-found} is given, it is additional shell code to
5772 execute when one of the functions is found.  You can give it a value of
5773 @samp{break} to break out of the loop on the first match.  If
5774 @var{action-if-not-found} is given, it is executed when one of the
5775 functions is not found.
5777 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5778 @end defmac
5780 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5781 @acindex{CHECK_FUNCS_ONCE}
5782 @cvindex HAVE_@var{function}
5783 For each @var{function} enumerated in the blank-or-newline-separated argument
5784 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5785 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5786 checking code at most once, so that @command{configure} is smaller and
5787 faster; but the checks cannot be conditionalized and are always done once,
5788 early during the @command{configure} run.
5789 @end defmac
5791 @sp 1
5793 Autoconf follows a philosophy that was formed over the years by those
5794 who have struggled for portability: isolate the portability issues in
5795 specific files, and then program as if you were in a Posix
5796 environment.  Some functions may be missing or unfixable, and your
5797 package must be ready to replace them.
5799 Suitable replacements for many such problem functions are available from
5800 Gnulib (@pxref{Gnulib}).
5802 @defmac AC_LIBOBJ (@var{function})
5803 @acindex{LIBOBJ}
5804 @ovindex LIBOBJS
5805 Specify that @samp{@var{function}.c} must be included in the executables
5806 to replace a missing or broken implementation of @var{function}.
5808 @vrindex ac_objext
5809 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5810 variable @code{LIBOBJS} if it is not already in, and calls
5811 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5812 directly change @code{LIBOBJS}, since this is not traceable.
5813 @end defmac
5815 @defmac AC_LIBSOURCE (@var{file})
5816 @acindex{LIBSOURCE}
5817 Specify that @var{file} might be needed to compile the project.  If you
5818 need to know what files might be needed by a @file{configure.ac}, you
5819 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5821 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5822 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5823 that case, since shell variables cannot be traced statically, you must
5824 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5825 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5826 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5827 @code{"foo"} or @code{"bar"}, you should do:
5829 @example
5830 AC_LIBSOURCE([foo.c])
5831 AC_LIBSOURCE([bar.c])
5832 AC_LIBOBJ([$foo_or_bar])
5833 @end example
5835 @noindent
5836 There is usually a way to avoid this, however, and you are encouraged to
5837 simply call @code{AC_LIBOBJ} with literal arguments.
5839 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5840 slightly different semantics: the old macro took the function name,
5841 e.g., @code{foo}, as its argument rather than the file name.
5842 @end defmac
5844 @defmac AC_LIBSOURCES (@var{files})
5845 @acindex{LIBSOURCES}
5846 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5847 comma-separated M4 list.  Thus, the above example might be rewritten:
5849 @example
5850 AC_LIBSOURCES([foo.c, bar.c])
5851 AC_LIBOBJ([$foo_or_bar])
5852 @end example
5853 @end defmac
5855 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5856 @acindex{CONFIG_LIBOBJ_DIR}
5857 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5858 @var{directory}, a name relative to the top level of the
5859 source tree.  The replacement directory defaults to @file{.}, the top
5860 level directory, and the most typical value is @file{lib}, corresponding
5861 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5863 @command{configure} might need to know the replacement directory for the
5864 following reasons: (i) some checks use the replacement files, (ii) some
5865 macros bypass broken system headers by installing links to the
5866 replacement headers (iii) when used in conjunction with Automake,
5867 within each makefile, @var{directory} is used as a relative path
5868 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5869 @code{LTLIBOBJS}, etc.
5870 @end defmac
5872 @sp 1
5874 It is common to merely check for the existence of a function, and ask
5875 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5876 a convenient shorthand.
5878 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5879 @acindex{REPLACE_FUNCS}
5880 @cvindex HAVE_@var{function}
5881 @ovindex LIBOBJS
5882 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5883 @var{action-if-not-found}.  You can declare your replacement function by
5884 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5885 system has the function, it probably declares it in a header file you
5886 should be including, so you shouldn't redeclare it lest your declaration
5887 conflict.
5888 @end defmac
5890 @node Header Files
5891 @section Header Files
5892 @cindex Header, checking
5894 The following macros check for the presence of certain C header files.
5895 If there is no macro specifically defined to check for a header file you need,
5896 and you don't need to check for any special properties of
5897 it, then you can use one of the general header-file check macros.
5899 @menu
5900 * Header Portability::          Collected knowledge on common headers
5901 * Particular Headers::          Special handling to find certain headers
5902 * Generic Headers::             How to find other headers
5903 @end menu
5905 @node Header Portability
5906 @subsection Portability of Headers
5907 @cindex Portability of headers
5908 @cindex Header portability
5910 This section documents some collected knowledge about common headers,
5911 and the problems they cause.  By definition, this list always requires
5912 additions.  A much more complete list is maintained by the Gnulib
5913 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5914 Posix Headers, gnulib, Gnulib} and @ref{Glibc Header File
5915 Substitutes, , Glibc Headers, gnulib, Gnulib}.  Please help us keep
5916 the Gnulib list as complete as possible.
5918 When we say that a header ``may require'' some set of other headers, we
5919 mean that it may be necessary for you to manually include those other
5920 headers first, or the contents of the header under test will fail to
5921 compile.  When checking for these headers, you must provide the
5922 potentially-required headers in the @var{includes} argument to
5923 @code{AC_CHECK_HEADER} or @code{AC_CHECK_HEADERS}, or the check will
5924 fail spuriously.  @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes})
5925 arranges to include a number of common requirements and should normally
5926 come first in your @var{includes}.  For example, @file{net/if.h} may
5927 require @file{sys/types.h}, @file{sys/socket.h}, or both, and
5928 @code{AC_INCLUDES_DEFAULT} handles @file{sys/types.h} but not
5929 @file{sys/socket.h}, so you should check for it like this:
5931 @example
5932 AC_CHECK_HEADERS([sys/socket.h])
5933 AC_CHECK_HEADERS([net/if.h], [], [],
5934 [AC_INCLUDES_DEFAULT[
5935 #ifdef HAVE_SYS_SOCKET_H
5936 # include <sys/socket.h>
5937 #endif
5939 @end example
5941 Note that the example mixes single quoting (for@code{AC_INCLUDES_DEFAULT},
5942 so that it gets expanded) and double quoting (to ensure that each
5943 preprocessor @code{#} gets treated as a literal string rather than a
5944 comment).
5946 @table @asis
5948 @item @file{limits.h}
5949 In C99 and later, @file{limits.h} defines @code{LLONG_MIN},
5950 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5951 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5952 define them.
5954 @item @file{memory.h}
5955 @hdrindex{memory.h}
5956 This header file is obsolete; use @file{string.h} instead.
5958 @item @file{strings.h}
5959 @hdrindex{strings.h}
5960 On some systems, this is the only header that declares
5961 @code{strcasecmp}, @code{strncasecmp}, and @code{ffs}.
5963 This header may or may not include @file{string.h} for you.  However, on
5964 all recent systems it is safe to include both @file{string.h} and
5965 @file{strings.h}, in either order, in the same source file.
5967 @item @file{inttypes.h} vs.@: @file{stdint.h}
5968 @hdrindex{inttypes.h}
5969 @hdrindex{stdint.h}
5970 C99 specifies that @file{inttypes.h} includes @file{stdint.h}, so there's
5971 no need to include @file{stdint.h} separately in a standard environment.
5972 However, some implementations have @file{inttypes.h} but not @file{stdint.h}
5973 (e.g., Solaris 7), and some have @file{stdint.h} but not @file{inttypes.h}
5974 (e.g. MSVC 2012).  Therefore, it is necessary to check for each and include
5975 each only if available.
5977 @item @file{linux/irda.h}
5978 @hdrindex{linux/irda.h}
5979 This header may require @file{linux/types.h} and/or @file{sys/socket.h}.
5981 @item @file{linux/random.h}
5982 @hdrindex{linux/random.h}
5983 This header may require @file{linux/types.h}.
5985 @item @file{net/if.h}
5986 @hdrindex{net/if.h}
5987 This header may require @file{sys/types.h} and/or @file{sys/socket.h}.
5989 @item @file{netinet/if_ether.h}
5990 @hdrindex{netinet/if_ether.h}
5991 This header may require some combination of @file{sys/types.h},
5992 @file{sys/socket.h}, @file{netinet/in.h}, and @file{net/if.h}.
5994 @item @file{sys/mount.h}
5995 @hdrindex{sys/mount.h}
5996 This header may require @file{sys/params.h}.
5998 @item @file{sys/ptem.h}
5999 @hdrindex{sys/ptem.h}
6000 This header may require @file{sys/stream.h}.
6002 @item @file{sys/socket.h}
6003 @hdrindex{sys/socket.h}
6004 This header may require @file{sys/types.h}.
6006 @item @file{sys/ucred.h}
6007 @hdrindex{sys/ucred.h}
6008 This header may require @file{sys/types.h}.
6010 @item @file{X11/extensions/scrnsaver.h}
6011 @hdrindex{X11/extensions/scrnsaver.h}
6012 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
6013 so required that you might not even consider looking for it.
6015 @end table
6018 @node Particular Headers
6019 @subsection Particular Header Checks
6021 These macros check for particular system header files---whether they
6022 exist, and in some cases whether they declare certain symbols.
6024 @defmac AC_CHECK_HEADER_STDBOOL
6025 @acindex{CHECK_HEADER_STDBOOL}
6026 @cvindex HAVE__BOOL
6027 @hdrindex{stdbool.h}
6028 @caindex header_stdbool_h
6029 Check whether @file{stdbool.h} exists and conforms to C99 or later,
6030 and cache the result in the @code{ac_cv_header_stdbool_h} variable.
6031 If the type @code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
6033 This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
6034 packages that supply a substitute @file{stdbool.h} on platforms lacking
6035 a conforming one.  The @code{AC_HEADER_STDBOOL} macro is better for code
6036 that explicitly checks for @file{stdbool.h}.
6037 @end defmac
6039 @defmac AC_HEADER_ASSERT
6040 @acindex{HEADER_ASSERT}
6041 @cvindex NDEBUG
6042 @hdrindex{assert.h}
6043 Check whether to enable assertions in the style of @file{assert.h}.
6044 Assertions are enabled by default, but the user can override this by
6045 invoking @command{configure} with the @option{--disable-assert} option.
6046 @end defmac
6048 @anchor{AC_HEADER_DIRENT}
6049 @defmac AC_HEADER_DIRENT
6050 @acindex{HEADER_DIRENT}
6051 @cvindex HAVE_DIRENT_H
6052 @cvindex HAVE_NDIR_H
6053 @cvindex HAVE_SYS_DIR_H
6054 @cvindex HAVE_SYS_NDIR_H
6055 @hdrindex{dirent.h}
6056 @hdrindex{sys/ndir.h}
6057 @hdrindex{sys/dir.h}
6058 @hdrindex{ndir.h}
6059 Check for the following header files.  For the first one that is
6060 found and defines @samp{DIR}, define the listed C preprocessor macro:
6062 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
6063 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
6064 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
6065 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
6066 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
6067 @end multitable
6069 The directory-library declarations in your source code should look
6070 something like the following:
6072 @example
6073 @group
6074 #include <sys/types.h>
6075 #ifdef HAVE_DIRENT_H
6076 # include <dirent.h>
6077 # define NAMLEN(dirent) strlen ((dirent)->d_name)
6078 #else
6079 # define dirent direct
6080 # define NAMLEN(dirent) ((dirent)->d_namlen)
6081 # ifdef HAVE_SYS_NDIR_H
6082 #  include <sys/ndir.h>
6083 # endif
6084 # ifdef HAVE_SYS_DIR_H
6085 #  include <sys/dir.h>
6086 # endif
6087 # ifdef HAVE_NDIR_H
6088 #  include <ndir.h>
6089 # endif
6090 #endif
6091 @end group
6092 @end example
6094 Using the above declarations, the program would declare variables to be
6095 of type @code{struct dirent}, not @code{struct direct}, and would access
6096 the length of a directory entry name by passing a pointer to a
6097 @code{struct dirent} to the @code{NAMLEN} macro.
6099 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
6101 This macro is obsolescent, as all current systems with directory
6102 libraries have @code{<dirent.h>}.  New programs need not use this macro.
6104 Also see @code{AC_STRUCT_DIRENT_D_INO} and
6105 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
6106 @end defmac
6108 @anchor{AC_HEADER_MAJOR}
6109 @defmac AC_HEADER_MAJOR
6110 @acindex{HEADER_MAJOR}
6111 @cvindex MAJOR_IN_MKDEV
6112 @cvindex MAJOR_IN_SYSMACROS
6113 @hdrindex{sys/mkdev.h}
6114 @hdrindex{sys/sysmacros.h}
6115 Detect the headers required to use @code{makedev}, @code{major}, and
6116 @code{minor}.  These functions may be defined by @file{sys/mkdev.h},
6117 @code{sys/sysmacros.h}, or @file{sys/types.h}.
6119 @code{AC_HEADER_MAJOR} defines @code{MAJOR_IN_MKDEV} if they are in
6120 @file{sys/mkdev.h}, or @code{MAJOR_IN_SYSMACROS} if they are in
6121 @file{sys/sysmacros.h}.  If neither macro is defined, they are either in
6122 @file{sys/types.h} or unavailable.
6124 To properly use these functions, your code should contain something
6125 like:
6127 @verbatim
6128 #include <sys/types.h>
6129 #ifdef MAJOR_IN_MKDEV
6130 # include <sys/mkdev.h>
6131 #elif defined MAJOR_IN_SYSMACROS
6132 # include <sys/sysmacros.h>
6133 #endif
6134 @end verbatim
6136 Note: Configure scripts built with Autoconf 2.69 or earlier will not
6137 detect a problem if @file{sys/types.h} contains definitions of
6138 @code{major}, @code{minor}, and/or @code{makedev} that trigger compiler
6139 warnings upon use.  This is known to occur with GNU libc 2.25, where
6140 those definitions are being deprecated to reduce namespace pollution.
6141 If it is not practical to use Autoconf 2.70 to regenerate the configure
6142 script of affected software, you can work around the problem by setting
6143 @samp{ac_cv_header_sys_types_h_makedev=no}, as an argument to
6144 @command{configure} or as part of a @file{config.site} site default file
6145 (@pxref{Site Defaults}).
6146 @end defmac
6148 @defmac AC_HEADER_RESOLV
6149 @acindex{HEADER_RESOLV}
6150 @cvindex HAVE_RESOLV_H
6151 @hdrindex{resolv.h}
6152 Checks for header @file{resolv.h}, checking for prerequisites first.
6153 To properly use @file{resolv.h}, your code should contain something like
6154 the following:
6156 @verbatim
6157 #ifdef HAVE_SYS_TYPES_H
6158 #  include <sys/types.h>
6159 #endif
6160 #ifdef HAVE_NETINET_IN_H
6161 #  include <netinet/in.h>   /* inet_ functions / structs */
6162 #endif
6163 #ifdef HAVE_ARPA_NAMESER_H
6164 #  include <arpa/nameser.h> /* DNS HEADER struct */
6165 #endif
6166 #ifdef HAVE_NETDB_H
6167 #  include <netdb.h>
6168 #endif
6169 #include <resolv.h>
6170 @end verbatim
6171 @end defmac
6173 @anchor{AC_HEADER_STAT}
6174 @defmac AC_HEADER_STAT
6175 @acindex{HEADER_STAT}
6176 @cvindex STAT_MACROS_BROKEN
6177 @hdrindex{sys/stat.h}
6178 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
6179 @file{sys/stat.h} do not work properly (returning false positives),
6180 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
6181 Amdahl UTS and Motorola System V/88.
6183 This macro is obsolescent, as no current systems have the bug.
6184 New programs need not use this macro.
6185 @end defmac
6187 @defmac AC_HEADER_STDBOOL
6188 @acindex{HEADER_STDBOOL}
6189 @cvindex HAVE_STDBOOL_H
6190 @cvindex HAVE__BOOL
6191 @hdrindex{stdbool.h}
6192 @caindex header_stdbool_h
6193 If @file{stdbool.h} exists and conforms to C99 or later, define
6194 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
6195 @code{HAVE__BOOL} to 1.  To fulfill the standard's requirements, your
6196 program could contain the following code:
6198 @example
6199 @group
6200 #ifdef HAVE_STDBOOL_H
6201 # include <stdbool.h>
6202 #else
6203 # ifndef HAVE__BOOL
6204 #  ifdef __cplusplus
6205 typedef bool _Bool;
6206 #  else
6207 #   define _Bool signed char
6208 #  endif
6209 # endif
6210 # define bool _Bool
6211 # define false 0
6212 # define true 1
6213 # define __bool_true_false_are_defined 1
6214 #endif
6215 @end group
6216 @end example
6218 Alternatively you can use the @samp{stdbool} package of Gnulib
6219 (@pxref{Gnulib}).  It simplifies your code so that it can say just
6220 @code{#include <stdbool.h>}, and it adds support for less-common
6221 platforms.
6223 This macro caches its result in the @code{ac_cv_header_stdbool_h}
6224 variable.
6226 This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
6227 defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
6228 does not.
6229 @end defmac
6231 @anchor{AC_HEADER_STDC}
6232 @defmac AC_HEADER_STDC
6233 @acindex{HEADER_STDC}
6234 @cvindex STDC_HEADERS
6235 @caindex header_stdc
6237 This macro is obsolescent.  Its sole effect is to make sure that all the
6238 headers that are included by @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6239 Includes}), but not part of ISO C90, have been checked for.
6241 All hosted environments that are still of interest for portable code
6242 provide all of the headers specified in ISO C90 (as amended in 1995).
6243 @end defmac
6245 @defmac AC_HEADER_SYS_WAIT
6246 @acindex{HEADER_SYS_WAIT}
6247 @cvindex HAVE_SYS_WAIT_H
6248 @hdrindex{sys/wait.h}
6249 @caindex header_sys_wait_h
6250 If @file{sys/wait.h} exists and is compatible with Posix, define
6251 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
6252 does not exist, or if it uses the old BSD @code{union wait} instead
6253 of @code{int} to store a status value.  If @file{sys/wait.h} is not
6254 Posix compatible, then instead of including it, define the
6255 Posix macros with their usual interpretations.  Here is an
6256 example:
6258 @example
6259 @group
6260 #include <sys/types.h>
6261 #ifdef HAVE_SYS_WAIT_H
6262 # include <sys/wait.h>
6263 #endif
6264 #ifndef WEXITSTATUS
6265 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6266 #endif
6267 #ifndef WIFEXITED
6268 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6269 #endif
6270 @end group
6271 @end example
6273 @noindent
6274 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6275 variable.
6277 This macro is obsolescent, as current systems are compatible with Posix.
6278 New programs need not use this macro.
6279 @end defmac
6281 @cvindex _POSIX_VERSION
6282 @hdrindex{unistd.h}
6283 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6284 Posix systems.  If there is no @file{unistd.h}, it is definitely
6285 not a Posix system.  However, some non-Posix systems do
6286 have @file{unistd.h}.
6288 The way to check whether the system supports Posix is:
6290 @example
6291 @group
6292 #ifdef HAVE_UNISTD_H
6293 # include <sys/types.h>
6294 # include <unistd.h>
6295 #endif
6297 #ifdef _POSIX_VERSION
6298 /* Code for Posix systems.  */
6299 #endif
6300 @end group
6301 @end example
6303 @defmac AC_HEADER_TIOCGWINSZ
6304 @acindex{HEADER_TIOCGWINSZ}
6305 @cvindex GWINSZ_IN_SYS_IOCTL
6306 @hdrindex{sys/ioctl.h}
6307 @hdrindex{termios.h}
6308 @c FIXME: I need clarifications from Jim.
6309 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6310 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6311 found in @file{<termios.h>}.
6313 Use:
6315 @example
6316 @group
6317 #ifdef HAVE_TERMIOS_H
6318 # include <termios.h>
6319 #endif
6321 #ifdef GWINSZ_IN_SYS_IOCTL
6322 # include <sys/ioctl.h>
6323 #endif
6324 @end group
6325 @end example
6326 @end defmac
6328 @node Generic Headers
6329 @subsection Generic Header Checks
6331 These macros are used to find system header files not covered by the
6332 ``particular'' test macros.  If you need to check the contents of a header
6333 as well as find out whether it is present, you have to write your own
6334 test for it (@pxref{Writing Tests}).
6336 @anchor{AC_CHECK_HEADER}
6337 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6338   @ovar{action-if-not-found}, @ovar{includes})
6339 @acindex{CHECK_HEADER}
6340 @caindex header_@var{header-file}
6341 If the system header file @var{header-file} is compilable, execute shell
6342 commands @var{action-if-found}, otherwise execute
6343 @var{action-if-not-found}.  If you just want to define a symbol if the
6344 header file is available, consider using @code{AC_CHECK_HEADERS}
6345 instead.
6347 @var{includes} should be the appropriate @dfn{prerequisite} code, i.e.@:
6348 whatever might be required to appear above
6349 @samp{#include <@var{header-file}>} for it to compile without error.
6350 This can be anything, but will normally be additional @samp{#include}
6351 directives. If @var{includes} is omitted or empty, @file{configure} will
6352 use the contents of the macro @code{AC_INCLUDES_DEFAULT}.
6353 @xref{Default Includes}.
6355 This macro used to check only for the @emph{presence} of a header, not
6356 whether its contents were acceptable to the compiler.  Some older
6357 @command{configure} scripts rely on this behavior, so it is still
6358 available by specifying @samp{-} as @var{includes}.  This mechanism is
6359 deprecated as of Autoconf 2.70; situations where a preprocessor-only
6360 check is required should use @code{AC_PREPROC_IFELSE}.
6361 @xref{Running the Preprocessor}.
6363 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6364 variable, with characters not suitable for a variable name mapped to
6365 underscores.
6366 @end defmac
6368 @anchor{AC_CHECK_HEADERS}
6369 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6370   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6371   @ovar{includes})
6372 @acindex{CHECK_HEADERS}
6373 @cvindex HAVE_@var{header}
6374 @caindex header_@var{header-file}
6375 For each given system header file @var{header-file} in the
6376 blank-separated argument list that exists, define
6377 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6378 is given, it is additional shell code to execute when one of the header
6379 files is found.  You can give it a value of @samp{break} to break out of
6380 the loop on the first match.  If @var{action-if-not-found} is given, it
6381 is executed when one of the header files is not found.
6383 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6384 choose the set of preprocessor directives supplied before the header
6385 under test.
6387 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6388 variable, with characters not suitable for a variable name mapped to
6389 underscores.
6390 @end defmac
6392 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6393 @acindex{CHECK_HEADERS_ONCE}
6394 @cvindex HAVE_@var{header}
6395 For each given system header file @var{header-file} in the
6396 blank-separated argument list that exists, define
6397 @code{HAVE_@var{header-file}} (in all capitals).
6399 If you do not need the full power of @code{AC_CHECK_HEADERS}, this
6400 variant generates smaller, faster @command{configure} files.  All
6401 headers passed to @code{AC_CHECK_HEADERS_ONCE} are checked for in one
6402 pass, early during the @command{configure} run.  The checks cannot be
6403 conditionalized, you cannot specify an @var{action-if-found} or
6404 @var{action-if-not-found}, and @code{AC_INCLUDES_DEFAULT} is always used
6405 for the prerequisites.
6406 @end defmac
6408 In previous versions of Autoconf, these macros merely checked whether
6409 the header was accepted by the preprocessor.  This was changed because
6410 the old test was inappropriate for typical uses.  Headers are typically
6411 used to compile, not merely to preprocess, and the old behavior
6412 sometimes accepted headers that clashed at compile-time
6413 (@pxref{Present But Cannot Be Compiled}).  If for some reason it is
6414 inappropriate to check whether a header is compilable, you should use
6415 @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}) instead of
6416 these macros.
6418 Requiring each header to compile improves the robustness of the test,
6419 but it also requires you to make sure that the @var{includes} are
6420 correct.  Most system headers nowadays make sure to @code{#include}
6421 whatever they require, or else have their dependencies satisfied by
6422 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), but
6423 @pxref{Header Portability}, for known exceptions.  In general, if you
6424 are looking for @file{bar.h}, which requires that @file{foo.h} be
6425 included first if it exists, you should do something like this:
6427 @example
6428 AC_CHECK_HEADERS([foo.h])
6429 AC_CHECK_HEADERS([bar.h], [], [],
6430 [#ifdef HAVE_FOO_H
6431 # include <foo.h>
6432 #endif
6434 @end example
6436 @node Declarations
6437 @section Declarations
6438 @cindex Declaration, checking
6440 The following macros check for the declaration of variables and
6441 functions.  If there is no macro specifically defined to check for a
6442 symbol you need, then you can use the general macros (@pxref{Generic
6443 Declarations}) or, for more complex tests, you may use
6444 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6446 @menu
6447 * Particular Declarations::     Macros to check for certain declarations
6448 * Generic Declarations::        How to find other declarations
6449 @end menu
6451 @node Particular Declarations
6452 @subsection Particular Declaration Checks
6454 There are no specific macros for declarations.
6456 @node Generic Declarations
6457 @subsection Generic Declaration Checks
6459 These macros are used to find declarations not covered by the ``particular''
6460 test macros.
6462 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6463   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6464 @acindex{CHECK_DECL}
6465 @caindex have_decl_@var{symbol}
6466 If @var{symbol} (a function, variable, or constant) is not declared in
6467 @var{includes} and a declaration is needed, run the shell commands
6468 @var{action-if-not-found}, otherwise @var{action-if-found}.
6469 @var{includes} is a series of include directives, defaulting to
6470 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6471 prior to the declaration under test.
6473 This macro actually tests whether @var{symbol} is defined as a macro or
6474 can be used as an r-value, not whether it is really declared, because it
6475 is much safer to avoid introducing extra declarations when they are not
6476 needed.  In order to facilitate use of C++ and overloaded function
6477 declarations, it is possible to specify function argument types in
6478 parentheses for types which can be zero-initialized:
6480 @example
6481 AC_CHECK_DECL([basename(char *)])
6482 @end example
6484 Some compilers don't indicate every missing declaration by the error
6485 status.  This macro checks the standard error from such compilers and
6486 considers a declaration missing if any warnings have been reported.  For
6487 most compilers, though, warnings do not affect this macro's outcome
6488 unless @code{AC_LANG_WERROR} is also specified.
6490 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6491 variable, with characters not suitable for a variable name mapped to
6492 underscores.
6493 @end defmac
6495 @anchor{AC_CHECK_DECLS}
6496 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6497   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6498 @acindex{CHECK_DECLS}
6499 @cvindex HAVE_DECL_@var{symbol}
6500 @caindex have_decl_@var{symbol}
6501 For each of the @var{symbols} (@emph{comma}-separated list with optional
6502 function argument types for C++ overloads), define
6503 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6504 @var{symbol} is declared, otherwise to @samp{0}.  If
6505 @var{action-if-not-found} is given, it is additional shell code to
6506 execute when one of the function declarations is needed, otherwise
6507 @var{action-if-found} is executed.
6509 @var{includes} is a series of include directives, defaulting to
6510 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6511 prior to the declarations under test.
6513 This macro uses an M4 list as first argument:
6514 @example
6515 AC_CHECK_DECLS([strdup])
6516 AC_CHECK_DECLS([strlen])
6517 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6518 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6519 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6520 @end example
6522 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6523 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6524 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6525 @emph{sure} that the check was performed, use
6526 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6528 @example
6529 #if !HAVE_DECL_SYMBOL
6530 extern char *symbol;
6531 #endif
6532 @end example
6534 @noindent
6535 If the test may have not been performed, however, because it is safer
6536 @emph{not} to declare a symbol than to use a declaration that conflicts
6537 with the system's one, you should use:
6539 @example
6540 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6541 void *malloc (size_t *s);
6542 #endif
6543 @end example
6545 @noindent
6546 You fall into the second category only in extreme situations: either
6547 your files may be used without being configured, or they are used during
6548 the configuration.  In most cases the traditional approach is enough.
6550 Some compilers don't indicate every missing declaration by the error
6551 status.  This macro checks the standard error from such compilers and
6552 considers a declaration missing if any warnings have been reported.  For
6553 most compilers, though, warnings do not affect this macro's outcome
6554 unless @code{AC_LANG_WERROR} is also specified.
6556 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6557 variables, with characters not suitable for a variable name mapped to
6558 underscores.
6559 @end defmac
6561 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6562 @acindex{CHECK_DECLS_ONCE}
6563 @cvindex HAVE_DECL_@var{symbol}
6564 For each of the @var{symbols} (@emph{comma}-separated list), define
6565 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6566 @var{symbol} is declared in the default include files, otherwise to
6567 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6568 generates the checking code at most once, so that @command{configure} is
6569 smaller and faster; but the checks cannot be conditionalized and are
6570 always done once, early during the @command{configure} run.
6571 @end defmac
6574 @node Structures
6575 @section Structures
6576 @cindex Structure, checking
6578 The following macros check for the presence of certain members in C
6579 structures.  If there is no macro specifically defined to check for a
6580 member you need, then you can use the general structure-member macros
6581 (@pxref{Generic Structures}) or, for more complex tests, you may use
6582 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6584 @menu
6585 * Particular Structures::       Macros to check for certain structure members
6586 * Generic Structures::          How to find other structure members
6587 @end menu
6589 @node Particular Structures
6590 @subsection Particular Structure Checks
6592 The following macros check for certain structures or structure members.
6594 @defmac AC_STRUCT_DIRENT_D_INO
6595 @acindex{STRUCT_DIRENT_D_INO}
6596 @cvindex HAVE_STRUCT_DIRENT_D_INO
6597 @c @caindex header_dirent_dirent_h
6598 @c @caindex member_struct_dirent_d_ino
6599 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6600 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6601 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6603 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6604 @code{d_ino}, not whether its contents are always reliable.
6605 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6606 though current systems hide this detail from the user and never return
6607 zero @code{d_ino} values.
6608 Many current systems report an incorrect @code{d_ino} for a directory
6609 entry that is a mount point.
6610 @end defmac
6612 @defmac AC_STRUCT_DIRENT_D_TYPE
6613 @acindex{STRUCT_DIRENT_D_TYPE}
6614 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6615 @c @caindex header_dirent_dirent_h
6616 @c @caindex member_struct_dirent_d_type
6617 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6618 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6619 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6620 @end defmac
6622 @anchor{AC_STRUCT_ST_BLOCKS}
6623 @defmac AC_STRUCT_ST_BLOCKS
6624 @acindex{STRUCT_ST_BLOCKS}
6625 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6626 @cvindex HAVE_ST_BLOCKS
6627 @ovindex LIBOBJS
6628 @caindex member_struct_stat_st_blocks
6629 If @code{struct stat} contains an @code{st_blocks} member, define
6630 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6631 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6632 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6633 future.
6635 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6636 variable.
6637 @end defmac
6639 @defmac AC_STRUCT_TM
6640 @acindex{STRUCT_TM}
6641 @cvindex TM_IN_SYS_TIME
6642 @hdrindex{time.h}
6643 @hdrindex{sys/time.h}
6644 If @file{time.h} does not define @code{struct tm}, define
6645 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6646 had better define @code{struct tm}.
6648 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6649 current systems.  New programs need not use this macro.
6650 @end defmac
6652 @anchor{AC_STRUCT_TIMEZONE}
6653 @defmac AC_STRUCT_TIMEZONE
6654 @acindex{STRUCT_TIMEZONE}
6655 @cvindex HAVE_DECL_TZNAME
6656 @cvindex HAVE_STRUCT_TM_TM_ZONE
6657 @cvindex HAVE_TM_ZONE
6658 @cvindex HAVE_TZNAME
6659 @c @caindex member_struct_tm_tm_zone
6660 @c @caindex struct_tm
6661 Figure out how to get the current timezone.  If @code{struct tm} has a
6662 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6663 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6664 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6665 define @code{HAVE_DECL_TZNAME}.
6666 @end defmac
6668 @node Generic Structures
6669 @subsection Generic Structure Checks
6671 These macros are used to find structure members not covered by the
6672 ``particular'' test macros.
6674 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6675   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6676   @dvar{includes, AC_INCLUDES_DEFAULT})
6677 @acindex{CHECK_MEMBER}
6678 @caindex member_@var{aggregate}_@var{member}
6679 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6680 If no @var{includes} are specified, the default includes are used
6681 (@pxref{Default Includes}).
6683 @example
6684 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6685                 [AC_MSG_ERROR([we need 'passwd.pw_gecos'])],
6686                 [[#include <pwd.h>]])
6687 @end example
6689 You can use this macro for submembers:
6691 @example
6692 AC_CHECK_MEMBER(struct top.middle.bot)
6693 @end example
6695 This macro caches its result in the
6696 @code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6697 characters not suitable for a variable name mapped to underscores.
6698 @end defmac
6700 @anchor{AC_CHECK_MEMBERS}
6701 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6702   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6703 @acindex{CHECK_MEMBERS}
6704 @cvindex HAVE_@var{aggregate}_@var{member}
6705 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6706 @var{members} using the previous macro.  When @var{member} belongs to
6707 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6708 capitals, with spaces and dots replaced by underscores).  If
6709 @var{action-if-found} is given, it is executed for each of the found
6710 members.  If @var{action-if-not-found} is given, it is executed for each
6711 of the members that could not be found.
6713 @var{includes} is a series of include directives, defaulting to
6714 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6715 prior to the members under test.
6717 This macro uses M4 lists:
6718 @example
6719 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6720 @end example
6721 @end defmac
6724 @node Types
6725 @section Types
6726 @cindex Types
6727 @cindex C types
6729 The following macros check for C types, either builtin or typedefs.  If
6730 there is no macro specifically defined to check for a type you need, and
6731 you don't need to check for any special properties of it, then you can
6732 use a general type-check macro.
6734 @menu
6735 * Particular Types::            Special handling to find certain types
6736 * Generic Types::               How to find other types
6737 @end menu
6739 @node Particular Types
6740 @subsection Particular Type Checks
6742 @hdrindex{sys/types.h}
6743 @hdrindex{stdlib.h}
6744 @hdrindex{stdint.h}
6745 @hdrindex{inttypes.h}
6746 These macros check for particular C types in @file{sys/types.h},
6747 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6748 exist.
6750 The Gnulib @code{stdint} module is an alternate way to define many of
6751 these symbols; it is useful if you prefer your code to assume a
6752 C99-or-better environment.  @xref{Gnulib}.
6754 @anchor{AC_TYPE_GETGROUPS}
6755 @defmac AC_TYPE_GETGROUPS
6756 @acindex{TYPE_GETGROUPS}
6757 @cvindex GETGROUPS_T
6758 @caindex type_getgroups
6759 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6760 is the base type of the array argument to @code{getgroups}.
6762 This macro caches the base type in the @code{ac_cv_type_getgroups}
6763 variable.
6764 @end defmac
6766 @defmac AC_TYPE_INT8_T
6767 @acindex{TYPE_INT8_T}
6768 @cvindex HAVE_INT8_T
6769 @cvindex int8_t
6770 @caindex c_int8_t
6771 If @file{stdint.h} or @file{inttypes.h} does not define the type
6772 @code{int8_t}, define @code{int8_t} to a signed
6773 integer type that is exactly 8 bits wide and that uses two's complement
6774 representation, if such a type exists.
6775 If you are worried about porting to hosts that lack such a type, you can
6776 use the results of this macro in C89-or-later code as follows:
6778 @example
6779 #if HAVE_STDINT_H
6780 # include <stdint.h>
6781 #endif
6782 #if defined INT8_MAX || defined int8_t
6783  @emph{code using int8_t}
6784 #else
6785  @emph{complicated alternative using >8-bit 'signed char'}
6786 #endif
6787 @end example
6789 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6790 @end defmac
6792 @defmac AC_TYPE_INT16_T
6793 @acindex{TYPE_INT16_T}
6794 @cvindex HAVE_INT16_T
6795 @cvindex int16_t
6796 @caindex c_int16_t
6797 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6798 @end defmac
6800 @defmac AC_TYPE_INT32_T
6801 @acindex{TYPE_INT32_T}
6802 @cvindex HAVE_INT32_T
6803 @cvindex int32_t
6804 @caindex c_int32_t
6805 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6806 @end defmac
6808 @defmac AC_TYPE_INT64_T
6809 @acindex{TYPE_INT64_T}
6810 @cvindex HAVE_INT64_T
6811 @cvindex int64_t
6812 @caindex c_int64_t
6813 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6814 @end defmac
6816 @defmac AC_TYPE_INTMAX_T
6817 @acindex{TYPE_INTMAX_T}
6818 @cvindex HAVE_INTMAX_T
6819 @cvindex intmax_t
6820 @c @caindex type_intmax_t
6821 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6822 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6823 widest signed integer type.
6824 @end defmac
6826 @defmac AC_TYPE_INTPTR_T
6827 @acindex{TYPE_INTPTR_T}
6828 @cvindex HAVE_INTPTR_T
6829 @cvindex intptr_t
6830 @c @caindex type_intptr_t
6831 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6832 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6833 signed integer type wide enough to hold a pointer, if such a type
6834 exists.
6835 @end defmac
6837 @defmac AC_TYPE_LONG_DOUBLE
6838 @acindex{TYPE_LONG_DOUBLE}
6839 @cvindex HAVE_LONG_DOUBLE
6840 @caindex type_long_double
6841 If the C compiler supports a working @code{long double} type, define
6842 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6843 same range and precision as @code{double}.
6845 This macro caches its result in the @code{ac_cv_type_long_double}
6846 variable.
6848 This macro is obsolescent, as current C compilers support @code{long
6849 double}.  New programs need not use this macro.
6850 @end defmac
6852 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6853 @acindex{TYPE_LONG_DOUBLE_WIDER}
6854 @cvindex HAVE_LONG_DOUBLE_WIDER
6855 @caindex type_long_double_wider
6856 If the C compiler supports a working @code{long double} type with more
6857 range or precision than the @code{double} type, define
6858 @code{HAVE_LONG_DOUBLE_WIDER}.
6860 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6861 variable.
6862 @end defmac
6864 @defmac AC_TYPE_LONG_LONG_INT
6865 @acindex{TYPE_LONG_LONG_INT}
6866 @cvindex HAVE_LONG_LONG_INT
6867 @caindex type_long_long_int
6868 If the C compiler supports a working @code{long long int} type, define
6869 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6870 @code{long long int} values in preprocessor @code{#if} expressions,
6871 because too many compilers mishandle such expressions.
6872 @xref{Preprocessor Arithmetic}.
6874 This macro caches its result in the @code{ac_cv_type_long_long_int}
6875 variable.
6876 @end defmac
6878 @defmac AC_TYPE_MBSTATE_T
6879 @acindex{TYPE_MBSTATE_T}
6880 @cvindex mbstate_t
6881 @hdrindex{wchar.h}
6882 @caindex type_mbstate_t
6883 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6884 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6885 @code{<wchar.h>} does not declare it.
6887 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6888 variable.
6889 @end defmac
6891 @anchor{AC_TYPE_MODE_T}
6892 @defmac AC_TYPE_MODE_T
6893 @acindex{TYPE_MODE_T}
6894 @cvindex mode_t
6895 @caindex type_mode_t
6896 Define @code{mode_t} to a suitable type, if standard headers do not
6897 define it.
6899 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6900 @end defmac
6902 @anchor{AC_TYPE_OFF_T}
6903 @defmac AC_TYPE_OFF_T
6904 @acindex{TYPE_OFF_T}
6905 @cvindex off_t
6906 @caindex type_off_t
6907 Define @code{off_t} to a suitable type, if standard headers do not
6908 define it.
6910 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6911 @end defmac
6913 @anchor{AC_TYPE_PID_T}
6914 @defmac AC_TYPE_PID_T
6915 @acindex{TYPE_PID_T}
6916 @cvindex pid_t
6917 @caindex type_pid_t
6918 Define @code{pid_t} to a suitable type, if standard headers do not
6919 define it.
6921 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6922 @end defmac
6924 @anchor{AC_TYPE_SIZE_T}
6925 @defmac AC_TYPE_SIZE_T
6926 @acindex{TYPE_SIZE_T}
6927 @cvindex size_t
6928 @caindex type_size_t
6929 Define @code{size_t} to a suitable type, if standard headers do not
6930 define it.
6932 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6933 @end defmac
6935 @defmac AC_TYPE_SSIZE_T
6936 @acindex{TYPE_SSIZE_T}
6937 @cvindex ssize_t
6938 @caindex type_ssize_t
6939 Define @code{ssize_t} to a suitable type, if standard headers do not
6940 define it.
6942 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6943 @end defmac
6945 @anchor{AC_TYPE_UID_T}
6946 @defmac AC_TYPE_UID_T
6947 @acindex{TYPE_UID_T}
6948 @cvindex uid_t
6949 @cvindex gid_t
6950 @caindex type_uid_t
6951 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6952 headers do not define them.
6954 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6955 @end defmac
6957 @defmac AC_TYPE_UINT8_T
6958 @acindex{TYPE_UINT8_T}
6959 @cvindex HAVE_UINT8_T
6960 @cvindex uint8_t
6961 @caindex c_uint8_t
6962 If @file{stdint.h} or @file{inttypes.h} does not define the type
6963 @code{uint8_t}, define @code{uint8_t} to an
6964 unsigned integer type that is exactly 8 bits wide, if such a type
6965 exists.
6966 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6967 @end defmac
6969 @defmac AC_TYPE_UINT16_T
6970 @acindex{TYPE_UINT16_T}
6971 @cvindex HAVE_UINT16_T
6972 @cvindex uint16_t
6973 @caindex c_uint16_t
6974 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6975 @end defmac
6977 @defmac AC_TYPE_UINT32_T
6978 @acindex{TYPE_UINT32_T}
6979 @cvindex HAVE_UINT32_T
6980 @cvindex uint32_t
6981 @caindex c_uint32_t
6982 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6983 @end defmac
6985 @defmac AC_TYPE_UINT64_T
6986 @acindex{TYPE_UINT64_T}
6987 @cvindex HAVE_UINT64_T
6988 @cvindex uint64_t
6989 @caindex c_uint64_t
6990 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6991 @end defmac
6993 @defmac AC_TYPE_UINTMAX_T
6994 @acindex{TYPE_UINTMAX_T}
6995 @cvindex HAVE_UINTMAX_T
6996 @cvindex uintmax_t
6997 @c @caindex type_uintmax_t
6998 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6999 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
7000 widest unsigned integer type.
7001 @end defmac
7003 @defmac AC_TYPE_UINTPTR_T
7004 @acindex{TYPE_UINTPTR_T}
7005 @cvindex HAVE_UINTPTR_T
7006 @cvindex uintptr_t
7007 @c @caindex type_uintptr_t
7008 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
7009 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
7010 unsigned integer type wide enough to hold a pointer, if such a type
7011 exists.
7012 @end defmac
7014 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
7015 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
7016 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
7017 @caindex type_unsigned_long_long_int
7018 If the C compiler supports a working @code{unsigned long long int} type,
7019 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
7020 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
7021 because too many compilers mishandle such expressions.
7022 @xref{Preprocessor Arithmetic}.
7024 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
7025 variable.
7026 @end defmac
7028 @node Generic Types
7029 @subsection Generic Type Checks
7031 These macros are used to check for types not covered by the ``particular''
7032 test macros.
7034 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
7035   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
7036 @acindex{CHECK_TYPE}
7037 @caindex type_@var{type}
7038 Check whether @var{type} is defined.  It may be a compiler builtin type
7039 or defined by the @var{includes}.  @var{includes} is a series of include
7040 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
7041 Includes}), which are used prior to the type under test.
7043 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
7044 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
7045 same test is applied when compiling for C++, which means that in C++
7046 @var{type} should be a type-id and should not be an anonymous
7047 @samp{struct} or @samp{union}.
7049 This macro caches its result in the @code{ac_cv_type_@var{type}}
7050 variable, with @samp{*} mapped to @samp{p} and other characters not
7051 suitable for a variable name mapped to underscores.
7052 @end defmac
7055 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
7056   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
7057 @acindex{CHECK_TYPES}
7058 @cvindex HAVE_@var{type}
7059 For each @var{type} of the @var{types} that is defined, define
7060 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
7061 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
7062 specified, the default includes are used (@pxref{Default Includes}).  If
7063 @var{action-if-found} is given, it is additional shell code to execute
7064 when one of the types is found.  If @var{action-if-not-found} is given,
7065 it is executed when one of the types is not found.
7067 This macro uses M4 lists:
7068 @example
7069 AC_CHECK_TYPES([ptrdiff_t])
7070 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
7071 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
7072 @end example
7074 @end defmac
7076 Autoconf, up to 2.13, used to provide to another version of
7077 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
7078 compatibility, a simple heuristic, quite safe but not totally, is
7079 implemented.  In case of doubt, read the documentation of the former
7080 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
7083 @node Compilers and Preprocessors
7084 @section Compilers and Preprocessors
7085 @cindex Compilers
7086 @cindex Preprocessors
7088 @ovindex EXEEXT
7089 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
7090 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
7091 the output of the compiler, typically to the empty string if
7092 Posix and @samp{.exe} if a DOS variant.
7094 @ovindex OBJEXT
7095 They also define the output variable @code{OBJEXT} based on the
7096 output of the compiler, after @file{.c} files have been excluded, typically
7097 to @samp{o} if Posix, @samp{obj} if a DOS variant.
7099 If the compiler being used does not produce executables, the tests fail.  If
7100 the executables can't be run, and cross-compilation is not enabled, they
7101 fail too.  @xref{Manual Configuration}, for more on support for cross
7102 compiling.
7104 @menu
7105 * Specific Compiler Characteristics::  Some portability issues
7106 * Generic Compiler Characteristics::  Language independent tests and features
7107 * C Compiler::                  Checking its characteristics
7108 * C++ Compiler::                Likewise
7109 * Objective C Compiler::        Likewise
7110 * Objective C++ Compiler::      Likewise
7111 * Erlang Compiler and Interpreter::  Likewise
7112 * Fortran Compiler::            Likewise
7113 * Go Compiler::                 Likewise
7114 @end menu
7116 @node Specific Compiler Characteristics
7117 @subsection Specific Compiler Characteristics
7119 Some compilers exhibit different behaviors.
7121 @table @asis
7122 @item Static/Dynamic Expressions
7123 Autoconf relies on a trick to extract one bit of information from the C
7124 compiler: using negative array sizes.  For instance the following
7125 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
7126 bytes wide:
7128 @example
7129 static int test_array[sizeof (int) == 4 ? 1 : -1];
7130 @end example
7132 @noindent
7133 To our knowledge, there is a single compiler that does not support this
7134 trick: the HP C compilers (the real ones, not only the
7135 ``bundled'') on HP-UX 11.00.
7136 They incorrectly reject the above program with the diagnostic
7137 ``Variable-length arrays cannot have static storage.''
7138 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
7139 not from the @code{? 1 : -1}, and
7140 Autoconf works around this problem by casting @code{sizeof (int)} to
7141 @code{long int} before comparing it.
7142 @end table
7144 @node Generic Compiler Characteristics
7145 @subsection Generic Compiler Characteristics
7147 @anchor{AC_CHECK_SIZEOF}
7148 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7149   @dvar{includes, AC_INCLUDES_DEFAULT})
7150 @acindex{CHECK_SIZEOF}
7151 @cvindex SIZEOF_@var{type-or-expr}
7152 @caindex sizeof_@var{type-or-expr}
7153 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7154 the size in bytes of @var{type-or-expr}, which may be either a type or
7155 an expression returning a value that has a size.  If the expression
7156 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7157 @var{includes} is a series of include directives, defaulting to
7158 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7159 prior to the expression under test.
7161 This macro now works even when cross-compiling.  The @var{unused}
7162 argument was used when cross-compiling.
7164 For example, the call
7166 @example
7167 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7168 AC_CHECK_SIZEOF([int *])
7169 @end example
7171 @noindent
7172 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
7174 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7175 variable, with @samp{*} mapped to @samp{p} and other characters not
7176 suitable for a variable name mapped to underscores.
7177 @end defmac
7179 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7180 @acindex{CHECK_ALIGNOF}
7181 @cvindex ALIGNOF_@var{type}
7182 @caindex alignof_@var{type-or-expr}
7183 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7184 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
7185 a structure member declaration.  If @samp{type} is unknown, the result
7186 is 0.  If no @var{includes} are specified, the default includes are used
7187 (@pxref{Default Includes}).
7189 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7190 variable, with @samp{*} mapped to @samp{p} and other characters not
7191 suitable for a variable name mapped to underscores.
7192 @end defmac
7194 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7195   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7196 @acindex{COMPUTE_INT}
7197 Store into the shell variable @var{var} the value of the integer
7198 @var{expression}.  The
7199 value should fit in an initializer in a C variable of type @code{signed
7200 long}.  To support cross compilation (in which case, the macro only works on
7201 hosts that use twos-complement arithmetic), it should be possible to evaluate
7202 the expression at compile-time.  If no @var{includes} are specified, the
7203 default includes are used (@pxref{Default Includes}).
7205 Execute @var{action-if-fails} if the value cannot be determined correctly.
7206 @end defmac
7208 @defmac AC_LANG_WERROR
7209 @acindex{LANG_WERROR}
7210 Normally Autoconf ignores warnings generated by the compiler, linker, and
7211 preprocessor.  If this macro is used, warnings count as fatal
7212 errors for the current language.  This macro is useful when the
7213 results of configuration are used where warnings are unacceptable; for
7214 instance, if parts of a program are built with the GCC
7215 @option{-Werror}
7216 option.  If the whole program is built using @option{-Werror} it is
7217 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7218 etc.).
7219 @end defmac
7221 @defmac AC_OPENMP
7222 @acindex{OPENMP}
7223 @cvindex _OPENMP
7224 @ovindex OPENMP_CFLAGS
7225 @ovindex OPENMP_CXXFLAGS
7226 @ovindex OPENMP_FFLAGS
7227 @ovindex OPENMP_FCFLAGS
7228 @caindex prog_c_openmp
7229 @caindex prog_cxx_openmp
7230 @caindex prog_f77_openmp
7231 @caindex prog_fc_openmp
7232 @uref{http://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7233 and Fortran that simplify optimization of shared memory parallelism,
7234 which is a common problem on multi-core CPUs.
7236 If the current language is C, the macro @code{AC_OPENMP} sets the
7237 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7238 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
7239 compiler already supports OpenMP, if it has no way to activate OpenMP
7240 support, or if the user rejects OpenMP support by invoking
7241 @samp{configure} with the @samp{--disable-openmp} option.
7243 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7244 preprocessing program source, and when linking programs.  Therefore you
7245 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7246 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
7247 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
7248 OpenMP support is revealed at compile time by the preprocessor macro
7249 @code{_OPENMP}.
7251 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7252 shared library to the program's dependencies, so its use is recommended
7253 only on programs that actually require OpenMP.
7255 If the current language is C++, @code{AC_OPENMP} sets the variable
7256 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7257 hold as for C.
7259 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7260 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7261 respectively.  Similar remarks as for C hold, except that
7262 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7263 signals OpenMP support.
7265 For portability, it is best to avoid spaces between @samp{#} and
7266 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7267 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7268 latter.
7270 This macro caches its result in the @code{ac_cv_prog_c_openmp},
7271 @code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7272 @code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7274 @strong{Caution:} Some of the compiler options that @code{AC_OPENMP}
7275 tests, mean ``enable OpenMP'' to one compiler, but ``write output to a
7276 file named @file{mp} or @file{penmp}'' to other compilers.  We cannot
7277 guarantee that the implementation of @code{AC_OPENMP} will not overwrite
7278 an existing file with either of these names.
7280 Therefore, as a defensive measure, a @command{configure} script that
7281 uses @code{AC_OPENMP} will issue an error and stop (before doing any of
7282 the operations that might overwrite these files) upon encountering
7283 either of these files in its working directory.
7284 @command{autoconf} will also issue an error if it finds either of
7285 these files in the same directory as a @file{configure.ac} that
7286 uses @code{AC_OPENMP}.
7288 If you have files with either of these names at the top level of your
7289 source tree, and you need to use @code{AC_OPENMP}, we recommend you
7290 either change their names or move them into a subdirectory.
7291 @end defmac
7293 @node C Compiler
7294 @subsection C Compiler Characteristics
7296 The following macros provide ways to find and exercise a C Compiler.
7297 There are a few constructs that ought to be avoided, but do not deserve
7298 being checked for, since they can easily be worked around.
7300 @table @asis
7301 @item Don't use lines containing solitary backslashes
7302 They tickle a bug in the HP-UX C compiler (checked on
7303 HP-UX 10.20,
7304 11.00, and 11i).  When given the following source:
7306 @example
7307 #ifdef __STDC__
7309 * A comment with backslash-newlines in it.  %@{ %@} *\
7312 char str[] = "\\
7313 " A string with backslash-newlines in it %@{ %@} \\
7315 char apostrophe = '\\
7319 #endif
7320 @end example
7322 @noindent
7323 the compiler incorrectly fails with the diagnostics ``Non-terminating
7324 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7325 Removing the lines with solitary backslashes solves the problem.
7327 @item Don't compile several files at once if output matters to you
7328 Some compilers, such as HP's, report names of files being
7329 compiled when given more than one file operand.  For instance:
7331 @example
7332 $ @kbd{cc a.c b.c}
7333 a.c:
7334 b.c:
7335 @end example
7337 @noindent
7338 This can cause problems if you observe the output of the compiler to
7339 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7340 b.o} solves the issue.
7342 @item Don't rely on @code{#error} failing
7343 The IRIX C compiler does not fail when #error is preprocessed; it
7344 simply emits a diagnostic and continues, exiting successfully.  So,
7345 instead of an error directive like @code{#error "Unsupported word size"}
7346 it is more portable to use an invalid directive like @code{#Unsupported
7347 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7348 OK, since installers with inadequate compilers like IRIX can simply
7349 examine these compilers' diagnostic output.
7351 @item Don't rely on correct @code{#line} support
7352 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7353 diagnoses @code{#line} directives whose line
7354 numbers are greater than 32767.  Nothing in Posix
7355 makes this invalid.  That is why Autoconf stopped issuing
7356 @code{#line} directives.
7357 @end table
7359 @anchor{AC_PROG_CC}
7360 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7361 @acindex{PROG_CC}
7362 @evindex CC
7363 @evindex CFLAGS
7364 @ovindex CC
7365 @ovindex CFLAGS
7366 @caindex prog_cc_stdc
7367 Determine a C compiler to use.  If @code{CC} is not already set in the
7368 environment, check for @code{gcc} and @code{cc}, then for other C
7369 compilers.  Set output variable @code{CC} to the name of the compiler
7370 found.
7372 This macro may, however, be invoked with an optional first argument
7373 which, if specified, must be a blank-separated list of C compilers to
7374 search for.  This just gives the user an opportunity to specify an
7375 alternative search list for the C compiler.  For example, if you didn't
7376 like the default order, then you could invoke @code{AC_PROG_CC} like
7377 this:
7379 @example
7380 AC_PROG_CC([gcc cl cc])
7381 @end example
7383 If necessary, add an option to output variable @code{CC} to enable
7384 support for ISO Standard C features with extensions.  Prefer the newest
7385 C standard that is supported.  Currently the newest standard is ISO C11,
7386 with ISO C99 and ANSI C89 (ISO C90) being the older versions.
7387 After calling this macro you can check whether the C compiler has been
7388 set to accept Standard C; if not, the shell variable
7389 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7391 When attempting to add compiler options, prefer extended functionality
7392 to strict conformance: the goal is to enable whatever standard features
7393 that are available, not to check for full conformance to the standard or
7394 to prohibit incompatible extensions.  Test for C11 support by checking
7395 for @code{_Alignas}, @code{_Alignof}, @code{_Noreturn},
7396 @code{_Static_assert}, UTF-8 string literals, duplicate @code{typedef}s,
7397 and anonymous structures and unions.  Test for C99 support by checking
7398 for @code{_Bool}, @code{//} comments, flexible array members,
7399 @code{inline}, signed and unsigned @code{long long int}, mixed code and
7400 declarations, named initialization of structs, @code{restrict},
7401 @code{va_copy}, varargs macros, variable declarations in @code{for}
7402 loops, and variable length arrays.  Test for C89 support by checking for
7403 function prototypes.
7405 If using a compiler that supports GNU C, set shell variable @code{GCC} to
7406 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
7407 it to @option{-g -O2} for a GNU C compiler (@option{-O2} on systems
7408 where the compiler does not accept @option{-g}), or @option{-g} for
7409 other compilers.  If your package does not like this default, then it is
7410 acceptable to insert the line @samp{: $@{CFLAGS=""@}} after @code{AC_INIT}
7411 and before @code{AC_PROG_CC} to select an empty default instead.
7413 Many Autoconf macros use a compiler, and thus call
7414 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7415 determined before the body of the outermost @code{AC_DEFUN} macro.
7416 @code{AC_PROG_CC} is therefore defined via @code{AC_DEFUN_ONCE} to avoid
7417 needless reexpansion (@pxref{One-Shot Macros}).
7418 @end defmac
7420 @anchor{AC_PROG_CC_C_O}
7421 @defmac AC_PROG_CC_C_O
7422 @acindex{PROG_CC_C_O}
7423 @cvindex NO_MINUS_C_MINUS_O
7424 @caindex prog_cc_@var{compiler}_c_o
7425 If the C compiler does not accept the @option{-c} and @option{-o} options
7426 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7427 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7428 the first @code{cc} in the path.  The test fails if one fails.  This
7429 macro was created for GNU Make to choose the default C compilation
7430 rule.
7432 For the compiler @var{compiler}, this macro caches its result in the
7433 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7434 @end defmac
7437 @defmac AC_PROG_CPP
7438 @acindex{PROG_CPP}
7439 @evindex CPP
7440 @ovindex CPP
7441 Set output variable @code{CPP} to a command that runs the
7442 C preprocessor.  If @samp{$CC -E} doesn't work, tries @code{cpp} and
7443 @file{/lib/cpp}, in that order.
7445 It is only portable to run @code{CPP} on files with a @file{.c}
7446 extension.
7448 Some preprocessors don't indicate missing include files by the error
7449 status.  For such preprocessors an internal variable is set that causes
7450 other macros to check the standard error from the preprocessor and
7451 consider the test failed if any warnings have been reported.
7452 For most preprocessors, though, warnings do not cause include-file
7453 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7454 @end defmac
7456 @defmac AC_PROG_CPP_WERROR
7457 @acindex{PROG_CPP_WERROR}
7458 @ovindex CPP
7459 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7460 preprocessor as errors even if the preprocessor exit status indicates
7461 success.  This is useful for avoiding headers that generate mandatory
7462 warnings, such as deprecation notices.
7463 @end defmac
7466 The following macros check for C compiler or machine architecture
7467 features.  To check for characteristics not listed here, use
7468 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7469 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7471 @defmac AC_C_BACKSLASH_A
7472 @acindex{C_BACKSLASH_A}
7473 @cvindex HAVE_C_BACKSLASH_A
7474 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7475 @samp{\a}.
7477 This macro is obsolescent, as current C compilers understand @samp{\a}.
7478 New programs need not use this macro.
7479 @end defmac
7481 @anchor{AC_C_BIGENDIAN}
7482 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7483   @ovar{action-if-unknown}, @ovar{action-if-universal})
7484 @acindex{C_BIGENDIAN}
7485 @cvindex WORDS_BIGENDIAN
7486 @cindex Endianness
7487 If words are stored with the most significant byte first (like Motorola
7488 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7489 the least significant byte first (like Intel and VAX CPUs), execute
7490 @var{action-if-false}.
7492 This macro runs a test-case if endianness cannot be determined from the
7493 system header files.  When cross-compiling, the test-case is not run but
7494 grep'ed for some magic values.  @var{action-if-unknown} is executed if
7495 the latter case fails to determine the byte sex of the host system.
7497 In some cases a single run of a compiler can generate code for multiple
7498 architectures.  This can happen, for example, when generating Mac OS X
7499 universal binary files, which work on both PowerPC and Intel
7500 architectures.  In this case, the different variants might be for
7501 architectures with differing endianness.  If
7502 @command{configure} detects this, it executes @var{action-if-universal}
7503 instead of @var{action-if-unknown}.
7505 The default for @var{action-if-true} is to define
7506 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7507 nothing.  The default for @var{action-if-unknown} is to
7508 abort configure and tell the installer how to bypass this test.
7509 And finally, the default for @var{action-if-universal} is to ensure that
7510 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7511 detected and the current code is big-endian; this default works only if
7512 @command{autoheader} is used (@pxref{autoheader Invocation}).
7514 If you use this macro without specifying @var{action-if-universal}, you
7515 should also use @code{AC_CONFIG_HEADERS}; otherwise
7516 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7517 binary files.
7518 @end defmac
7520 @anchor{AC_C_CONST}
7521 @defmac AC_C_CONST
7522 @acindex{C_CONST}
7523 @cvindex const
7524 @caindex c_const
7525 If the C compiler does not fully support the @code{const} keyword,
7526 define @code{const} to be empty.  Some C compilers that do
7527 not define @code{__STDC__} do support @code{const}; some compilers that
7528 define @code{__STDC__} do not completely support @code{const}.  Programs
7529 can simply use @code{const} as if every C compiler supported it; for
7530 those that don't, the makefile or configuration header file
7531 defines it as empty.
7533 Occasionally installers use a C++ compiler to compile C code, typically
7534 because they lack a C compiler.  This causes problems with @code{const},
7535 because C and C++ treat @code{const} differently.  For example:
7537 @example
7538 const int foo;
7539 @end example
7541 @noindent
7542 is valid in C but not in C++.  These differences unfortunately cannot be
7543 papered over by defining @code{const} to be empty.
7545 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7546 as this generally yields better results in practice.  However, using a
7547 C++ compiler to compile C code is not recommended or supported, and
7548 installers who run into trouble in this area should get a C compiler
7549 like GCC to compile their C code.
7551 This macro caches its result in the @code{ac_cv_c_const} variable.
7553 This macro is obsolescent, as current C compilers support @code{const}.
7554 New programs need not use this macro.
7555 @end defmac
7557 @defmac AC_C__GENERIC
7558 @acindex{C__GENERIC}
7559 @cvindex _Generic
7560 If the C compiler supports C11-style generic selection using the
7561 @code{_Generic} keyword, define @code{HAVE_C__GENERIC}.
7562 @end defmac
7564 @defmac AC_C_RESTRICT
7565 @acindex{C_RESTRICT}
7566 @cvindex restrict
7567 @caindex c_restrict
7568 If the C compiler recognizes a variant spelling for the @code{restrict}
7569 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7570 then define @code{restrict} to that; this is more likely to do the right
7571 thing with compilers that support language variants where plain
7572 @code{restrict} is not a keyword.  Otherwise, if the C compiler
7573 recognizes the @code{restrict} keyword, don't do anything.
7574 Otherwise, define @code{restrict} to be empty.
7575 Thus, programs may simply use @code{restrict} as if every C compiler
7576 supported it; for those that do not, the makefile
7577 or configuration header defines it away.
7579 Although support in C++ for the @code{restrict} keyword is not
7580 required, several C++ compilers do accept the keyword.
7581 This macro works for them, too.
7583 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7584 if @code{restrict} is not supported, and a supported spelling otherwise.
7585 @end defmac
7587 @defmac AC_C_VOLATILE
7588 @acindex{C_VOLATILE}
7589 @cvindex volatile
7590 If the C compiler does not understand the keyword @code{volatile},
7591 define @code{volatile} to be empty.  Programs can simply use
7592 @code{volatile} as if every C compiler supported it; for those that do
7593 not, the makefile or configuration header defines it as
7594 empty.
7596 If the correctness of your program depends on the semantics of
7597 @code{volatile}, simply defining it to be empty does, in a sense, break
7598 your code.  However, given that the compiler does not support
7599 @code{volatile}, you are at its mercy anyway.  At least your
7600 program compiles, when it wouldn't before.
7601 @xref{Volatile Objects}, for more about @code{volatile}.
7603 In general, the @code{volatile} keyword is a standard C feature, so
7604 you might expect that @code{volatile} is available only when
7605 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7606 support volatile, but does not define @code{__STDC__}.
7608 This macro is obsolescent, as current C compilers support @code{volatile}.
7609 New programs need not use this macro.
7610 @end defmac
7612 @anchor{AC_C_INLINE}
7613 @defmac AC_C_INLINE
7614 @acindex{C_INLINE}
7615 @cvindex inline
7616 If the C compiler supports the keyword @code{inline}, do nothing.
7617 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7618 if it accepts one of those, otherwise define @code{inline} to be empty.
7619 @end defmac
7621 @anchor{AC_C_CHAR_UNSIGNED}
7622 @defmac AC_C_CHAR_UNSIGNED
7623 @acindex{C_CHAR_UNSIGNED}
7624 @cvindex __CHAR_UNSIGNED__
7625 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7626 unless the C compiler predefines it.
7628 These days, using this macro is not necessary.  The same information can
7629 be determined by this portable alternative, thus avoiding the use of
7630 preprocessor macros in the namespace reserved for the implementation.
7632 @example
7633 #include <limits.h>
7634 #if CHAR_MIN == 0
7635 # define CHAR_UNSIGNED 1
7636 #endif
7637 @end example
7638 @end defmac
7640 @defmac AC_C_STRINGIZE
7641 @acindex{C_STRINGIZE}
7642 @cvindex HAVE_STRINGIZE
7643 If the C preprocessor supports the stringizing operator, define
7644 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7645 found in macros such as this:
7647 @example
7648 #define x(y) #y
7649 @end example
7651 This macro is obsolescent, as current C compilers support the
7652 stringizing operator.  New programs need not use this macro.
7653 @end defmac
7655 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7656 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7657 @cvindex FLEXIBLE_ARRAY_MEMBER
7658 If the C compiler supports flexible array members, define
7659 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7660 That way, a declaration like this:
7662 @example
7663 struct s
7664   @{
7665     size_t n_vals;
7666     double val[FLEXIBLE_ARRAY_MEMBER];
7667   @};
7668 @end example
7670 @noindent
7671 will let applications use the ``struct hack'' even with compilers that
7672 do not support flexible array members.  To allocate and use such an
7673 object, you can use code like this:
7675 @example
7676 size_t i;
7677 size_t n = compute_value_count ();
7678 struct s *p =
7679    malloc (offsetof (struct s, val)
7680            + n * sizeof (double));
7681 p->n_vals = n;
7682 for (i = 0; i < n; i++)
7683   p->val[i] = compute_value (i);
7684 @end example
7685 @end defmac
7687 @defmac AC_C_VARARRAYS
7688 @acindex{C_VARARRAYS}
7689 @cvindex __STDC_NO_VLA__
7690 @cvindex HAVE_C_VARARRAYS
7691 If the C compiler does not support variable-length arrays, define the
7692 macro @code{__STDC_NO_VLA__} to be 1 if it is not already defined.  A
7693 variable-length array is an array of automatic storage duration whose
7694 length is determined at run time, when the array is declared.  For
7695 backward compatibility this macro also defines @code{HAVE_C_VARARRAYS}
7696 if the C compiler supports variable-length arrays, but this usage is
7697 obsolescent and new programs should use @code{__STDC_NO_VLA__}.
7698 @end defmac
7700 @defmac AC_C_TYPEOF
7701 @acindex{C_TYPEOF}
7702 @cvindex HAVE_TYPEOF
7703 @cvindex typeof
7704 If the C compiler supports GNU C's @code{typeof} syntax either
7705 directly or
7706 through a different spelling of the keyword (e.g., @code{__typeof__}),
7707 define @code{HAVE_TYPEOF}.  If the support is available only through a
7708 different spelling, define @code{typeof} to that spelling.
7709 @end defmac
7711 @defmac AC_C_PROTOTYPES
7712 @acindex{C_PROTOTYPES}
7713 @cvindex PROTOTYPES
7714 @cvindex __PROTOTYPES
7715 @cvindex PARAMS
7716 If function prototypes are understood by the compiler (as determined by
7717 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7718 Defining @code{__PROTOTYPES} is for the benefit of
7719 header files that cannot use macros that infringe on user name space.
7721 This macro is obsolescent, as current C compilers support prototypes.
7722 New programs need not use this macro.
7723 @end defmac
7725 @anchor{AC_PROG_GCC_TRADITIONAL}
7726 @defmac AC_PROG_GCC_TRADITIONAL
7727 @acindex{PROG_GCC_TRADITIONAL}
7728 @ovindex CC
7729 Add @option{-traditional} to output variable @code{CC} if using a
7730 GNU C compiler and @code{ioctl} does not work properly without
7731 @option{-traditional}.  That usually happens when the fixed header files
7732 have not been installed on an old system.
7734 This macro is obsolescent, since current versions of the GNU C
7735 compiler fix the header files automatically when installed.
7736 @end defmac
7739 @node C++ Compiler
7740 @subsection C++ Compiler Characteristics
7743 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7744 @acindex{PROG_CXX}
7745 @evindex CXX
7746 @evindex CXXFLAGS
7747 @ovindex CXX
7748 @ovindex CXXFLAGS
7749 Determine a C++ compiler to use.
7751 If either the environment variable @code{CXX} or the environment
7752 variable @code{CCC} is set, its value will be taken as the name of a
7753 C++ compiler.  If both are set, @code{CXX} is preferred.  If neither
7754 are set, search for a C++ compiler under a series of likely names,
7755 trying @code{g++} and @code{c++} first.  Regardless, the output
7756 variable @code{CXX} is set to the chosen compiler.
7758 If the optional first argument to the macro is used, it must be a
7759 whitespace-separated list of potential names for a C++ compiler,
7760 which overrides the built-in list.
7762 If no C++ compiler can be found, as a last resort @code{CXX} is set to
7763 @code{g++} (and subsequent tests will probably fail).
7765 If the selected C++ compiler is found to be GNU C++ (regardless of
7766 its name), the shell variable @code{GXX} will be set to @samp{yes}.
7767 If the shell variable @code{CXXFLAGS} was not already set, it is set
7768 to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on systems
7769 where G++ does not accept @option{-g}), or @option{-g} for other
7770 compilers.  @code{CXXFLAGS} is then made an output variable.
7771 You can override the default for @code{CXXFLAGS} by inserting a shell
7772 default assignment between @code{AC_INIT} and @code{AC_PROG_CXX}:
7774 @example
7775 : $@{CXXFLAGS="@var{options}"@}
7776 @end example
7778 where @var{options} are the appropriate set of options to use by
7779 default.  (It is important to use this construct rather than a normal
7780 assignment, so that @code{CXXFLAGS} can still be overridden by the
7781 person building the package.  @xref{Preset Output Variables}.)
7783 If necessary, options are added to @code{CXX} to enable support for
7784 ISO Standard C++ features with extensions.  ISO C++ 2011 is preferred
7785 if the compiler supports it.  After calling this macro, you can check
7786 whether the C++ compiler has been set to accept standard C++ by
7787 inspecting cache variables.  If @code{ac_cv_prog_cxx_cxx11} is set to
7788 any value other than @samp{no} (including the empty string), then
7789 @code{CXX} can compile code as standard C++ 2011, and this mode has
7790 been enabled.  Otherwise, if @code{ac_cv_prog_cxx_cxx98} is set to
7791 any value other than @samp{no} (including the empty string), then
7792 @code{CXX} can compile code as standard C++ 1998, and this mode has
7793 been enabled.  Finally, if both variables are set to @samp{no}, then
7794 @code{CXX} cannot compile standard C++ at all.
7796 The tests for standard conformance are not comprehensive.  They test
7797 the value of @code{__cplusplus} and a representative sample of the
7798 language features added in each version of the C++ standard.  They do
7799 not exercise the C++ standard library, because this can be extremely
7800 slow.  If you need to know whether a particular C++ standard header
7801 exists, use @code{AC_CHECK_HEADER}.
7803 None of the options that may be added to @code{CXX} by this macro
7804 enable @emph{strict} conformance to the C++ standard.  In particular,
7805 system-specific extensions are not disabled.  (For example, for GNU
7806 C++, the @option{-std=gnu++@var{nn}} options may be used, but not the
7807 @option{-std=c++@var{nn}} options.)
7808 @end defmac
7810 @defmac AC_PROG_CXXCPP
7811 @acindex{PROG_CXXCPP}
7812 @evindex CXXCPP
7813 @ovindex CXXCPP
7814 Set output variable @code{CXXCPP} to a command that runs the C++
7815 preprocessor.  If @samp{$CXX -E} doesn't work, tries @code{cpp} and
7816 @file{/lib/cpp}, in that order.  Because of this fallback, @code{CXXCPP}
7817 may or may not set C++-specific predefined macros (such as @code{__cplusplus}).
7819 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7820 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7822 Some preprocessors don't indicate missing include files by the error
7823 status.  For such preprocessors an internal variable is set that causes
7824 other macros to check the standard error from the preprocessor and
7825 consider the test failed if any warnings have been reported.  However,
7826 it is not known whether such broken preprocessors exist for C++.
7827 @end defmac
7829 @defmac AC_PROG_CXX_C_O
7830 @acindex{PROG_CXX_C_O}
7831 @cvindex CXX_NO_MINUS_C_MINUS_O
7832 Test whether the C++ compiler accepts the options @option{-c} and
7833 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7834 if it does not.
7835 @end defmac
7838 @node Objective C Compiler
7839 @subsection Objective C Compiler Characteristics
7842 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7843 @acindex{PROG_OBJC}
7844 @evindex OBJC
7845 @evindex OBJCFLAGS
7846 @ovindex OBJC
7847 @ovindex OBJCFLAGS
7848 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7849 set in the environment, check for Objective C compilers.  Set output
7850 variable @code{OBJC} to the name of the compiler found.
7852 This macro may, however, be invoked with an optional first argument
7853 which, if specified, must be a blank-separated list of Objective C compilers to
7854 search for.  This just gives the user an opportunity to specify an
7855 alternative search list for the Objective C compiler.  For example, if you
7856 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7857 like this:
7859 @example
7860 AC_PROG_OBJC([gcc objcc objc])
7861 @end example
7863 If using a compiler that supports GNU Objective C, set shell variable
7864 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7865 already set, set it to @option{-g -O2} for a GNU Objective C
7866 compiler (@option{-O2} on systems where the compiler does not accept
7867 @option{-g}), or @option{-g} for other compilers.
7868 @end defmac
7870 @defmac AC_PROG_OBJCPP
7871 @acindex{PROG_OBJCPP}
7872 @evindex OBJCPP
7873 @ovindex OBJCPP
7874 Set output variable @code{OBJCPP} to a command that runs the Objective C
7875 preprocessor.  If @samp{$OBJC -E} doesn't work, tries @code{cpp} and
7876 @file{/lib/cpp}, in that order.  Because of this fallback, @code{CXXCPP}
7877 may or may not set Objective-C-specific predefined macros (such as
7878 @code{__OBJC__}).
7879 @end defmac
7882 @node Objective C++ Compiler
7883 @subsection Objective C++ Compiler Characteristics
7886 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7887 @acindex{PROG_OBJCXX}
7888 @evindex OBJCXX
7889 @evindex OBJCXXFLAGS
7890 @ovindex OBJCXX
7891 @ovindex OBJCXXFLAGS
7892 Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
7893 set in the environment, check for Objective C++ compilers.  Set output
7894 variable @code{OBJCXX} to the name of the compiler found.
7896 This macro may, however, be invoked with an optional first argument
7897 which, if specified, must be a blank-separated list of Objective C++ compilers
7898 to search for.  This just gives the user an opportunity to specify an
7899 alternative search list for the Objective C++ compiler.  For example, if you
7900 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7901 like this:
7903 @example
7904 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7905 @end example
7907 If using a compiler that supports GNU Objective C++, set shell variable
7908 @code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
7909 already set, set it to @option{-g -O2} for a GNU Objective C++
7910 compiler (@option{-O2} on systems where the compiler does not accept
7911 @option{-g}), or @option{-g} for other compilers.
7912 @end defmac
7914 @defmac AC_PROG_OBJCXXCPP
7915 @acindex{PROG_OBJCXXCPP}
7916 @evindex OBJCXXCPP
7917 @ovindex OBJCXXCPP
7918 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7919 preprocessor.  If @samp{$OBJCXX -E} doesn't work, tries @code{cpp} and
7920 @file{/lib/cpp}, in that order.  Because of this fallback, @code{CXXCPP}
7921 may or may not set Objective-C++-specific predefined macros (such as
7922 @code{__cplusplus} and @code{__OBJC__}).
7923 @end defmac
7926 @node Erlang Compiler and Interpreter
7927 @subsection Erlang Compiler and Interpreter Characteristics
7928 @cindex Erlang
7930 Autoconf defines the following macros for determining paths to the essential
7931 Erlang/OTP programs:
7933 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7934 @acindex{ERLANG_PATH_ERLC}
7935 @evindex ERLC
7936 @evindex ERLCFLAGS
7937 @ovindex ERLC
7938 @ovindex ERLCFLAGS
7939 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7940 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7941 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7942 is not set in the environment, set it to an empty value.
7944 The two optional arguments have the same meaning as the two last arguments of
7945 macro @code{AC_PATH_PROG} for looking for the @command{erlc} program.  For
7946 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7947 directory:
7949 @example
7950 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7951 @end example
7952 @end defmac
7954 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7955 @acindex{ERLANG_NEED_ERLC}
7956 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7957 error message and exits the @command{configure} script if the @command{erlc}
7958 program is not found.
7959 @end defmac
7961 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7962 @acindex{ERLANG_PATH_ERL}
7963 @evindex ERL
7964 @ovindex ERL
7965 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7966 set in the
7967 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7968 complete path of the interpreter command found.
7970 The two optional arguments have the same meaning as the two last arguments of
7971 macro @code{AC_PATH_PROG} for looking for the @command{erl} program.  For
7972 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7973 directory:
7975 @example
7976 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7977 @end example
7978 @end defmac
7980 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7981 @acindex{ERLANG_NEED_ERL}
7982 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7983 error message and exits the @command{configure} script if the @command{erl}
7984 program is not found.
7985 @end defmac
7988 @node Fortran Compiler
7989 @subsection Fortran Compiler Characteristics
7990 @cindex Fortran
7991 @cindex F77
7993 The Autoconf Fortran support is divided into two categories: legacy
7994 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7995 The former are intended for traditional Fortran 77 code, and have output
7996 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7997 are for newer programs that can (or must) compile under the newer
7998 Fortran standards, and have output variables like @code{FC},
7999 @code{FCFLAGS}, and @code{FCLIBS}.
8001 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
8002 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
8003 @code{FC} and @code{F77} macros behave almost identically, and so they
8004 are documented together in this section.
8007 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
8008 @acindex{PROG_F77}
8009 @evindex F77
8010 @evindex FFLAGS
8011 @ovindex F77
8012 @ovindex FFLAGS
8013 @caindex f77_compiler_gnu
8014 @caindex prog_f77_g
8015 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
8016 set in the environment, then check for @code{g77} and @code{f77}, and
8017 then some other names.  Set the output variable @code{F77} to the name
8018 of the compiler found.
8020 This macro may, however, be invoked with an optional first argument
8021 which, if specified, must be a blank-separated list of Fortran 77
8022 compilers to search for.  This just gives the user an opportunity to
8023 specify an alternative search list for the Fortran 77 compiler.  For
8024 example, if you didn't like the default order, then you could invoke
8025 @code{AC_PROG_F77} like this:
8027 @example
8028 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
8029 @end example
8031 If using a compiler that supports GNU Fortran 77,
8032 set the shell variable @code{G77} to @samp{yes}.
8033 If the output variable @code{FFLAGS} was not already set in the
8034 environment, set it to @option{-g -02} for @code{g77} (or @option{-O2}
8035 where the GNU Fortran 77 compiler does not accept @option{-g}), or
8036 @option{-g} for other compilers.
8038 The result of the GNU test is cached in the
8039 @code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
8040 @code{ac_cv_prog_f77_g} variable.
8041 @end defmac
8043 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
8044 @acindex{PROG_FC}
8045 @evindex FC
8046 @evindex FCFLAGS
8047 @ovindex FC
8048 @ovindex FCFLAGS
8049 @caindex fc_compiler_gnu
8050 @caindex prog_fc_g
8051 Determine a Fortran compiler to use.  If @code{FC} is not already set in
8052 the environment, then @code{dialect} is a hint to indicate what Fortran
8053 dialect to search for; the default is to search for the newest available
8054 dialect.  Set the output variable @code{FC} to the name of the compiler
8055 found.
8057 By default, newer dialects are preferred over older dialects, but if
8058 @code{dialect} is specified then older dialects are preferred starting
8059 with the specified dialect.  @code{dialect} can currently be one of
8060 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
8061 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
8062 and no attempt is made to guarantee that a particular language standard
8063 is actually supported.  Thus, it is preferable that you avoid the
8064 @code{dialect} option, and use AC_PROG_FC only for code compatible with
8065 the latest Fortran standard.
8067 This macro may, alternatively, be invoked with an optional first argument
8068 which, if specified, must be a blank-separated list of Fortran
8069 compilers to search for, just as in @code{AC_PROG_F77}.
8071 If using a compiler that supports GNU Fortran,
8072 set the shell variable @code{GFC} to @samp{yes}.
8073 If the output variable @code{FCFLAGS} was not already set in the
8074 environment, then set it to @option{-g -02} for a GNU Fortran compiler (or
8075 @option{-O2} where the compiler does not accept @option{-g}), or
8076 @option{-g} for other compilers.
8078 The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
8079 variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
8080 variable.
8081 @end defmac
8083 @defmac AC_PROG_F77_C_O
8084 @defmacx AC_PROG_FC_C_O
8085 @acindex{PROG_F77_C_O}
8086 @acindex{PROG_FC_C_O}
8087 @cvindex F77_NO_MINUS_C_MINUS_O
8088 @cvindex FC_NO_MINUS_C_MINUS_O
8089 @caindex prog_f77_c_o
8090 @caindex prog_fc_c_o
8091 Test whether the Fortran compiler accepts the options @option{-c} and
8092 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
8093 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
8095 The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
8096 @code{ac_cv_prog_fc_c_o} variable, respectively.
8097 @end defmac
8099 The following macros check for Fortran compiler characteristics.
8100 To check for characteristics not listed here, use
8101 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
8102 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
8103 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
8104 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
8107 @defmac AC_F77_LIBRARY_LDFLAGS
8108 @defmacx AC_FC_LIBRARY_LDFLAGS
8109 @acindex{F77_LIBRARY_LDFLAGS}
8110 @ovindex FLIBS
8111 @acindex{FC_LIBRARY_LDFLAGS}
8112 @ovindex FCLIBS
8113 @caindex prog_f77_v
8114 @caindex prog_fc_v
8115 @caindex f77_libs
8116 @caindex fc_libs
8117 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
8118 @dfn{Fortran intrinsic and runtime libraries} that are required to
8119 successfully link a Fortran program or shared library.  The output
8120 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
8121 should be included after @code{LIBS} when linking).
8123 This macro is intended to be used in those situations when it is
8124 necessary to mix, e.g., C++ and Fortran source code in a single
8125 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
8126 automake, GNU Automake}).
8128 For example, if object files from a C++ and Fortran compiler must be
8129 linked together, then the C++ compiler/linker must be used for linking
8130 (since special C++-ish things need to happen at link time like calling
8131 global constructors, instantiating templates, enabling exception
8132 support, etc.).
8134 However, the Fortran intrinsic and runtime libraries must be linked in
8135 as well, but the C++ compiler/linker doesn't know by default how to add
8136 these Fortran 77 libraries.  Hence, this macro was created to determine
8137 these Fortran libraries.
8139 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8140 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
8141 link C/C++ with Fortran; see below.  Further, it is highly recommended
8142 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
8143 because the complex defines that the function wrapper macros create
8144 may not work with C/C++ compiler drivers.
8146 These macros internally compute the flag needed to verbose linking
8147 output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
8148 variables, respectively.  The computed linker flags are cached in
8149 @code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
8150 @end defmac
8152 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @
8153   @dvar{action-if-not-found, AC_MSG_FAILURE})
8154 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @
8155   @dvar{action-if-not-found, AC_MSG_FAILURE})
8156 @acindex{F77_DUMMY_MAIN}
8157 @cvindex F77_DUMMY_MAIN
8158 @acindex{FC_DUMMY_MAIN}
8159 @cvindex FC_DUMMY_MAIN
8160 @caindex f77_dummy_main
8161 @caindex fc_dummy_main
8162 With many compilers, the Fortran libraries detected by
8163 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
8164 their own @code{main} entry function that initializes things like
8165 Fortran I/O, and which then calls a user-provided entry function named
8166 (say) @code{MAIN__} to run the user's program.  The
8167 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8168 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
8169 this interaction.
8171 When using Fortran for purely numerical functions (no I/O, etc.)@: often
8172 one prefers to provide one's own @code{main} and skip the Fortran
8173 library initializations.  In this case, however, one may still need to
8174 provide a dummy @code{MAIN__} routine in order to prevent linking errors
8175 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8176 detects whether any such routine is @emph{required} for linking, and
8177 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8178 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8179 was found, and @code{none} when no such dummy main is needed.
8181 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8182 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8183 @emph{if} it is required.  @var{action-if-not-found} defaults to
8184 exiting with an error.
8186 In order to link with Fortran routines, the user's C/C++ program should
8187 then include the following code to define the dummy main if it is
8188 needed:
8190 @example
8191 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8192 #ifdef F77_DUMMY_MAIN
8193 #  ifdef __cplusplus
8194      extern "C"
8195 #  endif
8196    int F77_DUMMY_MAIN () @{ return 1; @}
8197 #endif
8198 @end example
8200 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8202 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8203 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8204 explicitly unless one wants to change the default actions.
8206 The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8207 @code{ac_cv_fc_dummy_main} variable, respectively.
8208 @end defmac
8210 @defmac AC_F77_MAIN
8211 @defmacx AC_FC_MAIN
8212 @acindex{F77_MAIN}
8213 @cvindex F77_MAIN
8214 @acindex{FC_MAIN}
8215 @cvindex FC_MAIN
8216 @caindex f77_main
8217 @caindex fc_main
8218 As discussed above, many Fortran libraries allow you to provide an entry
8219 point called (say) @code{MAIN__} instead of the usual @code{main}, which
8220 is then called by a @code{main} function in the Fortran libraries that
8221 initializes things like Fortran I/O@.  The
8222 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8223 @emph{possible} to utilize such an alternate main function, and defines
8224 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
8225 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8226 simply defined to @code{main}.)
8228 Thus, when calling Fortran routines from C that perform things like I/O,
8229 one should use this macro and declare the "main" function like so:
8231 @example
8232 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8233 #ifdef __cplusplus
8234   extern "C"
8235 #endif
8236 int F77_MAIN (int argc, char *argv[]);
8237 @end example
8239 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8241 The result of this macro is cached in the @code{ac_cv_f77_main} or
8242 @code{ac_cv_fc_main} variable, respectively.
8243 @end defmac
8245 @defmac AC_F77_WRAPPERS
8246 @defmacx AC_FC_WRAPPERS
8247 @acindex{F77_WRAPPERS}
8248 @cvindex F77_FUNC
8249 @cvindex F77_FUNC_
8250 @acindex{FC_WRAPPERS}
8251 @cvindex FC_FUNC
8252 @cvindex FC_FUNC_
8253 @caindex f77_mangling
8254 @caindex fc_mangling
8255 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8256 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8257 mangle the names of C/C++ identifiers, and identifiers with underscores,
8258 respectively, so that they match the name-mangling scheme used by the
8259 Fortran compiler.
8261 Fortran is case-insensitive, and in order to achieve this the Fortran
8262 compiler converts all identifiers into a canonical case and format.  To
8263 call a Fortran subroutine from C or to write a C function that is
8264 callable from Fortran, the C program must explicitly use identifiers in
8265 the format expected by the Fortran compiler.  In order to do this, one
8266 simply wraps all C identifiers in one of the macros provided by
8267 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
8268 you have the following Fortran 77 subroutine:
8270 @example
8271 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8272       subroutine foobar (x, y)
8273       double precision x, y
8274       y = 3.14159 * x
8275       return
8276       end
8277 @end example
8279 You would then declare its prototype in C or C++ as:
8281 @example
8282 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8283 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8284 #ifdef __cplusplus
8285 extern "C"  /* prevent C++ name mangling */
8286 #endif
8287 void FOOBAR_F77 (double *x, double *y);
8288 @end example
8290 Note that we pass both the lowercase and uppercase versions of the
8291 function name to @code{F77_FUNC} so that it can select the right one.
8292 Note also that all parameters to Fortran 77 routines are passed as
8293 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8294 Automake}).
8296 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8298 Although Autoconf tries to be intelligent about detecting the
8299 name-mangling scheme of the Fortran compiler, there may be Fortran
8300 compilers that it doesn't support yet.  In this case, the above code
8301 generates a compile-time error, but some other behavior
8302 (e.g., disabling Fortran-related features) can be induced by checking
8303 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8305 Now, to call that routine from a C program, we would do something like:
8307 @example
8308 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8310     double x = 2.7183, y;
8311     FOOBAR_F77 (&x, &y);
8313 @end example
8315 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8316 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8317 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
8318 because some Fortran compilers mangle names differently if they contain
8319 an underscore.
8321 The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8322 @code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8323 the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8324 @end defmac
8326 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8327 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8328 @acindex{F77_FUNC}
8329 @acindex{FC_FUNC}
8330 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8331 hold the mangled version @var{name} according to the rules of the
8332 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8333 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
8334 supplied, the shell variable is simply @var{name}.  The purpose of
8335 this macro is to give the caller a way to access the name-mangling
8336 information other than through the C preprocessor as above, for example,
8337 to call Fortran routines from some language other than C/C++.
8338 @end defmac
8340 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8341   @dvar{action-if-failure, AC_MSG_FAILURE})
8342 @defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8343   @dvar{action-if-failure, AC_MSG_FAILURE})
8344 @acindex{FC_SRCEXT}
8345 @acindex{FC_PP_SRCEXT}
8346 @caindex fc_srcext_@var{ext}
8347 @caindex fc_pp_srcext_@var{ext}
8348 By default, the @code{FC} macros perform their tests using a @file{.f}
8349 extension for source-code files.  Some compilers, however, only enable
8350 newer language features for appropriately named files, e.g., Fortran 90
8351 features only for @file{.f90} files, or preprocessing only with
8352 @file{.F} files or maybe other upper-case extensions.  On the other
8353 hand, some other compilers expect all source files to end in @file{.f}
8354 and require special flags to support other file name extensions.  The
8355 @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8356 issues.
8358 The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8359 accept files ending with the extension @file{.@var{ext}} (i.e.,
8360 @var{ext} does @emph{not} contain the dot).  If any special compiler
8361 flags are needed for this, it stores them in the output variable
8362 @code{FCFLAGS_@var{ext}}.  This extension and these flags are then used
8363 for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8364 @code{AC_FC_PP_SRCEXT} is called another time).
8366 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8367 @file{.f90} extension in future tests, and it would set the
8368 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8369 to compile such files.
8371 Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8372 compiler to preprocess and compile files with the extension
8373 @file{.@var{ext}}.  When both @command{fpp} and @command{cpp} style
8374 preprocessing are provided, the former is preferred, as the latter may
8375 treat continuation lines, @code{//} tokens, and white space differently
8376 from what some Fortran dialects expect.  Conversely, if you do not want
8377 files to be preprocessed, use only lower-case characters in the file
8378 name extension.  Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8379 are stored in the @code{FCFLAGS_@var{ext}} variable.
8381 The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8382 into @code{FCFLAGS}, for two reasons based on the limitations of some
8383 compilers.  First, only one @code{FCFLAGS_@var{ext}} can be used at a
8384 time, so files with different extensions must be compiled separately.
8385 Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8386 the source-code file name when compiling.  So, continuing the example
8387 above, you might compile a @file{foo.f90} file in your makefile with the
8388 command:
8390 @example
8391 foo.o: foo.f90
8392        $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8393 @end example
8395 If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8396 files with the @var{ext} extension, it calls @var{action-if-success}
8397 (defaults to nothing).  If it fails, and cannot find a way to make the
8398 @code{FC} compiler accept such files, it calls @var{action-if-failure}
8399 (defaults to exiting with an error message).
8401 The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8402 results in @code{ac_cv_fc_srcext_@var{ext}} and
8403 @code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8404 @end defmac
8406 @defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @
8407   @dvar{action-if-failure, AC_MSG_FAILURE})
8408 @acindex{FC_PP_DEFINE}
8409 @caindex fc_pp_define
8411 Find a flag to specify defines for preprocessed Fortran.  Not all
8412 Fortran compilers use @option{-D}.  Substitute @code{FC_DEFINE} with
8413 the result and call @var{action-if-success} (defaults to nothing) if
8414 successful, and @var{action-if-failure} (defaults to failing with an
8415 error message) if not.
8417 This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8418 preprocess a @file{conftest.F} file, but restores a previously used
8419 Fortran source file extension afterwards again.
8421 The result of this test is cached in the @code{ac_cv_fc_pp_define}
8422 variable.
8423 @end defmac
8425 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @
8426   @dvar{action-if-failure, AC_MSG_FAILURE})
8427 @acindex{FC_FREEFORM}
8428 @caindex fc_freeform
8430 Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8431 source code (as opposed to the older fixed-format style from Fortran
8432 77).  If necessary, it may add some additional flags to @code{FCFLAGS}.
8434 This macro is most important if you are using the default @file{.f}
8435 extension, since many compilers interpret this extension as indicating
8436 fixed-format source unless an additional flag is supplied.  If you
8437 specify a different extension with @code{AC_FC_SRCEXT}, such as
8438 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8439 modifying @code{FCFLAGS}.  For extensions which the compiler does not
8440 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8441 the compiler assume Fortran 77 by default, however.
8443 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8444 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8445 calls @var{action-if-failure} (defaults to exiting with an error
8446 message).
8448 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8449 the @code{ac_cv_fc_freeform} variable.
8450 @end defmac
8452 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @
8453   @dvar{action-if-failure, AC_MSG_FAILURE})
8454 @acindex{FC_FIXEDFORM}
8455 @caindex fc_fixedform
8457 Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8458 fixed-format source code (as opposed to free-format style).  If
8459 necessary, it may add some additional flags to @code{FCFLAGS}.
8461 This macro is needed for some compilers alias names like @command{xlf95}
8462 which assume free-form source code by default, and in case you want to
8463 use fixed-form source with an extension like @file{.f90} which many
8464 compilers interpret as free-form by default.  If you specify a different
8465 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8466 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8467 @code{FCFLAGS}.
8469 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8470 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8471 calls @var{action-if-failure} (defaults to exiting with an error
8472 message).
8474 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8475 the @code{ac_cv_fc_fixedform} variable.
8476 @end defmac
8478 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8479   @dvar{action-if-failure, AC_MSG_FAILURE})
8480 @acindex{FC_LINE_LENGTH}
8481 @caindex fc_line_length
8483 Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8484 code lines.  The @var{length} argument may be given as 80, 132, or
8485 unlimited, and defaults to 132.  Note that line lengths above 250
8486 columns are not portable, and some compilers do not accept more than 132
8487 columns at least for fixed format source.  If necessary, it may add some
8488 additional flags to @code{FCFLAGS}.
8490 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8491 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8492 calls @var{action-if-failure} (defaults to exiting with an error
8493 message).
8495 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8496 the @code{ac_cv_fc_line_length} variable.
8497 @end defmac
8499 @defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8500   @dvar{action-if-failure, AC_MSG_FAILURE})
8501 @acindex{FC_CHECK_BOUNDS}
8502 @caindex fc_check_bounds
8504 The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8505 in the Fortran compiler.  If successful, the @var{action-if-success}
8506 is called and any needed flags are added to @code{FCFLAGS}.  Otherwise,
8507 @var{action-if-failure} is called, which defaults to failing with an error
8508 message.  The macro currently requires Fortran 90 or a newer dialect.
8510 The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8511 variable.
8512 @end defmac
8514 @defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8515   @dvar{action-if-failure, AC_MSG_FAILURE})
8516 @defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8517   @dvar{action-if-failure, AC_MSG_FAILURE})
8518 @acindex{F77_IMPLICIT_NONE}
8519 @acindex{FC_IMPLICIT_NONE}
8520 @caindex f77_implicit_none
8521 @caindex fc_implicit_none
8523 Try to disallow implicit declarations in the Fortran compiler.  If
8524 successful, @var{action-if-success} is called and any needed flags
8525 are added to @code{FFLAGS} or @code{FCFLAGS}, respectively.  Otherwise,
8526 @var{action-if-failure} is called, which defaults to failing with an error
8527 message.
8529 The result of these macros are cached in the
8530 @code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8531 variables, respectively.
8532 @end defmac
8534 @defmac AC_FC_MODULE_EXTENSION
8535 @acindex{FC_MODULE_EXTENSION}
8536 @caindex fc_module_ext
8537 @ovindex FC_MODEXT
8539 Find the Fortran 90 module file name extension.  Most Fortran 90
8540 compilers store module information in files separate from the object
8541 files.  The module files are usually named after the name of the module
8542 rather than the source file name, with characters possibly turned to
8543 upper case, plus an extension, often @file{.mod}.
8545 Not all compilers use module files at all, or by default.  The Cray
8546 Fortran compiler requires @option{-e m} in order to store and search
8547 module information in @file{.mod} files rather than in object files.
8548 Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8549 indicate how module information is stored.
8551 The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8552 without the leading dot, and stores that in the @code{FC_MODEXT}
8553 variable.  If the compiler does not produce module files, or the
8554 extension cannot be determined, @code{FC_MODEXT} is empty.  Typically,
8555 the result of this macro may be used in cleanup @command{make} rules as
8556 follows:
8558 @example
8559 clean-modules:
8560         -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8561 @end example
8563 The extension, or @samp{unknown}, is cached in the
8564 @code{ac_cv_fc_module_ext} variable.
8565 @end defmac
8567 @defmac AC_FC_MODULE_FLAG (@ovar{action-if-success}, @
8568   @dvar{action-if-failure, AC_MSG_FAILURE})
8569 @acindex{FC_MODULE_FLAG}
8570 @caindex fc_module_flag
8571 @ovindex FC_MODINC
8572 @ovindex ac_empty
8574 Find the compiler flag to include Fortran 90 module information from
8575 another directory, and store that in the @code{FC_MODINC} variable.
8576 Call @var{action-if-success} (defaults to nothing) if successful, and
8577 set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8578 to exiting with an error message) if not.
8580 Most Fortran 90 compilers provide a way to specify module directories.
8581 Some have separate flags for the directory to write module files to,
8582 and directories to search them in, whereas others only allow writing to
8583 the current directory or to the first directory specified in the include
8584 path.  Further, with some compilers, the module search path and the
8585 preprocessor search path can only be modified with the same flag.  Thus,
8586 for portability, write module files to the current directory only and
8587 list that as first directory in the search path.
8589 There may be no whitespace between @code{FC_MODINC} and the following
8590 directory name, but @code{FC_MODINC} may contain trailing white space.
8591 For example, if you use Automake and would like to search @file{../lib}
8592 for module files, you can use the following:
8594 @example
8595 AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8596 @end example
8598 Inside @command{configure} tests, you can use:
8600 @example
8601 if test -n "$FC_MODINC"; then
8602   FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8604 @end example
8606 The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8607 The substituted value of @code{FC_MODINC} may refer to the
8608 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8609 the significant trailing whitespace in a @file{Makefile}.
8610 @end defmac
8612 @defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-success}, @
8613   @dvar{action-if-failure, AC_MSG_FAILURE})
8614 @acindex{FC_MODULE_OUTPUT_FLAG}
8615 @caindex fc_module_output_flag
8616 @ovindex FC_MODOUT
8618 Find the compiler flag to write Fortran 90 module information to
8619 another directory, and store that in the @code{FC_MODOUT} variable.
8620 Call @var{action-if-success} (defaults to nothing) if successful, and
8621 set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8622 to exiting with an error message) if not.
8624 Not all Fortran 90 compilers write module files, and of those that do,
8625 not all allow writing to a directory other than the current one, nor
8626 do all have separate flags for writing and reading; see the description
8627 of @code{AC_FC_MODULE_FLAG} above.  If you need to be able to write to
8628 another directory, for maximum portability use @code{FC_MODOUT} before
8629 any @code{FC_MODINC} and include both the current directory and the one
8630 you write to in the search path:
8632 @example
8633 AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8634 @end example
8636 The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8637 The substituted value of @code{FC_MODOUT} may refer to the
8638 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8639 the significant trailing whitespace in a @file{Makefile}.
8640 @end defmac
8643 @node Go Compiler
8644 @subsection Go Compiler Characteristics
8645 @cindex Go
8647 Autoconf provides basic support for the Go programming language when
8648 using the @code{gccgo} compiler (there is currently no support for the
8649 @code{6g} and @code{8g} compilers).
8651 @defmac AC_PROG_GO (@ovar{compiler-search-list})
8652 Find the Go compiler to use.  Check whether the environment variable
8653 @code{GOC} is set; if so, then set output variable @code{GOC} to its
8654 value.
8656 Otherwise, if the macro is invoked without an argument, then search for
8657 a Go compiler named @code{gccgo}.  If it is not found, then as a last
8658 resort set @code{GOC} to @code{gccgo}.
8660 This macro may be invoked with an optional first argument which, if
8661 specified, must be a blank-separated list of Go compilers to search for.
8663 If output variable @code{GOFLAGS} was not already set, set it to
8664 @option{-g -O2}.  If your package does not like this default,
8665 @code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8666 @end defmac
8669 @node System Services
8670 @section System Services
8672 The following macros check for operating system services or capabilities.
8674 @anchor{AC_PATH_X}
8675 @defmac AC_PATH_X
8676 @acindex{PATH_X}
8677 @evindex XMKMF
8678 @cindex X Window System
8679 Try to locate the X Window System include files and libraries.  If the
8680 user gave the command line options @option{--x-includes=@var{dir}} and
8681 @option{--x-libraries=@var{dir}}, use those directories.
8683 If either or both were not given, get the missing values by running
8684 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8685 environment variable) on a trivial @file{Imakefile} and examining the
8686 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8687 disables this method.
8689 If this method fails to find the X Window System, @command{configure}
8690 looks for the files in several directories where they often reside.
8691 If either method is successful, set the shell variables
8692 @code{x_includes} and @code{x_libraries} to their locations, unless they
8693 are in directories the compiler searches by default.
8695 If both methods fail, or the user gave the command line option
8696 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8697 otherwise set it to the empty string.
8698 @end defmac
8700 @anchor{AC_PATH_XTRA}
8701 @defmac AC_PATH_XTRA
8702 @acindex{PATH_XTRA}
8703 @ovindex X_CFLAGS
8704 @ovindex X_LIBS
8705 @ovindex X_EXTRA_LIBS
8706 @ovindex X_PRE_LIBS
8707 @cvindex X_DISPLAY_MISSING
8708 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8709 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8710 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8711 available.
8713 This macro also checks for special libraries that some systems need in
8714 order to compile X programs.  It adds any that the system needs to
8715 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8716 libraries that need to be linked with before @option{-lX11}, and adds
8717 any found to the output variable @code{X_PRE_LIBS}.
8719 @c This is an incomplete kludge.  Make a real way to do it.
8720 @c If you need to check for other X functions or libraries yourself, then
8721 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8722 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8723 @end defmac
8725 @anchor{AC_SYS_INTERPRETER}
8726 @defmac AC_SYS_INTERPRETER
8727 @acindex{SYS_INTERPRETER}
8728 Check whether the system supports starting scripts with a line of the
8729 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8730 After running this macro, shell code in @file{configure.ac} can check
8731 the shell variable @code{interpval}; it is set to @samp{yes}
8732 if the system supports @samp{#!}, @samp{no} if not.
8733 @end defmac
8735 @defmac AC_SYS_LARGEFILE
8736 @acindex{SYS_LARGEFILE}
8737 @cvindex _FILE_OFFSET_BITS
8738 @cvindex _LARGE_FILES
8739 @ovindex CC
8740 @cindex Large file support
8741 @cindex LFS
8742 Arrange for 64-bit file offsets, known as
8743 @uref{http://@/www.unix.org/@/version2/@/whatsnew/@/lfs20mar.html,
8744 large-file support}.  On some hosts, one must use special compiler
8745 options to build programs that can access large files.  Append any such
8746 options to the output variable @code{CC}.  Define
8747 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8749 Large-file support can be disabled by configuring with the
8750 @option{--disable-largefile} option.
8752 If you use this macro, check that your program works even when
8753 @code{off_t} is wider than @code{long int}, since this is common when
8754 large-file support is enabled.  For example, it is not correct to print
8755 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8756 (long int) X)}.  Also, when using this macro in concert with
8757 @code{AC_CONFIG_HEADERS}, be sure that @file{config.h} is included
8758 before any system header.
8760 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8761 replace their C counterparts @code{fseek} and @code{ftell} that do not
8762 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8763 prototypes available when using them and large-file support is
8764 enabled.
8765 @end defmac
8767 @anchor{AC_SYS_LONG_FILE_NAMES}
8768 @defmac AC_SYS_LONG_FILE_NAMES
8769 @acindex{SYS_LONG_FILE_NAMES}
8770 @cvindex HAVE_LONG_FILE_NAMES
8771 If the system supports file names longer than 14 characters, define
8772 @code{HAVE_LONG_FILE_NAMES}.
8773 @end defmac
8775 @defmac AC_SYS_POSIX_TERMIOS
8776 @acindex{SYS_POSIX_TERMIOS}
8777 @cindex Posix termios headers
8778 @cindex termios Posix headers
8779 @caindex sys_posix_termios
8780 Check to see if the Posix termios headers and functions are available on the
8781 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8782 @samp{yes}.  If not, set the variable to @samp{no}.
8783 @end defmac
8785 @node C and Posix Variants
8786 @section C and Posix Variants
8788 The following macro makes it possible to use C language and library
8789 extensions defined by the C standards committee, features of Posix that
8790 are extensions to C, and platform extensions not defined by Posix.
8792 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8793 @defmac AC_USE_SYSTEM_EXTENSIONS
8794 @acindex{USE_SYSTEM_EXTENSIONS}
8795 If possible, enable extensions to C or Posix on hosts that normally
8796 disable the extensions, typically due to standards-conformance namespace
8797 issues.  This should be called before any macros that run the C
8798 compiler.  Also, when using this macro in concert with
8799 @code{AC_CONFIG_HEADERS}, be sure that @file{config.h} is included
8800 before any system header.  The following preprocessor macros are defined
8801 where appropriate:
8803 @table @code
8804 @item _GNU_SOURCE
8805 @cvindex _GNU_SOURCE
8806 Enable extensions on GNU/Linux.
8807 @item _ALL_SOURCE
8808 @cvindex _ALL_SOURCE
8809 Enable extensions for AIX 3, and for Interix.
8810 @item _DARWIN_C_SOURCE
8811 @cvindex _DARWIN_C_SOURCE
8812 Enable extensions for macOS.
8813 @item _MINIX
8814 @cvindex _MINIX
8815 Identify Minix platform.  This particular preprocessor macro is
8816 obsolescent, and may be removed in a future release of Autoconf.
8817 @item _NETBSD_SOURCE
8818 @cvindex _NETBSD_SOURCE
8819 Enable NetBSD-related extensions for Minix.
8820 @item _POSIX_1_SOURCE
8821 @cvindex _POSIX_1_SOURCE
8822 Enable additional Posix functions for Minix.
8823 @item _POSIX_PTHREAD_SEMANTICS
8824 @cvindex _POSIX_PTHREAD_SEMANTICS
8825 Enable threading extensions on Solaris.
8826 @item _POSIX_SOURCE
8827 @cvindex _POSIX_SOURCE
8828 Enable Posix functions for Minix.
8829 @item _TANDEM_SOURCE
8830 @cvindex _TANDEM_SOURCE
8831 Enable extensions for the HP NonStop platform.
8832 @item _XOPEN_SOURCE
8833 @cvindex _XOPEN_SOURCE
8834 Enable X/Open extensions for HP-UX.
8835 @item __EXTENSIONS__
8836 @cvindex __EXTENSIONS__
8837 Enable general extensions on Solaris.
8838 @item __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8839 @cvindex __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8840 Enable extensions specified by ISO/IEC TS 18661-5:2014.
8841 @item __STDC_WANT_IEC_60559_BFP_EXT__
8842 @cvindex __STDC_WANT_IEC_60559_BFP_EXT__
8843 Enable extensions specified by ISO/IEC TS 18661-1:2014.
8844 @item __STDC_WANT_IEC_60559_DFP_EXT__
8845 @cvindex __STDC_WANT_IEC_60559_DFP_EXT__
8846 Enable extensions specified by ISO/IEC TS 18661-2:2015.
8847 @item __STDC_WANT_IEC_60559_FUNCS_EXT__
8848 @cvindex __STDC_WANT_IEC_60559_FUNCS_EXT__
8849 Enable extensions specified by ISO/IEC TS 18661-4:2015.
8850 @item __STDC_WANT_IEC_60559_TYPES_EXT__
8851 @cvindex __STDC_WANT_IEC_60559_TYPES_EXT__
8852 Enable extensions specified by ISO/IEC TS 18661-3:2015.
8853 @item __STDC_WANT_LIB_EXT2__
8854 @cvindex __STDC_WANT_LIB_EXT2__
8855 Enable extensions specified by ISO/IEC TR 24731-2:2010.
8856 @item __STDC_WANT_MATH_SPEC_FUNCS__
8857 @cvindex __STDC_WANT_MATH_SPEC_FUNCS__
8858 Enable extensions specified by ISO/IEC 24747:2009.
8859 @end table
8861 @cvindex __STDC_WANT_DEC_FP__
8862 The C preprocessor macro @code{__STDC_WANT_DEC_FP__} is not defined.
8863 ISO/IEC TR 24732:2009 was superseded by ISO/IEC TS 18661-2:2015.
8865 @cvindex __STDC_WANT_LIB_EXT1__
8866 The C preprocessor macro @code{__STDC_WANT_LIB_EXT1__} is not defined,
8867 as C11 Annex K is problematic.  See: O'Donell C, Sebor M.
8868 @uref{http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm, Field
8869 Experience With Annex K---Bounds Checking Interfaces}.
8871 The Autoconf macro @code{AC_USE_SYSTEM_EXTENSIONS} was introduced in
8872 Autoconf 2.60.
8873 @end defmac
8876 @node Erlang Libraries
8877 @section Erlang Libraries
8878 @cindex Erlang, Library, checking
8880 The following macros check for an installation of Erlang/OTP, and for the
8881 presence of certain Erlang libraries.  All those macros require the
8882 configuration of an Erlang interpreter and an Erlang compiler
8883 (@pxref{Erlang Compiler and Interpreter}).
8885 @defmac AC_ERLANG_SUBST_ERTS_VER
8886 @acindex{ERLANG_SUBST_ERTS_VER}
8887 @ovindex ERLANG_ERTS_VER
8888 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8889 Erlang runtime system (as returned by Erlang's
8890 @code{erlang:system_info(version)} function).  The result of this test
8891 is cached if caching is enabled when running @command{configure}.  The
8892 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8893 for features of specific ERTS versions, but to be used for substituting
8894 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8895 files), as shown below.
8896 @end defmac
8898 @defmac AC_ERLANG_SUBST_ROOT_DIR
8899 @acindex{ERLANG_SUBST_ROOT_DIR}
8900 @ovindex ERLANG_ROOT_DIR
8901 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8902 directory in which Erlang/OTP is installed (as returned by Erlang's
8903 @code{code:root_dir/0} function).  The result of this test is cached if
8904 caching is enabled when running @command{configure}.
8905 @end defmac
8907 @defmac AC_ERLANG_SUBST_LIB_DIR
8908 @acindex{ERLANG_SUBST_LIB_DIR}
8909 @ovindex ERLANG_LIB_DIR
8910 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8911 directory of Erlang/OTP (as returned by Erlang's
8912 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8913 Erlang/OTP library.  The result of this test is cached if caching is enabled
8914 when running @command{configure}.
8915 @end defmac
8917 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8918   @ovar{action-if-not-found})
8919 @acindex{ERLANG_CHECK_LIB}
8920 @ovindex ERLANG_LIB_DIR_@var{library}
8921 @ovindex ERLANG_LIB_VER_@var{library}
8922 Test whether the Erlang/OTP library @var{library} is installed by
8923 calling Erlang's @code{code:lib_dir/1} function.  The result of this
8924 test is cached if caching is enabled when running @command{configure}.
8925 @var{action-if-found} is a list of shell commands to run if the library
8926 is installed; @var{action-if-not-found} is a list of shell commands to
8927 run if it is not.  Additionally, if the library is installed, the output
8928 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8929 library installation directory, and the output variable
8930 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8931 part of the subdirectory name, if it is in the standard form
8932 (@code{@var{library}-@var{version}}).  If the directory name does not
8933 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8934 empty string.  If the library is not installed,
8935 @samp{ERLANG_LIB_DIR_@var{library}} and
8936 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
8937 example, to check if library @code{stdlib} is installed:
8939 @example
8940 AC_ERLANG_CHECK_LIB([stdlib],
8941   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8942    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8943   [AC_MSG_ERROR([stdlib was not found!])])
8944 @end example
8946 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8947 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8948 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8949 testing for features of specific versions of libraries or of the Erlang
8950 runtime system.  Those variables are intended to be substituted in
8951 Erlang release resource files (@code{.rel} files).  For instance, to
8952 generate a @file{example.rel} file for an application depending on the
8953 @code{stdlib} library, @file{configure.ac} could contain:
8955 @example
8956 AC_ERLANG_SUBST_ERTS_VER
8957 AC_ERLANG_CHECK_LIB([stdlib],
8958   [],
8959   [AC_MSG_ERROR([stdlib was not found!])])
8960 AC_CONFIG_FILES([example.rel])
8961 @end example
8963 @noindent
8964 The @file{example.rel.in} file used to generate @file{example.rel}
8965 should contain:
8967 @example
8968 @{release,
8969     @{"@@PACKAGE@@", "@@VERSION@@"@},
8970     @{erts, "@@ERLANG_ERTS_VER@@"@},
8971     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8972      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8973 @end example
8974 @end defmac
8976 In addition to the above macros, which test installed Erlang libraries, the
8977 following macros determine the paths to the directories into which newly built
8978 Erlang libraries are to be installed:
8980 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8981 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8982 @ovindex ERLANG_INSTALL_LIB_DIR
8984 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8985 which every built Erlang library should be installed in a separate
8986 subdirectory.
8987 If this variable is not set in the environment when @command{configure} runs,
8988 its default value is @code{$@{libdir@}/erlang/lib}.
8989 @end defmac
8991 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8992 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8993 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8995 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8996 directory into which the built Erlang library @var{library} version
8997 @var{version} should be installed.  If this variable is not set in the
8998 environment when @command{configure} runs, its default value is
8999 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
9000 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
9001 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
9002 @end defmac
9008 @c ========================================================= Writing Tests
9010 @node Writing Tests
9011 @chapter Writing Tests
9013 If the existing feature tests don't do something you need, you have to
9014 write new ones.  These macros are the building blocks.  They provide
9015 ways for other macros to check whether various kinds of features are
9016 available and report the results.
9018 This chapter contains some suggestions and some of the reasons why the
9019 existing tests are written the way they are.  You can also learn a lot
9020 about how to write Autoconf tests by looking at the existing ones.  If
9021 something goes wrong in one or more of the Autoconf tests, this
9022 information can help you understand the assumptions behind them, which
9023 might help you figure out how to best solve the problem.
9025 These macros check the output of the compiler system of the current
9026 language (@pxref{Language Choice}).  They do not cache the results of
9027 their tests for future use (@pxref{Caching Results}), because they don't
9028 know enough about the information they are checking for to generate a
9029 cache variable name.  They also do not print any messages, for the same
9030 reason.  The checks for particular kinds of features call these macros
9031 and do cache their results and print messages about what they're
9032 checking for.
9034 When you write a feature test that could be applicable to more than one
9035 software package, the best thing to do is encapsulate it in a new macro.
9036 @xref{Writing Autoconf Macros}, for how to do that.
9038 @menu
9039 * Language Choice::             Selecting which language to use for testing
9040 * Writing Test Programs::       Forging source files for compilers
9041 * Running the Preprocessor::    Detecting preprocessor symbols
9042 * Running the Compiler::        Detecting language or header features
9043 * Running the Linker::          Detecting library features
9044 * Runtime::                     Testing for runtime features
9045 * Systemology::                 A zoology of operating systems
9046 * Multiple Cases::              Tests for several possible values
9047 @end menu
9049 @node Language Choice
9050 @section Language Choice
9051 @cindex Language
9053 Autoconf-generated @command{configure} scripts check for the C compiler and
9054 its features by default.  Packages that use other programming languages
9055 (maybe more than one, e.g., C and C++) need to test features of the
9056 compilers for the respective languages.  The following macros determine
9057 which programming language is used in the subsequent tests in
9058 @file{configure.ac}.
9060 @anchor{AC_LANG}
9061 @defmac AC_LANG (@var{language})
9062 @acindex{LANG}
9063 Do compilation tests using the compiler, preprocessor, and file
9064 extensions for the specified @var{language}.
9066 Supported languages are:
9068 @table @samp
9069 @item C
9070 Do compilation tests using @code{CC} and @code{CPP} and use extension
9071 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
9072 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
9074 @item C++
9075 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
9076 extension @file{.C} for test programs.  Use compilation flags:
9077 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
9078 @code{CXXFLAGS} with @code{CXX}.
9080 @item Fortran 77
9081 Do compilation tests using @code{F77} and use extension @file{.f} for
9082 test programs.  Use compilation flags: @code{FFLAGS}.
9084 @item Fortran
9085 Do compilation tests using @code{FC} and use extension @file{.f} (or
9086 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
9087 compilation flags: @code{FCFLAGS}.
9089 @item Erlang
9090 @ovindex ERLC
9091 @ovindex ERL
9092 @ovindex ERLCFLAGS
9093 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
9094 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
9096 @item Objective C
9097 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
9098 extension @file{.m} for test programs.  Use compilation flags:
9099 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
9100 @code{OBJCFLAGS} with @code{OBJC}.
9102 @item Objective C++
9103 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
9104 extension @file{.mm} for test programs.  Use compilation flags:
9105 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
9106 @code{OBJCXXFLAGS} with @code{OBJCXX}.
9108 @item Go
9109 Do compilation tests using @code{GOC} and use extension @file{.go} for
9110 test programs.  Use compilation flags @code{GOFLAGS}.
9111 @end table
9112 @end defmac
9114 @anchor{AC_LANG_PUSH}
9115 @defmac AC_LANG_PUSH (@var{language})
9116 @acindex{LANG_PUSH}
9117 Remember the current language (as set by @code{AC_LANG}) on a stack, and
9118 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
9119 in macros that need to temporarily switch to a particular language.
9120 @end defmac
9122 @defmac AC_LANG_POP (@ovar{language})
9123 @acindex{LANG_POP}
9124 Select the language that is saved on the top of the stack, as set by
9125 @code{AC_LANG_PUSH}, and remove it from the stack.
9127 If given, @var{language} specifies the language we just @emph{quit}.  It
9128 is a good idea to specify it when it's known (which should be the
9129 case@dots{}), since Autoconf detects inconsistencies.
9131 @example
9132 AC_LANG_PUSH([Fortran 77])
9133 # Perform some tests on Fortran 77.
9134 # @dots{}
9135 AC_LANG_POP([Fortran 77])
9136 @end example
9137 @end defmac
9139 @defmac AC_LANG_ASSERT (@var{language})
9140 @acindex{LANG_ASSERT}
9141 Check statically that the current language is @var{language}.
9142 You should use this in your language specific macros
9143 to avoid that they be called with an inappropriate language.
9145 This macro runs only at @command{autoconf} time, and incurs no cost at
9146 @command{configure} time.  Sadly enough and because Autoconf is a two
9147 layer language @footnote{Because M4 is not aware of Sh code,
9148 especially conditionals, some optimizations that look nice statically
9149 may produce incorrect results at runtime.}, the macros
9150 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
9151 therefore as much as possible you ought to avoid using them to wrap
9152 your code, rather, require from the user to run the macro with a
9153 correct current language, and check it with @code{AC_LANG_ASSERT}.
9154 And anyway, that may help the user understand she is running a Fortran
9155 macro while expecting a result about her Fortran 77 compiler@enddots{}
9156 @end defmac
9159 @defmac AC_REQUIRE_CPP
9160 @acindex{REQUIRE_CPP}
9161 Ensure that whichever preprocessor would currently be used for tests has
9162 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
9163 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
9164 depending on which language is current.
9165 @end defmac
9168 @node Writing Test Programs
9169 @section Writing Test Programs
9171 Autoconf tests follow a common scheme: feed some program with some
9172 input, and most of the time, feed a compiler with some source file.
9173 This section is dedicated to these source samples.
9175 @menu
9176 * Guidelines::                  General rules for writing test programs
9177 * Test Functions::              Avoiding pitfalls in test programs
9178 * Generating Sources::          Source program boilerplate
9179 @end menu
9181 @node Guidelines
9182 @subsection Guidelines for Test Programs
9184 The most important rule to follow when writing testing samples is:
9186 @center @emph{Look for realism.}
9188 This motto means that testing samples must be written with the same
9189 strictness as real programs are written.  In particular, you should
9190 avoid ``shortcuts'' and simplifications.
9192 Don't just play with the preprocessor if you want to prepare a
9193 compilation.  For instance, using @command{cpp} to check whether a header is
9194 functional might let your @command{configure} accept a header which
9195 causes some @emph{compiler} error.  Do not hesitate to check a header with
9196 other headers included before, especially required headers.
9198 Make sure the symbols you use are properly defined, i.e., refrain from
9199 simply declaring a function yourself instead of including the proper
9200 header.
9202 Test programs should not write to standard output.  They
9203 should exit with status 0 if the test succeeds, and with status 1
9204 otherwise, so that success
9205 can be distinguished easily from a core dump or other failure;
9206 segmentation violations and other failures produce a nonzero exit
9207 status.  Unless you arrange for @code{exit} to be declared, test
9208 programs should @code{return}, not @code{exit}, from @code{main},
9209 because on many systems @code{exit} is not declared by default.
9211 Test programs can use @code{#if} or @code{#ifdef} to check the values of
9212 preprocessor macros defined by tests that have already run.  For
9213 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9214 @file{configure.ac} you can have a test program that includes
9215 @file{stdbool.h} conditionally:
9217 @example
9218 @group
9219 #ifdef HAVE_STDBOOL_H
9220 # include <stdbool.h>
9221 #endif
9222 @end group
9223 @end example
9225 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9226 work with any standard C compiler.  Some developers prefer @code{#if}
9227 because it is easier to read, while others prefer @code{#ifdef} because
9228 it avoids diagnostics with picky compilers like GCC with the
9229 @option{-Wundef} option.
9231 If a test program needs to use or create a data file, give it a name
9232 that starts with @file{conftest}, such as @file{conftest.data}.  The
9233 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
9234 after running test programs and if the script is interrupted.
9236 @node Test Functions
9237 @subsection Test Functions
9239 These days it's safe to assume support for function prototypes
9240 (introduced in C89).
9242 Functions that test programs declare should also be conditionalized for
9243 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
9244 include any header files containing clashing prototypes.
9246 @example
9247 #ifdef __cplusplus
9248 extern "C"
9249 #endif
9250 void *valloc (size_t);
9251 @end example
9253 If a test program calls a function with invalid parameters (just to see
9254 whether it exists), organize the program to ensure that it never invokes
9255 that function.  You can do this by calling it in another function that is
9256 never invoked.  You can't do it by putting it after a call to
9257 @code{exit}, because GCC version 2 knows that @code{exit}
9258 never returns
9259 and optimizes out any code that follows it in the same block.
9261 If you include any header files, be sure to call the functions
9262 relevant to them with the correct number of arguments, even if they are
9263 just 0, to avoid compilation errors due to prototypes.  GCC
9264 version 2
9265 has internal prototypes for several functions that it automatically
9266 inlines; for example, @code{memcpy}.  To avoid errors when checking for
9267 them, either pass them the correct number of arguments or redeclare them
9268 with a different return type (such as @code{char}).
9271 @node Generating Sources
9272 @subsection Generating Sources
9274 Autoconf provides a set of macros that can be used to generate test
9275 source files.  They are written to be language generic, i.e., they
9276 actually depend on the current language (@pxref{Language Choice}) to
9277 ``format'' the output properly.
9280 @defmac AC_LANG_CONFTEST (@var{source})
9281 @acindex{LANG_CONFTEST}
9282 Save the @var{source} text in the current test source file:
9283 @file{conftest.@var{extension}} where the @var{extension} depends on the
9284 current language.  As of Autoconf 2.63b, the source file also contains
9285 the results of all of the @code{AC_DEFINE} performed so far.
9287 Note that the @var{source} is evaluated exactly once, like regular
9288 Autoconf macro arguments, and therefore (i) you may pass a macro
9289 invocation, (ii) if not, be sure to double quote if needed.
9291 This macro issues a warning during @command{autoconf} processing if
9292 @var{source} does not include an expansion of the macro
9293 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9294 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9296 This macro is seldom called directly, but is used under the hood by more
9297 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9298 @end defmac
9300 @defmac AC_LANG_DEFINES_PROVIDED
9301 @acindex{LANG_DEFINES_PROVIDED}
9302 This macro is called as a witness that the file
9303 @file{conftest.@var{extension}} appropriate for the current language is
9304 complete, including all previously determined results from
9305 @code{AC_DEFINE}.  This macro is seldom called directly, but exists if
9306 you have a compelling reason to write a conftest file without using
9307 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9308 @code{AC_LANG_CONFTEST}.
9309 @end defmac
9311 @defmac AC_LANG_SOURCE (@var{source})
9312 @acindex{LANG_SOURCE}
9313 Expands into the @var{source}, with the definition of
9314 all the @code{AC_DEFINE} performed so far.  This macro includes an
9315 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9317 In many cases, you may find it more convenient to use the wrapper
9318 @code{AC_LANG_PROGRAM}.
9319 @end defmac
9321 For instance, executing (observe the double quotation!):
9323 @example
9324 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9325 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9326         [https://www.example.org/])
9327 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9328   [Greetings string.])
9329 AC_LANG([C])
9330 AC_LANG_CONFTEST(
9331    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9332 gcc -E -dD conftest.c
9333 @end example
9335 @noindent
9336 on a system with @command{gcc} installed, results in:
9338 @example
9339 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9340 @dots{}
9341 @asis{#} 1 "conftest.c"
9343 #define PACKAGE_NAME "Hello"
9344 #define PACKAGE_TARNAME "hello"
9345 #define PACKAGE_VERSION "1.0"
9346 #define PACKAGE_STRING "Hello 1.0"
9347 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9348 #define PACKAGE_URL "https://www.example.org/"
9349 #define HELLO_WORLD "Hello, World\n"
9351 const char hw[] = "Hello, World\n";
9352 @end example
9354 When the test language is Fortran, Erlang, or Go, the @code{AC_DEFINE}
9355 definitions are not automatically translated into constants in the
9356 source code by this macro.
9358 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
9359 @acindex{LANG_PROGRAM}
9360 Expands into a source file which consists of the @var{prologue}, and
9361 then @var{body} as body of the main function (e.g., @code{main} in
9362 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9363 available.
9364 @end defmac
9366 For instance:
9368 @example
9369 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9370 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9371         [https://www.example.org/])
9372 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9373   [Greetings string.])
9374 AC_LANG_CONFTEST(
9375 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9376                  [[fputs (hw, stdout);]])])
9377 gcc -E -dD conftest.c
9378 @end example
9380 @noindent
9381 on a system with @command{gcc} installed, results in:
9383 @example
9384 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9385 @dots{}
9386 @asis{#} 1 "conftest.c"
9388 #define PACKAGE_NAME "Hello"
9389 #define PACKAGE_TARNAME "hello"
9390 #define PACKAGE_VERSION "1.0"
9391 #define PACKAGE_STRING "Hello 1.0"
9392 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9393 #define PACKAGE_URL "https://www.example.org/"
9394 #define HELLO_WORLD "Hello, World\n"
9396 const char hw[] = "Hello, World\n";
9398 main (void)
9400 fputs (hw, stdout);
9401   ;
9402   return 0;
9404 @end example
9406 In Erlang tests, the created source file is that of an Erlang module called
9407 @code{conftest} (@file{conftest.erl}).  This module defines and exports
9408 at least
9409 one @code{start/0} function, which is called to perform the test.  The
9410 @var{prologue} is optional code that is inserted between the module header and
9411 the @code{start/0} function definition.  @var{body} is the body of the
9412 @code{start/0} function without the final period (@pxref{Runtime}, about
9413 constraints on this function's behavior).
9415 For instance:
9417 @example
9418 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9419 AC_LANG(Erlang)
9420 AC_LANG_CONFTEST(
9421 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9422                  [[io:format("~s~n", [?HELLO_WORLD])]])])
9423 cat conftest.erl
9424 @end example
9426 @noindent
9427 results in:
9429 @example
9430 -module(conftest).
9431 -export([start/0]).
9432 -define(HELLO_WORLD, "Hello, world!").
9433 start() ->
9434 io:format("~s~n", [?HELLO_WORLD])
9436 @end example
9438 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
9439 @acindex{LANG_CALL}
9440 Expands into a source file which consists of the @var{prologue}, and
9441 then a call to the @var{function} as body of the main function (e.g.,
9442 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
9443 of the latter are available.
9445 This function will probably be replaced in the future by a version
9446 which would enable specifying the arguments.  The use of this macro is
9447 not encouraged, as it violates strongly the typing system.
9449 This macro cannot be used for Erlang tests.
9450 @end defmac
9452 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9453 @acindex{LANG_FUNC_LINK_TRY}
9454 Expands into a source file which uses the @var{function} in the body of
9455 the main function (e.g., @code{main} in C).  Since it uses
9456 @code{AC_LANG_PROGRAM}, the features of the latter are available.
9458 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9459 It is considered to be severely broken, and in the future will be
9460 removed in favor of actual function calls (with properly typed
9461 arguments).
9463 This macro cannot be used for Erlang tests.
9464 @end defmac
9466 @node Running the Preprocessor
9467 @section Running the Preprocessor
9469 Sometimes one might need to run the preprocessor on some source file.
9470 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9471 your project, not merely run the preprocessor on it; therefore you
9472 certainly want to run the compiler, not the preprocessor.  Resist the
9473 temptation of following the easiest path.
9475 Nevertheless, if you need to run the preprocessor, then use
9476 @code{AC_PREPROC_IFELSE}.
9478 The macros described in this section cannot be used for tests in Erlang,
9479 Fortran, or Go, since those languages require no preprocessor.
9481 @anchor{AC_PREPROC_IFELSE}
9482 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9483   @ovar{action-if-false})
9484 @acindex{PREPROC_IFELSE}
9485 Run the preprocessor of the current language (@pxref{Language Choice})
9486 on the @var{input}, run the shell commands @var{action-if-true} on
9487 success, @var{action-if-false} otherwise.  The @var{input} can be made
9488 by @code{AC_LANG_PROGRAM} and friends.
9490 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9491 @option{-g}, @option{-O}, etc.@: are not valid options to many C
9492 preprocessors.
9494 It is customary to report unexpected failures with
9495 @code{AC_MSG_FAILURE}.  If needed, @var{action-if-true} can further access
9496 the preprocessed output in the file @file{conftest.i}.
9497 @end defmac
9499 For instance:
9501 @example
9502 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9503 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9504   [Greetings string.])
9505 AC_PREPROC_IFELSE(
9506    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9507                     [[fputs (hw, stdout);]])],
9508    [AC_MSG_RESULT([OK])],
9509    [AC_MSG_FAILURE([unexpected preprocessor failure])])
9510 @end example
9512 @noindent
9513 might result in:
9515 @example
9516 checking for gcc... gcc
9517 checking whether the C compiler works... yes
9518 checking for C compiler default output file name... a.out
9519 checking for suffix of executables...
9520 checking whether we are cross compiling... no
9521 checking for suffix of object files... o
9522 checking whether the compiler supports GNU C... yes
9523 checking whether gcc accepts -g... yes
9524 checking for gcc option to enable C11 features... -std=gnu11
9525 checking how to run the C preprocessor... gcc -std=gnu11 -E
9527 @end example
9529 @sp 1
9531 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9532 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9533 it impossible to use it to elaborate sources.  You are encouraged to
9534 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9535 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9536 to run the @emph{preprocessor} and not the compiler?
9538 @anchor{AC_EGREP_HEADER}
9539 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9540   @var{action-if-found}, @ovar{action-if-not-found})
9541 @acindex{EGREP_HEADER}
9542 If the output of running the preprocessor on the system header file
9543 @var{header-file} matches the extended regular expression
9544 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9545 execute @var{action-if-not-found}.
9547 See below for some problems involving this macro.
9548 @end defmac
9550 @anchor{AC_EGREP_CPP}
9551 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9552   @ovar{action-if-found}, @ovar{action-if-not-found})
9553 @acindex{EGREP_CPP}
9554 @var{program} is the text of a C or C++ program, on which shell
9555 variable, back quote, and backslash substitutions are performed.  If the
9556 output of running the preprocessor on @var{program} matches the
9557 extended regular expression @var{pattern}, execute shell commands
9558 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9560 See below for some problems involving this macro.
9561 @end defmac
9563 @code{AC_EGREP_CPP} and @code{AC_EGREP_HEADER} should be used with care,
9564 as preprocessors can insert line breaks between output tokens.  For
9565 example, the preprocessor might transform this:
9567 @example
9568 #define MAJOR 2
9569 #define MINOR 23
9570 Version MAJOR . MINOR
9571 @end example
9573 @noindent
9574 into this:
9576 @example
9577 Version
9578        2
9579                  .
9580                    23
9581 @end example
9583 @noindent
9584 Because preprocessors are allowed to insert white space, change escapes
9585 in string contants, insert backlash-newline pairs, or do any of a number
9586 of things that do not change the meaning of the preprocessed program, it
9587 is better to rely on @code{AC_PREPROC_IFELSE} than to resort to
9588 @code{AC_EGREP_CPP} or @code{AC_EGREP_HEADER}.
9591 @node Running the Compiler
9592 @section Running the Compiler
9594 To check for a syntax feature of the current language's (@pxref{Language
9595 Choice}) compiler, such as whether it recognizes a certain keyword, or
9596 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9597 to compile a small program that uses that feature.
9599 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9600   @ovar{action-if-false})
9601 @acindex{COMPILE_IFELSE}
9602 Run the compiler and compilation flags of the current language
9603 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9604 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
9605 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9607 It is customary to report unexpected failures with
9608 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
9609 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9610 Linker}).  If needed, @var{action-if-true} can further access the
9611 just-compiled object file @file{conftest.$OBJEXT}.
9613 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9614 current language, which means that if the compiler has not yet been
9615 determined, the compiler determination will be made prior to the body of
9616 the outermost @code{AC_DEFUN} macro that triggered this macro to
9617 expand (@pxref{Expanded Before Required}).
9618 @end defmac
9620 @ovindex ERL
9621 For tests in Erlang, the @var{input} must be the source code of a module named
9622 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9623 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
9624 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9625 to ensure that the Erlang module has the right name.
9627 @node Running the Linker
9628 @section Running the Linker
9630 To check for a library, a function, or a global variable, Autoconf
9631 @command{configure} scripts try to compile and link a small program that
9632 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
9633 @code{ar} on the C library to try to figure out which functions are
9634 available.  Trying to link with the function is usually a more reliable
9635 approach because it avoids dealing with the variations in the options
9636 and output formats of @code{nm} and @code{ar} and in the location of the
9637 standard libraries.  It also allows configuring for cross-compilation or
9638 checking a function's runtime behavior if needed.  On the other hand,
9639 it can be slower than scanning the libraries once, but accuracy is more
9640 important than speed.
9642 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9643 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
9644 to check for libraries (@pxref{Libraries}), by adding the library being
9645 checked for to @code{LIBS} temporarily and trying to link a small
9646 program.
9648 @anchor{AC_LINK_IFELSE}
9649 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9650   @ovar{action-if-false})
9651 @acindex{LINK_IFELSE}
9652 Run the compiler (and compilation flags) and the linker of the current
9653 language (@pxref{Language Choice}) on the @var{input}, run the shell
9654 commands @var{action-if-true} on success, @var{action-if-false}
9655 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
9656 friends.  If needed, @var{action-if-true} can further access the
9657 just-linked program file @file{conftest$EXEEXT}.
9659 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9660 current compilation flags.
9662 It is customary to report unexpected failures with
9663 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
9664 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9665 @end defmac
9667 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9668 programs are interpreted and do not require linking.
9672 @node Runtime
9673 @section Checking Runtime Behavior
9675 Sometimes you need to find out how a system performs at runtime, such
9676 as whether a given function has a certain capability or bug.  If you
9677 can, make such checks when your program runs instead of when it is
9678 configured.  You can check for things like the machine's endianness when
9679 your program initializes itself.
9681 If you really need to test for a runtime behavior while configuring,
9682 you can write a test program to determine the result, and compile and
9683 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
9684 possible, because this prevents people from configuring your package for
9685 cross-compiling.
9687 @anchor{AC_RUN_IFELSE}
9688 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9689   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9690 @acindex{RUN_IFELSE}
9691 Run the compiler (and compilation flags) and the linker of the current
9692 language (@pxref{Language Choice}) on the @var{input}, then execute the
9693 resulting program.  If the program returns an exit
9694 status of 0 when executed, run shell commands @var{action-if-true}.
9695 Otherwise, run shell commands @var{action-if-false}.
9697 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9698 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9699 compilation flags of the current language (@pxref{Language Choice}).
9700 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9701 for further testing.
9703 In the @var{action-if-false} section, the failing exit status is
9704 available in the shell variable @samp{$?}.  This exit status might be
9705 that of a failed compilation, or it might be that of a failed program
9706 execution.
9708 If cross-compilation mode is enabled (this is the case if either the
9709 compiler being used does not produce executables that run on the system
9710 where @command{configure} is being run, or if the options @code{--build}
9711 and @code{--host} were both specified and their values are different),
9712 then the test program is
9713 not run.  If the optional shell commands @var{action-if-cross-compiling}
9714 are given, those commands are run instead; typically these commands
9715 provide pessimistic defaults that allow cross-compilation to work even
9716 if the guess was wrong.  If the fourth argument is empty or omitted, but
9717 cross-compilation is detected, then @command{configure} prints an error
9718 message and exits.  If you want your package to be useful in a
9719 cross-compilation scenario, you @emph{should} provide a non-empty
9720 @var{action-if-cross-compiling} clause, as well as wrap the
9721 @code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9722 (@pxref{Caching Results}) which allows the user to override the
9723 pessimistic default if needed.
9725 It is customary to report unexpected failures with
9726 @code{AC_MSG_FAILURE}.
9727 @end defmac
9729 @command{autoconf} prints a warning message when creating
9730 @command{configure} each time it encounters a call to
9731 @code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9732 given.  If you are not concerned about users configuring your package
9733 for cross-compilation, you may ignore the warning.  A few of the macros
9734 distributed with Autoconf produce this warning message; but if this is a
9735 problem for you, please report it as a bug, along with an appropriate
9736 pessimistic guess to use instead.
9738 To configure for cross-compiling you can also choose a value for those
9739 parameters based on the canonical system name (@pxref{Manual
9740 Configuration}).  Alternatively, set up a test results cache file with
9741 the correct values for the host system (@pxref{Caching Results}).
9743 @ovindex cross_compiling
9744 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9745 in other macros, including a few of the ones that come with Autoconf,
9746 you can test whether the shell variable @code{cross_compiling} is set to
9747 @samp{yes}, and then use an alternate method to get the results instead
9748 of calling the macros.
9750 It is also permissible to temporarily assign to @code{cross_compiling}
9751 in order to force tests to behave as though they are in a
9752 cross-compilation environment, particularly since this provides a way to
9753 test your @var{action-if-cross-compiling} even when you are not using a
9754 cross-compiler.
9756 @example
9757 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9758 # to use the slow link-only method
9759 save_cross_compiling=$cross_compiling
9760 cross_compiling=yes
9761 AC_COMPUTE_INT([@dots{}])
9762 cross_compiling=$save_cross_compiling
9763 @end example
9765 A C or C++ runtime test should be portable.
9766 @xref{Portable C and C++}.
9768 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9769 function: the given status code is used to determine the success of the test
9770 (status is @code{0}) or its failure (status is different than @code{0}), as
9771 explained above.  It must be noted that data output through the standard output
9772 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9773 Therefore, if a test must output configuration information, it is recommended
9774 to create and to output data into the temporary file named @file{conftest.out},
9775 using the functions of module @code{file}.  The @code{conftest.out} file is
9776 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9777 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9778 macro is:
9780 @example
9781 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9782 AC_ERLANG_NEED_ERL
9783 AC_LANG(Erlang)
9784 AC_RUN_IFELSE(
9785   [AC_LANG_PROGRAM([], [dnl
9786     file:write_file("conftest.out", code:lib_dir()),
9787     halt(0)])],
9788   [echo "code:lib_dir() returned: `cat conftest.out`"],
9789   [AC_MSG_FAILURE([test Erlang program execution failed])])
9790 @end example
9793 @node Systemology
9794 @section Systemology
9795 @cindex Systemology
9797 This section aims at presenting some systems and pointers to
9798 documentation.  It may help you addressing particular problems reported
9799 by users.
9801 @uref{https://@/en.wikipedia.org/@/wiki/@/POSIX, Posix-conforming
9802 systems} are derived from the
9803 @uref{https://@/en.wikipedia.org/@/wiki/@/Unix, Unix operating system}.
9805 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9806 contains a table correlating the features of various Posix-conforming
9807 systems.  @uref{https://@/www.levenez.com/@/unix/, Unix History} is a
9808 simplified diagram of how many Unix systems were derived from each
9809 other.
9811 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9812 provides some variants of traditional implementations of Unix utilities.
9814 @table @asis
9815 @item Darwin
9816 @cindex Darwin
9817 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
9818 case-preserving, but case insensitive.  This can cause nasty problems,
9819 since for instance the installation attempt for a package having an
9820 @file{INSTALL} file can result in @samp{make install} report that
9821 nothing was to be done!
9823 That's all dependent on whether the file system is a UFS (case
9824 sensitive) or HFS+ (case preserving).  By default Apple wants you to
9825 install the OS on HFS+.  Unfortunately, there are some pieces of
9826 software which really need to be built on UFS@.  We may want to rebuild
9827 Darwin to have both UFS and HFS+ available (and put the /local/build
9828 tree on the UFS).
9830 @item QNX 4.25
9831 @cindex QNX 4.25
9832 @c FIXME: Please, if you feel like writing something more precise,
9833 @c it'd be great.  In particular, I can't understand the difference with
9834 @c QNX Neutrino.
9835 QNX is a realtime operating system running on Intel architecture
9836 meant to be scalable from the small embedded systems to the hundred
9837 processor super-computer.  It claims to be Posix certified.  More
9838 information is available on the
9839 @uref{https://@/blackberry.qnx.com/@/en, QNX home page}.
9841 @item Unix version 7
9842 @cindex Unix version 7
9843 @cindex V7
9844 Officially this was called the ``Seventh Edition'' of ``the UNIX
9845 time-sharing system'' but we use the more-common name ``Unix version 7''.
9846 Documentation is available in the
9847 @uref{https://@/s3.amazonaws.com/@/plan9-bell-labs/@/7thEdMan/@/index.html,
9848 Unix Seventh Edition Manual}.
9849 Previous versions of Unix are called ``Unix version 6'', etc., but
9850 they were not as widely used.
9851 @end table
9854 @node Multiple Cases
9855 @section Multiple Cases
9857 Some operations are accomplished in several possible ways, depending on
9858 the OS variant.  Checking for them essentially requires a ``case
9859 statement''.  Autoconf does not directly provide one; however, it is
9860 easy to simulate by using a shell variable to keep track of whether a
9861 way to perform the operation has been found yet.
9863 Here is an example that uses the shell variable @code{fstype} to keep
9864 track of whether the remaining cases need to be checked.  Note that
9865 since the value of @code{fstype} is under our control, we don't have to
9866 use the longer @samp{test "x$fstype" = xno}.
9868 @example
9869 @group
9870 AC_MSG_CHECKING([how to get file system type])
9871 fstype=no
9872 # The order of these tests is important.
9873 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9874 #include <sys/fstyp.h>]])],
9875                   [AC_DEFINE([FSTYPE_STATVFS], [1],
9876                      [Define if statvfs exists.])
9877                    fstype=SVR4])
9878 if test $fstype = no; then
9879   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9880 #include <sys/fstyp.h>]])],
9881                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9882                      [Define if USG statfs.])
9883                    fstype=SVR3])
9885 if test $fstype = no; then
9886   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9887 #include <sys/vmount.h>]])]),
9888                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9889                      [Define if AIX statfs.])
9890                    fstype=AIX])
9892 # (more cases omitted here)
9893 AC_MSG_RESULT([$fstype])
9894 @end group
9895 @end example
9897 @c ====================================================== Results of Tests.
9899 @node Results
9900 @chapter Results of Tests
9902 Once @command{configure} has determined whether a feature exists, what can
9903 it do to record that information?  There are four sorts of things it can
9904 do: define a C preprocessor symbol, set a variable in the output files,
9905 save the result in a cache file for future @command{configure} runs, and
9906 print a message letting the user know the result of the test.
9908 @menu
9909 * Defining Symbols::            Defining C preprocessor symbols
9910 * Setting Output Variables::    Replacing variables in output files
9911 * Special Chars in Variables::  Characters to beware of in variables
9912 * Caching Results::             Speeding up subsequent @command{configure} runs
9913 * Printing Messages::           Notifying @command{configure} users
9914 @end menu
9916 @node Defining Symbols
9917 @section Defining C Preprocessor Symbols
9919 A common action to take in response to a feature test is to define a C
9920 preprocessor symbol indicating the results of the test.  That is done by
9921 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9923 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9924 into the output variable @code{DEFS}, which contains an option
9925 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
9926 Autoconf version 1, there is no variable @code{DEFS} defined while
9927 @command{configure} is running.  To check whether Autoconf macros have
9928 already defined a certain C preprocessor symbol, test the value of the
9929 appropriate cache variable, as in this example:
9931 @example
9932 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9933                           [Define if vprintf exists.])])
9934 if test "x$ac_cv_func_vprintf" != xyes; then
9935   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9936                             [Define if _doprnt exists.])])
9938 @end example
9940 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9941 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9942 correct values into @code{#define} statements in a template file.
9943 @xref{Configuration Headers}, for more information about this kind of
9944 output.
9946 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9947 @defmacx AC_DEFINE (@var{variable})
9948 @cvindex @var{variable}
9949 @acindex{DEFINE}
9950 Define @var{variable} to @var{value} (verbatim), by defining a C
9951 preprocessor macro for @var{variable}.  @var{variable} should be a C
9952 identifier, optionally suffixed by a parenthesized argument list to
9953 define a C preprocessor macro with arguments.  The macro argument list,
9954 if present, should be a comma-separated list of C identifiers, possibly
9955 terminated by an ellipsis @samp{...} if C99-or-later syntax is employed.
9956 @var{variable} should not contain comments, white space, trigraphs,
9957 backslash-newlines, universal character names, or non-ASCII
9958 characters.
9960 @var{value} may contain backslash-escaped newlines, which will be
9961 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9962 via @code{@@DEFS@@} (with no effect on the compilation, since the
9963 preprocessor sees only one line in the first place).  @var{value} should
9964 not contain raw newlines.  If you are not using
9965 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9966 characters, as @command{make} tends to eat them.  To use a shell
9967 variable, use @code{AC_DEFINE_UNQUOTED} instead.
9969 @var{description} is only useful if you are using
9970 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
9971 the generated @file{config.h.in} as the comment before the macro define.
9972 The following example defines the C preprocessor variable
9973 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
9975 @example
9976 AC_DEFINE([EQUATION], ["$a > $b"],
9977   [Equation string.])
9978 @end example
9980 If neither @var{value} nor @var{description} are given, then
9981 @var{value} defaults to 1 instead of to the empty string.  This is for
9982 backwards compatibility with older versions of Autoconf, but this usage
9983 is obsolescent and may be withdrawn in future versions of Autoconf.
9985 If the @var{variable} is a literal string, it is passed to
9986 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9988 If multiple @code{AC_DEFINE} statements are executed for the same
9989 @var{variable} name (not counting any parenthesized argument list),
9990 the last one wins.
9991 @end defmac
9993 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9994 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
9995 @acindex{DEFINE_UNQUOTED}
9996 @cvindex @var{variable}
9997 Like @code{AC_DEFINE}, but three shell expansions are
9998 performed---once---on @var{variable} and @var{value}: variable expansion
9999 (@samp{$}), command substitution (@samp{`}), and backslash escaping
10000 (@samp{\}), as if in an unquoted here-document.  Single and double quote
10001 characters in the value have no
10002 special meaning.  Use this macro instead of @code{AC_DEFINE} when
10003 @var{variable} or @var{value} is a shell variable.  Examples:
10005 @example
10006 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
10007   [Configuration machine file.])
10008 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
10009   [getgroups return type.])
10010 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
10011   [Translated header name.])
10012 @end example
10013 @end defmac
10015 Due to a syntactical oddity of the Bourne shell, do not use
10016 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
10017 calls from other macro calls or shell code; that can cause syntax errors
10018 in the resulting @command{configure} script.  Use either blanks or
10019 newlines.  That is, do this:
10021 @example
10022 AC_CHECK_HEADER([elf.h],
10023   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
10024 @end example
10026 @noindent
10027 or this:
10029 @example
10030 AC_CHECK_HEADER([elf.h],
10031   [AC_DEFINE([SVR4], [1], [System V Release 4])
10032    LIBS="-lelf $LIBS"])
10033 @end example
10035 @noindent
10036 instead of this:
10038 @example
10039 AC_CHECK_HEADER([elf.h],
10040   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
10041 @end example
10043 @node Setting Output Variables
10044 @section Setting Output Variables
10045 @cindex Output variables
10047 Another way to record the results of tests is to set @dfn{output
10048 variables}, which are shell variables whose values are substituted into
10049 files that @command{configure} outputs.  The two macros below create new
10050 output variables.  @xref{Preset Output Variables}, for a list of output
10051 variables that are always available.
10053 @defmac AC_SUBST (@var{variable}, @ovar{value})
10054 @acindex{SUBST}
10055 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
10056 substitute the variable @var{variable} into output files (typically one
10057 or more makefiles).  This means that @code{AC_OUTPUT}
10058 replaces instances of @samp{@@@var{variable}@@} in input files with the
10059 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
10060 is called.  The value can contain any non-@code{NUL} character, including
10061 newline.  If you are using Automake 1.11 or newer, for newlines in values
10062 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
10063 @command{automake} from adding a line @code{@var{variable} =
10064 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
10065 Automake, automake, Other things Automake recognizes}).
10067 Variable occurrences should not overlap: e.g., an input file should
10068 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
10069 are variable names.
10070 The substituted value is not rescanned for more output variables;
10071 occurrences of @samp{@@@var{variable}@@} in the value are inserted
10072 literally into the output file.  (The algorithm uses the special marker
10073 @code{|#_!!_#|} internally, so neither the substituted value nor the
10074 output file may contain @code{|#_!!_#|}.)
10076 If @var{value} is given, in addition assign it to @var{variable}.
10078 The string @var{variable} is passed to @code{m4_pattern_allow}
10079 (@pxref{Forbidden Patterns}).  @var{variable} is not further expanded,
10080 even if there is another macro by the same name.
10081 @end defmac
10083 @defmac AC_SUBST_FILE (@var{variable})
10084 @acindex{SUBST_FILE}
10085 Another way to create an output variable from a shell variable.  Make
10086 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
10087 named by shell variable @var{variable} into output files.  This means
10088 that @code{AC_OUTPUT} replaces instances of
10089 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
10090 with the contents of the file that the shell variable @var{variable}
10091 names when @code{AC_OUTPUT} is called.  Set the variable to
10092 @file{/dev/null} for cases that do not have a file to insert.
10093 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
10094 line by itself, optionally surrounded by spaces and tabs.  The
10095 substitution replaces the whole line, including the spaces, tabs, and
10096 the terminating newline.
10098 This macro is useful for inserting makefile fragments containing
10099 special dependencies or other @command{make} directives for particular host
10100 or target types into makefiles.  For example, @file{configure.ac}
10101 could contain:
10103 @example
10104 AC_SUBST_FILE([host_frag])
10105 host_frag=$srcdir/conf/sun4.mh
10106 @end example
10108 @noindent
10109 and then a @file{Makefile.in} could contain:
10111 @example
10112 @@host_frag@@
10113 @end example
10115 The string @var{variable} is passed to @code{m4_pattern_allow}
10116 (@pxref{Forbidden Patterns}).
10117 @end defmac
10119 @cindex Precious Variable
10120 @cindex Variable, Precious
10121 Running @command{configure} in varying environments can be extremely
10122 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
10123 ./configure}, then the cache, @file{config.h}, and many other output
10124 files depend upon @command{bizarre-cc} being the C compiler.  If
10125 for some reason the user runs @command{./configure} again, or if it is
10126 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
10127 and @pxref{config.status Invocation}), then the configuration can be
10128 inconsistent, composed of results depending upon two different
10129 compilers.
10131 Environment variables that affect this situation, such as @samp{CC}
10132 above, are called @dfn{precious variables}, and can be declared as such
10133 by @code{AC_ARG_VAR}.
10135 @defmac AC_ARG_VAR (@var{variable}, @var{description})
10136 @acindex{ARG_VAR}
10137 Declare @var{variable} is a precious variable, and include its
10138 @var{description} in the variable section of @samp{./configure --help}.
10140 Being precious means that
10141 @itemize @minus
10142 @item
10143 @var{variable} is substituted via @code{AC_SUBST}.
10145 @item
10146 The value of @var{variable} when @command{configure} was launched is
10147 saved in the cache, including if it was not specified on the command
10148 line but via the environment.  Indeed, while @command{configure} can
10149 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
10150 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
10151 which, unfortunately, is what most users do.
10153 We emphasize that it is the @emph{initial} value of @var{variable} which
10154 is saved, not that found during the execution of @command{configure}.
10155 Indeed, specifying @samp{./configure FOO=foo} and letting
10156 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
10157 different things.
10159 @item
10160 @var{variable} is checked for consistency between two
10161 @command{configure} runs.  For instance:
10163 @example
10164 $ @kbd{./configure --silent --config-cache}
10165 $ @kbd{CC=cc ./configure --silent --config-cache}
10166 configure: error: 'CC' was not set in the previous run
10167 configure: error: changes in the environment can compromise \
10168 the build
10169 configure: error: run 'make distclean' and/or \
10170 'rm config.cache' and start over
10171 @end example
10173 @noindent
10174 and similarly if the variable is unset, or if its content is changed.
10175 If the content has white space changes only, then the error is degraded
10176 to a warning only, but the old value is reused.
10178 @item
10179 @var{variable} is kept during automatic reconfiguration
10180 (@pxref{config.status Invocation}) as if it had been passed as a command
10181 line argument, including when no cache is used:
10183 @example
10184 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
10185 $ @kbd{./config.status --recheck}
10186 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
10187   CC=/usr/bin/cc  --no-create --no-recursion
10188 @end example
10189 @end itemize
10190 @end defmac
10192 @node Special Chars in Variables
10193 @section Special Characters in Output Variables
10194 @cindex Output variables, special characters in
10196 Many output variables are intended to be evaluated both by
10197 @command{make} and by the shell.  Some characters are expanded
10198 differently in these two contexts, so to avoid confusion these
10199 variables' values should not contain any of the following characters:
10201 @example
10202 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
10203 @end example
10205 Also, these variables' values should neither contain newlines, nor start
10206 with @samp{~}, nor contain white space or @samp{:} immediately followed
10207 by @samp{~}.  The values can contain nonempty sequences of white space
10208 characters like tabs and spaces, but each such sequence might
10209 arbitrarily be replaced by a single space during substitution.
10211 These restrictions apply both to the values that @command{configure}
10212 computes, and to the values set directly by the user.  For example, the
10213 following invocations of @command{configure} are problematic, since they
10214 attempt to use special characters within @code{CPPFLAGS} and white space
10215 within @code{$(srcdir)}:
10217 @example
10218 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
10220 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
10221 @end example
10223 @node Caching Results
10224 @section Caching Results
10225 @cindex Cache
10227 To avoid checking for the same features repeatedly in various
10228 @command{configure} scripts (or in repeated runs of one script),
10229 @command{configure} can optionally save the results of many checks in a
10230 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
10231 runs with caching enabled and finds a cache file, it reads the results
10232 of previous runs from the cache and avoids rerunning those checks.  As a
10233 result, @command{configure} can then run much faster than if it had to
10234 perform all of the checks every time.
10236 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10237 @acindex{CACHE_VAL}
10238 Ensure that the results of the check identified by @var{cache-id} are
10239 available.  If the results of the check were in the cache file that was
10240 read, and @command{configure} was not given the @option{--quiet} or
10241 @option{--silent} option, print a message saying that the result was
10242 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
10243 the shell commands are run to determine the value, the value is
10244 saved in the cache file just before @command{configure} creates its output
10245 files.  @xref{Cache Variable Names}, for how to choose the name of the
10246 @var{cache-id} variable.
10248 The @var{commands-to-set-it} @emph{must have no side effects} except for
10249 setting the variable @var{cache-id}, see below.
10250 @end defmac
10252 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10253   @var{commands-to-set-it})
10254 @acindex{CACHE_CHECK}
10255 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10256 messages.  This macro provides a convenient shorthand for the most
10257 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
10258 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10259 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10261 The @var{commands-to-set-it} @emph{must have no side effects} except for
10262 setting the variable @var{cache-id}, see below.
10263 @end defmac
10265 It is common to find buggy macros using @code{AC_CACHE_VAL} or
10266 @code{AC_CACHE_CHECK}, because people are tempted to call
10267 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
10268 @emph{follows} the call to @code{AC_CACHE_VAL} should call
10269 @code{AC_DEFINE}, by examining the value of the cache variable.  For
10270 instance, the following macro is broken:
10272 @example
10273 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10274 @group
10275 AC_DEFUN([AC_SHELL_TRUE],
10276 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10277                 [my_cv_shell_true_works=no
10278                  (true) 2>/dev/null && my_cv_shell_true_works=yes
10279                  if test "x$my_cv_shell_true_works" = xyes; then
10280                    AC_DEFINE([TRUE_WORKS], [1],
10281                              [Define if 'true(1)' works properly.])
10282                  fi])
10284 @end group
10285 @end example
10287 @noindent
10288 This fails if the cache is enabled: the second time this macro is run,
10289 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
10292 @example
10293 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10294 @group
10295 AC_DEFUN([AC_SHELL_TRUE],
10296 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10297                 [my_cv_shell_true_works=no
10298                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
10299  if test "x$my_cv_shell_true_works" = xyes; then
10300    AC_DEFINE([TRUE_WORKS], [1],
10301              [Define if 'true(1)' works properly.])
10302  fi
10304 @end group
10305 @end example
10307 Also, @var{commands-to-set-it} should not print any messages, for
10308 example with @code{AC_MSG_CHECKING}; do that before calling
10309 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10310 the results of the check are retrieved from the cache or determined by
10311 running the shell commands.
10313 @menu
10314 * Cache Variable Names::        Shell variables used in caches
10315 * Cache Files::                 Files @command{configure} uses for caching
10316 * Cache Checkpointing::         Loading and saving the cache file
10317 @end menu
10319 @node Cache Variable Names
10320 @subsection Cache Variable Names
10321 @cindex Cache variable
10323 The names of cache variables should have the following format:
10325 @example
10326 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10327 @end example
10329 @noindent
10330 for example, @samp{ac_cv_header_stat_broken} or
10331 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
10333 @table @asis
10334 @item @var{package-prefix}
10335 An abbreviation for your package or organization; the same prefix you
10336 begin local Autoconf macros with, except lowercase by convention.
10337 For cache values used by the distributed Autoconf macros, this value is
10338 @samp{ac}.
10340 @item @code{_cv_}
10341 Indicates that this shell variable is a cache value.  This string
10342 @emph{must} be present in the variable name, including the leading
10343 underscore.
10345 @item @var{value-type}
10346 A convention for classifying cache values, to produce a rational naming
10347 system.  The values used in Autoconf are listed in @ref{Macro Names}.
10349 @item @var{specific-value}
10350 Which member of the class of cache values this test applies to.
10351 For example, which function (@samp{alloca}), program (@samp{gcc}), or
10352 output variable (@samp{INSTALL}).
10354 @item @var{additional-options}
10355 Any particular behavior of the specific member that this test applies to.
10356 For example, @samp{broken} or @samp{set}.  This part of the name may
10357 be omitted if it does not apply.
10358 @end table
10360 The values assigned to cache variables may not contain newlines.
10361 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10362 names of files or functions; so this is not an important restriction.
10363 @ref{Cache Variable Index} for an index of cache variables with
10364 documented semantics.
10367 @node Cache Files
10368 @subsection Cache Files
10370 A cache file is a shell script that caches the results of configure
10371 tests run on one system so they can be shared between configure scripts
10372 and configure runs.  It is not useful on other systems.  If its contents
10373 are invalid for some reason, the user may delete or edit it, or override
10374 documented cache variables on the @command{configure} command line.
10376 By default, @command{configure} uses no cache file,
10377 to avoid problems caused by accidental
10378 use of stale cache files.
10380 To enable caching, @command{configure} accepts @option{--config-cache} (or
10381 @option{-C}) to cache results in the file @file{config.cache}.
10382 Alternatively, @option{--cache-file=@var{file}} specifies that
10383 @var{file} be the cache file.  The cache file is created if it does not
10384 exist already.  When @command{configure} calls @command{configure} scripts in
10385 subdirectories, it uses the @option{--cache-file} argument so that they
10386 share the same cache.  @xref{Subdirectories}, for information on
10387 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10389 @file{config.status} only pays attention to the cache file if it is
10390 given the @option{--recheck} option, which makes it rerun
10391 @command{configure}.
10393 It is wrong to try to distribute cache files for particular system types.
10394 There is too much room for error in doing that, and too much
10395 administrative overhead in maintaining them.  For any features that
10396 can't be guessed automatically, use the standard method of the canonical
10397 system type and linking files (@pxref{Manual Configuration}).
10399 The site initialization script can specify a site-wide cache file to
10400 use, instead of the usual per-program cache.  In this case, the cache
10401 file gradually accumulates information whenever someone runs a new
10402 @command{configure} script.  (Running @command{configure} merges the new cache
10403 results with the existing cache file.)  This may cause problems,
10404 however, if the system configuration (e.g., the installed libraries or
10405 compilers) changes and the stale cache file is not deleted.
10407 If @command{configure} is interrupted at the right time when it updates
10408 a cache file outside of the build directory where the @command{configure}
10409 script is run, it may leave behind a temporary file named after the
10410 cache file with digits following it.  You may safely delete such a file.
10413 @node Cache Checkpointing
10414 @subsection Cache Checkpointing
10416 If your configure script, or a macro called from @file{configure.ac}, happens
10417 to abort the configure process, it may be useful to checkpoint the cache
10418 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
10419 reduces the amount of time it takes to rerun the configure script with
10420 (hopefully) the error that caused the previous abort corrected.
10422 @c FIXME: Do we really want to document this guy?
10423 @defmac AC_CACHE_LOAD
10424 @acindex{CACHE_LOAD}
10425 Loads values from existing cache file, or creates a new cache file if a
10426 cache file is not found.  Called automatically from @code{AC_INIT}.
10427 @end defmac
10429 @defmac AC_CACHE_SAVE
10430 @acindex{CACHE_SAVE}
10431 Flushes all cached values to the cache file.  Called automatically from
10432 @code{AC_OUTPUT}, but it can be quite useful to call
10433 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10434 @end defmac
10436 For instance:
10438 @example
10439 @r{ @dots{} AC_INIT, etc. @dots{}}
10440 @group
10441 # Checks for programs.
10442 AC_PROG_CC
10443 AC_PROG_AWK
10444 @r{ @dots{} more program checks @dots{}}
10445 AC_CACHE_SAVE
10446 @end group
10448 @group
10449 # Checks for libraries.
10450 AC_CHECK_LIB([nsl], [gethostbyname])
10451 AC_CHECK_LIB([socket], [connect])
10452 @r{ @dots{} more lib checks @dots{}}
10453 AC_CACHE_SAVE
10454 @end group
10456 @group
10457 # Might abort@dots{}
10458 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10459 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10460 @end group
10461 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
10462 @end example
10464 @node Printing Messages
10465 @section Printing Messages
10466 @cindex Messages, from @command{configure}
10468 @command{configure} scripts need to give users running them several kinds
10469 of information.  The following macros print messages in ways appropriate
10470 for each kind.  The arguments to all of them get enclosed in shell
10471 double quotes, so the shell performs variable and back-quote
10472 substitution on them.
10474 These macros are all wrappers around the @command{echo} shell command.
10475 They direct output to the appropriate file descriptor (@pxref{File
10476 Descriptor Macros}).
10477 @command{configure} scripts should rarely need to run @command{echo} directly
10478 to print messages for the user.  Using these macros makes it easy to
10479 change how and when each kind of message is printed; such changes need
10480 only be made to the macro definitions and all the callers change
10481 automatically.
10483 To diagnose static issues, i.e., when @command{autoconf} is run, see
10484 @ref{Diagnostic Macros}.
10486 @defmac AC_MSG_CHECKING (@var{feature-description})
10487 @acindex{MSG_CHECKING}
10488 Notify the user that @command{configure} is checking for a particular
10489 feature.  This macro prints a message that starts with @samp{checking }
10490 and ends with @samp{...} and no newline.  It must be followed by a call
10491 to @code{AC_MSG_RESULT} to print the result of the check and the
10492 newline.  The @var{feature-description} should be something like
10493 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10494 _Alignof}.
10496 This macro prints nothing if @command{configure} is run with the
10497 @option{--quiet} or @option{--silent} option.
10498 @end defmac
10500 @anchor{AC_MSG_RESULT}
10501 @defmac AC_MSG_RESULT (@var{result-description})
10502 @acindex{MSG_RESULT}
10503 Notify the user of the results of a check.  @var{result-description} is
10504 almost always the value of the cache variable for the check, typically
10505 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
10506 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10507 the completion of the message printed by the call to
10508 @code{AC_MSG_CHECKING}.
10510 This macro prints nothing if @command{configure} is run with the
10511 @option{--quiet} or @option{--silent} option.
10512 @end defmac
10514 @anchor{AC_MSG_NOTICE}
10515 @defmac AC_MSG_NOTICE (@var{message})
10516 @acindex{MSG_NOTICE}
10517 Deliver the @var{message} to the user.  It is useful mainly to print a
10518 general description of the overall purpose of a group of feature checks,
10519 e.g.,
10521 @example
10522 AC_MSG_NOTICE([checking if stack overflow is detectable])
10523 @end example
10525 This macro prints nothing if @command{configure} is run with the
10526 @option{--quiet} or @option{--silent} option.
10527 @end defmac
10529 @anchor{AC_MSG_ERROR}
10530 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10531 @acindex{MSG_ERROR}
10532 Notify the user of an error that prevents @command{configure} from
10533 completing.  This macro prints an error message to the standard error
10534 output and exits @command{configure} with @var{exit-status} (@samp{$?}
10535 by default, except that @samp{0} is converted to @samp{1}).
10536 @var{error-description} should be something like @samp{invalid value
10537 $HOME for \$HOME}.
10539 The @var{error-description} should start with a lower-case letter, and
10540 ``cannot'' is preferred to ``can't''.
10541 @end defmac
10543 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10544 @acindex{MSG_FAILURE}
10545 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10546 prevents @command{configure} from completing @emph{and} that additional
10547 details are provided in @file{config.log}.  This is typically used when
10548 abnormal results are found during a compilation.
10549 @end defmac
10551 @anchor{AC_MSG_WARN}
10552 @defmac AC_MSG_WARN (@var{problem-description})
10553 @acindex{MSG_WARN}
10554 Notify the @command{configure} user of a possible problem.  This macro
10555 prints the message to the standard error output; @command{configure}
10556 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10557 provide a default (back-up) behavior for the situations they warn about.
10558 @var{problem-description} should be something like @samp{ln -s seems to
10559 make hard links}.
10560 @end defmac
10564 @c ====================================================== Programming in M4.
10566 @node Programming in M4
10567 @chapter Programming in M4
10568 @cindex M4
10570 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10571 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10572 provides macros dedicated to shell script generation.
10574 As of this version of Autoconf, these two layers still contain
10575 experimental macros, whose interface might change in the future.  As a
10576 matter of fact, @emph{anything that is not documented must not be used}.
10578 @menu
10579 * M4 Quotation::                Protecting macros from unwanted expansion
10580 * Using autom4te::              The Autoconf executables backbone
10581 * Programming in M4sugar::      Convenient pure M4 macros
10582 * Debugging via autom4te::      Figuring out what M4 was doing
10583 @end menu
10585 @node M4 Quotation
10586 @section M4 Quotation
10587 @cindex M4 quotation
10588 @cindex quotation
10590 The most common problem with existing macros is an improper quotation.
10591 This section, which users of Autoconf can skip, but which macro writers
10592 @emph{must} read, first justifies the quotation scheme that was chosen
10593 for Autoconf and then ends with a rule of thumb.  Understanding the
10594 former helps one to follow the latter.
10596 @menu
10597 * Active Characters::           Characters that change the behavior of M4
10598 * One Macro Call::              Quotation and one macro call
10599 * Quoting and Parameters::      M4 vs. shell parameters
10600 * Quotation and Nested Macros::  Macros calling macros
10601 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
10602 * Quadrigraphs::                Another way to escape special characters
10603 * Balancing Parentheses::       Dealing with unbalanced parentheses
10604 * Quotation Rule Of Thumb::     One parenthesis, one quote
10605 @end menu
10607 @node Active Characters
10608 @subsection Active Characters
10610 To fully understand where proper quotation is important, you first need
10611 to know what the special characters are in Autoconf: @samp{#} introduces
10612 a comment inside which no macro expansion is performed, @samp{,}
10613 separates arguments, @samp{[} and @samp{]} are the quotes
10614 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10615 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10616 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10617 @samp{$} inside a macro definition.
10619 In order to understand the delicate case of macro calls, we first have
10620 to present some obvious failures.  Below they are ``obvious-ified'',
10621 but when you find them in real life, they are usually in disguise.
10623 Comments, introduced by a hash and running up to the newline, are opaque
10624 tokens to the top level: active characters are turned off, and there is
10625 no macro expansion:
10627 @example
10628 # define([def], ine)
10629 @result{}# define([def], ine)
10630 @end example
10632 Each time there can be a macro expansion, there is a quotation
10633 expansion, i.e., one level of quotes is stripped:
10635 @example
10636 int tab[10];
10637 @result{}int tab10;
10638 [int tab[10];]
10639 @result{}int tab[10];
10640 @end example
10642 Without this in mind, the reader might try hopelessly to use her macro
10643 @code{array}:
10645 @example
10646 define([array], [int tab[10];])
10647 array
10648 @result{}int tab10;
10649 [array]
10650 @result{}array
10651 @end example
10653 @noindent
10654 How can you correctly output the intended results@footnote{Using
10655 @code{defn}.}?
10658 @node One Macro Call
10659 @subsection One Macro Call
10661 Let's proceed on the interaction between active characters and macros
10662 with this small macro, which just returns its first argument:
10664 @example
10665 define([car], [$1])
10666 @end example
10668 @noindent
10669 The two pairs of quotes above are not part of the arguments of
10670 @code{define}; rather, they are understood by the top level when it
10671 tries to find the arguments of @code{define}.  Therefore, assuming
10672 @code{car} is not already defined, it is equivalent to write:
10674 @example
10675 define(car, $1)
10676 @end example
10678 @noindent
10679 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10680 quotes, it is bad practice for Autoconf macros which must both be more
10681 robust and also advocate perfect style.
10683 At the top level, there are only two possibilities: either you
10684 quote or you don't:
10686 @example
10687 car(foo, bar, baz)
10688 @result{}foo
10689 [car(foo, bar, baz)]
10690 @result{}car(foo, bar, baz)
10691 @end example
10693 Let's pay attention to the special characters:
10695 @example
10696 car(#)
10697 @error{}EOF in argument list
10698 @end example
10700 The closing parenthesis is hidden in the comment; with a hypothetical
10701 quoting, the top level understood it this way:
10703 @example
10704 car([#)]
10705 @end example
10707 @noindent
10708 Proper quotation, of course, fixes the problem:
10710 @example
10711 car([#])
10712 @result{}#
10713 @end example
10715 Here are more examples:
10717 @example
10718 car(foo, bar)
10719 @result{}foo
10720 car([foo, bar])
10721 @result{}foo, bar
10722 car((foo, bar))
10723 @result{}(foo, bar)
10724 car([(foo], [bar)])
10725 @result{}(foo
10726 define([a], [b])
10727 @result{}
10728 car(a)
10729 @result{}b
10730 car([a])
10731 @result{}b
10732 car([[a]])
10733 @result{}a
10734 car([[[a]]])
10735 @result{}[a]
10736 @end example
10738 @node Quoting and Parameters
10739 @subsection Quoting and Parameters
10741 When M4 encounters @samp{$} within a macro definition, followed
10742 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10743 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10744 expansion.  This happens regardless of how many layers of quotes the
10745 parameter expansion is nested within, or even if it occurs in text that
10746 will be rescanned as a comment.
10748 @example
10749 define([none], [$1])
10750 @result{}
10751 define([one], [[$1]])
10752 @result{}
10753 define([two], [[[$1]]])
10754 @result{}
10755 define([comment], [# $1])
10756 @result{}
10757 define([active], [ACTIVE])
10758 @result{}
10759 none([active])
10760 @result{}ACTIVE
10761 one([active])
10762 @result{}active
10763 two([active])
10764 @result{}[active]
10765 comment([active])
10766 @result{}# active
10767 @end example
10769 On the other hand, since autoconf generates shell code, you often want
10770 to output shell variable expansion, rather than performing M4 parameter
10771 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10772 from the next character in the definition of your macro.  If the macro
10773 definition occurs in single-quoted text, then insert another level of
10774 quoting; if the usage is already inside a double-quoted string, then
10775 split it into concatenated strings.
10777 @example
10778 define([foo], [a single-quoted $[]1 definition])
10779 @result{}
10780 define([bar], [[a double-quoted $][1 definition]])
10781 @result{}
10783 @result{}a single-quoted $1 definition
10785 @result{}a double-quoted $1 definition
10786 @end example
10788 Posix states that M4 implementations are free to provide implementation
10789 extensions when @samp{$@{} is encountered in a macro definition.
10790 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10791 extensions that will be available in the future GNU M4 2.0,
10792 but guarantees that all other instances of @samp{$@{} will be output
10793 literally.  Therefore, this idiom can also be used to output shell code
10794 parameter references:
10796 @example
10797 define([first], [$@{1@}])first
10798 @result{}$@{1@}
10799 @end example
10801 Posix also states that @samp{$11} should expand to the first parameter
10802 concatenated with a literal @samp{1}, although some versions of
10803 GNU M4 expand the eleventh parameter instead.  For
10804 portability, you should only use single-digit M4 parameter expansion.
10806 With this in mind, we can explore the cases where macros invoke
10807 macros@enddots{}
10809 @node Quotation and Nested Macros
10810 @subsection Quotation and Nested Macros
10812 The examples below use the following macros:
10814 @example
10815 define([car], [$1])
10816 define([active], [ACT, IVE])
10817 define([array], [int tab[10]])
10818 @end example
10820 Each additional embedded macro call introduces other possible
10821 interesting quotations:
10823 @example
10824 car(active)
10825 @result{}ACT
10826 car([active])
10827 @result{}ACT, IVE
10828 car([[active]])
10829 @result{}active
10830 @end example
10832 In the first case, the top level looks for the arguments of @code{car},
10833 and finds @samp{active}.  Because M4 evaluates its arguments
10834 before applying the macro, @samp{active} is expanded, which results in:
10836 @example
10837 car(ACT, IVE)
10838 @result{}ACT
10839 @end example
10841 @noindent
10842 In the second case, the top level gives @samp{active} as first and only
10843 argument of @code{car}, which results in:
10845 @example
10846 active
10847 @result{}ACT, IVE
10848 @end example
10850 @noindent
10851 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10852 In the third case, @code{car} receives @samp{[active]}, which results in:
10854 @example
10855 [active]
10856 @result{}active
10857 @end example
10859 @noindent
10860 exactly as we already saw above.
10862 The example above, applied to a more realistic example, gives:
10864 @example
10865 car(int tab[10];)
10866 @result{}int tab10;
10867 car([int tab[10];])
10868 @result{}int tab10;
10869 car([[int tab[10];]])
10870 @result{}int tab[10];
10871 @end example
10873 @noindent
10874 Huh?  The first case is easily understood, but why is the second wrong,
10875 and the third right?  To understand that, you must know that after
10876 M4 expands a macro, the resulting text is immediately subjected
10877 to macro expansion and quote removal.  This means that the quote removal
10878 occurs twice---first before the argument is passed to the @code{car}
10879 macro, and second after the @code{car} macro expands to the first
10880 argument.
10882 As the author of the Autoconf macro @code{car}, you then consider it to
10883 be incorrect that your users have to double-quote the arguments of
10884 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
10885 quoted car:
10887 @example
10888 define([qar], [[$1]])
10889 @end example
10891 @noindent
10892 and check that @code{qar} is properly fixed:
10894 @example
10895 qar([int tab[10];])
10896 @result{}int tab[10];
10897 @end example
10899 @noindent
10900 Ahhh!  That's much better.
10902 But note what you've done: now that the result of @code{qar} is always
10903 a literal string, the only time a user can use nested macros is if she
10904 relies on an @emph{unquoted} macro call:
10906 @example
10907 qar(active)
10908 @result{}ACT
10909 qar([active])
10910 @result{}active
10911 @end example
10913 @noindent
10914 leaving no way for her to reproduce what she used to do with @code{car}:
10916 @example
10917 car([active])
10918 @result{}ACT, IVE
10919 @end example
10921 @noindent
10922 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10923 macros:
10925 @example
10926 define([my_includes], [#include <stdio.h>])
10927 car([my_includes])
10928 @result{}#include <stdio.h>
10929 qar(my_includes)
10930 @error{}EOF in argument list
10931 @end example
10933 This macro, @code{qar}, because it double quotes its arguments, forces
10934 its users to leave their macro calls unquoted, which is dangerous.
10935 Commas and other active symbols are interpreted by M4 before
10936 they are given to the macro, often not in the way the users expect.
10937 Also, because @code{qar} behaves differently from the other macros,
10938 it's an exception that should be avoided in Autoconf.
10940 @node Changequote is Evil
10941 @subsection @code{changequote} is Evil
10942 @cindex @code{changequote}
10944 The temptation is often high to bypass proper quotation, in particular
10945 when it's late at night.  Then, many experienced Autoconf hackers
10946 finally surrender to the dark side of the force and use the ultimate
10947 weapon: @code{changequote}.
10949 The M4 builtin @code{changequote} belongs to a set of primitives that
10950 allow one to adjust the syntax of the language to adjust it to one's
10951 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
10952 quotes, but in the context of shell programming (and actually of most
10953 programming languages), that's about the worst choice one can make:
10954 because of strings and back-quoted expressions in shell code (such as
10955 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
10956 programming languages (as in @samp{'0'}), there are many unbalanced
10957 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
10958 not impossible.  In order to make M4 useful in such a context, its
10959 designers have equipped it with @code{changequote}, which makes it
10960 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
10961 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
10962 because they are unlikely characters, but @emph{because they are
10963 characters unlikely to be unbalanced}.
10965 There are other magic primitives, such as @code{changecom} to specify
10966 what syntactic forms are comments (it is common to see
10967 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10968 @code{changeword} and @code{changesyntax} to change other syntactic
10969 details (such as the character to denote the @var{n}th argument, @samp{$} by
10970 default, the parentheses around arguments, etc.).
10972 These primitives are really meant to make M4 more useful for specific
10973 domains: they should be considered like command line options:
10974 @option{--quotes}, @option{--comments}, @option{--words}, and
10975 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
10976 it makes M4 libraries self contained (no need for additional options).
10978 There lies the problem@enddots{}
10980 @sp 1
10982 The problem is that it is then tempting to use them in the middle of an
10983 M4 script, as opposed to its initialization.  This, if not carefully
10984 thought out, can lead to disastrous effects: @emph{you are changing the
10985 language in the middle of the execution}.  Changing and restoring the
10986 syntax is often not enough: if you happened to invoke macros in between,
10987 these macros are lost, as the current syntax is probably not
10988 the one they were implemented with.
10990 @c FIXME: I've been looking for a short, real case example, but I
10991 @c lost them all :(
10994 @node Quadrigraphs
10995 @subsection Quadrigraphs
10996 @cindex quadrigraphs
10997 @cindex @samp{@@S|@@}
10998 @cindex @samp{@@&t@@}
10999 @c Info cannot handle ':' in index entries.
11000 @ifnotinfo
11001 @cindex @samp{@@<:@@}
11002 @cindex @samp{@@:>@@}
11003 @cindex @samp{@@%:@@}
11004 @cindex @samp{@@@{:@@}
11005 @cindex @samp{@@:@}@@}
11006 @end ifnotinfo
11008 When writing an Autoconf macro you may occasionally need to generate
11009 special characters that are difficult to express with the standard
11010 Autoconf quoting rules.  For example, you may need to output the regular
11011 expression @samp{[^[]}, which matches any character other than @samp{[}.
11012 This expression contains unbalanced brackets so it cannot be put easily
11013 into an M4 macro.
11015 Additionally, there are a few m4sugar macros (such as @code{m4_split}
11016 and @code{m4_expand}) which internally use special markers in addition
11017 to the regular quoting characters.  If the arguments to these macros
11018 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
11019 might behave incorrectly.
11021 You can work around these problems by using one of the following
11022 @dfn{quadrigraphs}:
11024 @table @samp
11025 @item @@<:@@
11026 @samp{[}
11027 @item @@:>@@
11028 @samp{]}
11029 @item @@S|@@
11030 @samp{$}
11031 @item @@%:@@
11032 @samp{#}
11033 @item @@@{:@@
11034 @samp{(}
11035 @item @@:@}@@
11036 @samp{)}
11037 @item @@&t@@
11038 Expands to nothing.
11039 @end table
11041 Quadrigraphs are replaced at a late stage of the translation process,
11042 after @command{m4} is run, so they do not get in the way of M4 quoting.
11043 For example, the string @samp{^@@<:@@}, independently of its quotation,
11044 appears as @samp{^[} in the output.
11046 The empty quadrigraph can be used:
11048 @itemize @minus
11049 @item to mark trailing spaces explicitly
11051 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
11053 @item to produce quadrigraphs and other strings reserved by m4sugar
11055 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
11056 contrived example:
11058 @example
11059 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
11060 m4_split([a )@}>=- b -=<@{( c])
11061 @result{}[a], [], [B], [], [c]
11062 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
11063 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
11064 @end example
11066 @item to escape @emph{occurrences} of forbidden patterns
11068 For instance you might want to mention @code{AC_FOO} in a comment, while
11069 still being sure that @command{autom4te} still catches unexpanded
11070 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
11071 @end itemize
11073 The name @samp{@@&t@@} was suggested by Paul Eggert:
11075 @quotation
11076 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
11077 own invention, but the @samp{t} came from the source code of the
11078 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
11079 and which used @samp{mt} to denote the empty string.  In C, it would
11080 have looked like something like:
11082 @example
11083 char const mt[] = "";
11084 @end example
11086 @noindent
11087 but of course the source code was written in Algol 68.
11089 I don't know where he got @samp{mt} from: it could have been his own
11090 invention, and I suppose it could have been a common pun around the
11091 Cambridge University computer lab at the time.
11092 @end quotation
11095 @node Balancing Parentheses
11096 @subsection Dealing with unbalanced parentheses
11097 @cindex balancing parentheses
11098 @cindex parentheses, balancing
11099 @cindex unbalanced parentheses, managing
11101 One of the pitfalls of portable shell programming is that
11102 if you intend your script to run with obsolescent shells,
11103 @command{case} statements require unbalanced parentheses.
11104 @xref{case, , Limitations of Shell Builtins}.
11105 With syntax highlighting
11106 editors, the presence of unbalanced @samp{)} can interfere with editors
11107 that perform syntax highlighting of macro contents based on finding the
11108 matching @samp{(}.  Another concern is how much editing must be done
11109 when transferring code snippets between shell scripts and macro
11110 definitions.  But most importantly, the presence of unbalanced
11111 parentheses can introduce expansion bugs.
11113 For an example, here is an underquoted attempt to use the macro
11114 @code{my_case}, which happens to expand to a portable @command{case}
11115 statement:
11117 @example
11118 AC_DEFUN([my_case],
11119 [case $file_name in
11120   *.c) echo "C source code";;
11121 esac])
11122 AS_IF(:, my_case)
11123 @end example
11125 @noindent
11126 In the above example, the @code{AS_IF} call under-quotes its arguments.
11127 As a result, the unbalanced @samp{)} generated by the premature
11128 expansion of @code{my_case} results in expanding @code{AS_IF} with a
11129 truncated parameter, and the expansion is syntactically invalid:
11131 @example
11132 if :; then
11133   case $file_name in
11134   *.c
11135 fi echo "C source code";;
11136 esac)
11137 @end example
11139 If nothing else, this should emphasize the importance of the quoting
11140 arguments to macro calls.  On the other hand, there are several
11141 variations for defining @code{my_case} to be more robust, even when used
11142 without proper quoting, each with some benefits and some drawbacks.
11144 @itemize @w{}
11145 @item Use left parenthesis before pattern
11146 @example
11147 AC_DEFUN([my_case],
11148 [case $file_name in
11149   (*.c) echo "C source code";;
11150 esac])
11151 @end example
11152 @noindent
11153 This is simple and provides balanced parentheses.  Although this is not
11154 portable to obsolescent shells (notably Solaris 10 @command{/bin/sh}),
11155 platforms with these shells invariably have a more-modern shell
11156 available somewhere so this approach typically suffices nowadays.
11158 @item Creative literal shell comment
11159 @example
11160 AC_DEFUN([my_case],
11161 [case $file_name in #(
11162   *.c) echo "C source code";;
11163 esac])
11164 @end example
11165 @noindent
11166 This version provides balanced parentheses to several editors, and can
11167 be copied and pasted into a terminal as is.  Unfortunately, it is still
11168 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
11169 that masks the normal properties of @samp{(}.
11171 @item Quadrigraph shell comment
11172 @example
11173 AC_DEFUN([my_case],
11174 [case $file_name in @@%:@@(
11175   *.c) echo "C source code";;
11176 esac])
11177 @end example
11178 @noindent
11179 This version provides balanced parentheses to even more editors, and can
11180 be used as a balanced Autoconf argument.  Unfortunately, it requires
11181 some editing before it can be copied and pasted into a terminal, and the
11182 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
11184 @item Quoting just the parenthesis
11185 @example
11186 AC_DEFUN([my_case],
11187 [case $file_name in
11188   *.c[)] echo "C source code";;
11189 esac])
11190 @end example
11191 @noindent
11192 This version quotes the @samp{)}, so that it can be used as a balanced
11193 Autoconf argument.  As written, this is not balanced to an editor, but
11194 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
11195 still requires some edits before it can be copied and pasted into a
11196 terminal.
11198 @item Double-quoting the entire statement
11199 @example
11200 AC_DEFUN([my_case],
11201 [[case $file_name in #(
11202   *.c) echo "C source code";;
11203 esac]])
11204 @end example
11205 @noindent
11206 Since the entire macro is double-quoted, there is no problem with using
11207 this as an Autoconf argument; and since the double-quoting is over the
11208 entire statement, this code can be easily copied and pasted into a
11209 terminal.  However, the double quoting prevents the expansion of any
11210 macros inside the case statement, which may cause its own set of
11211 problems.
11213 @item Using @code{AS_CASE}
11214 @example
11215 AC_DEFUN([my_case],
11216 [AS_CASE([$file_name],
11217   [*.c], [echo "C source code"])])
11218 @end example
11219 @noindent
11220 This version avoids the balancing issue altogether, by relying on
11221 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
11222 expansion of @code{AC_REQUIRE} to occur prior to the entire case
11223 statement, rather than within a branch of the case statement that might
11224 not be taken.  However, the abstraction comes with a penalty that it is
11225 no longer a quick copy, paste, and edit to get back to shell code.
11226 @end itemize
11229 @node Quotation Rule Of Thumb
11230 @subsection Quotation Rule Of Thumb
11232 To conclude, the quotation rule of thumb is:
11234 @center @emph{One pair of quotes per pair of parentheses.}
11236 Never over-quote, never under-quote, in particular in the definition of
11237 macros.  In the few places where the macros need to use brackets
11238 (usually in C program text or regular expressions), properly quote
11239 @emph{the arguments}!
11241 It is common to read Autoconf programs with snippets like:
11243 @example
11244 AC_TRY_LINK(
11245 changequote(<<, >>)dnl
11246 <<#include <time.h>
11247 #ifndef tzname /* For SGI.  */
11248 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11249 #endif>>,
11250 changequote([, ])dnl
11251 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11252 @end example
11254 @noindent
11255 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11256 double quoting, so you just need:
11258 @example
11259 AC_TRY_LINK(
11260 [#include <time.h>
11261 #ifndef tzname /* For SGI.  */
11262 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11263 #endif],
11264             [atoi (*tzname);],
11265             [ac_cv_var_tzname=yes],
11266             [ac_cv_var_tzname=no])
11267 @end example
11269 @noindent
11270 The M4-fluent reader might note that these two examples are rigorously
11271 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11272 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11273 quotes are not part of the arguments!
11275 Simplified, the example above is just doing this:
11277 @example
11278 changequote(<<, >>)dnl
11279 <<[]>>
11280 changequote([, ])dnl
11281 @end example
11283 @noindent
11284 instead of simply:
11286 @example
11287 [[]]
11288 @end example
11290 With macros that do not double quote their arguments (which is the
11291 rule), double-quote the (risky) literals:
11293 @example
11294 AC_LINK_IFELSE([AC_LANG_PROGRAM(
11295 [[#include <time.h>
11296 #ifndef tzname /* For SGI.  */
11297 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11298 #endif]],
11299                                 [atoi (*tzname);])],
11300                [ac_cv_var_tzname=yes],
11301                [ac_cv_var_tzname=no])
11302 @end example
11304 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11305 should be using @code{AC_LINK_IFELSE} instead.
11307 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
11308 where quoting does not suffice.
11310 When you create a @command{configure} script using newly written macros,
11311 examine it carefully to check whether you need to add more quotes in
11312 your macros.  If one or more words have disappeared in the M4
11313 output, you need more quotes.  When in doubt, quote.
11315 However, it's also possible to put on too many layers of quotes.  If
11316 this happens, the resulting @command{configure} script may contain
11317 unexpanded macros.  The @command{autoconf} program checks for this problem
11318 by looking for the string @samp{AC_} in @file{configure}.  However, this
11319 heuristic does not work in general: for example, it does not catch
11320 overquoting in @code{AC_DEFINE} descriptions.
11323 @c ---------------------------------------- Using autom4te
11325 @node Using autom4te
11326 @section Using @command{autom4te}
11328 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11329 to Autoconf per se, heavily rely on M4.  All these different uses
11330 revealed common needs factored into a layer over M4:
11331 @command{autom4te}@footnote{
11333 Yet another great name from Lars J. Aas.
11337 @command{autom4te} is a preprocessor that is like @command{m4}.
11338 It supports M4 extensions designed for use in tools like Autoconf.
11340 @menu
11341 * autom4te Invocation::         A GNU M4 wrapper
11342 * Customizing autom4te::        Customizing the Autoconf package
11343 @end menu
11345 @node autom4te Invocation
11346 @subsection Invoking @command{autom4te}
11348 The command line arguments are modeled after M4's:
11350 @example
11351 autom4te @var{options} @var{files}
11352 @end example
11354 @noindent
11355 @evindex M4
11356 where the @var{files} are directly passed to @command{m4}.  By default,
11357 GNU M4 is found during configuration, but the environment
11358 variable
11359 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
11360 to the regular expansion, it handles the replacement of the quadrigraphs
11361 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11362 output.  It supports an extended syntax for the @var{files}:
11364 @table @file
11365 @item @var{file}.m4f
11366 This file is an M4 frozen file.  Note that @emph{all the previous files
11367 are ignored}.  See the @option{--melt} option for the rationale.
11369 @item @var{file}?
11370 If found in the library path, the @var{file} is included for expansion,
11371 otherwise it is ignored instead of triggering a failure.
11372 @end table
11374 @sp 1
11376 Of course, it supports the Autoconf common subset of options:
11378 @table @option
11379 @item --help
11380 @itemx -h
11381 Print a summary of the command line options and exit.
11383 @item --version
11384 @itemx -V
11385 Print the version number of Autoconf and exit.
11387 @item --verbose
11388 @itemx -v
11389 Report processing steps.
11391 @item --debug
11392 @itemx -d
11393 Don't remove the temporary files and be even more verbose.
11395 @item --include=@var{dir}
11396 @itemx -I @var{dir}
11397 Also look for input files in @var{dir}.  Multiple invocations
11398 accumulate.
11400 @item --output=@var{file}
11401 @itemx -o @var{file}
11402 Save output (script or trace) to @var{file}.  The file @option{-} stands
11403 for the standard output.
11404 @end table
11406 @sp 1
11408 As an extension of @command{m4}, it includes the following options:
11410 @table @option
11412 @item --warnings=@var{category}[,@var{category}...]
11413 @itemx -W@var{category}[,@var{category}...]
11414 @evindex WARNINGS
11415 Enable or disable warnings related to each @var{category}.
11416 @xref{m4_warn}, for a comprehensive list of categories.
11417 Special values include:
11419 @table @samp
11420 @item all
11421 Enable all categories of warnings.
11423 @item none
11424 Disable all categories of warnings.
11426 @item error
11427 Treat all warnings as errors.
11429 @item no-@var{category}
11430 Disable warnings falling into @var{category}.
11431 @end table
11433 The enviroment variable @env{WARNINGS} may also be set to a
11434 comma-separated list of warning categories to enable or disable.
11435 It is interpreted exactly the same way as the argument of
11436 @option{--warnings}, but unknown categories are silently ignored.
11437 The command line takes precedence; for instance, if @env{WARNINGS}
11438 is set to @code{obsolete}, but @option{-Wnone} is given on the
11439 command line, no warnings will be issued.
11441 Some categories of warnings are on by default.
11442 Again, for details see @ref{m4_warn}.
11444 @item --melt
11445 @itemx -M
11446 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
11447 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
11448 are executed only when the files are frozen, typically
11449 @code{m4_define}.  For instance, running:
11451 @example
11452 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11453 @end example
11455 @noindent
11456 is roughly equivalent to running:
11458 @example
11459 m4 1.m4 2.m4 3.m4 4.m4 input.m4
11460 @end example
11462 @noindent
11463 while
11465 @example
11466 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11467 @end example
11469 @noindent
11470 is equivalent to:
11472 @example
11473 m4 --reload-state=4.m4f input.m4
11474 @end example
11476 @item --freeze
11477 @itemx -F
11478 Produce a frozen state file.  @command{autom4te} freezing is stricter
11479 than M4's: it must produce no warnings, and no output other than empty
11480 lines (a line with white space is @emph{not} empty) and comments
11481 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
11482 this option takes no argument:
11484 @example
11485 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11486 @end example
11488 @noindent
11489 corresponds to
11491 @example
11492 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11493 @end example
11495 @item --mode=@var{octal-mode}
11496 @itemx -m @var{octal-mode}
11497 Set the mode of the non-traces output to @var{octal-mode}; by default
11498 @samp{0666}.
11499 @end table
11501 @sp 1
11503 @cindex @file{autom4te.cache}
11504 As another additional feature over @command{m4}, @command{autom4te}
11505 caches its results.  GNU M4 is able to produce a regular
11506 output and traces at the same time.  Traces are heavily used in the
11507 GNU Build System: @command{autoheader} uses them to build
11508 @file{config.h.in}, @command{autoreconf} to determine what
11509 GNU Build System components are used, @command{automake} to
11510 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
11511 traces are cached while performing regular expansion,
11512 and conversely.  This cache is (actually, the caches are) stored in
11513 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
11514 at any moment (especially if for some reason @command{autom4te}
11515 considers it trashed).
11517 @table @option
11518 @item --cache=@var{directory}
11519 @itemx -C @var{directory}
11520 Specify the name of the directory where the result should be cached.
11521 Passing an empty value disables caching.  Be sure to pass a relative
11522 file name, as for the time being, global caches are not supported.
11524 @item --no-cache
11525 Don't cache the results.
11527 @item --force
11528 @itemx -f
11529 If a cache is used, consider it obsolete (but update it anyway).
11530 @end table
11532 @sp 1
11534 Because traces are so important to the GNU Build System,
11535 @command{autom4te} provides high level tracing features as compared to
11536 M4, and helps exploiting the cache:
11538 @table @option
11539 @item --trace=@var{macro}[:@var{format}]
11540 @itemx -t @var{macro}[:@var{format}]
11541 Trace the invocations of @var{macro} according to the @var{format}.
11542 Multiple @option{--trace} arguments can be used to list several macros.
11543 Multiple @option{--trace} arguments for a single macro are not
11544 cumulative; instead, you should just make @var{format} as long as
11545 needed.
11547 The @var{format} is a regular string, with newlines if desired, and
11548 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
11549 use the following special escapes:
11551 @table @samp
11552 @item $$
11553 @c $$ restore font-lock
11554 The character @samp{$}.
11556 @item $f
11557 The file name from which @var{macro} is called.
11559 @item $l
11560 The line number from which @var{macro} is called.
11562 @item $d
11563 The depth of the @var{macro} call.  This is an M4 technical detail that
11564 you probably don't want to know about.
11566 @item $n
11567 The name of the @var{macro}.
11569 @item $@var{num}
11570 The @var{num}th argument of the call to @var{macro}.
11572 @item $@@
11573 @itemx $@var{sep}@@
11574 @itemx $@{@var{separator}@}@@
11575 All the arguments passed to @var{macro}, separated by the character
11576 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
11577 argument is quoted, i.e., enclosed in a pair of square brackets.
11579 @item $*
11580 @itemx $@var{sep}*
11581 @itemx $@{@var{separator}@}*
11582 As above, but the arguments are not quoted.
11584 @item $%
11585 @itemx $@var{sep}%
11586 @itemx $@{@var{separator}@}%
11587 As above, but the arguments are not quoted, all new line characters in
11588 the arguments are smashed, and the default separator is @samp{:}.
11590 The escape @samp{$%} produces single-line trace outputs (unless you put
11591 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11592 not.
11593 @end table
11595 @xref{autoconf Invocation}, for examples of trace uses.
11597 @item --preselect=@var{macro}
11598 @itemx -p @var{macro}
11599 Cache the traces of @var{macro}, but do not enable traces.  This is
11600 especially important to save CPU cycles in the future.  For instance,
11601 when invoked, @command{autoconf} pre-selects all the macros that
11602 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11603 trace, so that running @command{m4} is not needed to trace them: the
11604 cache suffices.  This results in a huge speed-up.
11605 @end table
11607 @sp 1
11609 @cindex Autom4te Library
11610 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11611 libraries}.  They consists in a powerful yet extremely simple feature:
11612 sets of combined command line arguments:
11614 @table @option
11615 @item --language=@var{language}
11616 @itemx -l @var{language}
11617 Use the @var{language} Autom4te library.  Current languages include:
11619 @table @code
11620 @item M4sugar
11621 create M4sugar output.
11623 @item M4sh
11624 create M4sh executable shell scripts.
11626 @item Autotest
11627 create Autotest executable test suites.
11629 @item Autoconf-without-aclocal-m4
11630 create Autoconf executable configure scripts without
11631 reading @file{aclocal.m4}.
11633 @item Autoconf
11634 create Autoconf executable configure scripts.  This language inherits
11635 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11636 additionally reads @file{aclocal.m4}.
11637 @end table
11639 @item --prepend-include=@var{dir}
11640 @itemx -B @var{dir}
11641 Prepend directory @var{dir} to the search path.  This is used to include
11642 the language-specific files before any third-party macros.
11644 @end table
11646 @cindex @file{autom4te.cfg}
11647 As an example, if Autoconf is installed in its default location,
11648 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11649 strictly equivalent to the command:
11651 @example
11652 autom4te --prepend-include /usr/local/share/autoconf \
11653   m4sugar/m4sugar.m4f foo.m4
11654 @end example
11656 @noindent
11657 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11658 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11659 foo.m4}, i.e.:
11661 @example
11662 autom4te --prepend-include /usr/local/share/autoconf \
11663   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11664 @end example
11666 @noindent
11667 The definition of the languages is stored in @file{autom4te.cfg}.
11669 @node Customizing autom4te
11670 @subsection Customizing @command{autom4te}
11672 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11673 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11674 as found in the directory from which @command{autom4te} is run).  The
11675 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11676 then @file{./.autom4te.cfg}, and finally the command line arguments.
11678 In these text files, comments are introduced with @code{#}, and empty
11679 lines are ignored.  Customization is performed on a per-language basis,
11680 wrapped in between a @samp{begin-language: "@var{language}"},
11681 @samp{end-language: "@var{language}"} pair.
11683 Customizing a language stands for appending options (@pxref{autom4te
11684 Invocation}) to the current definition of the language.  Options, and
11685 more generally arguments, are introduced by @samp{args:
11686 @var{arguments}}.  You may use the traditional shell syntax to quote the
11687 @var{arguments}.
11689 As an example, to disable Autoconf caches (@file{autom4te.cache})
11690 globally, include the following lines in @file{~/.autom4te.cfg}:
11692 @verbatim
11693 ## ------------------ ##
11694 ## User Preferences.  ##
11695 ## ------------------ ##
11697 begin-language: "Autoconf-without-aclocal-m4"
11698 args: --no-cache
11699 end-language: "Autoconf-without-aclocal-m4"
11700 @end verbatim
11703 @node Programming in M4sugar
11704 @section Programming in M4sugar
11706 @cindex M4sugar
11707 M4 by itself provides only a small, but sufficient, set of all-purpose
11708 macros.  M4sugar introduces additional generic macros.  Its name was
11709 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11710 M4sugar''.
11712 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11713 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
11714 define your own macros into these namespaces.
11716 @menu
11717 * Redefined M4 Macros::         M4 builtins changed in M4sugar
11718 * Diagnostic Macros::           Diagnostic messages from M4sugar
11719 * Diversion support::           Diversions in M4sugar
11720 * Conditional constructs::      Conditions in M4
11721 * Looping constructs::          Iteration in M4
11722 * Evaluation Macros::           More quotation and evaluation control
11723 * Text processing Macros::      String manipulation in M4
11724 * Number processing Macros::    Arithmetic computation in M4
11725 * Set manipulation Macros::     Set manipulation in M4
11726 * Forbidden Patterns::          Catching unexpanded macros
11727 @end menu
11729 @node Redefined M4 Macros
11730 @subsection Redefined M4 Macros
11732 @msindex{builtin}
11733 @msindex{changecom}
11734 @msindex{changequote}
11735 @msindex{debugfile}
11736 @msindex{debugmode}
11737 @msindex{decr}
11738 @msindex{define}
11739 @msindex{divnum}
11740 @msindex{errprint}
11741 @msindex{esyscmd}
11742 @msindex{eval}
11743 @msindex{format}
11744 @msindex{ifdef}
11745 @msindex{incr}
11746 @msindex{index}
11747 @msindex{indir}
11748 @msindex{len}
11749 @msindex{pushdef}
11750 @msindex{shift}
11751 @msindex{substr}
11752 @msindex{syscmd}
11753 @msindex{sysval}
11754 @msindex{traceoff}
11755 @msindex{traceon}
11756 @msindex{translit}
11757 With a few exceptions, all the M4 native macros are moved in the
11758 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11759 @code{m4_define} etc.
11761 The list of macros unchanged from M4, except for their name, is:
11762 @itemize @minus
11763 @item m4_builtin
11764 @item m4_changecom
11765 @item m4_changequote
11766 @item m4_debugfile
11767 @item m4_debugmode
11768 @item m4_decr
11769 @item m4_define
11770 @item m4_divnum
11771 @item m4_errprint
11772 @item m4_esyscmd
11773 @item m4_eval
11774 @item m4_format
11775 @item m4_ifdef
11776 @item m4_incr
11777 @item m4_index
11778 @item m4_indir
11779 @item m4_len
11780 @item m4_pushdef
11781 @item m4_shift
11782 @item m4_substr
11783 @item m4_syscmd
11784 @item m4_sysval
11785 @item m4_traceoff
11786 @item m4_traceon
11787 @item m4_translit
11788 @end itemize
11790 Some M4 macros are redefined, and are slightly incompatible with their
11791 native equivalent.
11793 @defmac __file__
11794 @defmacx __line__
11795 @MSindex __file__
11796 @MSindex __line__
11797 All M4 macros starting with @samp{__} retain their original name: for
11798 example, no @code{m4__file__} is defined.
11799 @end defmac
11801 @defmac __oline__
11802 @MSindex __oline__
11803 This is not technically a macro, but a feature of Autom4te.  The
11804 sequence @code{__oline__} can be used similarly to the other m4sugar
11805 location macros, but rather than expanding to the location of the input
11806 file, it is translated to the line number where it appears in the output
11807 file after all other M4 expansions.
11808 @end defmac
11810 @defmac dnl
11811 @MSindex dnl
11812 This macro kept its original name: no @code{m4_dnl} is defined.
11813 @end defmac
11815 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11816 @msindex{bpatsubst}
11817 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
11818 is kept for future versions of M4sugar, once GNU M4 2.0 is
11819 released and supports extended regular expression syntax.
11820 @end defmac
11822 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11823 @msindex{bregexp}
11824 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
11825 is kept for future versions of M4sugar, once GNU M4 2.0 is
11826 released and supports extended regular expression syntax.
11827 @end defmac
11829 @defmac m4_copy (@var{source}, @var{dest})
11830 @defmacx m4_copy_force (@var{source}, @var{dest})
11831 @defmacx m4_rename (@var{source}, @var{dest})
11832 @defmacx m4_rename_force (@var{source}, @var{dest})
11833 @msindex{copy}
11834 @msindex{copy_force}
11835 @msindex{rename}
11836 @msindex{rename_force}
11837 These macros aren't directly builtins, but are closely related to
11838 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
11839 @code{m4_rename} ensure that @var{dest} is undefined, while
11840 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11841 definition.  All four macros then proceed to copy the entire pushdef
11842 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
11843 and @code{m4_copy_force} preserve the source (including in the special
11844 case where @var{source} is undefined), while @code{m4_rename} and
11845 @code{m4_rename_force} undefine the original macro name (making it an
11846 error to rename an undefined @var{source}).
11848 Note that attempting to invoke a renamed macro might not work, since the
11849 macro may have a dependence on helper macros accessed via composition of
11850 @samp{$0} but that were not also renamed; likewise, other macros may
11851 have a hard-coded dependence on @var{source} and could break if
11852 @var{source} has been deleted.  On the other hand, it is always safe to
11853 rename a macro to temporarily move it out of the way, then rename it
11854 back later to restore original semantics.
11855 @end defmac
11857 @defmac m4_defn (@var{macro}@dots{})
11858 @msindex{defn}
11859 This macro fails if @var{macro} is not defined, even when using older
11860 versions of M4 that did not warn.  See @code{m4_undefine}.
11861 Unfortunately, in order to support these older versions of M4, there are
11862 some situations involving unbalanced quotes where concatenating multiple
11863 macros together will work in newer M4 but not in m4sugar; use
11864 quadrigraphs to work around this.
11865 @end defmac
11867 @defmac m4_divert (@var{diversion})
11868 @msindex{divert}
11869 M4sugar relies heavily on diversions, so rather than behaving as a
11870 primitive, @code{m4_divert} behaves like:
11871 @example
11872 m4_divert_pop()m4_divert_push([@var{diversion}])
11873 @end example
11874 @noindent
11875 @xref{Diversion support}, for more details about the use of the
11876 diversion stack.  In particular, this implies that @var{diversion}
11877 should be a named diversion rather than a raw number.  But be aware that
11878 it is seldom necessary to explicitly change the diversion stack, and
11879 that when done incorrectly, it can lead to syntactically invalid
11880 scripts.
11881 @end defmac
11883 @defmac m4_dumpdef (@var{name}@dots{})
11884 @defmacx m4_dumpdefs (@var{name}@dots{})
11885 @msindex{dumpdef}
11886 @msindex{dumpdefs}
11887 @code{m4_dumpdef} is like the M4 builtin, except that this version
11888 requires at least one argument, output always goes to standard error
11889 rather than the current debug file, no sorting is done on multiple
11890 arguments, and an error is issued if any
11891 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
11892 calls @code{m4_dumpdef} for all of the
11893 @code{m4_pushdef} stack of definitions, starting with the current, and
11894 silently does nothing if @var{name} is undefined.
11896 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11897 builtin is output as the empty string.  This behavior is rectified by
11898 using M4 1.6 or newer.  However, this behavior difference means that
11899 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11900 and never in the final published form of a macro.
11901 @end defmac
11903 @defmac m4_esyscmd_s (@var{command})
11904 @msindex{esyscmd_s}
11905 Like @code{m4_esyscmd}, this macro expands to the result of running
11906 @var{command} in a shell.  The difference is that any trailing newlines
11907 are removed, so that the output behaves more like shell command
11908 substitution.
11909 @end defmac
11911 @defmac m4_exit (@var{exit-status})
11912 @msindex{exit}
11913 This macro corresponds to @code{m4exit}.
11914 @end defmac
11916 @defmac m4_if (@var{comment})
11917 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11918 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11919   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11920 @msindex{if}
11921 This macro corresponds to @code{ifelse}.  @var{string-1} and
11922 @var{string-2} are compared literally, so usually one of the two
11923 arguments is passed unquoted.  @xref{Conditional constructs}, for more
11924 conditional idioms.
11925 @end defmac
11927 @defmac m4_include (@var{file})
11928 @defmacx m4_sinclude (@var{file})
11929 @msindex{include}
11930 @msindex{sinclude}
11931 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11932 @end defmac
11934 @defmac m4_mkstemp (@var{template})
11935 @defmacx m4_maketemp (@var{template})
11936 @msindex{maketemp}
11937 @msindex{mkstemp}
11938 Posix requires @code{maketemp} to replace the trailing @samp{X}
11939 characters in @var{template} with the process id, without regards to the
11940 existence of a file by that name, but this a security hole.  When this
11941 was pointed out to the Posix folks, they agreed to invent a new macro
11942 @code{mkstemp} that always creates a uniquely named file, but not all
11943 versions of GNU M4 support the new macro.  In M4sugar,
11944 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11945 and both have the secure semantics regardless of which macro the
11946 underlying M4 provides.
11947 @end defmac
11949 @defmac m4_popdef (@var{macro}@dots{})
11950 @msindex{popdef}
11951 This macro fails if @var{macro} is not defined, even when using older
11952 versions of M4 that did not warn.  See @code{m4_undefine}.
11953 @end defmac
11955 @defmac m4_undefine (@var{macro}@dots{})
11956 @msindex{undefine}
11957 This macro fails if @var{macro} is not defined, even when using older
11958 versions of M4 that did not warn.  Use
11960 @example
11961 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11962 @end example
11964 @noindent
11965 if you are not sure whether @var{macro} is defined.
11966 @end defmac
11968 @defmac m4_undivert (@var{diversion}@dots{})
11969 @msindex{undivert}
11970 Unlike the M4 builtin, at least one @var{diversion} must be specified.
11971 Also, since the M4sugar diversion stack prefers named
11972 diversions, the use of @code{m4_undivert} to include files is risky.
11973 @xref{Diversion support}, for more details about the use of the
11974 diversion stack.  But be aware that it is seldom necessary to explicitly
11975 change the diversion stack, and that when done incorrectly, it can lead
11976 to syntactically invalid scripts.
11977 @end defmac
11979 @defmac m4_wrap (@var{text})
11980 @defmacx m4_wrap_lifo (@var{text})
11981 @msindex{wrap}
11982 @msindex{wrap_lifo}
11983 These macros correspond to @code{m4wrap}.  Posix requires arguments of
11984 multiple wrap calls to be reprocessed at EOF in the same order
11985 as the original calls (first-in, first-out).  GNU M4 versions
11986 through 1.4.10, however, reprocess them in reverse order (last-in,
11987 first-out).  Both orders are useful, therefore, you can rely on
11988 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11989 LIFO semantics, regardless of the underlying GNU M4 version.
11991 Unlike the GNU M4 builtin, these macros only recognize one
11992 argument, and avoid token pasting between consecutive invocations.  On
11993 the other hand, nested calls to @code{m4_wrap} from within wrapped text
11994 work just as in the builtin.
11995 @end defmac
11998 @node Diagnostic Macros
11999 @subsection Diagnostic messages from M4sugar
12000 @cindex Messages, from @command{M4sugar}
12002 When macros statically diagnose abnormal situations, benign or fatal,
12003 they should report them using these macros.  For issuing dynamic issues,
12004 i.e., when @command{configure} is run, see @ref{Printing Messages}.
12006 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
12007 @msindex{assert}
12008 Assert that the arithmetic @var{expression} evaluates to non-zero.
12009 Otherwise, issue a fatal error, and exit @command{autom4te} with
12010 @var{exit-status}.
12011 @end defmac
12013 @defmac m4_errprintn (@var{message})
12014 @msindex{errprintn}
12015 Similar to the builtin @code{m4_errprint}, except that a newline is
12016 guaranteed after @var{message}.
12017 @end defmac
12019 @anchor{m4_fatal}
12020 @defmac m4_fatal (@var{message})
12021 @msindex{fatal}
12022 Report a severe error @var{message} prefixed with the current location,
12023 and have @command{autom4te} die.
12024 @end defmac
12026 @defmac m4_location
12027 @msindex{location}
12028 Useful as a prefix in a message line.  Short for:
12029 @example
12030 __file__:__line__
12031 @end example
12032 @end defmac
12034 @anchor{m4_warn}
12035 @defmac m4_warn (@var{category}, @var{message})
12036 @msindex{warn}
12037 Report @var{message} as a warning (or as an error if requested by the
12038 user) if warnings of the @var{category} are turned on.  If the message
12039 is emitted, it is prefixed with the current location, and followed by a
12040 call trace of all macros defined via @code{AC_DEFUN} used to get to the
12041 current expansion.
12043 The @var{category} must be one of:
12045 @table @samp
12046 @item cross
12047 Warnings about constructs that may interfere with cross-compilation,
12048 such as using @code{AC_RUN_IFELSE} without a default.
12050 @item gnu
12051 Warnings related to the GNU Coding Standards
12052 (@pxref{Top,,, standards, The GNU Coding Standards}).
12053 On by default.
12055 @item obsolete
12056 Warnings about obsolete features.  On by default.
12058 @item override
12059 Warnings about redefinitions of Autoconf internals.
12061 @item portability
12062 Warnings about non-portable constructs.
12064 @item portability-recursive
12065 Warnings about recursive Make variable expansions (@code{$(foo$(x))}).
12067 @item extra-portability
12068 Extra warnings about non-portable constructs, covering rarely-used
12069 tools.
12071 @item syntax
12072 Warnings about questionable syntactic constructs, incorrectly ordered
12073 macro calls, typos, etc.  On by default.
12075 @item unsupported
12076 Warnings about unsupported features.  On by default.
12077 @end table
12079 @strong{Hacking Note:} The set of categories is defined by code in
12080 @command{autom4te}, not by M4sugar itself.  Additions should be
12081 coordinated with Automake, so that both sets of tools accept the same
12082 options.
12083 @end defmac
12085 @node Diversion support
12086 @subsection Diversion support
12088 M4sugar makes heavy use of diversions under the hood, because it is
12089 often the case that
12090 text that must appear early in the output is not discovered until late
12091 in the input.  Additionally, some of the topological sorting algorithms
12092 used in resolving macro dependencies use diversions.  However, most
12093 macros should not need to change diversions directly, but rather rely on
12094 higher-level M4sugar macros to manage diversions transparently.  If you
12095 change diversions improperly, you risk generating a syntactically
12096 invalid script, because an incorrect diversion will violate assumptions
12097 made by many macros about whether prerequisite text has been previously
12098 output.  In short, if you manually change the diversion, you should not
12099 expect any macros provided by the Autoconf package to work until you
12100 have restored the diversion stack back to its original state.
12102 In the rare case that it is necessary to write a macro that explicitly
12103 outputs text to a different diversion, it is important to be aware of an
12104 M4 limitation regarding diversions: text only goes to a diversion if it
12105 is not part of argument collection.  Therefore, any macro that changes
12106 the current diversion cannot be used as an unquoted argument to another
12107 macro, but must be expanded at the top level.  The macro
12108 @code{m4_expand} will diagnose any attempt to change diversions, since
12109 it is generally useful only as an argument to another macro.  The
12110 following example shows what happens when diversion manipulation is
12111 attempted within macro arguments:
12113 @example
12114 m4_do([normal text]
12115 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
12116 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
12117 @result{}normal text
12118 @result{}unwanted
12119 @end example
12121 @noindent
12122 Notice that the unquoted text @code{unwanted} is output, even though it
12123 was processed while the current diversion was @code{KILL}, because it
12124 was collected as part of the argument to @code{m4_do}.  However, the
12125 text @code{discarded} disappeared as desired, because the diversion
12126 changes were single-quoted, and were not expanded until the top-level
12127 rescan of the output of @code{m4_do}.
12129 To make diversion management easier, M4sugar uses the concept of named
12130 diversions.  Rather than using diversion numbers directly, it is nicer
12131 to associate a name with each diversion.  The diversion number associated
12132 with a particular diversion name is an implementation detail, and a
12133 syntax warning is issued if a diversion number is used instead of a
12134 name.  In general, you should not output text
12135 to a named diversion until after calling the appropriate initialization
12136 routine for your language (@code{m4_init}, @code{AS_INIT},
12137 @code{AT_INIT}, @dots{}), although there are some exceptions documented
12138 below.
12140 M4sugar defines two named diversions.
12141 @table @code
12142 @item KILL
12143 Text written to this diversion is discarded.  This is the default
12144 diversion once M4sugar is initialized.
12145 @item GROW
12146 This diversion is used behind the scenes by topological sorting macros,
12147 such as @code{AC_REQUIRE}.
12148 @end table
12150 M4sh adds several more named diversions.
12151 @table @code
12152 @item BINSH
12153 This diversion is reserved for the @samp{#!} interpreter line.
12154 @item HEADER-REVISION
12155 This diversion holds text from @code{AC_REVISION}.
12156 @item HEADER-COMMENT
12157 This diversion holds comments about the purpose of a file.
12158 @item HEADER-COPYRIGHT
12159 This diversion is managed by @code{AC_COPYRIGHT}.
12160 @item M4SH-SANITIZE
12161 This diversion contains M4sh sanitization code, used to ensure M4sh is
12162 executing in a reasonable shell environment.
12163 @item M4SH-INIT
12164 This diversion contains M4sh initialization code, initializing variables
12165 that are required by other M4sh macros.
12166 @item BODY
12167 This diversion contains the body of the shell code, and is the default
12168 diversion once M4sh is initialized.
12169 @end table
12171 Autotest inherits diversions from M4sh, and changes the default
12172 diversion from @code{BODY} back to @code{KILL}.  It also adds several
12173 more named diversions, with the following subset designed for developer
12174 use.
12175 @table @code
12176 @item PREPARE_TESTS
12177 This diversion contains initialization sequences which are executed
12178 after @file{atconfig} and @file{atlocal}, and after all command line
12179 arguments have been parsed, but prior to running any tests.  It can be
12180 used to set up state that is required across all tests.  This diversion
12181 will work even before @code{AT_INIT}.
12182 @end table
12184 Autoconf inherits diversions from M4sh, and adds the following named
12185 diversions which developers can utilize.
12186 @table @code
12187 @item DEFAULTS
12188 This diversion contains shell variable assignments to set defaults that
12189 must be in place before arguments are parsed.  This diversion is placed
12190 early enough in @file{configure} that it is unsafe to expand any
12191 autoconf macros into this diversion.
12192 @item HELP_ENABLE
12193 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
12194 diversion will be included as part of a quoted here-doc providing all of
12195 the @option{--help} output of @file{configure} related to options
12196 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
12197 @item INIT_PREPARE
12198 This diversion occurs after all command line options have been parsed,
12199 but prior to the main body of the @file{configure} script.  This
12200 diversion is the last chance to insert shell code such as variable
12201 assignments or shell function declarations that will used by the
12202 expansion of other macros.
12203 @end table
12205 For now, the remaining named diversions of Autoconf, Autoheader, and
12206 Autotest are not documented.  In other words,
12207 intentionally outputting text into an undocumented diversion is subject
12208 to breakage in a future release of Autoconf.
12210 @defmac m4_cleardivert (@var{diversion}@dots{})
12211 @msindex{cleardivert}
12212 Permanently discard any text that has been diverted into
12213 @var{diversion}.
12214 @end defmac
12216 @defmac m4_divert_once (@var{diversion}, @ovar{content})
12217 @msindex{divert_once}
12218 Similar to @code{m4_divert_text}, except that @var{content} is only
12219 output to @var{diversion} if this is the first time that
12220 @code{m4_divert_once} has been called with its particular arguments.
12221 @end defmac
12223 @defmac m4_divert_pop (@ovar{diversion})
12224 @msindex{divert_pop}
12225 If provided, check that the current diversion is indeed @var{diversion}.
12226 Then change to the diversion located earlier on the stack, giving an
12227 error if an attempt is made to pop beyond the initial m4sugar diversion
12228 of @code{KILL}.
12229 @end defmac
12231 @defmac m4_divert_push (@var{diversion})
12232 @msindex{divert_push}
12233 Remember the former diversion on the diversion stack, and output
12234 subsequent text into @var{diversion}.  M4sugar maintains a diversion
12235 stack, and issues an error if there is not a matching pop for every
12236 push.
12237 @end defmac
12239 @anchor{m4_divert_text}
12240 @defmac m4_divert_text (@var{diversion}, @ovar{content})
12241 @msindex{divert_text}
12242 Output @var{content} and a newline into @var{diversion}, without
12243 affecting the current diversion.  Shorthand for:
12244 @example
12245 m4_divert_push([@var{diversion}])@var{content}
12246 m4_divert_pop([@var{diversion}])dnl
12247 @end example
12249 One use of @code{m4_divert_text} is to develop two related macros, where
12250 macro @samp{MY_A} does the work, but adjusts what work is performed
12251 based on whether the optional macro @samp{MY_B} has also been expanded.
12252 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
12253 require that @samp{MY_B} occurs first, if it occurs at all.  But this
12254 imposes an ordering restriction on the user; it would be nicer if macros
12255 @samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
12256 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
12257 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
12258 expanded.
12260 @example
12261 AC_DEFUN([MY_A],
12262 [# various actions
12263 if test -n "$b_was_used"; then
12264   # extra action
12265 fi])
12266 AC_DEFUN([MY_B],
12267 [AC_REQUIRE([MY_A])dnl
12268 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12269 @end example
12271 @end defmac
12273 @defmac m4_init
12274 @msindex{init}
12275 Initialize the M4sugar environment, setting up the default named
12276 diversion to be @code{KILL}.
12277 @end defmac
12279 @node Conditional constructs
12280 @subsection Conditional constructs
12282 The following macros provide additional conditional constructs as
12283 convenience wrappers around @code{m4_if}.
12285 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12286   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12287 @msindex{bmatch}
12288 The string @var{string} is repeatedly compared against a series of
12289 @var{regex} arguments; if a match is found, the expansion is the
12290 corresponding @var{value}, otherwise, the macro moves on to the next
12291 @var{regex}.  If no @var{regex} match, then the result is the optional
12292 @var{default}, or nothing.
12293 @end defmac
12295 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12296   @ovar{regex-2}, @ovar{subst-2}, @dots{})
12297 @msindex{bpatsubsts}
12298 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12299 as if by:
12300 @example
12301 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12302 @end example
12304 @noindent
12305 The result of the substitution is then passed through the next set of
12306 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
12307 deletion of any matched portions in the current string.  Note that this
12308 macro over-quotes @var{string}; this behavior is intentional, so that
12309 the result of each step of the recursion remains as a quoted string.
12310 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12311 will line up with the extra quotations, and not the characters of the
12312 original string.  The overquoting is removed after the final
12313 substitution.
12314 @end defmac
12316 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12317   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12318 @msindex{case}
12319 Test @var{string} against multiple @var{value} possibilities, resulting
12320 in the first @var{if-value} for a match, or in the optional
12321 @var{default}.  This is shorthand for:
12322 @example
12323 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12324       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12325       [@var{default}])
12326 @end example
12327 @end defmac
12329 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12330   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12331 @msindex{cond}
12332 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
12333 except that each @var{test} is expanded only when it is encountered.
12334 This is useful for short-circuiting expensive tests; while @code{m4_if}
12335 requires all its strings to be expanded up front before doing
12336 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12337 tests have failed.
12339 For an example, these two sequences give the same result, but in the
12340 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12341 version only expands @code{m4_index} once, instead of five times, for
12342 faster computation if this is a common case for @samp{$1}.  Notice that
12343 every third argument is unquoted for @code{m4_if}, and quoted for
12344 @code{m4_cond}:
12346 @example
12347 m4_if(m4_index([$1], [\]), [-1], [$2],
12348       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12349       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12350       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12351       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12352       [$2])
12353 m4_cond([m4_index([$1], [\])], [-1], [$2],
12354         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12355         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12356         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12357         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12358         [$2])
12359 @end example
12360 @end defmac
12362 @defmac m4_default (@var{expr-1}, @var{expr-2})
12363 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12364 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12365 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12366 @msindex{default}
12367 @msindex{default_quoted}
12368 @msindex{default_nblank}
12369 @msindex{default_nblank_quoted}
12370 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
12371 @code{m4_default} expands the result, while @code{m4_default_quoted}
12372 does not.  Useful for providing a fixed default if the expression that
12373 results in @var{expr-1} would otherwise be empty.  The difference
12374 between @code{m4_default} and @code{m4_default_nblank} is whether an
12375 argument consisting of just blanks (space, tab, newline) is
12376 significant.  When using the expanding versions, note that an argument
12377 may contain text but still expand to an empty string.
12379 @example
12380 m4_define([active], [ACTIVE])dnl
12381 m4_define([empty], [])dnl
12382 m4_define([demo1], [m4_default([$1], [$2])])dnl
12383 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12384 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12385 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12386 demo1([active], [default])
12387 @result{}ACTIVE
12388 demo1([], [active])
12389 @result{}ACTIVE
12390 demo1([empty], [text])
12391 @result{}
12392 -demo1([ ], [active])-
12393 @result{}- -
12394 demo2([active], [default])
12395 @result{}active
12396 demo2([], [active])
12397 @result{}active
12398 demo2([empty], [text])
12399 @result{}empty
12400 -demo2([ ], [active])-
12401 @result{}- -
12402 demo3([active], [default])
12403 @result{}ACTIVE
12404 demo3([], [active])
12405 @result{}ACTIVE
12406 demo3([empty], [text])
12407 @result{}
12408 -demo3([ ], [active])-
12409 @result{}-ACTIVE-
12410 demo4([active], [default])
12411 @result{}active
12412 demo4([], [active])
12413 @result{}active
12414 demo4([empty], [text])
12415 @result{}empty
12416 -demo4([ ], [active])-
12417 @result{}-active-
12418 @end example
12419 @end defmac
12421 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
12422 @msindex{define_default}
12423 If @var{macro} does not already have a definition, then define it to
12424 @var{default-definition}.
12425 @end defmac
12427 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12428 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12429 @msindex{ifblank}
12430 @msindex{ifnblank}
12431 If @var{cond} is empty or consists only of blanks (space, tab, newline),
12432 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
12433 variants exist, in order to make it easier to select the correct logical
12434 sense when using only two parameters.  Note that this is more efficient
12435 than the equivalent behavior of:
12436 @example
12437 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12438 @end example
12439 @end defmac
12441 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12442 @msindex{ifndef}
12443 This is shorthand for:
12444 @example
12445 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12446 @end example
12447 @end defmac
12449 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12450 @msindex{ifset}
12451 If @var{macro} is undefined, or is defined as the empty string, expand
12452 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
12453 @example
12454 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12455 @end example
12456 @noindent
12457 except that it is not an error if @var{macro} is undefined.
12458 @end defmac
12460 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12461 @msindex{ifval}
12462 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12463 @var{if-false}.  This is shorthand for:
12464 @example
12465 m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12466 @end example
12467 @end defmac
12469 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12470 @msindex{ifvaln}
12471 Similar to @code{m4_ifval}, except guarantee that a newline is present
12472 after any non-empty expansion.  Often followed by @code{dnl}.
12473 @end defmac
12475 @defmac m4_n (@var{text})
12476 @msindex{n}
12477 Expand to @var{text}, and add a newline if @var{text} is not empty.
12478 Often followed by @code{dnl}.
12479 @end defmac
12482 @node Looping constructs
12483 @subsection Looping constructs
12485 The following macros are useful in implementing recursive algorithms in
12486 M4, including loop operations.  An M4 list is formed by quoting a list
12487 of quoted elements; generally the lists are comma-separated, although
12488 @code{m4_foreach_w} is whitespace-separated.  For example, the list
12489 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12490 It is common to see lists with unquoted elements when those elements are
12491 not likely to be macro names, as in @samp{[fputc_unlocked,
12492 fgetc_unlocked]}.
12494 Although not generally recommended, it is possible for quoted lists to
12495 have side effects; all side effects are expanded only once, and prior to
12496 visiting any list element.  On the other hand, the fact that unquoted
12497 macros are expanded exactly once means that macros without side effects
12498 can be used to generate lists.  For example,
12500 @example
12501 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12502 @error{}hi
12503 @result{}123
12504 m4_define([list], [[1], [2], [3]])
12505 @result{}
12506 m4_foreach([i], [list], [i])
12507 @result{}123
12508 @end example
12510 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12511 @msindex{argn}
12512 Extracts argument @var{n} (larger than 0) from the remaining arguments.
12513 If there are too few arguments, the empty string is used.  For any
12514 @var{n} besides 1, this is more efficient than the similar
12515 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12516 @end defmac
12518 @defmac m4_car (@var{arg}@dots{})
12519 @msindex{car}
12520 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
12521 to recursively iterate
12522 through a list.  Generally, when using quoted lists of quoted elements,
12523 @code{m4_car} should be called without any extra quotes.
12524 @end defmac
12526 @defmac m4_cdr (@var{arg}@dots{})
12527 @msindex{cdr}
12528 Expands to a quoted list of all but the first @var{arg}, or the empty
12529 string if there was only one argument.  Generally, when using quoted
12530 lists of quoted elements, @code{m4_cdr} should be called without any
12531 extra quotes.
12533 For example, this is a simple implementation of @code{m4_map}; note how
12534 each iteration checks for the end of recursion, then merely applies the
12535 first argument to the first element of the list, then repeats with the
12536 rest of the list.  (The actual implementation in M4sugar is a bit more
12537 involved, to gain some speed and share code with @code{m4_map_sep}, and
12538 also to avoid expanding side effects in @samp{$2} twice).
12539 @example
12540 m4_define([m4_map], [m4_ifval([$2],
12541   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12542 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12543 @result{} 1 2 a
12544 @end example
12545 @end defmac
12547 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12548   @var{expression})
12549 @msindex{for}
12550 Loop over the numeric values between @var{first} and @var{last}
12551 including bounds by increments of @var{step}.  For each iteration,
12552 expand @var{expression} with the numeric value assigned to @var{var}.
12553 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12554 on the order of the limits.  If given, @var{step} has to match this
12555 order.  The number of iterations is determined independently from
12556 definition of @var{var}; iteration cannot be short-circuited or
12557 lengthened by modifying @var{var} from within @var{expression}.
12558 @end defmac
12560 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12561 @msindex{foreach}
12562 Loop over the comma-separated M4 list @var{list}, assigning each value
12563 to @var{var}, and expand @var{expression}.  The following example
12564 outputs two lines:
12566 @example
12567 m4_foreach([myvar], [[foo], [bar, baz]],
12568            [echo myvar
12569 ])dnl
12570 @result{}echo foo
12571 @result{}echo bar, baz
12572 @end example
12574 Note that for some forms of @var{expression}, it may be faster to use
12575 @code{m4_map_args}.
12576 @end defmac
12578 @anchor{m4_foreach_w}
12579 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12580 @msindex{foreach_w}
12581 Loop over the white-space-separated list @var{list}, assigning each value
12582 to @var{var}, and expand @var{expression}.  If @var{var} is only
12583 referenced once in @var{expression}, it is more efficient to use
12584 @code{m4_map_args_w}.
12586 The deprecated macro @code{AC_FOREACH} is an alias of
12587 @code{m4_foreach_w}.
12588 @end defmac
12590 @defmac m4_map (@var{macro}, @var{list})
12591 @defmacx m4_mapall (@var{macro}, @var{list})
12592 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12593 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12594 @msindex{map}
12595 @msindex{mapall}
12596 @msindex{map_sep}
12597 @msindex{mapall_sep}
12598 Loop over the comma separated quoted list of argument descriptions in
12599 @var{list}, and invoke @var{macro} with the arguments.  An argument
12600 description is in turn a comma-separated quoted list of quoted elements,
12601 suitable for @code{m4_apply}.  The macros @code{m4_map} and
12602 @code{m4_map_sep} ignore empty argument descriptions, while
12603 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12604 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12605 additionally expand @var{separator} between invocations of @var{macro}.
12607 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
12608 separating output with commas, this means that the map result can be
12609 used as a series of arguments, by using a single-quoted comma as
12610 @var{separator}, or as a single string, by using a double-quoted comma.
12612 @example
12613 m4_map([m4_count], [])
12614 @result{}
12615 m4_map([ m4_count], [[],
12616                      [[1]],
12617                      [[1], [2]]])
12618 @result{} 1 2
12619 m4_mapall([ m4_count], [[],
12620                         [[1]],
12621                         [[1], [2]]])
12622 @result{} 0 1 2
12623 m4_map_sep([m4_eval], [,], [[[1+2]],
12624                             [[10], [16]]])
12625 @result{}3,a
12626 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12627 @result{}a,b
12628 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12629 @result{}2
12630 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12631 @result{}a,b
12632 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12633 @result{}1
12634 @end example
12635 @end defmac
12637 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12638 @msindex{map_args}
12639 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12640 argument.  In the following example, three solutions are presented with
12641 the same expansion; the solution using @code{m4_map_args} is the most
12642 efficient.
12643 @example
12644 m4_define([active], [ACTIVE])dnl
12645 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12646 @result{} plain active
12647 m4_map([ m4_echo], [[[plain]], [[active]]])
12648 @result{} plain active
12649 m4_map_args([ m4_echo], [plain], [active])
12650 @result{} plain active
12651 @end example
12653 In cases where it is useful to operate on additional parameters besides
12654 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12655 to supply the argument currying necessary to generate the desired
12656 argument list.  In the following example, @code{list_add_n} is more
12657 efficient than @code{list_add_x}.  On the other hand, using
12658 @code{m4_map_args_sep} can be even more efficient.
12660 @example
12661 m4_define([list], [[1], [2], [3]])dnl
12662 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12663 dnl list_add_n(N, ARG...)
12664 dnl Output a list consisting of each ARG added to N
12665 m4_define([list_add_n],
12666 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12667 list_add_n([1], list)
12668 @result{}2,3,4
12669 list_add_n([2], list)
12670 @result{}3,4,5
12671 m4_define([list_add_x],
12672 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12673   [,add([$1],m4_defn([var]))]))])dnl
12674 list_add_x([1], list)
12675 @result{}2,3,4
12676 @end example
12677 @end defmac
12679 @defmac m4_map_args_pair (@var{macro}, @dvarv{macro-end, macro}, @
12680   @var{arg}@dots{})
12681 @msindex{map_args_pair}
12682 For every pair of arguments @var{arg}, invoke @var{macro} with two
12683 arguments.  If there is an odd number of arguments, invoke
12684 @var{macro-end}, which defaults to @var{macro}, with the remaining
12685 argument.
12687 @example
12688 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12689 @result{}, 2, 1, 3
12690 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12691 @result{}, 2, 1, [3]
12692 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12693 @result{}, 2, 1, 4, 3
12694 @end example
12695 @end defmac
12697 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12698 @msindex{map_args_sep}
12699 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12700 argument, additionally expanding @var{sep} between arguments.  One
12701 common use of this macro is constructing a macro call, where the opening
12702 and closing parentheses are split between @var{pre} and @var{post}; in
12703 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12704 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
12705 macro provides the most efficient means for iterating over an arbitrary
12706 list of arguments, particularly when repeatedly constructing a macro
12707 call with more arguments than @var{arg}.
12708 @end defmac
12710 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12711 @msindex{map_args_w}
12712 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12713 the whitespace-separated @var{string}, additionally expanding @var{sep}
12714 between words.  This macro provides the most efficient means for
12715 iterating over a whitespace-separated string.  In particular,
12716 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12717 efficient than @code{m4_foreach_w([var], [@var{string}],
12718 [@var{action}(m4_defn([var]))])}.
12719 @end defmac
12721 @defmac m4_shiftn (@var{count}, @dots{})
12722 @defmacx m4_shift2 (@dots{})
12723 @defmacx m4_shift3 (@dots{})
12724 @msindex{shift2}
12725 @msindex{shift3}
12726 @msindex{shiftn}
12727 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12728 along with validation that enough arguments were passed in to match the
12729 shift count, and that the count is positive.  @code{m4_shift2} and
12730 @code{m4_shift3} are specializations
12731 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12732 for two and three shifts, respectively.
12733 @end defmac
12735 @defmac m4_stack_foreach (@var{macro}, @var{action})
12736 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12737 @msindex{stack_foreach}
12738 @msindex{stack_foreach_lifo}
12739 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12740 @var{action} with the single argument of a definition of @var{macro}.
12741 @code{m4_stack_foreach} starts with the oldest definition, while
12742 @code{m4_stack_foreach_lifo} starts with the current definition.
12743 @var{action} should not push or pop definitions of @var{macro}, nor is
12744 there any guarantee that the current definition of @var{macro} matches
12745 the argument that was passed to @var{action}.  The macro @code{m4_curry}
12746 can be used if @var{action} needs more than one argument, although in
12747 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12749 Due to technical limitations, there are a few low-level m4sugar
12750 functions, such as @code{m4_pushdef}, that cannot be used as the
12751 @var{macro} argument.
12753 @example
12754 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12755 m4_stack_foreach([a], [ m4_incr])
12756 @result{} 2 3
12757 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12758 @result{} cd bcd
12759 @end example
12760 @end defmac
12762 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12763 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12764   @ovar{sep})
12765 @msindex{stack_foreach_sep}
12766 @msindex{stack_foreach_sep_lifo}
12767 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12768 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12769 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
12770 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12771 the current definition first.  This macro provides the most efficient
12772 means for iterating over a pushdef stack.  In particular,
12773 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12774 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12775 @end defmac
12777 @node Evaluation Macros
12778 @subsection Evaluation Macros
12780 The following macros give some control over the order of the evaluation
12781 by adding or removing levels of quotes.
12783 @defmac m4_apply (@var{macro}, @var{list})
12784 @msindex{apply}
12785 Apply the elements of the quoted, comma-separated @var{list} as the
12786 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12787 without arguments.  Note the difference between @code{m4_indir}, which
12788 expects its first argument to be a macro name but can use names that are
12789 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12790 other text, but must end in a valid macro name.
12791 @example
12792 m4_apply([m4_count], [])
12793 @result{}0
12794 m4_apply([m4_count], [[]])
12795 @result{}1
12796 m4_apply([m4_count], [[1], [2]])
12797 @result{}2
12798 m4_apply([m4_join], [[|], [1], [2]])
12799 @result{}1|2
12800 @end example
12801 @end defmac
12803 @defmac m4_count (@var{arg}, @dots{})
12804 @msindex{count}
12805 This macro returns the decimal count of the number of arguments it was
12806 passed.
12807 @end defmac
12809 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12810 @msindex{curry}
12811 This macro performs argument currying.  The expansion of this macro is
12812 another macro name that expects exactly one argument; that argument is
12813 then appended to the @var{arg} list, and then @var{macro} is expanded
12814 with the resulting argument list.
12816 @example
12817 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12818 @result{}3, 2, 1
12819 @end example
12821 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12822 pass the definition of a builtin macro as the argument to the output of
12823 @code{m4_curry}; the empty string is used instead of the builtin token.
12824 This behavior is rectified by using M4 1.6 or newer.
12825 @end defmac
12827 @defmac m4_do (@var{arg}, @dots{})
12828 @msindex{do}
12829 This macro loops over its arguments and expands each @var{arg} in
12830 sequence.  Its main use is for readability; it allows the use of
12831 indentation and fewer @code{dnl} to result in the same expansion.  This
12832 macro guarantees that no expansion will be concatenated with subsequent
12833 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12834 @var{arg@dots{}}))}.
12836 @example
12837 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12838 m4_do([a],[b])c
12839 @result{}abc
12840 m4_unquote(m4_join([],[a],[b]))c
12841 @result{}3
12842 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12843 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12844 m4_do([a],[b])c
12845 @result{}ABC
12846 m4_unquote(m4_join([],[a],[b]))c
12847 @result{}3
12848 @end example
12849 @end defmac
12851 @defmac m4_dquote (@var{arg}, @dots{})
12852 @msindex{dquote}
12853 Return the arguments as a quoted list of quoted arguments.
12854 Conveniently, if there is just one @var{arg}, this effectively adds a
12855 level of quoting.
12856 @end defmac
12858 @defmac m4_dquote_elt (@var{arg}, @dots{})
12859 @msindex{dquote_elt}
12860 Return the arguments as a series of double-quoted arguments.  Whereas
12861 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12862 as many arguments as it was passed.
12863 @end defmac
12865 @defmac m4_echo (@var{arg}, @dots{})
12866 @msindex{echo}
12867 Return the arguments, with the same level of quoting.  Other than
12868 discarding whitespace after unquoted commas, this macro is a no-op.
12869 @end defmac
12871 @defmac m4_expand (@var{arg})
12872 @msindex{expand}
12873 Return the expansion of @var{arg} as a quoted string.  Whereas
12874 @code{m4_quote} is designed to collect expanded text into a single
12875 argument, @code{m4_expand} is designed to perform one level of expansion
12876 on quoted text.  One distinction is in the treatment of whitespace
12877 following a comma in the original @var{arg}.  Any time multiple
12878 arguments are collected into one with @code{m4_quote}, the M4 argument
12879 collection rules discard the whitespace.  However, with @code{m4_expand},
12880 whitespace is preserved, even after the expansion of macros contained in
12881 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
12882 would involve an unterminated comment, whereas expanding that same text
12883 as the argument to @code{m4_quote} runs into difficulty in finding the
12884 end of the argument.  Since manipulating diversions during argument
12885 collection is inherently unsafe, @code{m4_expand} issues an error if
12886 @var{arg} attempts to change the current diversion (@pxref{Diversion
12887 support}).
12889 @example
12890 m4_define([active], [ACT, IVE])dnl
12891 m4_define([active2], [[ACT, IVE]])dnl
12892 m4_quote(active, active)
12893 @result{}ACT,IVE,ACT,IVE
12894 m4_expand([active, active])
12895 @result{}ACT, IVE, ACT, IVE
12896 m4_quote(active2, active2)
12897 @result{}ACT, IVE,ACT, IVE
12898 m4_expand([active2, active2])
12899 @result{}ACT, IVE, ACT, IVE
12900 m4_expand([# m4_echo])
12901 @result{}# m4_echo
12902 m4_quote(# m4_echo)
12904 @result{}# m4_echo)
12905 @result{}
12906 @end example
12908 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12909 literal unbalanced quotes, but that quadrigraphs can be used when
12910 unbalanced output is necessary.  Likewise, unbalanced parentheses should
12911 be supplied with double quoting or a quadrigraph.
12913 @example
12914 m4_define([pattern], [[!@@<:@@]])dnl
12915 m4_define([bar], [BAR])dnl
12916 m4_expand([case $foo in
12917   m4_defn([pattern])@@:@}@@ bar ;;
12918   *[)] blah ;;
12919 esac])
12920 @result{}case $foo in
12921 @result{}  [![]) BAR ;;
12922 @result{}  *) blah ;;
12923 @result{}esac
12924 @end example
12925 @end defmac
12927 @defmac m4_ignore (@dots{})
12928 @msindex{ignore}
12929 This macro was introduced in Autoconf 2.62.  Expands to nothing,
12930 ignoring all of its arguments.  By itself, this isn't very useful.
12931 However, it can be used to conditionally ignore an arbitrary number of
12932 arguments, by deciding which macro name to apply to a list of arguments.
12933 @example
12934 dnl foo outputs a message only if [debug] is defined.
12935 m4_define([foo],
12936 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12937 @end example
12939 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12940 serve the same purpose, although it is less readable.
12941 @end defmac
12943 @defmac m4_make_list (@var{arg}, @dots{})
12944 @msindex{make_list}
12945 This macro exists to aid debugging of M4sugar algorithms.  Its net
12946 effect is similar to @code{m4_dquote}---it produces a quoted list of
12947 quoted arguments, for each @var{arg}.  The difference is that this
12948 version uses a comma-newline separator instead of just comma, to improve
12949 readability of the list; with the result that it is less efficient than
12950 @code{m4_dquote}.
12951 @example
12952 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12953 m4_dquote(zero, [one], [[two]])
12954 @result{}[0],[one],[[two]]
12955 m4_make_list(zero, [one], [[two]])
12956 @result{}[0],
12957 @result{}[one],
12958 @result{}[[two]]
12959 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12960 @result{} 0 1 two
12961 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12962 @result{} 0 1 two
12963 @end example
12964 @end defmac
12966 @c m4_noquote is too dangerous to document - it invokes macros that
12967 @c probably rely on @samp{[]} nested quoting for proper operation.  The
12968 @c user should generally prefer m4_unquote instead.
12970 @defmac m4_quote (@var{arg}, @dots{})
12971 @msindex{quote}
12972 Return the arguments as a single entity, i.e., wrap them into a pair of
12973 quotes.  This effectively collapses multiple arguments into one,
12974 although it loses whitespace after unquoted commas in the process.
12975 @end defmac
12977 @defmac m4_reverse (@var{arg}, @dots{})
12978 @msindex{reverse}
12979 Outputs each argument with the same level of quoting, but in reverse
12980 order, and with space following each comma for readability.
12982 @example
12983 m4_define([active], [ACT,IVE])
12984 @result{}
12985 m4_reverse(active, [active])
12986 @result{}active, IVE, ACT
12987 @end example
12988 @end defmac
12990 @defmac m4_unquote (@var{arg}, @dots{})
12991 @msindex{unquote}
12992 This macro was introduced in Autoconf 2.62.  Expand each argument,
12993 separated by commas.  For a single @var{arg}, this effectively removes a
12994 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12995 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
12996 this results in an unquoted list of expansions.  This is commonly used
12997 with @code{m4_split}, in order to convert a single quoted list into a
12998 series of quoted elements.
12999 @end defmac
13001 The following example aims at emphasizing the difference between several
13002 scenarios: not using these macros, using @code{m4_defn}, using
13003 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
13005 @example
13006 $ @kbd{cat example.m4}
13007 dnl Overquote, so that quotes are visible.
13008 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
13009 m4_define([a], [A])
13010 m4_define([mkargs], [1, 2[,] 3])
13011 m4_define([arg1], [[$1]])
13012 m4_divert([0])dnl
13013 show(a, b)
13014 show([a, b])
13015 show(m4_quote(a, b))
13016 show(m4_dquote(a, b))
13017 show(m4_expand([a, b]))
13019 arg1(mkargs)
13020 arg1([mkargs])
13021 arg1(m4_defn([mkargs]))
13022 arg1(m4_quote(mkargs))
13023 arg1(m4_dquote(mkargs))
13024 arg1(m4_expand([mkargs]))
13025 $ @kbd{autom4te -l m4sugar example.m4}
13026 $1 = A, $@@ = [A],[b]
13027 $1 = a, b, $@@ = [a, b]
13028 $1 = A,b, $@@ = [A,b]
13029 $1 = [A],[b], $@@ = [[A],[b]]
13030 $1 = A, b, $@@ = [A, b]
13033 mkargs
13034 1, 2[,] 3
13035 1,2, 3
13036 [1],[2, 3]
13037 1, 2, 3
13038 @end example
13041 @node Text processing Macros
13042 @subsection String manipulation in M4
13044 The following macros may be used to manipulate strings in M4.  Many of
13045 the macros in this section intentionally result in quoted strings as
13046 output, rather than subjecting the arguments to further expansions.  As
13047 a result, if you are manipulating text that contains active M4
13048 characters, the arguments are passed with single quoting rather than
13049 double.
13051 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
13052 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
13053   @ovar{if-uniq}, @ovar{if-duplicate})
13054 @msindex{append}
13055 @msindex{append_uniq}
13056 Redefine @var{macro-name} to its former contents with @var{separator}
13057 and @var{string} added at the end.  If @var{macro-name} was undefined
13058 before (but not if it was defined but empty), then no @var{separator} is
13059 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
13060 are expanded during this macro; instead, they are expanded when
13061 @var{macro-name} is invoked.
13063 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
13064 to grow strings without duplicating substrings.  Additionally,
13065 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
13066 @var{if-uniq} is expanded if @var{string} was appended, and
13067 @var{if-duplicate} is expanded if @var{string} was already present.
13068 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
13069 occurs within @var{string}, since that can lead to duplicates.
13071 Note that @code{m4_append} can scale linearly in the length of the final
13072 string, depending on the quality of the underlying M4 implementation,
13073 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
13074 If an algorithm can tolerate duplicates in the final string, use the
13075 former for speed.  If duplicates must be avoided, consider using
13076 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
13078 @example
13079 m4_define([active], [ACTIVE])dnl
13080 m4_append([sentence], [This is an])dnl
13081 m4_append([sentence], [ active ])dnl
13082 m4_append([sentence], [symbol.])dnl
13083 sentence
13084 @result{}This is an ACTIVE symbol.
13085 m4_undefine([active])dnl
13086 @result{}This is an active symbol.
13087 m4_append_uniq([list], [one], [, ], [new], [existing])
13088 @result{}new
13089 m4_append_uniq([list], [one], [, ], [new], [existing])
13090 @result{}existing
13091 m4_append_uniq([list], [two], [, ], [new], [existing])
13092 @result{}new
13093 m4_append_uniq([list], [three], [, ], [new], [existing])
13094 @result{}new
13095 m4_append_uniq([list], [two], [, ], [new], [existing])
13096 @result{}existing
13097 list
13098 @result{}one, two, three
13099 m4_dquote(list)
13100 @result{}[one],[two],[three]
13101 m4_append([list2], [one], [[, ]])dnl
13102 m4_append_uniq([list2], [two], [[, ]])dnl
13103 m4_append([list2], [three], [[, ]])dnl
13104 list2
13105 @result{}one, two, three
13106 m4_dquote(list2)
13107 @result{}[one, two, three]
13108 @end example
13109 @end defmac
13111 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
13112 @msindex{append_uniq_w}
13113 This macro was introduced in Autoconf 2.62.  It is similar to
13114 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
13115 separated list of words to append, and only appends unique words.
13116 @var{macro-name} is updated with a single space between new words.
13117 @example
13118 m4_append_uniq_w([numbers], [1 1 2])dnl
13119 m4_append_uniq_w([numbers], [ 2 3 ])dnl
13120 numbers
13121 @result{}1 2 3
13122 @end example
13123 @end defmac
13125 @defmac m4_chomp (@var{string})
13126 @defmacx m4_chomp_all (@var{string})
13127 @msindex{chomp}
13128 @msindex{chomp_all}
13129 Output @var{string} in quotes, but without a trailing newline.  The
13130 macro @code{m4_chomp} is slightly faster, and removes at most one
13131 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
13132 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
13133 and backslash does not influence the result.
13134 @end defmac
13136 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
13137   @var{suffix-1}, @ovar{suffix-2}, @dots{})
13138 @msindex{combine}
13139 This macro produces a quoted string containing the pairwise combination
13140 of every element of the quoted, comma-separated @var{prefix-list}, and
13141 every element from the @var{suffix} arguments.  Each pairwise
13142 combination is joined with @var{infix} in the middle, and successive
13143 pairs are joined by @var{separator}.  No expansion occurs on any of the
13144 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
13145 list is empty, but the lists can contain empty elements.
13146 @example
13147 m4_define([a], [oops])dnl
13148 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
13149 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
13150 m4_combine([, ], [[a], [b]], [-])
13151 @result{}
13152 m4_combine([, ], [[a], [b]], [-], [])
13153 @result{}a-, b-
13154 m4_combine([, ], [], [-], [1], [2])
13155 @result{}
13156 m4_combine([, ], [[]], [-], [1], [2])
13157 @result{}-1, -2
13158 @end example
13159 @end defmac
13161 @defmac m4_escape (@var{string})
13162 @msindex{escape}
13163 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
13164 within @var{string} into their respective quadrigraphs.  The result is
13165 still a quoted string.
13166 @end defmac
13168 @defmac m4_flatten (@var{string})
13169 @msindex{flatten}
13170 Flatten @var{string} into a single line.  Delete all backslash-newline
13171 pairs, and replace all remaining newlines with a space.  The result is
13172 still a quoted string.
13173 @end defmac
13175 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
13176 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
13177 @msindex{join}
13178 @msindex{joinall}
13179 Concatenate each @var{arg}, separated by @var{separator}.
13180 @code{joinall} uses every argument, while @code{join} omits empty
13181 arguments so that there are no back-to-back separators in the output.
13182 The result is a quoted string.
13183 @example
13184 m4_define([active], [ACTIVE])dnl
13185 m4_join([|], [one], [], [active], [two])
13186 @result{}one|active|two
13187 m4_joinall([|], [one], [], [active], [two])
13188 @result{}one||active|two
13189 @end example
13191 Note that if all you intend to do is join @var{args} with commas between
13192 them, to form a quoted list suitable for @code{m4_foreach}, it is more
13193 efficient to use @code{m4_dquote}.
13194 @end defmac
13196 @defmac m4_newline (@ovar{text})
13197 @msindex{newline}
13198 This macro was introduced in Autoconf 2.62, and expands to a newline,
13199 followed by any @var{text}.
13200 It is primarily useful for maintaining macro formatting, and ensuring
13201 that M4 does not discard leading whitespace during argument collection.
13202 @end defmac
13204 @defmac m4_normalize (@var{string})
13205 @msindex{normalize}
13206 Remove leading and trailing spaces and tabs, sequences of
13207 backslash-then-newline, and replace multiple spaces, tabs, and newlines
13208 with a single space.  This is a combination of @code{m4_flatten} and
13209 @code{m4_strip}.  To determine if @var{string} consists only of bytes
13210 that would be removed by @code{m4_normalize}, you can use
13211 @code{m4_ifblank}.
13212 @end defmac
13214 @defmac m4_re_escape (@var{string})
13215 @msindex{re_escape}
13216 Backslash-escape all characters in @var{string} that are active in
13217 regexps.
13218 @end defmac
13220 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13221 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
13222 @msindex{split}
13223 Split @var{string} into an M4 list of elements quoted by @samp{[} and
13224 @samp{]}, while keeping white space at the beginning and at the end.
13225 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
13226 If @var{string} is empty, the result is an empty list.
13227 @end defmac
13229 @defmac m4_strip (@var{string})
13230 @msindex{strip}
13231 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
13232 reduced to a single space, then leading and trailing spaces are removed.
13233 The result is still a quoted string.  Note that this does not interfere
13234 with newlines; if you want newlines stripped as well, consider
13235 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
13236 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
13237 @end defmac
13239 @defmac m4_text_box (@var{message}, @dvar{frame, -})
13240 @msindex{text_box}
13241 Add a text box around @var{message}, using @var{frame} as the border
13242 character above and below the message.  The @var{frame} argument must be
13243 a single byte, and does not support quadrigraphs.
13244 The frame correctly accounts for
13245 the subsequent expansion of @var{message}.  For example:
13246 @example
13247 m4_define([macro], [abc])dnl
13248 m4_text_box([macro])
13249 @result{}## --- ##
13250 @result{}## abc ##
13251 @result{}## --- ##
13252 @end example
13254 The @var{message} must contain balanced quotes and parentheses, although
13255 quadrigraphs can be used to work around this.
13256 @end defmac
13258 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
13259   @dvarv{prefix1, prefix}, @dvar{width, 79})
13260 @msindex{text_wrap}
13261 Break @var{string} into a series of whitespace-separated words, then
13262 output those words separated by spaces, and wrapping lines any time the
13263 output would exceed @var{width} columns.  If given, @var{prefix1} begins
13264 the first line, and @var{prefix} begins all wrapped lines.  If
13265 @var{prefix1} is longer than @var{prefix}, then the first line consists
13266 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
13267 padding is inserted so that the first word of @var{string} begins at the
13268 same indentation as all wrapped lines.  Note that using literal tab
13269 characters in any of the arguments will interfere with the calculation
13270 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
13271 words of @var{string}, although quadrigraphs are recognized.
13273 For some examples:
13274 @example
13275 m4_text_wrap([Short string */], [   ], [/* ], [20])
13276 @result{}/* Short string */
13277 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
13278 @result{}/* Much longer
13279 @result{}   string */
13280 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
13281 @result{}  --short Short doc.
13282 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
13283 @result{}  --too-wide
13284 @result{}          Short doc.
13285 m4_text_wrap([Super long documentation.], [     ],
13286              [  --too-wide ], 30)
13287 @result{}  --too-wide
13288 @result{}     Super long
13289 @result{}     documentation.
13290 @end example
13291 @end defmac
13293 @defmac m4_tolower (@var{string})
13294 @defmacx m4_toupper (@var{string})
13295 @msindex{tolower}
13296 @msindex{toupper}
13297 Return @var{string} with letters converted to upper or lower case,
13298 respectively.
13299 @end defmac
13301 @node Number processing Macros
13302 @subsection Arithmetic computation in M4
13304 The following macros facilitate integer arithmetic operations.
13305 Where a parameter is documented as taking an arithmetic expression, you
13306 can use anything that can be parsed by @code{m4_eval}.
13308 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
13309 @msindex{cmp}
13310 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13311 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13312 equal, and @samp{1} if @var{expr-1} is larger.
13313 @end defmac
13315 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
13316 @msindex{list_cmp}
13317 Compare the two M4 lists consisting of comma-separated arithmetic
13318 expressions, left to right.  Expand to @samp{-1} for the first element
13319 pairing where the value from @var{list-1} is smaller, @samp{1} where the
13320 value from @var{list-2} is smaller, or @samp{0} if both lists have the
13321 same values.  If one list is shorter than the other, the remaining
13322 elements of the longer list are compared against zero.
13323 @example
13324 m4_list_cmp([1, 0],       [1])
13325 @result{}0
13326 m4_list_cmp([1, [1 * 0]], [1, 0])
13327 @result{}0
13328 m4_list_cmp([1, 2],       [1, 0])
13329 @result{}1
13330 m4_list_cmp([1, [1+1], 3],[1, 2])
13331 @result{}1
13332 m4_list_cmp([1, 2, -3],   [1, 2])
13333 @result{}-1
13334 m4_list_cmp([1, 0],       [1, 2])
13335 @result{}-1
13336 m4_list_cmp([1],          [1, 2])
13337 @result{}-1
13338 @end example
13339 @end defmac
13341 @defmac m4_max (@var{arg}, @dots{})
13342 @msindex{max}
13343 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13344 of the maximum arithmetic expression among all the arguments.
13345 @end defmac
13347 @defmac m4_min (@var{arg}, @dots{})
13348 @msindex{min}
13349 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13350 of the minimum arithmetic expression among all the arguments.
13351 @end defmac
13353 @defmac m4_sign (@var{expr})
13354 @msindex{sign}
13355 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13356 @samp{1} if it is positive, and @samp{0} if it is zero.
13357 @end defmac
13359 @anchor{m4_version_compare}
13360 @defmac m4_version_compare (@var{version-1}, @var{version-2})
13361 @msindex{version_compare}
13362 This macro was introduced in Autoconf 2.53, but had a number of
13363 usability limitations that were not lifted until Autoconf 2.62.  Compare
13364 the version strings @var{version-1} and @var{version-2}, and expand to
13365 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13366 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
13367 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13368 element is a number along with optional case-insensitive letters
13369 designating beta releases.  The comparison stops at the leftmost element
13370 that contains a difference, although a 0 element compares equal to a
13371 missing element.
13373 It is permissible to include commit identifiers in @var{version}, such
13374 as an abbreviated SHA1 of the commit, provided there is still a
13375 monotonically increasing prefix to allow for accurate version-based
13376 comparisons.  For example, this paragraph was written when the
13377 development snapshot of autoconf claimed to be at version
13378 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13379 abbreviated commit identification of @samp{dc51}.
13381 @example
13382 m4_version_compare([1.1], [2.0])
13383 @result{}-1
13384 m4_version_compare([2.0b], [2.0a])
13385 @result{}1
13386 m4_version_compare([1.1.1], [1.1.1a])
13387 @result{}-1
13388 m4_version_compare([1.2], [1.1.1a])
13389 @result{}1
13390 m4_version_compare([1.0], [1])
13391 @result{}0
13392 m4_version_compare([1.1pre], [1.1PRE])
13393 @result{}0
13394 m4_version_compare([1.1a], [1,10])
13395 @result{}-1
13396 m4_version_compare([2.61a], [2.61a-248-dc51])
13397 @result{}-1
13398 m4_version_compare([2.61b], [2.61a-248-dc51])
13399 @result{}1
13400 @end example
13401 @end defmac
13403 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13404   @dvar{if-old, m4_fatal})
13405 @msindex{version_prereq}
13406 Compares @var{version} against the version of Autoconf currently
13407 running.  If the running version is at @var{version} or newer, expand
13408 @var{if-new-enough}, but if @var{version} is larger than the version
13409 currently executing, expand @var{if-old}, which defaults to printing an
13410 error message and exiting m4sugar with status 63.  When given only one
13411 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13412 Remember that the autoconf philosophy favors feature checks over version
13413 checks.
13414 @end defmac
13416 @node Set manipulation Macros
13417 @subsection Set manipulation in M4
13418 @cindex Set manipulation
13419 @cindex Data structure, set
13420 @cindex Unordered set manipulation
13422 Sometimes, it is necessary to track a set of data, where the order does
13423 not matter and where there are no duplicates in the set.  The following
13424 macros facilitate set manipulations.  Each set is an opaque object,
13425 which can only be accessed via these basic operations.  The underlying
13426 implementation guarantees linear scaling for set creation, which is more
13427 efficient than using the quadratic @code{m4_append_uniq}.  Both set
13428 names and values can be arbitrary strings, except for unbalanced quotes.
13429 This implementation ties up memory for removed elements until the next
13430 operation that must traverse all the elements of a set; and although
13431 that may slow down some operations until the memory for removed elements
13432 is pruned, it still guarantees linear performance.
13434 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13435 @msindex{set_add}
13436 Adds the string @var{value} as a member of set @var{set}.  Expand
13437 @var{if-uniq} if the element was added, or @var{if-dup} if it was
13438 previously in the set.  Operates in amortized constant time, so that set
13439 creation scales linearly.
13440 @end defmac
13442 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13443 @msindex{set_add_all}
13444 Adds each @var{value} to the set @var{set}.  This is slightly more
13445 efficient than repeatedly invoking @code{m4_set_add}.
13446 @end defmac
13448 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13449  @ovar{if-absent})
13450 @msindex{set_contains}
13451 Expands @var{if-present} if the string @var{value} is a member of
13452 @var{set}, otherwise @var{if-absent}.
13454 @example
13455 m4_set_contains([a], [1], [yes], [no])
13456 @result{}no
13457 m4_set_add([a], [1], [added], [dup])
13458 @result{}added
13459 m4_set_add([a], [1], [added], [dup])
13460 @result{}dup
13461 m4_set_contains([a], [1], [yes], [no])
13462 @result{}yes
13463 m4_set_remove([a], [1], [removed], [missing])
13464 @result{}removed
13465 m4_set_contains([a], [1], [yes], [no])
13466 @result{}no
13467 m4_set_remove([a], [1], [removed], [missing])
13468 @result{}missing
13469 @end example
13470 @end defmac
13472 @defmac m4_set_contents (@var{set}, @ovar{sep})
13473 @defmacx m4_set_dump (@var{set}, @ovar{sep})
13474 @msindex{set_contents}
13475 @msindex{set_dump}
13476 Expands to a single string consisting of all the members of the set
13477 @var{set}, each separated by @var{sep}, which is not expanded.
13478 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13479 memory occupied by removed elements, while @code{m4_set_dump} is a
13480 faster one-shot action that also deletes the set.  No provision is made
13481 for disambiguating members that contain a non-empty @var{sep} as a
13482 substring; use @code{m4_set_empty} to distinguish between an empty set
13483 and the set containing only the empty string.  The order of the output
13484 is unspecified; in the current implementation, part of the speed of
13485 @code{m4_set_dump} results from using a different output order than
13486 @code{m4_set_contents}.  These macros scale linearly in the size of the
13487 set before memory pruning, and @code{m4_set_contents([@var{set}],
13488 [@var{sep}])} is faster than
13489 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13491 @example
13492 m4_set_add_all([a], [1], [2], [3])
13493 @result{}
13494 m4_set_contents([a], [-])
13495 @result{}1-2-3
13496 m4_joinall([-]m4_set_listc([a]))
13497 @result{}1-2-3
13498 m4_set_dump([a], [-])
13499 @result{}3-2-1
13500 m4_set_contents([a])
13501 @result{}
13502 m4_set_add([a], [])
13503 @result{}
13504 m4_set_contents([a], [-])
13505 @result{}
13506 @end example
13507 @end defmac
13509 @defmac m4_set_delete (@var{set})
13510 @msindex{set_delete}
13511 Delete all elements and memory associated with @var{set}.  This is
13512 linear in the set size, and faster than removing one element at a time.
13513 @end defmac
13515 @defmac m4_set_difference (@var{seta}, @var{setb})
13516 @defmacx m4_set_intersection (@var{seta}, @var{setb})
13517 @defmacx m4_set_union (@var{seta}, @var{setb})
13518 @msindex{set_difference}
13519 @msindex{set_intersection}
13520 @msindex{set_union}
13521 Compute the relation between @var{seta} and @var{setb}, and output the
13522 result as a list of quoted arguments without duplicates and with a
13523 leading comma.  Set difference selects the elements in @var{seta} but
13524 not @var{setb}, intersection selects only elements in both sets, and
13525 union selects elements in either set.  These actions are linear in the
13526 sum of the set sizes.  The leading comma is necessary to distinguish
13527 between no elements and the empty string as the only element.
13529 @example
13530 m4_set_add_all([a], [1], [2], [3])
13531 @result{}
13532 m4_set_add_all([b], [3], [], [4])
13533 @result{}
13534 m4_set_difference([a], [b])
13535 @result{},1,2
13536 m4_set_difference([b], [a])
13537 @result{},,4
13538 m4_set_intersection([a], [b])
13539 @result{},3
13540 m4_set_union([a], [b])
13541 @result{},1,2,3,,4
13542 @end example
13543 @end defmac
13545 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13546 @msindex{set_empty}
13547 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13548 expand @var{if-elements}.  This macro operates in constant time.  Using
13549 this macro can help disambiguate output from @code{m4_set_contents} or
13550 @code{m4_set_list}.
13551 @end defmac
13553 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13554 @msindex{set_foreach}
13555 For each element in the set @var{set}, expand @var{action} with the
13556 macro @var{variable} defined as the set element.  Behavior is
13557 unspecified if @var{action} recursively lists the contents of @var{set}
13558 (although listing other sets is acceptable), or if it modifies the set
13559 in any way other than removing the element currently contained in
13560 @var{variable}.  This macro is faster than the corresponding
13561 @code{m4_foreach([@var{variable}],
13562 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13563 although @code{m4_set_map} might be faster still.
13565 @example
13566 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13567 @result{}
13568 m4_set_contents([a])
13569 @result{}12345
13570 m4_set_foreach([a], [i],
13571   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13572 @result{}24
13573 m4_set_contents([a])
13574 @result{}135
13575 @end example
13576 @end defmac
13578 @defmac m4_set_list (@var{set})
13579 @defmacx m4_set_listc (@var{set})
13580 @msindex{set_list}
13581 @msindex{set_listc}
13582 Produce a list of arguments, where each argument is a quoted element
13583 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
13584 by adding a leading comma if there are any set elements, whereas the
13585 variant @code{m4_set_list} cannot distinguish between an empty set and a
13586 set containing only the empty string.  These can be directly used in
13587 macros that take multiple arguments, such as @code{m4_join} or
13588 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13589 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
13590 memory occupied by removed elements is reclaimed during these macros.
13592 @example
13593 m4_set_add_all([a], [1], [2], [3])
13594 @result{}
13595 m4_set_list([a])
13596 @result{}1,2,3
13597 m4_set_list([b])
13598 @result{}
13599 m4_set_listc([b])
13600 @result{}
13601 m4_count(m4_set_list([b]))
13602 @result{}1
13603 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13604 @result{}0
13605 m4_set_add([b], [])
13606 @result{}
13607 m4_set_list([b])
13608 @result{}
13609 m4_set_listc([b])
13610 @result{},
13611 m4_count(m4_set_list([b]))
13612 @result{}1
13613 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13614 @result{}1
13615 @end example
13616 @end defmac
13618 @defmac m4_set_map (@var{set}, @var{action})
13619 @msindex{set_map}
13620 For each element in the set @var{set}, expand @var{action} with a single
13621 argument of the set element.  Behavior is unspecified if @var{action}
13622 recursively lists the contents of @var{set} (although listing other sets
13623 is acceptable), or if it modifies the set in any way other than removing
13624 the element passed as an argument.  This macro is faster than either
13625 corresponding counterpart of
13626 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13627 @code{m4_set_foreach([@var{set}], [var],
13628 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
13629 if more than one argument is needed for @var{action}, although it is
13630 more efficient to use @code{m4_set_map_sep} in that case.
13631 @end defmac
13633 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13634 @msindex{set_map_sep}
13635 For each element in the set @var{set}, expand
13636 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13637 between elements.  Behavior is unspecified if the expansion recursively
13638 lists the contents of @var{set} (although listing other sets
13639 is acceptable), or if it modifies the set in any way other than removing
13640 the element visited by the expansion.  This macro provides the most
13641 efficient means for non-destructively visiting the elements of a set; in
13642 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13643 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13644 @end defmac
13646 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13647  @ovar{if-absent})
13648 @msindex{set_remove}
13649 If @var{value} is an element in the set @var{set}, then remove it and
13650 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
13651 operates in constant time so that multiple removals will scale linearly
13652 rather than quadratically; but when used outside of
13653 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13654 until the set is later
13655 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
13656 other set operations are then less efficient between the time of element
13657 removal and subsequent memory compaction, but still maintain their
13658 guaranteed scaling performance.
13659 @end defmac
13661 @defmac m4_set_size (@var{set})
13662 @msindex{set_size}
13663 Expand to the size of the set @var{set}.  This implementation operates
13664 in constant time, and is thus more efficient than
13665 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13666 @end defmac
13669 @node Forbidden Patterns
13670 @subsection Forbidden Patterns
13671 @cindex Forbidden patterns
13672 @cindex Patterns, forbidden
13674 M4sugar provides a means to define suspicious patterns, patterns
13675 describing tokens which should not be found in the output.  For
13676 instance, if an Autoconf @file{configure} script includes tokens such as
13677 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13678 wrong (typically a macro was not evaluated because of overquotation).
13680 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13681 Additional layers, such as M4sh and Autoconf, add additional forbidden
13682 patterns to the list.
13684 @defmac m4_pattern_forbid (@var{pattern})
13685 @msindex{pattern_forbid}
13686 Declare that no token matching @var{pattern} must be found in the
13687 output.  The output file is (temporarily) split into one word per line
13688 as part of the @command{autom4te} post-processing, with each line (and
13689 therefore word) then being checked against the Perl regular expression
13690 @var{pattern}.  If the regular expression matches, and
13691 @code{m4_pattern_allow} does not also match, then an error is raised.
13693 Comments are not checked; this can be a problem if, for instance, you
13694 have some macro left unexpanded after an @samp{#include}.  No consensus
13695 is currently found in the Autoconf community, as some people consider it
13696 should be valid to name macros in comments (which doesn't make sense to
13697 the authors of this documentation: input, such as macros, should be
13698 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13699 document the output).
13701 As an example, if you define your own macros that begin with @samp{M_}
13702 and are composed from capital letters and underscores, the specification
13703 of @code{m4_pattern_forbid([^M_[A-Z_]+])} will ensure all your macros
13704 are expanded when not used in comments.
13706 As an example of a common use of this macro, consider what happens in
13707 packages that want to use the @command{pkg-config} script via the
13708 third-party @code{PKG_CHECK_MODULES} macro.  By default, if a developer
13709 checks out the development tree but has not yet installed the pkg-config
13710 macros locally, they can manage to successfully run @command{autoconf}
13711 on the package, but the resulting @file{configure} file will likely
13712 result in a confusing shell message about a syntax error on the line
13713 mentioning the unexpanded @code{PKG_CHECK_MODULES} macro.  On the other hand,
13714 if @file{configure.ac} includes @code{m4_pattern_forbid([^PKG_])}, the
13715 missing pkg-config macros will be detected immediately without allowing
13716 @command{autoconf} to succeed.
13717 @end defmac
13719 Of course, you might encounter exceptions to these generic rules, for
13720 instance you might have to refer to @samp{$m4_flags}.
13722 @defmac m4_pattern_allow (@var{pattern})
13723 @msindex{pattern_allow}
13724 Any token matching @var{pattern} is allowed, including if it matches an
13725 @code{m4_pattern_forbid} pattern.
13727 For example, Gnulib uses @code{m4_pattern_forbid([^gl_])} to reserve the
13728 @code{gl_} namespace for itself, but also uses
13729 @code{m4_pattern_allow([^gl_ES$])} to avoid a false negative on the
13730 valid locale name.
13731 @end defmac
13733 @node Debugging via autom4te
13734 @section Debugging via autom4te
13735 @cindex debugging tips
13736 @cindex autom4te debugging tips
13737 @cindex m4sugar debugging tips
13738 At times, it is desirable to see what was happening inside m4, to see
13739 why output was not matching expectations.  However, post-processing done
13740 by @command{autom4te} means that directly using the m4 builtin
13741 @code{m4_traceon} is likely to interfere with operation.  Also, frequent
13742 diversion changes and the concept of forbidden tokens make it difficult
13743 to use @code{m4_defn} to generate inline comments in the final output.
13745 There are a couple of tools to help with this.  One is the use of the
13746 @option{--trace} option provided by @command{autom4te} (as well as each
13747 of the programs that wrap @command{autom4te}, such as
13748 @command{autoconf}), in order to inspect when a macro is called and with
13749 which arguments.  For example, when this paragraph was written, the
13750 autoconf version could be found by:
13752 @example
13753 $ @kbd{autoconf --trace=AC_INIT}
13754 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13755 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13756 version is 2.63b.95-3963
13757 @end example
13759 Another trick is to print out the expansion of various m4 expressions to
13760 standard error or to an independent file, with no further m4 expansion,
13761 and without interfering with diversion changes or the post-processing
13762 done to standard output.  @code{m4_errprintn} shows a given expression
13763 on standard error.  For example, if you want to see the expansion of an
13764 autoconf primitive or of one of your autoconf macros, you can do it like
13765 this:
13767 @example
13768 $ @kbd{cat <<\EOF > configure.ac}
13769 AC_INIT
13770 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13771 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13772 AC_OUTPUT
13774 $ @kbd{autoconf}
13775 @error{}The definition of AC_DEFINE_UNQUOTED:
13776 @error{}_AC_DEFINE_Q([], $@@)
13777 @end example
13779 @node Programming in M4sh
13780 @chapter Programming in M4sh
13782 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13783 scripts.  This name was coined by Lars J. Aas, who notes that,
13784 according to the Webster's Revised Unabridged Dictionary (1913):
13786 @quotation
13787 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
13788 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
13790 @enumerate 1
13791 @item
13792 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13793 pressure@enddots{}
13795 @item
13796 A mixture of meal or bran and water fed to animals.
13798 @item
13799 A mess; trouble.  [Obs.] --Beau.@: & Fl.
13800 @end enumerate
13801 @end quotation
13803 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13804 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
13805 and environment variable namespace @samp{^as_}, and the here-document
13806 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
13807 define your own macros or output shell code that conflicts with these
13808 namespaces.
13810 @menu
13811 * Common Shell Constructs::     Portability layer for common shell constructs
13812 * Polymorphic Variables::       Support for indirect variable names
13813 * Initialization Macros::       Macros to establish a sane shell environment
13814 * File Descriptor Macros::      File descriptor macros for input and output
13815 @end menu
13817 @node Common Shell Constructs
13818 @section Common Shell Constructs
13820 M4sh provides portable alternatives for some common shell constructs
13821 that unfortunately are not portable in practice.
13823 @c Deprecated, to be replaced by a better API
13824 @ignore
13825 @defmac AS_BASENAME (@var{file-name})
13826 @asindex{BASENAME}
13827 Output the non-directory portion of @var{file-name}.  For example,
13828 if @code{$file} is @samp{/one/two/three}, the command
13829 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13830 @end defmac
13831 @end ignore
13833 @defmac AS_BOX (@var{text}, @dvar{char, -})
13834 @asindex{BOX}
13835 Expand into shell code that will output @var{text} surrounded by a box
13836 with @var{char} in the top and bottom border.  @var{text} should not
13837 contain a newline, but may contain shell expansions valid for unquoted
13838 here-documents.  @var{char} defaults to @samp{-}, but can be any
13839 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13840 @samp{&}, or @samp{`}.  This is useful for outputting a comment box into
13841 log files to separate distinct phases of script operation.
13842 @end defmac
13844 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13845   @dots{}, @ovar{default})
13846 @asindex{CASE}
13847 Expand into a shell @samp{case} statement, where @var{word} is matched
13848 against one or more patterns.  @var{if-matched} is run if the
13849 corresponding pattern matched @var{word}, else @var{default} is run.
13850 @xref{Prerequisite Macros} for why
13851 this macro should be used instead of plain @samp{case} in code
13852 outside of an @code{AC_DEFUN} macro, when the contents of the
13853 @samp{case} use @code{AC_REQUIRE} directly or indirectly.
13854 @xref{case, , Limitations of Shell Builtins},
13855 for how this macro avoids some portability issues.
13856 @xref{Balancing Parentheses}
13857 for how this macro lets you write code with balanced parentheses
13858 even if your code must run on obsolescent shells.
13859 @end defmac
13861 @c Deprecated, to be replaced by a better API
13862 @defmac AS_DIRNAME (@var{file-name})
13863 @asindex{DIRNAME}
13864 Output the directory portion of @var{file-name}.  For example,
13865 if @code{$file} is @samp{/one/two/three}, the command
13866 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13868 This interface may be improved in the future to avoid forks and losing
13869 trailing newlines.
13870 @end defmac
13872 @defmac AS_ECHO (@var{word})
13873 @asindex{ECHO}
13874 Emits @var{word} to the standard output, followed by a newline.  @var{word}
13875 must be a single shell word (typically a quoted string).  The bytes of
13876 @var{word} are output as-is, even if it starts with "-" or contains "\".
13877 Redirections can be placed outside the macro invocation.  This is much
13878 more portable than using @command{echo} (@pxref{echo, , Limitations of
13879 Shell Builtins}).
13880 @end defmac
13882 @defmac AS_ECHO_N (@var{word})
13883 @asindex{ECHO_N}
13884 Emits @var{word} to the standard output, without a following newline.
13885 @var{word} must be a single shell word (typically a quoted string) and,
13886 for portability, should not include more than one newline.  The bytes of
13887 @var{word} are output as-is, even if it starts with "-" or contains "\".
13888 Redirections can be placed outside the macro invocation.
13889 @end defmac
13891 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13892 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13893 @asindex{ESCAPE}
13894 Expands to @var{string}, with any characters in @var{chars} escaped with
13895 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
13896 and only contain characters from the set @samp{`\"$}; however,
13897 characters may be safely listed more than once in @var{chars} for the
13898 sake of syntax highlighting editors.  The current implementation expands
13899 @var{string} after adding escapes; if @var{string} contains macro calls
13900 that in turn expand to text needing shell quoting, you can use
13901 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13903 The default for @var{chars} (@samp{\"$`}) is the set of characters
13904 needing escapes when @var{string} will be used literally within double
13905 quotes.  One common variant is the set of characters to protect when
13906 @var{string} will be used literally within back-ticks or an unquoted
13907 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
13908 be used to form a double-quoted string containing the same expansions
13909 that would have occurred if @var{string} were expanded in an unquoted
13910 here-document; however, when using this variant, care must be taken that
13911 @var{string} does not use double quotes within complex variable
13912 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13913 with improper escapes.
13915 This macro is often used with @code{AS_ECHO}.  For an example, observe
13916 the output generated by the shell code generated from this snippet:
13918 @example
13919 foo=bar
13920 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13921 @result{}"$foo" = "bar"
13922 m4_define([macro], [a, [\b]])
13923 AS_ECHO(["AS_ESCAPE([[macro]])"])
13924 @result{}macro
13925 AS_ECHO(["AS_ESCAPE([macro])"])
13926 @result{}a, b
13927 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13928 @result{}a, \b
13929 @end example
13931 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13932 @comment the case of @var{string} that does not contain '.
13933 To escape a string that will be placed within single quotes, use:
13935 @example
13936 m4_bpatsubst([[@var{string}]], ['], ['\\''])
13937 @end example
13938 @end defmac
13940 @defmac AS_EXECUTABLE_P (@var{file})
13941 @asindex{EXECUTABLE_P}
13942 Emit code to probe whether @var{file} is a regular file with executable
13943 permissions (and not a directory with search permissions).  The caller
13944 is responsible for quoting @var{file}.
13945 @end defmac
13947 @defmac AS_EXIT (@dvar{status, $?})
13948 @asindex{EXIT}
13949 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13950 This macro
13951 works around shells that see the exit status of the command prior to
13952 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13953 of Shell Builtins}).
13954 @end defmac
13956 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13957 @asindex{IF}
13958 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
13959 run shell code @var{run-if-true1}, else examine further tests.  If no test
13960 exits with a zero status, run shell code @var{run-if-false}, with
13961 simplifications if either @var{run-if-true1} or @var{run-if-false}
13962 is empty.  For example,
13964 @example
13965 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13966       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13967       [echo foo not specified])
13968 @end example
13970 @noindent
13971 ensures any required macros of @code{HANDLE_FOO}
13972 are expanded before the first test.
13974 The @var{run-if-false} argument should either consist entirely of
13975 blanks, or expand to a nonempty shell command.  For example,
13976 @code{AS_IF([:], [:], [[]])} is invalid because its @var{run-if-false}
13977 argument contains the nonblank characters @code{[]} which expand to
13978 nothing.  This restriction on @var{run-if-false} also applies to other
13979 macros with ``if-false'' arguments denoting shell commands.
13981 This macro should be used instead of plain @samp{if} in code
13982 outside of an @code{AC_DEFUN} macro, when the contents of the @samp{if}
13983 use @code{AC_REQUIRE} directly or indirectly (@pxref{Prerequisite Macros}).
13984 @end defmac
13986 @defmac AS_MKDIR_P (@var{file-name})
13987 @asindex{MKDIR_P}
13988 Make the directory @var{file-name}, including intervening directories
13989 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
13990 except that it is portable to older versions of @command{mkdir} that
13991 lack support for the @option{-p} option or for the @option{--}
13992 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
13993 @code{AS_MKDIR_P}
13994 succeeds if @var{file-name} is a symbolic link to an existing directory,
13995 even though Posix is unclear whether @samp{mkdir -p} should
13996 succeed in that case.  If creation of @var{file-name} fails, exit the
13997 script.
13999 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
14000 @end defmac
14002 @defmac AS_SET_STATUS (@var{status})
14003 @asindex{SET_STATUS}
14004 Emit shell code to set the value of @samp{$?} to @var{status}, as
14005 efficiently as possible.  However, this is not guaranteed to abort a
14006 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
14007 Builtins}).  This should also be used at the end of a complex shell
14008 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
14009 a DJGPP shell bug.
14010 @end defmac
14012 @defmac AS_TR_CPP (@var{expression})
14013 @asindex{TR_CPP}
14014 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
14015 For example:
14017 @example
14018 # This outputs "#define HAVE_CHAR_P 1".
14019 # Notice the m4 quoting around #, to prevent an m4 comment
14020 type="char *"
14021 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
14022 @end example
14023 @end defmac
14025 @defmac AS_TR_SH (@var{expression})
14026 @asindex{TR_SH}
14027 Transform @var{expression} into shell code that generates a valid shell
14028 variable name.  The result is literal when possible at m4 time, but must
14029 be used with @code{eval} if @var{expression} causes shell indirections.
14030 For example:
14032 @example
14033 # This outputs "Have it!".
14034 header="sys/some file.h"
14035 eval AS_TR_SH([HAVE_$header])=yes
14036 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
14037 @end example
14038 @end defmac
14040 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
14041 @asindex{SET_CATFILE}
14042 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
14043 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
14044 @var{file} is absolute, etc.).
14045 @end defmac
14047 @defmac AS_UNSET (@var{var})
14048 @asindex{UNSET}
14049 Unsets the shell variable @var{var}, working around bugs in older
14050 shells (@pxref{unset, , Limitations of Shell
14051 Builtins}).  @var{var} can be a literal or indirect variable name.
14052 @end defmac
14054 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
14055   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
14056 @asindex{VERSION_COMPARE}
14057 Compare two strings @var{version-1} and @var{version-2}, possibly
14058 containing shell variables, as version strings, and expand
14059 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
14060 depending upon the result.
14061 The algorithm to compare is similar to the one used by strverscmp in
14062 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
14063 The GNU C Library}).
14064 @end defmac
14066 @node Polymorphic Variables
14067 @section Support for indirect variable names
14068 @cindex variable name indirection
14069 @cindex polymorphic variable name
14070 @cindex indirection, variable name
14072 Often, it is convenient to write a macro that will emit shell code
14073 operating on a shell variable.  The simplest case is when the variable
14074 name is known.  But a more powerful idiom is writing shell code that can
14075 work through an indirection, where another variable or command
14076 substitution produces the name of the variable to actually manipulate.
14077 M4sh supports the notion of polymorphic shell variables, making it easy
14078 to write a macro that can deal with either literal or indirect variable
14079 names and output shell code appropriate for both use cases.  Behavior is
14080 undefined if expansion of an indirect variable does not result in a
14081 literal variable name.
14083 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
14084   @dvarv{if-simple-ref, if-not})
14085 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
14086   @ovar{if-not}, @dvarv{if-simple-ref, if-not})
14087 @asindex{LITERAL_IF}
14088 @asindex{LITERAL_WORD_IF}
14089 If the expansion of @var{expression} is definitely a shell literal,
14090 expand @var{if-literal}.  If the expansion of @var{expression} looks
14091 like it might contain shell indirections (such as @code{$var} or
14092 @code{`expr`}), then @var{if-not} is expanded.  Sometimes, it is
14093 possible to output optimized code if @var{expression} consists only of
14094 shell variable expansions (such as @code{$@{var@}}), in which case
14095 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
14096 should always be safe.  @code{AS_LITERAL_WORD_IF} only expands
14097 @var{if-literal} if @var{expression} looks like a single shell word,
14098 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
14099 in @var{expression}.
14101 In order to reduce the time spent recognizing whether an
14102 @var{expression} qualifies as a literal or a simple indirection, the
14103 implementation is somewhat conservative: @var{expression} must be a
14104 single shell word (possibly after stripping whitespace), consisting only
14105 of bytes that would have the same meaning whether unquoted or enclosed
14106 in double quotes (for example, @samp{a.b} results in @var{if-literal},
14107 even though it is not a valid shell variable name; while both @samp{'a'}
14108 and @samp{[$]} result in @var{if-not}, because they behave differently
14109 than @samp{"'a'"} and @samp{"[$]"}).  This macro can be used in contexts
14110 for recognizing portable file names (such as in the implementation of
14111 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
14112 valid variable names (such as in the implementation of @code{AS_TR_SH},
14113 which uses an additional @code{m4_translit} to convert @samp{.} to
14114 @samp{_}).
14116 This example shows how to read the contents of the shell variable
14117 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}.  It
14118 results in a script that will output the line @samp{hello} three times.
14120 @example
14121 AC_DEFUN([MY_ACTION],
14122 [AS_LITERAL_IF([$1],
14123   [echo "$$1"],
14124 @c $$
14125   [AS_VAR_COPY([var], [$1])
14126    echo "$var"],
14127   [eval 'echo "$'"$1"\"])])
14128 foo=bar bar=hello
14129 MY_ACTION([bar])
14130 MY_ACTION([`echo bar`])
14131 MY_ACTION([$foo])
14132 @end example
14133 @end defmac
14135 @defmac AS_VAR_APPEND (@var{var}, @var{text})
14136 @asindex{VAR_APPEND}
14137 Emit shell code to append the shell expansion of @var{text} to the end
14138 of the current contents of the polymorphic shell variable @var{var},
14139 taking advantage of shells that provide the @samp{+=} extension for more
14140 efficient scaling.
14142 For situations where the final contents of @var{var} are relatively
14143 short (less than 256 bytes), it is more efficient to use the simpler
14144 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
14145 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
14146 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}).  But in the case
14147 when the script will be repeatedly appending text into @code{var},
14148 issues of scaling start to become apparent.  A naive implementation
14149 requires execution time linear to the length of the current contents of
14150 @var{var} as well as the length of @var{text} for a single append, for
14151 an overall quadratic scaling with multiple appends.  This macro takes
14152 advantage of shells which provide the extension
14153 @code{@var{var}+=@var{text}}, which can provide amortized constant time
14154 for a single append, for an overall linear scaling with multiple
14155 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
14156 @var{text} be quoted properly to avoid field splitting and file name
14157 expansion.
14158 @end defmac
14160 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
14161 @asindex{VAR_ARITH}
14162 Emit shell code to compute the arithmetic expansion of @var{expression},
14163 assigning the result as the contents of the polymorphic shell variable
14164 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
14165 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
14166 syntax for a valid @var{expression} is rather limited: all operators
14167 must occur as separate shell arguments and with proper quoting, there is
14168 no portable equality operator, all variables containing numeric values
14169 must be expanded prior to the computation, all numeric values must be
14170 provided in decimal without leading zeroes, and the first shell argument
14171 should not be a negative number.  In the following example, this snippet
14172 will print @samp{(2+3)*4 == 20}.
14174 @example
14175 bar=3
14176 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
14177 echo "(2+$bar)*4 == $foo"
14178 @end example
14179 @end defmac
14181 @defmac AS_VAR_COPY (@var{dest}, @var{source})
14182 @asindex{VAR_COPY}
14183 Emit shell code to assign the contents of the polymorphic shell variable
14184 @var{source} to the polymorphic shell variable @var{dest}.  For example,
14185 executing this M4sh snippet will output @samp{bar hi}:
14187 @example
14188 foo=bar bar=hi
14189 AS_VAR_COPY([a], [foo])
14190 AS_VAR_COPY([b], [$foo])
14191 echo "$a $b"
14192 @end example
14194 When it is necessary to access the contents of an indirect variable
14195 inside a shell double-quoted context, the recommended idiom is to first
14196 copy the contents into a temporary literal shell variable.
14198 @smallexample
14199 for header in stdint_h inttypes_h ; do
14200   AS_VAR_COPY([var], [ac_cv_header_$header])
14201   echo "$header detected: $var"
14202 done
14203 @end smallexample
14204 @end defmac
14206 @comment AS_VAR_GET is intentionally undocumented; it can't handle
14207 @comment trailing newlines uniformly, and forks too much.
14209 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
14210   @ovar{if-not-equal})
14211 @asindex{VAR_IF}
14212 Output a shell conditional statement.  If the contents of the
14213 polymorphic shell variable @var{var} match the string @var{word},
14214 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  @var{word}
14215 must be a single shell word (typically a quoted string).  Avoids
14216 shell bugs if an interrupt signal arrives while a command substitution
14217 in @var{var} is being expanded.
14218 @end defmac
14220 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
14221 @defmacx AS_VAR_POPDEF (@var{m4-name})
14222 @asindex{VAR_PUSHDEF}
14223 @asindex{VAR_POPDEF}
14224 @cindex composing variable names
14225 @cindex variable names, composing
14226 A common M4sh idiom involves composing shell variable names from an m4
14227 argument (for example, writing a macro that uses a cache variable).
14228 @var{value} can be an arbitrary string, which will be transliterated
14229 into a valid shell name by @code{AS_TR_SH}.  In order to access the
14230 composed variable name based on @var{value}, it is easier to declare a
14231 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
14232 that macro as the argument to subsequent @code{AS_VAR} macros as a
14233 polymorphic variable name, and finally free the temporary macro with
14234 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
14235 to avoid excess newlines in the output.
14237 Here is an involved example, that shows the power of writing macros that
14238 can handle composed shell variable names:
14240 @example
14241 m4_define([MY_CHECK_HEADER],
14242 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
14243 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
14244 AS_VAR_POPDEF([my_Header])dnl
14246 MY_CHECK_HEADER([stdint.h])
14247 for header in inttypes.h stdlib.h ; do
14248   MY_CHECK_HEADER([$header])
14249 done
14250 @end example
14252 @noindent
14253 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
14254 variable names.  In the first invocation, the m4 argument is
14255 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
14256 As a result, the temporary macro @code{my_Header} expands to the literal
14257 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
14258 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
14259 temporary macro @code{my_Header} expands to the indirect shell name
14260 @samp{$as_my_Header}.  During the shell execution of the for loop, when
14261 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
14262 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
14263 platform where all three headers have been previously detected, the
14264 output of the script will include:
14266 @smallexample
14267 header stdint.h detected
14268 header inttypes.h detected
14269 header stdlib.h detected
14270 @end smallexample
14271 @end defmac
14273 @defmac AS_VAR_SET (@var{var}, @ovar{value})
14274 @asindex{VAR_SET}
14275 Emit shell code to assign the contents of the polymorphic shell variable
14276 @var{var} to the shell expansion of @var{value}.  @var{value} is not
14277 subject to field splitting or file name expansion, so if command
14278 substitution is used, it may be done with @samp{`""`} rather than using
14279 an intermediate variable (@pxref{Shell Substitutions}).  However,
14280 @var{value} does undergo rescanning for additional macro names; behavior
14281 is unspecified if late expansion results in any shell meta-characters.
14282 @end defmac
14284 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
14285 @asindex{VAR_SET_IF}
14286 Emit a shell conditional statement, which executes @var{if-set} if the
14287 polymorphic shell variable @code{var} is set to any value, and
14288 @var{if-undef} otherwise.
14289 @end defmac
14291 @defmac AS_VAR_TEST_SET (@var{var})
14292 @asindex{VAR_TEST_SET}
14293 Emit a shell statement that results in a successful exit status only if
14294 the polymorphic shell variable @code{var} is set.
14295 @end defmac
14297 @node Initialization Macros
14298 @section Initialization Macros
14300 @defmac AS_BOURNE_COMPATIBLE
14301 @asindex{BOURNE_COMPATIBLE}
14302 Set up the shell to be more compatible with the Bourne shell as
14303 standardized by Posix, if possible.  This may involve setting
14304 environment variables, or setting options, or similar
14305 implementation-specific actions.  This macro is deprecated, since
14306 @code{AS_INIT} already invokes it.
14307 @end defmac
14309 @defmac AS_INIT
14310 @asindex{INIT}
14311 @evindex LC_ALL
14312 @evindex SHELL
14313 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
14314 outputs the @code{#! /bin/sh} line, a notice about where the output was
14315 generated from, and code to sanitize the environment for the rest of the
14316 script.  Among other initializations, this sets @env{SHELL} to the shell
14317 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14318 ensure the C locale.  Finally, it changes the current diversion to
14319 @code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
14320 and @code{AT_INIT}, so shell code in @file{configure},
14321 @file{config.status}, and @file{testsuite} all benefit from a sanitized
14322 shell environment.
14323 @end defmac
14325 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14326 @asindex{INIT_GENERATED}
14327 Emit shell code to start the creation of a subsidiary shell script in
14328 @var{file}, including changing @var{file} to be executable.  This macro
14329 populates the child script with information learned from the parent
14330 (thus, the emitted code is equivalent in effect, but more efficient,
14331 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14332 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
14333 beginning of the child, prior to the shell initialization code, and is
14334 subject to parameter expansion, command substitution, and backslash
14335 quote removal.  The
14336 parent script should check the exit status after this macro, in case
14337 @var{file} could not be properly created (for example, if the disk was
14338 full).  If successfully created, the parent script can then proceed to
14339 append additional M4sh constructs into the child script.
14341 Note that the child script starts life without a log file open, so if
14342 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14343 must temporarily disable any attempts to use the log file until after
14344 emitting code to open a log within the child.  On the other hand, if the
14345 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14346 @samp{1}, then the child script already has code that copies stdout to
14347 that descriptor.  Currently, the suggested
14348 idiom for writing a M4sh shell script from within another script is:
14350 @example
14351 AS_INIT_GENERATED([@var{file}], [[# My child script.
14352 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14353 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14354 cat >> "@var{file}" <<\__EOF__
14355 # Code to initialize AS_MESSAGE_LOG_FD
14356 m4_popdef([AS_MESSAGE_LOG_FD])dnl
14357 # Additional code
14358 __EOF__
14359 @end example
14361 This, however, may change in the future as the M4sh interface is
14362 stabilized further.
14364 Also, be aware that use of @env{LINENO} within the child script may
14365 report line numbers relative to their location in the parent script,
14366 even when using @code{AS_LINENO_PREPARE}, if the parent script was
14367 unable to locate a shell with working @env{LINENO} support.
14368 @end defmac
14370 @defmac AS_LINENO_PREPARE
14371 @asindex{LINENO_PREPARE}
14372 @evindex LINENO
14373 Find a shell that supports the special variable @env{LINENO}, which
14374 contains the number of the currently executing line.  This macro is
14375 automatically invoked by @code{AC_INIT} in configure scripts.
14376 @end defmac
14378 @defmac AS_ME_PREPARE
14379 @asindex{ME_PREPARE}
14380 Set up variable @env{as_me} to be the basename of the currently executing
14381 script.  This macro is automatically invoked by @code{AC_INIT} in
14382 configure scripts.
14383 @end defmac
14385 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14386 @asindex{TMPDIR}
14387 @evindex TMPDIR
14388 @ovindex tmp
14389 Create, as safely as possible, a temporary sub-directory within
14390 @var{dir} with a name starting with @var{prefix}.  @var{prefix} should
14391 be 2--4 characters, to make it slightly easier to identify the owner of
14392 the directory.  If @var{dir} is omitted, then the value of @env{TMPDIR}
14393 will be used (defaulting to @samp{/tmp}).  On success, the name of the
14394 newly created directory is stored in the shell variable @code{tmp}.  On
14395 error, the script is aborted.
14397 Typically, this macro is coupled with some exit traps to delete the created
14398 directory and its contents on exit or interrupt.  However, there is a
14399 slight window between when the directory is created and when the name is
14400 actually known to the shell, so an interrupt at the right moment might
14401 leave the temporary directory behind.  Hence it is important to use a
14402 @var{prefix} that makes it easier to determine if a leftover temporary
14403 directory from an interrupted script is safe to delete.
14405 The use of the output variable @samp{$tmp} rather than something in the
14406 @samp{as_} namespace is historical; it has the unfortunate consequence
14407 that reusing this otherwise common name for any other purpose inside
14408 your script has the potential to break any cleanup traps designed to
14409 remove the temporary directory.
14410 @end defmac
14412 @defmac AS_SHELL_SANITIZE
14413 @asindex{SHELL_SANITIZE}
14414 Initialize the shell suitably for @command{configure} scripts.  This has
14415 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14416 environment variables for predictable results from configuration tests.
14417 For example, it sets @env{LC_ALL} to change to the default C locale.
14418 @xref{Special Shell Variables}.  This macro is deprecated, since
14419 @code{AS_INIT} already invokes it.
14420 @end defmac
14423 @node File Descriptor Macros
14424 @section File Descriptor Macros
14425 @cindex input
14426 @cindex standard input
14427 @cindex file descriptors
14428 @cindex descriptors
14429 @cindex low-level output
14430 @cindex output, low-level
14432 The following macros define file descriptors used to output messages
14433 (or input values) from @file{configure} scripts.
14434 For example:
14436 @example
14437 echo "$wombats found" >&AS_MESSAGE_LOG_FD
14438 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
14439 read kangaroos <&AS_ORIGINAL_STDIN_FD`
14440 @end example
14442 @noindent
14443 However doing so is seldom needed, because Autoconf provides higher
14444 level macros as described below.
14446 @defmac AS_MESSAGE_FD
14447 @asindex{MESSAGE_FD}
14448 The file descriptor for @samp{checking for...}  messages and results.
14449 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14450 clients.  However, @code{AC_INIT} shuffles things around to another file
14451 descriptor, in order to allow the @option{-q} option of
14452 @command{configure} to choose whether messages should go to the script's
14453 standard output or be discarded.
14455 If you want to display some messages, consider using one of the printing
14456 macros (@pxref{Printing Messages}) instead.  Copies of messages output
14457 via these macros are also recorded in @file{config.log}.
14458 @end defmac
14460 @anchor{AS_MESSAGE_LOG_FD}
14461 @defmac AS_MESSAGE_LOG_FD
14462 @asindex{MESSAGE_LOG_FD}
14463 This must either be empty, or expand to a file descriptor for log
14464 messages.  By default, @code{AS_INIT} sets this macro to the empty
14465 string for standalone M4sh clients, thus disabling logging.  However,
14466 @code{AC_INIT} shuffles things around so that both @command{configure}
14467 and @command{config.status} use @file{config.log} for log messages.
14468 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14469 Compiler}), redirect all output to this descriptor.  You may want to do
14470 so if you develop such a low-level macro.
14471 @end defmac
14473 @defmac AS_ORIGINAL_STDIN_FD
14474 @asindex{ORIGINAL_STDIN_FD}
14475 This must expand to a file descriptor for the original standard input.
14476 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14477 M4sh clients.  However, @code{AC_INIT} shuffles things around for
14478 safety.
14480 When @command{configure} runs, it may accidentally execute an
14481 interactive command that has the same name as the non-interactive meant
14482 to be used or checked.  If the standard input was the terminal, such
14483 interactive programs would cause @command{configure} to stop, pending
14484 some user input.  Therefore @command{configure} redirects its standard
14485 input from @file{/dev/null} during its initialization.  This is not
14486 normally a problem, since @command{configure} normally does not need
14487 user input.
14489 In the extreme case where your @file{configure} script really needs to
14490 obtain some values from the original standard input, you can read them
14491 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14492 @end defmac
14495 @c =================================================== Writing Autoconf Macros.
14497 @node Writing Autoconf Macros
14498 @chapter Writing Autoconf Macros
14500 When you write a feature test that could be applicable to more than one
14501 software package, the best thing to do is encapsulate it in a new macro.
14502 Here are some instructions and guidelines for writing Autoconf macros.
14503 You should also familiarize yourself with M4sugar (@pxref{Programming in M4})
14504 and M4sh (@pxref{Programming in M4sh}).
14506 @menu
14507 * Macro Definitions::           Basic format of an Autoconf macro
14508 * Macro Names::                 What to call your new macros
14509 * Dependencies Between Macros::  What to do when macros depend on other macros
14510 * Obsoleting Macros::           Warning about old ways of doing things
14511 * Coding Style::                Writing Autoconf macros @`a la Autoconf
14512 @end menu
14514 @node Macro Definitions
14515 @section Macro Definitions
14517 @defmac AC_DEFUN (@var{name}, @ovar{body})
14518 @acindex{DEFUN}
14519 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14520 similar to the M4 builtin @code{m4_define} macro; this creates a macro
14521 named @var{name} and with @var{body} as its expansion.  In addition to
14522 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14523 constrain the order in which macros are called, while avoiding redundant
14524 output (@pxref{Prerequisite Macros}).
14525 @end defmac
14527 An Autoconf macro definition looks like this:
14529 @example
14530 AC_DEFUN(@var{macro-name}, @var{macro-body})
14531 @end example
14533 You can refer to any arguments passed to the macro as @samp{$1},
14534 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4,
14535 GNU M4}, for more complete information on writing M4 macros.
14537 Most macros fall in one of two general categories.  The first category
14538 includes macros which take arguments, in order to generate output
14539 parameterized by those arguments.  Macros in this category are designed
14540 to be directly expanded, often multiple times, and should not be used as
14541 the argument to @code{AC_REQUIRE}.  The other category includes macros
14542 which are shorthand for a fixed block of text, and therefore do not take
14543 arguments.  For this category of macros, directly expanding the macro
14544 multiple times results in redundant output, so it is more common to use
14545 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14546 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14548 Be sure to properly quote both the @var{macro-body} @emph{and} the
14549 @var{macro-name} to avoid any problems if the macro happens to have
14550 been previously defined.
14552 Each macro should have a header comment that gives its prototype, and a
14553 brief description.  When arguments have default values, display them in
14554 the prototype.  For example:
14556 @example
14557 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14558 # --------------------------------------
14559 m4_define([AC_MSG_ERROR],
14560   [@{ AS_MESSAGE([error: $1], [2])
14561      exit m4_default([$2], [1]); @}])
14562 @end example
14564 Comments about the macro should be left in the header comment.  Most
14565 other comments make their way into @file{configure}, so just keep
14566 using @samp{#} to introduce comments.
14568 @cindex @code{dnl}
14569 If you have some special comments about pure M4 code, comments
14570 that make no sense in @file{configure} and in the header comment, then
14571 use the builtin @code{dnl}: it causes M4 to discard the text
14572 through the next newline.
14574 Keep in mind that @code{dnl} is rarely needed to introduce comments;
14575 @code{dnl} is more useful to get rid of the newlines following macros
14576 that produce no output, such as @code{AC_REQUIRE}.
14578 Public third-party macros need to use @code{AC_DEFUN}, and not
14579 @code{m4_define}, in order to be found by @command{aclocal}
14580 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14581 Additionally, if it is ever determined that a macro should be made
14582 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14583 in order to have @command{autoupdate} assist the user in choosing a
14584 better alternative, but there is no corresponding way to make
14585 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14587 There is another subtle, but important, difference between using
14588 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14589 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
14590 block of text with a @code{m4_define} macro that will expand to the same
14591 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
14592 the same content does not necessarily give the same results, because it
14593 changes the location where any embedded but unsatisfied
14594 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
14595 example of this, see @ref{Expanded Before Required}.
14597 @node Macro Names
14598 @section Macro Names
14600 All of the public Autoconf macros have all-uppercase names in the
14601 namespace @samp{^AC_} to prevent them from accidentally conflicting with
14602 other text; Autoconf also reserves the namespace @samp{^_AC_} for
14603 internal macros.  All shell variables that they use for internal
14604 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
14605 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
14606 @command{configure}, files produced by Autoconf make heavy use of the
14607 file system namespace @samp{^conf}.
14609 Since Autoconf is built on top of M4sugar (@pxref{Programming in
14610 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14611 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
14612 @file{configure.ac} is also designed to be scanned by Autoheader,
14613 Autoscan, Autoupdate, and Automake, you should be aware of the
14614 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
14615 the namespace of a package that does not own the macro or shell code you
14616 are writing.
14618 To ensure that your macros don't conflict with present or future
14619 Autoconf macros, you should prefix your own macro names and any shell
14620 variables they use with some other sequence.  Possibilities include your
14621 initials, or an abbreviation for the name of your organization or
14622 software package.  Historically, people have not always followed the
14623 rule of using a namespace appropriate for their package, and this has
14624 made it difficult for determining the origin of a macro (and where to
14625 report bugs about that macro), as well as difficult for the true
14626 namespace owner to add new macros without interference from pre-existing
14627 uses of third-party macros.  Perhaps the best example of this confusion
14628 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14629 to Gettext.
14631 Most of the Autoconf macros' names follow a structured naming convention
14632 that indicates the kind of feature check by the name.  The macro names
14633 consist of several words, separated by underscores, going from most
14634 general to most specific.  The names of their cache variables use the
14635 same convention (@pxref{Cache Variable Names}, for more information on
14636 them).
14638 The first word of the name after the namespace initials (such as
14639 @samp{AC_}) usually tells the category
14640 of the feature being tested.  Here are the categories used in Autoconf for
14641 specific test macros, the kind of macro that you are more likely to
14642 write.  They are also used for cache variables, in all-lowercase.  Use
14643 them where applicable; where they're not, invent your own categories.
14645 @table @code
14646 @item C
14647 C language builtin features.
14648 @item DECL
14649 Declarations of C variables in header files.
14650 @item FUNC
14651 Functions in libraries.
14652 @item GROUP
14653 Posix group owners of files.
14654 @item HEADER
14655 Header files.
14656 @item LIB
14657 C libraries.
14658 @item PROG
14659 The base names of programs.
14660 @item MEMBER
14661 Members of aggregates.
14662 @item SYS
14663 Operating system features.
14664 @item TYPE
14665 C builtin or declared types.
14666 @item VAR
14667 C variables in libraries.
14668 @end table
14670 After the category comes the name of the particular feature being
14671 tested.  Any further words in the macro name indicate particular aspects
14672 of the feature.  For example, @code{AC_PROG_MAKE_SET} checks whether
14673 @command{make} sets a variable to its own name.
14675 An internal macro should have a name that starts with an underscore;
14676 Autoconf internals should therefore start with @samp{_AC_}.
14677 Additionally, a macro that is an internal subroutine of another macro
14678 should have a name that starts with an underscore and the name of that
14679 other macro, followed by one or more words saying what the internal
14680 macro does.  For example, @code{AC_PATH_X} has internal macros
14681 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14683 @node Dependencies Between Macros
14684 @section Dependencies Between Macros
14685 @cindex Dependencies between macros
14687 Some Autoconf macros depend on other macros having been called first in
14688 order to work correctly.  Autoconf provides a way to ensure that certain
14689 macros are called if needed and a way to warn the user if macros are
14690 called in an order that might cause incorrect operation.
14692 @menu
14693 * Prerequisite Macros::         Ensuring required information
14694 * Suggested Ordering::          Warning about possible ordering problems
14695 * One-Shot Macros::             Ensuring a macro is called only once
14696 @end menu
14698 @node Prerequisite Macros
14699 @subsection Prerequisite Macros
14700 @cindex Prerequisite macros
14701 @cindex Macros, prerequisites
14703 A macro that you write might need to use values that have previously
14704 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
14705 examines the output of @code{flex} or @code{lex}, so it depends on
14706 @code{AC_PROG_LEX} having been called first to set the shell variable
14707 @code{LEX}.
14709 Rather than forcing the user of the macros to keep track of the
14710 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14711 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
14712 called if it is needed, and only called once.
14714 @defmac AC_REQUIRE (@var{macro-name})
14715 @acindex{REQUIRE}
14716 If the M4 macro @var{macro-name} has not already been called, call it
14717 (without any arguments).  Make sure to quote @var{macro-name} with
14718 square brackets.  @var{macro-name} must have been defined using
14719 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14720 that it has been called.
14722 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14723 must not be called from the top level.  Also, it does not make sense to
14724 require a macro that takes parameters.
14725 @end defmac
14727 @code{AC_REQUIRE} is often misunderstood.  It really implements
14728 dependencies between macros in the sense that if one macro depends upon
14729 another, the latter is expanded @emph{before} the body of the
14730 former.  To be more precise, the required macro is expanded before
14731 the outermost defined macro in the current expansion stack.
14732 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14733 @code{FOO}.  For instance, this definition of macros:
14735 @example
14736 @group
14737 AC_DEFUN([TRAVOLTA],
14738 [test "$body_temperature_in_celsius" -gt 38 &&
14739   dance_floor=occupied])
14740 AC_DEFUN([NEWTON_JOHN],
14741 [test "x$hair_style" = xcurly &&
14742   dance_floor=occupied])
14743 @end group
14745 @group
14746 AC_DEFUN([RESERVE_DANCE_FLOOR],
14747 [if test "x`date +%A`" = xSaturday; then
14748   AC_REQUIRE([TRAVOLTA])
14749   AC_REQUIRE([NEWTON_JOHN])
14750 fi])
14751 @end group
14752 @end example
14754 @noindent
14755 with this @file{configure.ac}
14757 @example
14758 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14759 RESERVE_DANCE_FLOOR
14760 if test "x$dance_floor" = xoccupied; then
14761   AC_MSG_ERROR([cannot pick up here, let's move])
14763 @end example
14765 @noindent
14766 does not leave you with a better chance to meet a kindred soul on
14767 days other than Saturday, since the call to @code{RESERVE_DANCE_FLOOR}
14768 expands to:
14770 @example
14771 @group
14772 test "$body_temperature_in_Celsius" -gt 38 &&
14773   dance_floor=occupied
14774 test "x$hair_style" = xcurly &&
14775   dance_floor=occupied
14777 if test "x`date +%A`" = xSaturday; then
14781 @end group
14782 @end example
14784 This behavior was chosen on purpose: (i) it prevents messages in
14785 required macros from interrupting the messages in the requiring macros;
14786 (ii) it avoids bad surprises when shell conditionals are used, as in:
14788 @example
14789 @group
14790 if @dots{}; then
14791   AC_REQUIRE([SOME_CHECK])
14793 @dots{}
14794 SOME_CHECK
14795 @end group
14796 @end example
14798 However, this implementation can lead to another class of problems.
14799 Consider the case where an outer macro first expands, then indirectly
14800 requires, an inner macro:
14802 @example
14803 AC_DEFUN([TESTA], [[echo in A
14804 if test -n "$SEEN_A" ; then echo duplicate ; fi
14805 SEEN_A=:]])
14806 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14807 if test -z "$SEEN_A" ; then echo bug ; fi]])
14808 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14809 AC_DEFUN([OUTER], [[echo in OUTER]
14810 TESTA
14811 TESTC])
14812 OUTER
14813 @end example
14815 @noindent
14816 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14817 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14818 of @code{OUTER}, but because @code{TESTA} had already been directly
14819 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
14820 @code{TESTB} occurs prior to its prerequisites, leading to the following
14821 output:
14823 @example
14824 in B
14826 in OUTER
14827 in A
14828 in C
14829 @end example
14831 @noindent
14832 Newer Autoconf is smart enough to recognize this situation, and hoists
14833 @code{TESTA} even though it has already been expanded, but issues a
14834 syntax warning in the process.  This is because the hoisted expansion of
14835 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14836 redundant code, and causes its own set of problems if the hoisted macro
14837 is not idempotent:
14839 @example
14840 in A
14841 in B
14842 in OUTER
14843 in A
14844 duplicate
14845 in C
14846 @end example
14848 The bug is not in Autoconf, but in the macro definitions.  If you ever
14849 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14850 that the macro only needs to be expanded once.  But to enforce this,
14851 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14852 this only helps in Autoconf 2.64 or newer), or all
14853 uses of that macro should be through @code{AC_REQUIRE}; directly
14854 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14855 eliminate redundant expansion.  In the example, this rule of thumb was
14856 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14857 directly expands it.  One way of fixing the bug is to factor
14858 @code{TESTA} into two macros, the portion designed for direct and
14859 repeated use (here, named @code{TESTA}), and the portion designed for
14860 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14861 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
14862 calling convention according to their needs:
14864 @example
14865 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14866 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14867 if test -n "$SEEN_A" ; then echo duplicate ; fi
14868 SEEN_A=:]])
14869 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14870 if test -z "$SEEN_A" ; then echo bug ; fi]])
14871 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14872 AC_DEFUN([OUTER], [[echo in OUTER]
14873 TESTA
14874 TESTC])
14875 OUTER
14876 @end example
14878 @noindent
14879 the resulting output will then obey all dependency rules and avoid any
14880 syntax warnings, whether the script is built with old or new Autoconf
14881 versions:
14883 @example
14884 in A_PREREQ
14885 in B
14886 in OUTER
14887 in A
14888 in C
14889 @end example
14891 You can use the helper macros @code{AS_IF} and @code{AS_CASE} in
14892 top-level code to enforce expansion of required macros outside of shell
14893 conditional constructs; these helpers are not needed in the bodies of
14894 macros defined by @code{AC_DEFUN}.
14895 You are furthermore encouraged, although not required, to
14896 put all @code{AC_REQUIRE} calls
14897 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
14898 lines they leave.
14900 Autoconf will normally warn if an @code{AC_REQUIRE} call refers to a
14901 macro that has not been defined.  However, the @command{aclocal} tool
14902 relies on parsing an incomplete set of input files to trace which macros
14903 have been required, in order to then pull in additional files that
14904 provide those macros; for this particular use case, pre-defining the
14905 macro @code{m4_require_silent_probe} will avoid the warnings.
14907 @node Suggested Ordering
14908 @subsection Suggested Ordering
14909 @cindex Macros, ordering
14910 @cindex Ordering macros
14912 Some macros should be run before another macro if both are called, but
14913 neither @emph{requires} that the other be called.  For example, a macro
14914 that changes the behavior of the C compiler should be called before any
14915 macros that run the C compiler.  Many of these dependencies are noted in
14916 the documentation.
14918 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14919 with this kind of dependency appear out of order in a
14920 @file{configure.ac} file.  The warning occurs when creating
14921 @command{configure} from @file{configure.ac}, not when running
14922 @command{configure}.
14924 For example, @code{AC_PROG_CPP} checks whether the C compiler
14925 can run the C preprocessor when given the @option{-E} option.  It should
14926 therefore be called after any macros that change which C compiler is
14927 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
14929 @example
14930 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14931 @end example
14933 @noindent
14934 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14935 when @code{AC_PROG_CC} is called.
14937 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14938 @acindex{BEFORE}
14939 Make M4 print a warning message to the standard error output if
14940 @var{called-macro-name} has already been called.  @var{this-macro-name}
14941 should be the name of the macro that is calling @code{AC_BEFORE}.  The
14942 macro @var{called-macro-name} must have been defined using
14943 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14944 that it has been called.
14945 @end defmac
14947 @node One-Shot Macros
14948 @subsection One-Shot Macros
14949 @cindex One-shot macros
14950 @cindex Macros, called once
14952 Some macros should be called only once, either because calling them
14953 multiple time is unsafe, or because it is bad style.  For instance
14954 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14955 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
14956 sense to run these expensive checks more than once.  Such one-shot
14957 macros can be defined using @code{AC_DEFUN_ONCE}.
14959 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14960 @acindex{DEFUN_ONCE}
14961 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14962 Definitions}), but add additional logic that guarantees that only the
14963 first use of the macro (whether by direct expansion or
14964 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14965 expansion will occur before the start of any enclosing macro defined by
14966 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
14967 Generally, it does not make sense for @var{macro-body} to use parameters
14968 such as @code{$1}.
14969 @end defmac
14971 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14972 emit a warning if it was directly expanded a second time, so for
14973 portability, it is better to use @code{AC_REQUIRE} than direct
14974 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14975 (@pxref{Prerequisite Macros}).
14977 @node Obsoleting Macros
14978 @section Obsoleting Macros
14979 @cindex Obsoleting macros
14980 @cindex Macros, obsoleting
14982 Configuration and portability technology has evolved over the years.
14983 Often better ways of solving a particular problem are developed, or
14984 ad-hoc approaches are systematized.  This process has occurred in many
14985 parts of Autoconf.  One result is that some of the macros are now
14986 considered @dfn{obsolete}; they still work, but are no longer considered
14987 the best thing to do, hence they should be replaced with more modern
14988 macros.  Ideally, @command{autoupdate} should replace the old macro calls
14989 with their modern implementation.
14991 Autoconf provides a simple means to obsolete a macro.
14993 @anchor{AU_DEFUN}
14994 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message}, @ovar{silent})
14995 @auindex{DEFUN}
14996 Define @var{old-macro} as @var{implementation}, just like
14997 @code{AC_DEFUN}, but also declare @var{old-macro} to be obsolete.
14998 When @command{autoupdate} is run, occurrences of @var{old-macro} will
14999 be replaced by the text of @var{implementation} in the updated
15000 @file{configure.ac} file.
15002 If a simple textual replacement is not enough to finish the job of
15003 updating a @file{configure.ac} to modern style, provide instructions for
15004 whatever additional manual work is required as @var{message}.  These
15005 instructions will be printed by @command{autoupdate}, and embedded in the
15006 updated @file{configure.ac} file, next to the text of @var{implementation}.
15008 Normally, @command{autoconf} will also issue a warning (in the
15009 ``obsolete'' category) when it expands @var{old-macro}.  This warning
15010 does not include @var{message}; it only advises the maintainer to run
15011 @command{autoupdate}.  If it is inappropriate to issue this warning, set
15012 the @var{silent} argument to the word @code{silent}.  One might want to
15013 use a silent @code{AU_DEFUN} when @var{old-macro} is used in a
15014 widely-distributed third-party macro.  If that macro's maintainers are
15015 aware of the need to update their code, it's unnecessary to nag all
15016 of the transitive users of @var{old-macro} as well.  This capability
15017 was added to @code{AU_DEFUN} in Autoconf 2.70; older versions of
15018 autoconf will ignore the @var{silent} argument and issue the warning
15019 anyway.
15021 @strong{Caution:} If @var{implementation} contains M4 or M4sugar macros,
15022 they will be evaluated when @command{autoupdate} is run, not emitted
15023 verbatim like the rest of @var{implementation}.  This cannot be avoided
15024 with extra quotation, because then @var{old-macro} will not work when
15025 it is called normally.  See the definition of @code{AC_FOREACH} in
15026 @file{general.m4} for a workaround.
15027 @end defmac
15029 @defmac AU_ALIAS (@var{old-name}, @var{new-name}, @ovar{silent})
15030 @auindex{ALIAS}
15031 A shorthand version of @code{AU_DEFUN}, to be used when a macro has
15032 simply been renamed.  @command{autoupdate} will replace calls to
15033 @var{old-name} with calls to @var{new-name}, keeping any arguments
15034 intact.  No instructions for additional manual work will be printed.
15036 The @var{silent} argument works the same as the @var{silent} argument
15037 to @code{AU_DEFUN}.  It was added to @code{AU_ALIAS} in Autoconf 2.70.
15039 @strong{Caution:} @code{AU_ALIAS} cannot be used when @var{new-name} is
15040 an M4 or M4sugar macro.  See above.
15041 @end defmac
15043 @node Coding Style
15044 @section Coding Style
15045 @cindex Coding style
15047 The Autoconf macros follow a strict coding style.  You are encouraged to
15048 follow this style, especially if you intend to distribute your macro,
15049 either by contributing it to Autoconf itself or the
15050 @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
15051 Archive}, or by other means.
15053 The first requirement is to pay great attention to the quotation.  For
15054 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
15056 Do not try to invent new interfaces.  It is likely that there is a macro
15057 in Autoconf that resembles the macro you are defining: try to stick to
15058 this existing interface (order of arguments, default values, etc.).  We
15059 @emph{are} conscious that some of these interfaces are not perfect;
15060 nevertheless, when harmless, homogeneity should be preferred over
15061 creativity.
15063 Be careful about clashes both between M4 symbols and between shell
15064 variables.
15066 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
15067 you are unlikely to generate conflicts.  Nevertheless, when you need to
15068 set a special value, @emph{avoid using a regular macro name}; rather,
15069 use an ``impossible'' name.  For instance, up to version 2.13, the macro
15070 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
15071 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
15072 But since there is a macro named @code{AC_SUBST_FILE}, it was just
15073 impossible to @samp{AC_SUBST(FILE)}!  In this case,
15074 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
15075 have been used (yes, with the parentheses).
15076 @c or better yet, high-level macros such as @code{m4_expand_once}
15078 No Autoconf macro should ever enter the user-variable name space; i.e.,
15079 except for the variables that are the actual result of running the
15080 macro, all shell variables should start with @code{ac_}.  In
15081 addition, small macros or any macro that is likely to be embedded in
15082 other macros should be careful not to use obvious names.
15084 @cindex @code{dnl}
15085 Do not use @code{dnl} to introduce comments: most of the comments you
15086 are likely to write are either header comments which are not output
15087 anyway, or comments that should make their way into @file{configure}.
15088 There are exceptional cases where you do want to comment special M4
15089 constructs, in which case @code{dnl} is right, but keep in mind that it
15090 is unlikely.
15092 M4 ignores the leading blanks and newlines before each argument.
15093 Use this feature to
15094 indent in such a way that arguments are (more or less) aligned with the
15095 opening parenthesis of the macro being called.  For instance, instead of
15097 @example
15098 AC_CACHE_CHECK(for EMX OS/2 environment,
15099 ac_cv_emxos2,
15100 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
15101 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
15102 @end example
15104 @noindent
15105 write
15107 @example
15108 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15109 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15110                    [ac_cv_emxos2=yes],
15111                    [ac_cv_emxos2=no])])
15112 @end example
15114 @noindent
15115 or even
15117 @example
15118 AC_CACHE_CHECK([for EMX OS/2 environment],
15119                [ac_cv_emxos2],
15120                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
15121                                                    [return __EMX__;])],
15122                                   [ac_cv_emxos2=yes],
15123                                   [ac_cv_emxos2=no])])
15124 @end example
15126 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
15127 cross-compiling, provide a pessimistic value (typically @samp{no}).
15129 Feel free to use various tricks to prevent auxiliary tools, such as
15130 syntax-highlighting editors, from behaving improperly.  For instance,
15131 instead of:
15133 @example
15134 m4_bpatsubst([$1], [$"])
15135 @end example
15137 @noindent
15140 @example
15141 m4_bpatsubst([$1], [$""])
15142 @end example
15144 @noindent
15145 so that Emacsen do not open an endless ``string'' at the first quote.
15146 For the same reasons, avoid:
15148 @example
15149 test $[#] != 0
15150 @end example
15152 @noindent
15153 and use:
15155 @example
15156 test $[@@%:@@] != 0
15157 @end example
15159 @noindent
15160 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
15161 breaking the bracket-matching highlighting from Emacsen.  Note the
15162 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
15163 not escape when it is unnecessary.  Common examples of useless quotation
15164 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
15165 etc.  If you add portability issues to the picture, you'll prefer
15166 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
15167 better than hacking Autoconf @code{:-)}.
15169 When using @command{sed}, don't use @option{-e} except for indenting
15170 purposes.  With the @code{s} and @code{y} commands, the preferred
15171 separator is @samp{/} unless @samp{/} itself might appear in the pattern
15172 or replacement, in which case you should use @samp{|}, or optionally
15173 @samp{,} if you know the pattern and replacement cannot contain a file
15174 name.  If none of these characters will do, choose a printable character
15175 that cannot appear in the pattern or replacement.  Characters from the
15176 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
15177 replacement might contain a file name, since they have special meaning
15178 to the shell and are less likely to occur in file names.
15180 @xref{Macro Definitions}, for details on how to define a macro.  If a
15181 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
15182 of an @code{AC_REQUIRE} directive, and macros required by other macros
15183 inside arguments do not need to be expanded before this macro, then
15184 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
15185 Also take into account that public third-party macros need to use
15186 @code{AC_DEFUN} in order to be found by @command{aclocal}
15187 (@pxref{Extending aclocal,,, automake, GNU Automake}).
15188 All the @code{AC_REQUIRE} statements should be at the beginning of the
15189 macro, and each statement should be followed by @code{dnl}.
15191 You should not rely on the number of arguments: instead of checking
15192 whether an argument is missing, test that it is not empty.  It provides
15193 both a simpler and a more predictable interface to the user, and saves
15194 room for further arguments.
15196 Unless the macro is short, try to leave the closing @samp{])} at the
15197 beginning of a line, followed by a comment that repeats the name of the
15198 macro being defined.  This introduces an additional newline in
15199 @command{configure}; normally, that is not a problem, but if you want to
15200 remove it you can use @samp{[]dnl} on the last line.  You can similarly
15201 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
15202 is recommended instead of @samp{dnl} to ensure that M4 does not
15203 interpret the @samp{dnl} as being attached to the preceding text or
15204 macro output.  For example, instead of:
15206 @example
15207 AC_DEFUN([AC_PATH_X],
15208 [AC_MSG_CHECKING([for X])
15209 AC_REQUIRE_CPP()
15210 @r{# @dots{}omitted@dots{}}
15211   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15212 fi])
15213 @end example
15215 @noindent
15216 you would write:
15218 @example
15219 AC_DEFUN([AC_PATH_X],
15220 [AC_REQUIRE_CPP()[]dnl
15221 AC_MSG_CHECKING([for X])
15222 @r{# @dots{}omitted@dots{}}
15223   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15224 fi[]dnl
15225 ])# AC_PATH_X
15226 @end example
15228 If the macro is long, try to split it into logical chunks.  Typically,
15229 macros that check for a bug in a function and prepare its
15230 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
15231 this setup.  Do not hesitate to introduce auxiliary macros to factor
15232 your code.
15234 In order to highlight the recommended coding style, here is a macro
15235 written the old way:
15237 @example
15238 dnl Check for EMX on OS/2.
15239 dnl _AC_EMXOS2
15240 AC_DEFUN(_AC_EMXOS2,
15241 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
15242 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
15243 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
15244 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
15245 @end example
15247 @noindent
15248 and the new way:
15250 @example
15251 # _AC_EMXOS2
15252 # ----------
15253 # Check for EMX on OS/2.
15254 m4_define([_AC_EMXOS2],
15255 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15256 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15257                    [ac_cv_emxos2=yes],
15258                    [ac_cv_emxos2=no])])
15259 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
15260 ])# _AC_EMXOS2
15261 @end example
15266 @c ============================================= Portable Shell Programming
15268 @node Portable Shell
15269 @chapter Portable Shell Programming
15270 @cindex Portable shell programming
15272 When writing your own checks, there are some shell-script programming
15273 techniques you should avoid in order to make your code portable.  The
15274 Bourne shell and upward-compatible shells like the Korn shell and Bash
15275 have evolved over the years, and many features added to the original
15276 System7 shell are now supported on all interesting porting targets.
15277 However, the following discussion between Russ Allbery and Robert Lipe
15278 is worth reading:
15280 @noindent
15281 Russ Allbery:
15283 @quotation
15284 The GNU assumption that @command{/bin/sh} is the one and only shell
15285 leads to a permanent deadlock.  Vendors don't want to break users'
15286 existing shell scripts, and there are some corner cases in the Bourne
15287 shell that are not completely compatible with a Posix shell.  Thus,
15288 vendors who have taken this route will @emph{never} (OK@dots{}``never say
15289 never'') replace the Bourne shell (as @command{/bin/sh}) with a
15290 Posix shell.
15291 @end quotation
15293 @noindent
15294 Robert Lipe:
15296 @quotation
15297 This is exactly the problem.  While most (at least most System V's) do
15298 have a Bourne shell that accepts shell functions most vendor
15299 @command{/bin/sh} programs are not the Posix shell.
15301 So while most modern systems do have a shell @emph{somewhere} that meets the
15302 Posix standard, the challenge is to find it.
15303 @end quotation
15305 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15306 is to find such a shell.  But to prevent trouble, if you're not using
15307 M4sh you should not take advantage of features that were added after Unix
15308 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15309 negated character classes, or even @command{unset}.  @code{#} comments,
15310 while not in Unix version 7, were retrofitted in the original Bourne
15311 shell and can be assumed to be part of the least common denominator.
15313 On the other hand, if you're using M4sh you can assume that the shell
15314 has the features that were added in SVR2 (circa 1984), including shell
15315 functions,
15316 @command{return}, @command{unset}, and I/O redirection for builtins.  For
15317 more information, refer to @uref{https://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15318 However, some pitfalls have to be avoided for portable use of these
15319 constructs; these will be documented in the rest of this chapter.
15320 See in particular @ref{Shell Functions} and @ref{Limitations of
15321 Builtins, , Limitations of Shell Builtins}.
15323 Some ancient systems have quite
15324 small limits on the length of the @samp{#!} line; for instance, 32
15325 bytes (not including the newline) on SunOS 4.
15326 However, these ancient systems are no longer of practical concern.
15328 The set of external programs you should run in a @command{configure} script
15329 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
15330 Makefiles, standards, The GNU Coding Standards}, for the list.  This
15331 restriction allows users to start out with a fairly small set of
15332 programs and build the rest, avoiding too many interdependencies between
15333 packages.
15335 Some of these external utilities have a portable subset of features; see
15336 @ref{Limitations of Usual Tools}.
15338 There are other sources of documentation about shells.  The
15339 specification for the Posix
15340 @uref{https://@/pubs.opengroup.org/@/onlinepubs/@/9699919799/@/utilities/@/V3_chap02.html,
15341 Shell Command Language}, though more generous than the restrictive shell
15342 subset described above, is fairly portable nowadays.  Also please see
15343 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15345 @menu
15346 * Shellology::                  A zoology of shells
15347 * Invoking the Shell::          Invoking the shell as a command
15348 * Here-Documents::              Quirks and tricks
15349 * File Descriptors::            FDs and redirections
15350 * Signal Handling::             Shells, signals, and headaches
15351 * File System Conventions::     File names
15352 * Shell Pattern Matching::      Pattern matching
15353 * Shell Substitutions::         Variable and command expansions
15354 * Assignments::                 Varying side effects of assignments
15355 * Parentheses::                 Parentheses in shell scripts
15356 * Slashes::                     Slashes in shell scripts
15357 * Special Shell Variables::     Variables you should not change
15358 * Shell Functions::             What to look out for if you use them
15359 * Limitations of Builtins::     Portable use of not so portable /bin/sh
15360 * Limitations of Usual Tools::  Portable use of portable tools
15361 @end menu
15363 @node Shellology
15364 @section Shellology
15365 @cindex Shellology
15367 There are several families of shells, most prominently the Bourne family
15368 and the C shell family which are deeply incompatible.  If you want to
15369 write portable shell scripts, avoid members of the C shell family.  The
15370 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15371 Shell difference FAQ} includes a small history of Posix shells, and a
15372 comparison between several of them.
15374 Below we describe some of the members of the Bourne shell family.
15376 @table @asis
15377 @item Ash
15378 @cindex Ash
15379 Ash is often used on GNU/Linux and BSD
15380 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
15381 bugs that are fixed in the 0.3.x series, but portable shell scripts
15382 should work around them, since version 0.2 is still shipped with many
15383 GNU/Linux distributions.
15385 To be compatible with Ash 0.2:
15387 @itemize @minus
15388 @item
15389 don't use @samp{$?} after expanding empty or unset variables,
15390 or at the start of an @command{eval}:
15392 @example
15393 foo=
15394 false
15395 $foo
15396 echo "Do not use it: $?"
15397 false
15398 eval 'echo "Do not use it: $?"'
15399 @end example
15401 @item
15402 don't use command substitution within variable expansion:
15404 @example
15405 cat $@{FOO=`bar`@}
15406 @end example
15408 @item
15409 beware that single builtin substitutions are not performed by a
15410 subshell, hence their effect applies to the current shell!  @xref{Shell
15411 Substitutions}, item ``Command Substitution''.
15412 @end itemize
15414 @item Bash
15415 @cindex Bash
15416 To detect whether you are running Bash, test whether
15417 @code{BASH_VERSION} is set.  To require
15418 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
15419 Mode, , Bash Posix Mode, bash, The GNU Bash Reference
15420 Manual}, for details.
15422 @item Bash 2.05 and later
15423 @cindex Bash 2.05 and later
15424 Versions 2.05 and later of Bash use a different format for the
15425 output of the @command{set} builtin, designed to make evaluating its
15426 output easier.  However, this output is not compatible with earlier
15427 versions of Bash (or with many other shells, probably).  So if
15428 you use Bash 2.05 or higher to execute @command{configure},
15429 you'll need to use Bash 2.05 for all other build tasks as well.
15431 @item Ksh
15432 @cindex Ksh
15433 @cindex Korn shell
15434 @prindex @samp{ksh}
15435 @prindex @samp{ksh88}
15436 @prindex @samp{ksh93}
15437 The Korn shell is compatible with the Bourne family and it mostly
15438 conforms to Posix.  It has two major variants commonly
15439 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15440 release.  It is usually called @command{ksh}, but is called @command{sh}
15441 on some hosts if you set your path appropriately.
15443 On Solaris 11, @command{/bin/sh} and @command{/usr/bin/ksh} are both
15444 @samp{ksh93}.  On Solaris 10 and earlier, @command{/bin/sh} is a
15445 pre-Posix Bourne shell and the Korn shell is found elsewhere:
15446 @prindex @command{/usr/bin/ksh} on Solaris
15447 @command{/usr/bin/ksh} is @samp{ksh88} on Solaris 2.0 through 10,
15448 @prindex @command{/usr/xpg4/bin/sh} on Solaris
15449 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
15450 @samp{ksh88} on Solaris 9 and later,
15451 @prindex @command{/usr/dt/bin/dtksh} on Solaris
15452 and @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15453 Variants that are not standard may be parts of optional
15454 packages.  There is no extra charge for these packages, but they are
15455 not part of a minimal OS install and therefore some installations may
15456 not have it.
15458 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
15459 is also available as @command{/usr/bin/posix/sh}.  If the environment
15460 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15461 the standard shell conform to Posix.
15463 @item Pdksh
15464 @prindex @samp{pdksh}
15465 A public-domain clone of the Korn shell called @command{pdksh} is widely
15466 available: it has most of the @samp{ksh88} features along with a few of
15467 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
15468 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15469 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
15470 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
15471 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
15472 at least one respect, see @ref{Shell Substitutions}.
15474 @item Zsh
15475 @cindex Zsh
15476 To detect whether you are running @command{zsh}, test whether
15477 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
15478 compatible with the Bourne shell: you must execute @samp{emulate sh},
15479 and for @command{zsh} versions before 3.1.6-dev-18 you must also
15480 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
15481 zsh, The Z Shell Manual}, for details.
15483 The default Mac OS X @command{sh} was originally Zsh; it was changed to
15484 Bash in Mac OS X 10.2.
15485 @end table
15487 @node Invoking the Shell
15488 @section Invoking the Shell
15489 @cindex invoking the shell
15490 @cindex shell invocation
15492 The Korn shell (up to at least version M-12/28/93d) has a bug when
15493 invoked on a file whose name does not contain a slash.  It first
15494 searches for the file's name in @env{PATH}, and if found it executes
15495 that rather than the original file.  For example, assuming there is a
15496 binary executable @file{/usr/bin/script} in your @env{PATH}, the last
15497 command in the following example fails because the Korn shell finds
15498 @file{/usr/bin/script} and refuses to execute it as a shell script:
15500 @example
15501 $ @kbd{touch xxyzzyz script}
15502 $ @kbd{ksh xxyzzyz}
15503 $ @kbd{ksh ./script}
15504 $ @kbd{ksh script}
15505 ksh: script: cannot execute
15506 @end example
15508 Bash 2.03 has a bug when invoked with the @option{-c} option: if the
15509 option-argument ends in backslash-newline, Bash incorrectly reports a
15510 syntax error.  The problem does not occur if a character follows the
15511 backslash:
15513 @example
15514 $ @kbd{$ bash -c 'echo foo \}
15515 > @kbd{'}
15516 bash: -c: line 2: syntax error: unexpected end of file
15517 $ @kbd{bash -c 'echo foo \}
15518 > @kbd{ '}
15520 @end example
15522 @noindent
15523 @xref{Backslash-Newline-Empty}, for how this can cause problems in makefiles.
15525 @node Here-Documents
15526 @section Here-Documents
15527 @cindex Here-documents
15528 @cindex Shell here-documents
15530 Don't rely on @samp{\} being preserved just because it has no special
15531 meaning together with the next symbol.  In the native @command{sh}
15532 on OpenBSD 2.7 @samp{\"} expands to @samp{"} in here-documents with
15533 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
15534 use @samp{\\} to get @samp{\}.
15536 With OpenBSD 2.7's @command{sh}
15538 @example
15539 @group
15540 $ @kbd{cat <<EOF
15541 > \" \\
15542 > EOF}
15543 " \
15544 @end group
15545 @end example
15547 @noindent
15548 and with Bash:
15550 @example
15551 @group
15552 bash-2.04$ @kbd{cat <<EOF
15553 > \" \\
15554 > EOF}
15555 \" \
15556 @end group
15557 @end example
15559 Using command substitutions in a here-document that is fed to a shell
15560 function is not portable.  For example, with Solaris 10 @command{/bin/sh}:
15562 @example
15563 $ @kbd{kitty () @{ cat; @}}
15564 $ @kbd{kitty <<EOF
15565 > `echo ok`
15566 > EOF}
15567 /tmp/sh199886: cannot open
15568 $ @kbd{echo $?}
15570 @end example
15572 Some shells mishandle large here-documents: for example,
15573 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
15574 derived from Korn shell version M-12/28/93d, mishandle braced variable
15575 expansion that crosses a 1024- or 4096-byte buffer boundary
15576 within a here-document.  Only the part of the variable name after the boundary
15577 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
15578 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
15579 boundary, the shell reports an error, as if you used @code{$@{@}}.
15580 Instead of @code{$@{variable-default@}}, the shell may expand
15581 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
15582 be worked around by omitting the braces: @code{$variable}.  The bug was
15583 fixed in
15584 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15585 still shipping older versions with the bug.
15587 Empty here-documents are not portable either; with the following code,
15588 @command{zsh} up to at least version 4.3.10 creates a file with a single
15589 newline, whereas other shells create an empty file:
15591 @example
15592 cat >file <<EOF
15594 @end example
15596 Many shells (including the Bourne shell) implement here-documents
15597 inefficiently.  In particular, some shells can be extremely inefficient when
15598 a single statement contains many here-documents.  For instance if your
15599 @file{configure.ac} includes something like:
15601 @example
15602 @group
15603 if <cross_compiling>; then
15604   assume this and that
15605 else
15606   check this
15607   check that
15608   check something else
15609   @dots{}
15610   on and on forever
15611   @dots{}
15613 @end group
15614 @end example
15616 A shell parses the whole @code{if}/@code{fi} construct, creating
15617 temporary files for each here-document in it.  Some shells create links
15618 for such here-documents on every @code{fork}, so that the clean-up code
15619 they had installed correctly removes them.  It is creating the links
15620 that can take the shell forever.
15622 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15623 @code{if}/@code{fi} constructs, would improve the performance
15624 significantly.  Anyway, this kind of construct is not exactly the
15625 typical use of Autoconf.  In fact, it's even not recommended, because M4
15626 macros can't look into shell conditionals, so we may fail to expand a
15627 macro when it was expanded before in a conditional path, and the
15628 condition turned out to be false at runtime, and we end up not
15629 executing the macro at all.
15631 Be careful with the use of @samp{<<-} to unindent here-documents.  The
15632 behavior is only portable for stripping leading @key{TAB}s, and things
15633 can silently break if an overzealous editor converts to using leading
15634 spaces (not all shells are nice enough to warn about unterminated
15635 here-documents).
15637 @example
15638 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
15641 done
15642 $ @kbd{printf 'cat <<-x\n 1\n  2\n x\n' | bash-3.2 && echo done}
15644   2
15646 done
15647 @end example
15649 @node File Descriptors
15650 @section File Descriptors
15651 @cindex Descriptors
15652 @cindex File descriptors
15653 @cindex Shell file descriptors
15655 Most shells, if not all (including Bash, Zsh, Ash), output traces on
15656 stderr, even for subshells.  This might result in undesirable content
15657 if you meant to capture the standard-error output of the inner command:
15659 @example
15660 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15661 $ @kbd{cat stderr}
15662 + eval echo foo >&2
15663 + echo foo
15665 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15666 $ @kbd{cat stderr}
15667 + eval 'echo foo >&2'
15668 ++ echo foo
15670 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15671 @i{# Traces on startup files deleted here.}
15672 $ @kbd{cat stderr}
15673 +zsh:1> eval echo foo >&2
15674 +zsh:1> echo foo
15676 @end example
15678 @noindent
15679 One workaround is to grep out uninteresting lines, hoping not to remove
15680 good ones.
15682 If you intend to redirect both standard error and standard output,
15683 redirect standard output first.  This works better with HP-UX,
15684 since its shell mishandles tracing if standard error is redirected
15685 first:
15687 @example
15688 $ @kbd{sh -x -c ': 2>err >out'}
15689 + :
15690 + 2> err $ @kbd{cat err}
15691 1> out
15692 @end example
15694 Don't try to redirect the standard error of a command substitution.  It
15695 must be done @emph{inside} the command substitution.  When running
15696 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15697 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15699 On the other hand, some shells, such as Solaris or FreeBSD
15700 @command{/bin/sh}, warn about missing programs before performing
15701 redirections.  Therefore, to silently check whether a program exists, it
15702 is necessary to perform redirections on a subshell or brace group:
15703 @example
15704 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15705 nosuch: not found
15706 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15707 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15708 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15709 @end example
15711 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15712 shell pipeline.
15714 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15715 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15717 Some shells, like @command{ash}, don't recognize bi-directional
15718 redirection (@samp{<>}).  And even on shells that recognize it, it is
15719 not portable to use on fifos: Posix does not require read-write support
15720 for named pipes, and Cygwin does not support it:
15722 @example
15723 $ @kbd{mkfifo fifo}
15724 $ @kbd{exec 5<>fifo}
15725 $ @kbd{echo hi >&5}
15726 bash: echo: write error: Communication error on send
15727 @end example
15729 @noindent
15730 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15731 regular files when using @samp{<>}:
15733 @example
15734 $ @kbd{echo a > file}
15735 $ @kbd{bash -c ': 1<>file'; cat file}
15737 $ @kbd{dash -c ': 1<>file'; cat file}
15738 $ rm a
15739 @end example
15741 Solaris 10 @code{/bin/sh} executes redirected compound commands
15742 in a subshell, while other shells don't:
15744 @example
15745 $ @kbd{/bin/sh -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15747 $ @kbd{ksh -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15749 $ @kbd{bash -c 'foo=0; @{ foo=1; @} 2>/dev/null; echo $foo'}
15751 @end example
15753 When catering to old systems, don't redirect the same file descriptor
15754 several times, as you are doomed to failure under Ultrix.
15756 @example
15757 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
15758 UWS V4.4 (Rev. 11)
15759 $ @kbd{eval 'echo matter >fullness' >void}
15760 illegal io
15761 $ @kbd{eval '(echo matter >fullness)' >void}
15762 illegal io
15763 $ @kbd{(eval '(echo matter >fullness)') >void}
15764 Ambiguous output redirect.
15765 @end example
15767 @noindent
15768 In each case the expected result is of course @file{fullness} containing
15769 @samp{matter} and @file{void} being empty.  However, this bug is
15770 probably not of practical concern to modern platforms.
15772 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15773 (even if it is redirected) in a loop after the first iteration, or in a
15774 shell function after the first call:
15776 @example
15777 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15778 $ @kbd{ls x*}
15780 $ @kbd{f () @{ : >$1; @}; f y1; f y2; f y3;}
15781 $ @kbd{ls y*}
15783 @end example
15785 @noindent
15786 As a workaround, @command{echo} or @command{eval} can be used.
15788 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15789 subsidiary program.  If any of these descriptors is closed, the
15790 operating system may open an unspecified file for the descriptor in the
15791 new process image.  Posix 2008 says this may be done only if the
15792 subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15793 it even for ordinary programs, and the next version of Posix will allow
15794 HP-UX behavior.
15796 If you want a file descriptor above 2 to be inherited into a child
15797 process, then you must use redirections specific to that command or a
15798 containing subshell or command group, rather than relying on
15799 @command{exec} in the shell. In @command{ksh} as well as HP-UX
15800 @command{sh}, file descriptors above 2 which are opened using
15801 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15802 that involved in the fork-and-exec which runs a program or script):
15804 @example
15805 $ @kbd{echo 'echo hello >&5' >k}
15806 $ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15807 hello
15808 $ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15809 hello
15810 $ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15811 ./k[1]: 5: cannot open [Bad file number]
15812 $ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
15813 hello
15814 $ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
15815 hello
15816 $ @kbd{ksh -c '5>t ksh ./k; cat t}
15817 hello
15818 @end example
15820 Don't rely on duplicating a closed file descriptor to cause an
15821 error.  With Solaris 10 @command{/bin/sh}, failed duplication is silently
15822 ignored, which can cause unintended leaks to the original file
15823 descriptor.  In this example, observe the leak to standard output:
15825 @example
15826 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15827 bash: 3: Bad file descriptor
15829 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15832 @end example
15834 Fortunately, an attempt to close an already closed file descriptor will
15835 portably succeed.  Likewise, it is safe to use either style of
15836 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15837 even if it doesn't match the read/write mode that the file descriptor
15838 was opened with.
15840 DOS variants cannot rename or remove open files, such as in
15841 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15842 perfectly portable among Posix hosts.
15844 A few ancient systems reserved some file descriptors.  By convention,
15845 file descriptor 3 was opened to @file{/dev/tty} when you logged into
15846 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
15847 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
15848 1990), though we don't now remember what it was.  Both these systems are
15849 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15850 other file descriptors.
15852 On the other hand, you can't portably use multi-digit file descriptors.
15853 @command{dash} and Solaris @command{ksh} don't understand any file
15854 descriptor larger than @samp{9}:
15856 @example
15857 $ @kbd{bash -c 'exec 10>&-'; echo $?}
15859 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
15861 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
15862 ksh[1]: exec: 10: not found
15864 $ @kbd{dash -c 'exec 9>&-'; echo $?}
15866 $ @kbd{dash -c 'exec 10>&-'; echo $?}
15867 exec: 1: 10: not found
15869 @end example
15871 @c <https://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
15872 @node Signal Handling
15873 @section Signal Handling
15874 @cindex Signal handling in the shell
15875 @cindex Signals, shells and
15877 Portable handling of signals within the shell is another major source of
15878 headaches.  This is worsened by the fact that various different, mutually
15879 incompatible approaches are possible in this area, each with its
15880 distinctive merits and demerits.  A detailed description of these possible
15881 approaches, as well as of their pros and cons, can be found in
15882 @uref{https://www.cons.org/cracauer/sigint.html, this article}.
15884 Solaris 10 @command{/bin/sh} automatically traps most signals by default;
15885 the shell still exits with error upon termination by one of those signals,
15886 but in such a case the exit status might be somewhat unexpected (even if
15887 allowed by POSIX, strictly speaking):
15888 @c FIXME: We had a reference for this behavior but the website no longer
15889 @c exists and the page is not in the Internet Archive. --zw 2020-07-10.
15891 @example
15892 $ @kbd{bash -c 'kill -1 $$'; echo $?} # Will exit 128 + (signal number).
15893 Hangup
15895 $ @kbd{/bin/ksh -c 'kill -15 $$'; echo $?} # Likewise.
15896 Terminated
15898 $ @kbd{for sig in 1 2 3 15; do}
15899 > @kbd{  echo $sig:}
15900 > @kbd{  /bin/sh -c "kill -$s \$\$"; echo $?}
15901 > @kbd{done}
15902 signal 1:
15903 Hangup
15905 signal 2:
15907 signal 3:
15909 signal 15:
15911 @end example
15913 This gets even worse if one is using the POSIX ``wait'' interface to get
15914 details about the shell process terminations: it will result in the shell
15915 having exited normally, rather than by receiving a signal.
15917 @example
15918 $ @kbd{cat > foo.c <<'END'}
15919 #include <stdio.h>    /* for printf */
15920 #include <stdlib.h>   /* for system */
15921 #include <sys/wait.h> /* for WIF* macros */
15922 int main(void)
15924   int status = system ("kill -15 $$");
15925   printf ("Terminated by signal: %s\n",
15926           WIFSIGNALED (status) ? "yes" : "no");
15927   printf ("Exited normally: %s\n",
15928           WIFEXITED (status) ? "yes" : "no");
15929   return 0;
15932 @c $$ font-lock
15933 $ @kbd{cc -o foo foo.c}
15934 $ @kbd{./a.out} # On GNU/Linux
15935 Terminated by signal: no
15936 Exited normally: yes
15937 $ @kbd{./a.out} # On Solaris 10
15938 Terminated by signal: yes
15939 Exited normally: no
15940 @end example
15942 Various shells seem to handle @code{SIGQUIT} specially: they ignore it even
15943 if it is not blocked, and even if the shell is not running interactively
15944 (in fact, even if the shell has no attached tty); among these shells
15945 are at least Bash (from version 2 onward), Zsh 4.3.12, Solaris 10
15946 @code{/bin/ksh} and @code{/usr/xpg4/bin/sh}, and AT&T @code{ksh93} (2011).
15947 Still, @code{SIGQUIT} seems to be trappable quite portably within all
15948 these shells.  OTOH, some other shells doesn't special-case the handling
15949 of @code{SIGQUIT}; among these shells are at least @code{pdksh} 5.2.14,
15950 Solaris 10 and NetBSD 5.1 @code{/bin/sh}, and the Almquist Shell 0.5.5.1.
15952 Some shells (especially Korn shells and derivatives) might try to
15953 propagate to themselves a signal that has killed a child process; this is
15954 not a bug, but a conscious design choice (although its overall value might
15955 be debatable).  The exact details of how this is attained vary from shell
15956 to shell.  For example, upon running @code{perl -e 'kill 2, $$'}, after
15957 the perl process has been interrupted, AT&T @code{ksh93} (2011) will
15958 proceed to send itself a @code{SIGINT}, while Solaris 10 @code{/bin/ksh}
15959 and @code{/usr/xpg4/bin/sh} will proceed to exit with status 130 (i.e.,
15960 128 + 2). In any case, if there is an active trap associated with
15961 @code{SIGINT}, those shells will correctly execute it.
15963 @c See: <https://www.austingroupbugs.net/view.php?id=51>
15964 Some Korn shells, when a child process die due receiving a signal with
15965 signal number @var{n}, can leave in @samp{$?} an exit status of
15966 256+@var{n} instead of the more common 128+@var{n}.  Observe the
15967 difference between AT&T @code{ksh93} (2011) and @code{bash} 4.1.5 on
15968 Debian:
15970 @example
15971 $ @kbd{/bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?'}
15972 /bin/ksh: line 1: 7837: Hangup
15974 $ @kbd{/bin/bash -c 'sh -c "kill -1 \$\$"; echo $?'}
15975 /bin/bash: line 1:  7861 Hangup        (sh -c "kill -1 \$\$")
15977 @end example
15979 @noindent
15980 This @command{ksh} behavior is allowed by POSIX, if implemented with
15981 due care; see this @uref{https://www.austingroupbugs.net/view.php?id=51,
15982 Austin Group discussion} for more background.  However, if it is not
15983 implemented with proper care, such a behavior might cause problems
15984 in some corner cases.  To see why, assume we have a ``wrapper'' script
15985 like this:
15987 @example
15988 #!/bin/sh
15989 # Ignore some signals in the shell only, not in its child processes.
15990 trap : 1 2 13 15
15991 wrapped_command "$@@"
15992 ret=$?
15993 other_command
15994 exit $ret
15995 @end example
15997 @noindent
15998 If @command{wrapped_command} is interrupted by a @code{SIGHUP} (which
15999 has signal number 1), @code{ret} will be set to 257.  Unless the
16000 @command{exit} shell builtin is smart enough to understand that such
16001 a value can only have originated from a signal, and adjust the final
16002 wait status of the shell appropriately, the value 257 will just get
16003 truncated to 1 by the closing @code{exit} call, so that a caller of
16004 the script will have no way to determine that termination by a signal
16005 was involved.  Observe the different behavior of AT&T @code{ksh93}
16006 (2011) and @code{bash} 4.1.5 on Debian:
16008 @example
16009 $ @kbd{cat foo.sh}
16010 #!/bin/sh
16011 sh -c 'kill -1 $$'
16012 ret=$?
16013 echo $ret
16014 exit $ret
16015 $ @kbd{/bin/ksh foo.sh; echo $?}
16016 foo.sh: line 2: 12479: Hangup
16019 $ @kbd{/bin/bash foo.sh; echo $?}
16020 foo.sh: line 2: 12487 Hangup        (sh -c 'kill -1 $$')
16023 @end example
16025 @node File System Conventions
16026 @section File System Conventions
16027 @cindex File system conventions
16029 Autoconf uses shell-script processing extensively, so the file names
16030 that it processes should not contain characters that are special to the
16031 shell.  Special characters include space, tab, newline, NUL, and
16032 the following:
16034 @example
16035 " # $ & ' ( ) * ; < = > ? [ \ ` |
16036 @end example
16038 Also, file names should not begin with @samp{~} or @samp{-}, and should
16039 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
16040 immediately after @samp{:}.  On Posix-like platforms, directory names
16041 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
16042 path separator.
16044 These restrictions apply not only to the files that you distribute, but
16045 also to the absolute file names of your source, build, and destination
16046 directories.
16048 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
16049 they should be avoided.
16051 Posix lets implementations treat leading @file{//} specially, but
16052 requires leading @file{///} and beyond to be equivalent to @file{/}.
16053 Most Unix variants treat @file{//} like @file{/}.  However, some treat
16054 @file{//} as a ``super-root'' that can provide access to files that are
16055 not otherwise reachable from @file{/}.  The super-root tradition began
16056 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
16057 has revived it.
16059 While @command{autoconf} and friends are usually run on some Posix
16060 variety, they can be used on other systems, most notably DOS
16061 variants.  This impacts several assumptions regarding file names.
16063 @noindent
16064 For example, the following code:
16066 @example
16067 case $foo_dir in
16068   /*) # Absolute
16069      ;;
16070   *)
16071      foo_dir=$dots$foo_dir ;;
16072 esac
16073 @end example
16075 @noindent
16076 fails to properly detect absolute file names on those systems, because
16077 they can use a drivespec, and usually use a backslash as directory
16078 separator.  If you want to be portable to DOS variants (at the
16079 price of rejecting valid but oddball Posix file names like @file{a:\b}),
16080 you can check for absolute file names like this:
16082 @cindex absolute file names, detect
16083 @example
16084 case $foo_dir in
16085   [\\/]* | ?:[\\/]* ) # Absolute
16086      ;;
16087   *)
16088      foo_dir=$dots$foo_dir ;;
16089 esac
16090 @end example
16092 @noindent
16093 Make sure you quote the brackets if appropriate and keep the backslash as
16094 first character.  @xref{case, , Limitations of Shell Builtins}.
16096 Also, because the colon is used as part of a drivespec, these systems don't
16097 use it as path separator.  When creating or accessing paths, you can use the
16098 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
16099 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
16100 starts up.
16102 File names need extra care as well.  While DOS variants
16103 that are Posixy enough to run @command{autoconf} (such as DJGPP)
16104 are usually able to handle long file names properly, there are still
16105 limitations that can seriously break packages.  Several of these issues
16106 can be easily detected by the
16107 @uref{https://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
16108 package.
16110 A short overview follows; problems are marked with SFN/LFN to
16111 indicate where they apply: SFN means the issues are only relevant to
16112 plain DOS, not to DOS under Microsoft Windows
16113 variants, while LFN identifies problems that exist even under
16114 Microsoft Windows variants.
16116 @table @asis
16117 @item No multiple dots (SFN)
16118 DOS cannot handle multiple dots in file names.  This is an especially
16119 important thing to remember when building a portable configure script,
16120 as @command{autoconf} uses a .in suffix for template files.
16122 This is perfectly OK on Posix variants:
16124 @example
16125 AC_CONFIG_HEADERS([config.h])
16126 AC_CONFIG_FILES([source.c foo.bar])
16127 AC_OUTPUT
16128 @end example
16130 @noindent
16131 but it causes problems on DOS, as it requires @samp{config.h.in},
16132 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
16133 to DOS-based environments, you should use this instead:
16135 @example
16136 AC_CONFIG_HEADERS([config.h:config.hin])
16137 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
16138 AC_OUTPUT
16139 @end example
16141 @item No leading dot (SFN)
16142 DOS cannot handle file names that start with a dot.  This is usually
16143 not important for @command{autoconf}.
16145 @item Case insensitivity (LFN)
16146 DOS is case insensitive, so you cannot, for example, have both a
16147 file called @samp{INSTALL} and a directory called @samp{install}.  This
16148 also affects @command{make}; if there's a file called @samp{INSTALL} in
16149 the directory, @samp{make install} does nothing (unless the
16150 @samp{install} target is marked as PHONY).
16152 @item The 8+3 limit (SFN)
16153 Because the DOS file system only stores the first 8 characters of
16154 the file name and the first 3 of the extension, those must be unique.
16155 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
16156 @file{foobar-prettybird.c} all resolve to the same file name
16157 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
16158 @file{foo.bartender}.
16160 The 8+3 limit is not usually a problem under Microsoft Windows, as it
16161 uses numeric
16162 tails in the short version of file names to make them unique.  However, a
16163 registry setting can turn this behavior off.  While this makes it
16164 possible to share file trees containing long file names between SFN
16165 and LFN environments, it also means the above problem applies there
16166 as well.
16168 @item Invalid characters (LFN)
16169 Some characters are invalid in DOS file names, and should therefore
16170 be avoided.  In a LFN environment, these are @samp{/}, @samp{\},
16171 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
16172 In a SFN environment, other characters are also invalid.  These
16173 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
16175 @item Invalid names (LFN)
16176 Some DOS file names are reserved, and cause problems if you
16177 try to use files with those names.  These names include @file{CON},
16178 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
16179 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
16180 File names are case insensitive, so even names like
16181 @file{aux/config.guess} are disallowed.
16183 @end table
16185 @node Shell Pattern Matching
16186 @section Shell Pattern Matching
16187 @cindex Shell pattern matching
16189 Nowadays portable patterns can use negated character classes like
16190 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
16191 some shells but not others; hence portable scripts should never use
16192 @samp{^} as the first character of a bracket pattern.
16194 Outside the C locale, patterns like @samp{[a-z]} are problematic since
16195 they may match characters that are not lower-case letters.
16197 @node Shell Substitutions
16198 @section Shell Substitutions
16199 @cindex Shell substitutions
16201 Contrary to a persistent urban legend, the Bourne shell does not
16202 systematically split variables and back-quoted expressions, in particular
16203 on the right-hand side of assignments and in the argument of @code{case}.
16204 For instance, the following code:
16206 @example
16207 case "$given_srcdir" in
16208 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
16209 *)  top_srcdir="$dots$given_srcdir" ;;
16210 esac
16211 @end example
16213 @noindent
16214 is more readable when written as:
16216 @example
16217 case $given_srcdir in
16218 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
16219 *)  top_srcdir=$dots$given_srcdir ;;
16220 esac
16221 @end example
16223 @noindent
16224 and in fact it is even @emph{more} portable: in the first case of the
16225 first attempt, the computation of @code{top_srcdir} is not portable,
16226 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
16227 for example Solaris 10 @command{ksh}:
16229 @example
16230 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
16231 ksh: : cannot execute
16232 ksh: bar | sed 's, ,,': cannot execute
16233 @end example
16235 @noindent
16236 Posix does not specify behavior for this sequence.  On the other hand,
16237 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by Posix,
16238 but in practice, not all shells understand it the same way: pdksh 5.2.14
16239 prints spurious quotes when in Posix mode:
16241 @example
16242 $ @kbd{echo "`echo \"hello\"`"}
16243 hello
16244 $ @kbd{set -o posix}
16245 $ @kbd{echo "`echo \"hello\"`"}
16246 "hello"
16247 @end example
16249 @noindent
16250 There is just no portable way to use double-quoted strings inside
16251 double-quoted back-quoted expressions (pfew!).
16253 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
16254 parameter expansions are elided during word splitting.  Meanwhile, zsh
16255 does not perform word splitting except when in Bourne compatibility
16256 mode.  In the example below, the correct behavior is to have five
16257 arguments to the function, and exactly two spaces on either side of the
16258 middle @samp{-}, since word splitting collapses multiple spaces in
16259 @samp{$f} but leaves empty arguments intact.
16261 @example
16262 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16263 3- - -
16264 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16265 5-  -  -
16266 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16267 3-   -   -
16268 $ @kbd{zsh -c 'emulate sh;}
16269 > @kbd{n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16270 5-  -  -
16271 @end example
16273 @noindent
16274 You can work around this by doing manual word splitting, such as using
16275 @samp{"$str" $list} rather than @samp{"$str"$list}.
16277 There are also portability pitfalls with particular expansions:
16279 @table @code
16280 @item $@@
16281 @cindex @code{"$@@"}
16282 One of the most famous shell-portability issues is related to
16283 @samp{"$@@"}.  When there are no positional arguments, Posix says
16284 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
16285 original Unix version 7 Bourne shell treated it as equivalent to
16286 @samp{""} instead, and this behavior survives in later implementations
16287 like Digital Unix 5.0.
16289 The traditional way to work around this portability problem is to use
16290 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
16291 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
16292 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
16294 @example
16295 zsh $ @kbd{emulate sh}
16296 zsh $ @kbd{for i in "$@@"; do echo $i; done}
16297 Hello World
16299 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
16300 Hello
16301 World
16303 @end example
16305 @noindent
16306 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
16307 @samp{"$@@"} because of the portability problems mentioned above.
16308 One workaround relies on Zsh's ``global aliases'' to convert
16309 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
16311 @example
16312 test $@{ZSH_VERSION+y@} && alias -g '$@{1+"$@@"@}'='"$@@"'
16313 @end example
16315 Zsh only recognizes this alias when a shell word matches it exactly;
16316 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
16317 case always yields at least one shell word, use plain @samp{"$@@"}.
16319 A more conservative workaround is to avoid @samp{"$@@"} if it is
16320 possible that there may be no positional arguments.  For example,
16321 instead of:
16323 @example
16324 cat conftest.c "$@@"
16325 @end example
16327 you can use this instead:
16329 @example
16330 case $# in
16331 0) cat conftest.c;;
16332 *) cat conftest.c "$@@";;
16333 esac
16334 @end example
16336 Autoconf macros often use the @command{set} command to update
16337 @samp{$@@}, so if you are writing shell code intended for
16338 @command{configure} you should not assume that the value of @samp{$@@}
16339 persists for any length of time.
16342 @item $@{10@}
16343 @cindex positional parameters
16344 The 10th, 11th, @dots{} positional parameters can be accessed only after
16345 a @code{shift}.  The 7th Edition shell reported an error if given
16346 @code{$@{10@}}, and
16347 Solaris 10 @command{/bin/sh} still acts that way:
16349 @example
16350 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
16351 $ @kbd{echo $@{10@}}
16352 bad substitution
16353 @end example
16355 Conversely, not all shells obey the Posix rule that when braces are
16356 omitted, multiple digits beyond a @samp{$} imply the single-digit
16357 positional parameter expansion concatenated with the remaining literal
16358 digits.  To work around the issue, you must use braces.
16360 @example
16361 $ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16362 a0 a0
16363 $ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16364 j a0
16365 @end example
16367 @item $@{@var{var}:-@var{value}@}
16368 @itemx $@{@var{var}:=@var{value}@}
16369 @itemx $@{@var{var}:?@var{value}@}
16370 @itemx $@{@var{var}:+@var{value}@}
16371 @c Info cannot handle ':' in index entries.
16372 @ifnotinfo
16373 @cindex @code{$@{@var{var}:-@var{value}@}}
16374 @cindex @code{$@{@var{var}:=@var{value}@}}
16375 @cindex @code{$@{@var{var}:?@var{value}@}}
16376 @cindex @code{$@{@var{var}:+@var{value}@}}
16377 @end ifnotinfo
16378 Old BSD shells, including the Ultrix @code{sh}, don't accept the
16379 colon for any shell substitution, and complain and die.
16380 Similarly for @code{$@{@var{var}:=@var{value}@}},
16381 @code{$@{@var{var}:?@var{value}@}}, etc.
16382 However, all shells that support functions allow the use of colon in
16383 shell substitution, and since m4sh requires functions, you can portably
16384 use null variable substitution patterns in configure scripts.
16386 @item $@{@var{var}-@var{value}@}
16387 @itemx $@{@var{var}:-@var{value}@}
16388 @itemx $@{@var{var}=@var{value}@}
16389 @itemx $@{@var{var}:=@var{value}@}
16390 @itemx $@{@var{var}?@var{value}@}
16391 @itemx $@{@var{var}:?@var{value}@}
16392 @itemx $@{@var{var}+@var{value}@}
16393 @itemx $@{@var{var}:+@var{value}@}
16394 @cindex @code{$@{@var{var}-@var{value}@}}
16395 @cindex @code{$@{@var{var}=@var{value}@}}
16396 @cindex @code{$@{@var{var}?@var{value}@}}
16397 @cindex @code{$@{@var{var}+@var{value}@}}
16398 @c Info cannot handle ':' in index entries.
16399 @ifnotinfo
16400 @cindex @code{$@{@var{var}:-@var{value}@}}
16401 @cindex @code{$@{@var{var}:=@var{value}@}}
16402 @cindex @code{$@{@var{var}:?@var{value}@}}
16403 @cindex @code{$@{@var{var}:+@var{value}@}}
16404 @end ifnotinfo
16405 When using @samp{$@{@var{var}-@var{value}@}} or
16406 similar notations that modify a parameter expansion,
16407 Posix requires that @var{value} must be a single shell word,
16408 which can contain quoted strings but cannot contain unquoted spaces.
16409 If this requirement is not met Solaris 10 @command{/bin/sh}
16410 sometimes complains, and anyway the behavior is not portable.
16412 @example
16413 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
16414 /bin/sh: bad substitution
16415 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
16416 b c
16417 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
16418 b c
16419 $ @kbd{/bin/sh -c 'cat <<EOF
16420 $@{a-b c@}
16421 EOF}
16422 b c
16423 @end example
16425 Most shells treat the special parameters @code{*} and @code{@@} as being
16426 unset if there are no positional parameters.  However, some shells treat
16427 them as being set to the empty string.  Posix does not clearly specify
16428 either behavior.
16430 @example
16431 $ @kbd{bash -c 'echo "* is $@{*-unset@}."'}
16432 * is unset.
16433 $ @kbd{dash -c 'echo "* is $@{*-unset@}."'}
16434 * is .
16435 @end example
16437 According to Posix, if an expansion occurs inside double quotes, then
16438 the use of unquoted double quotes within @var{value} is unspecified, and
16439 any single quotes become literal characters; in that case, escaping must
16440 be done with backslash.  Likewise, the use of unquoted here-documents is
16441 a case where double quotes have unspecified results:
16443 @example
16444 $ @kbd{/bin/sh -c 'echo "$@{a-"b  c"@}"'}
16445 /bin/sh: bad substitution
16446 $ @kbd{ksh -c 'echo "$@{a-"b  c"@}"'}
16447 b c
16448 $ @kbd{bash -c 'echo "$@{a-"b  c"@}"'}
16449 b  c
16450 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b  c'\''@}'}
16451 b  c
16452 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b  c'\''@}"'}
16453 'b  c'
16454 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b  c\"@}"'}
16455 "b  c"
16456 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b  c@}"'}
16457 b  c
16458 $ @kbd{/bin/sh -c 'cat <<EOF
16459 $@{a-"b  c"@}
16460 EOF'}
16461 "b  c"
16462 $ @kbd{/bin/sh -c 'cat <<EOF
16463 $@{a-'b  c'@}
16464 EOF'}
16465 'b  c'
16466 $ @kbd{bash -c 'cat <<EOF
16467 $@{a-"b  c"@}
16468 EOF'}
16469 b  c
16470 $ @kbd{bash -c 'cat <<EOF
16471 $@{a-'b  c'@}
16472 EOF'}
16473 'b  c'
16474 @end example
16476 Perhaps the easiest way to work around quoting issues in a manner
16477 portable to all shells is to place the results in a temporary variable,
16478 then use @samp{$t} as the @var{value}, rather than trying to inline
16479 the expression needing quoting.
16481 @example
16482 $ @kbd{/bin/sh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16483 b  c"'@}\
16484 $ @kbd{ksh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16485 b  c"'@}\
16486 $ @kbd{bash -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16487 b  c"'@}\
16488 @end example
16490 @item $@{@var{var}=@var{value}@}
16491 @cindex @code{$@{@var{var}=@var{value}@}}
16492 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
16493 to @var{var}, remember that even though the assignment to @var{var} does
16494 not undergo file name expansion, the result of the variable expansion
16495 does unless the expansion occurred within double quotes.  In particular,
16496 when using @command{:} followed by unquoted variable expansion for the
16497 side effect of setting a default value, if the final value of
16498 @samp{$var} contains any globbing characters (either from @var{value} or
16499 from prior contents), the shell has to spend time performing file name
16500 expansion and field splitting even though those results will not be
16501 used.  Therefore, it is a good idea to consider double quotes when performing
16502 default initialization; while remembering how this impacts any quoting
16503 characters appearing in @var{value}.
16505 @example
16506 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
16507 /usr/bin/*
16509 real    0m0.005s
16510 user    0m0.002s
16511 sys     0m0.003s
16512 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
16513 /usr/bin/*
16515 real    0m0.039s
16516 user    0m0.026s
16517 sys     0m0.009s
16518 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
16519 /usr/bin/*
16521 real    0m0.031s
16522 user    0m0.020s
16523 sys     0m0.010s
16525 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
16526 /usr/bin/*
16528 real    0m0.006s
16529 user    0m0.002s
16530 sys     0m0.003s
16531 @end example
16533 As with @samp{+} and @samp{-}, @var{value} must be a single shell word,
16534 otherwise some shells, such as Solaris 10 @command{/bin/sh} or on Digital
16535 Unix V 5.0, die because of a ``bad substitution''.  Meanwhile, Posix
16536 requires that with @samp{=}, quote removal happens prior to the
16537 assignment, and the expansion be the final contents of @var{var} without
16538 quoting (and thus subject to field splitting), in contrast to the
16539 behavior with @samp{-} passing the quoting through to the final
16540 expansion.  However, @command{bash} 4.1 does not obey this rule.
16542 @example
16543 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16544 a  b
16545 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16546 a b
16547 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16548 a  b
16549 @end example
16551 Finally, Posix states that when mixing @samp{$@{a=b@}} with regular
16552 commands, it is unspecified whether the assignments affect the parent
16553 shell environment.  It is best to perform assignments independently from
16554 commands, to avoid the problems demonstrated in this example:
16556 @example
16557 $ @kbd{bash -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16558 +b+b+
16560 $ @kbd{/bin/sh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16561 ++b+
16563 $ @kbd{ksh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16564 +b+b+
16566 @end example
16568 @item $@{@var{var}=@var{value}@}
16569 @cindex @code{$@{@var{var}=@var{literal}@}}
16570 Solaris 10 @command{/bin/sh} has a frightening bug in its handling of
16571 literal assignments.  Imagine you need set a variable to a string containing
16572 @samp{@}}.  This @samp{@}} character confuses Solaris 10 @command{/bin/sh}
16573 when the affected variable was already set.  This bug can be exercised
16574 by running:
16576 @example
16577 $ @kbd{unset foo}
16578 $ @kbd{foo=$@{foo='@}'@}}
16579 $ @kbd{echo $foo}
16581 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
16582 $ @kbd{echo $foo}
16584 $ @kbd{foo=$@{foo='@}'@}}
16585 $ @kbd{echo $foo}
16586 @}@}
16587  ^ ugh!
16588 @end example
16590 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16591 though it is enclosed in single quotes.  The problem doesn't happen
16592 using double quotes, or when using a temporary variable holding the
16593 problematic string.
16595 @item $@{@var{var}=@var{expanded-value}@}
16596 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
16597 On Ultrix,
16598 running
16600 @example
16601 default="yu,yaa"
16602 : $@{var="$default"@}
16603 @end example
16605 @noindent
16606 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
16607 each char is set.  You don't observe the phenomenon using a simple
16608 @samp{echo $var} since apparently the shell resets the 8th bit when it
16609 expands $var.  Here are two means to make this shell confess its sins:
16611 @example
16612 $ @kbd{cat -v <<EOF
16613 $var
16614 EOF}
16615 @end example
16617 @noindent
16620 @example
16621 $ @kbd{set | grep '^var=' | cat -v}
16622 @end example
16624 One classic incarnation of this bug is:
16626 @example
16627 default="a b c"
16628 : $@{list="$default"@}
16629 for c in $list; do
16630   echo $c
16631 done
16632 @end example
16634 @noindent
16635 You'll get @samp{a b c} on a single line.  Why?  Because there are no
16636 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
16637 bit set, hence no IFS splitting is performed!!!
16639 One piece of good news is that Ultrix works fine with @samp{:
16640 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
16641 then that QNX 4.25 then sets @var{list} to the @emph{last} item of
16642 @var{default}!
16644 The portable way out consists in using a double assignment, to switch
16645 the 8th bit twice on Ultrix:
16647 @example
16648 list=$@{list="$default"@}
16649 @end example
16651 @noindent
16652 @dots{}but beware of the @samp{@}} bug from Solaris 10 (see above).
16653 For safety, use:
16655 @example
16656 test $@{var+y@} || var=@var{@{value@}}
16657 @end example
16659 @item $@{#@var{var}@}
16660 @itemx $@{@var{var}%@var{word}@}
16661 @itemx $@{@var{var}%%@var{word}@}
16662 @itemx $@{@var{var}#@var{word}@}
16663 @itemx $@{@var{var}##@var{word}@}
16664 @cindex @code{$@{#@var{var}@}}
16665 @cindex @code{$@{@var{var}%@var{word}@}}
16666 @cindex @code{$@{@var{var}%%@var{word}@}}
16667 @cindex @code{$@{@var{var}#@var{word}@}}
16668 @cindex @code{$@{@var{var}##@var{word}@}}
16669 Posix requires support for these usages, but they do not work with many
16670 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16672 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
16673 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16674 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16675 yields the empty string.
16678 @item `@var{commands}`
16679 @cindex @code{`@var{commands}`}
16680 @cindex Command Substitution
16681 Posix requires shells to trim all trailing newlines from command
16682 output before substituting it, so assignments like
16683 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
16684 @samp{$file} ends in a newline.
16686 While in general it makes no sense, do not substitute a single builtin
16687 with side effects, because Ash 0.2, trying to optimize, does not fork a
16688 subshell to perform the command.
16690 For instance, if you wanted to check that @command{cd} is silent, do not
16691 use @samp{test -z "`cd /`"} because the following can happen:
16693 @example
16694 $ @kbd{pwd}
16695 /tmp
16696 $ @kbd{test -z "`cd /`" && pwd}
16698 @end example
16700 @noindent
16701 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16703 The MSYS shell leaves a stray byte in the expansion of a double-quoted
16704 command substitution of a native program, if the end of the substitution
16705 is not aligned with the end of the double quote.  This may be worked
16706 around by inserting another pair of quotes:
16708 @example
16709 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16710 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16711 - broken differ: char 4, line 1
16712 @end example
16714 Upon interrupt or SIGTERM, some shells may abort a command substitution,
16715 replace it with a null string, and wrongly evaluate the enclosing
16716 command before entering the trap or ending the script.  This can lead to
16717 spurious errors:
16719 @example
16720 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16721 $ @kbd{^C}
16722 sh: test: hi: unexpected operator/operand
16723 @end example
16725 @noindent
16726 You can avoid this by assigning the command substitution to a temporary
16727 variable:
16729 @example
16730 $ @kbd{sh -c 'res=`sleep 5; echo hi`
16731          if test "x$res" = xhi; then echo yes; fi'}
16732 $ @kbd{^C}
16733 @end example
16735 @item $(@var{commands})
16736 @cindex @code{$(@var{commands})}
16737 This construct is meant to replace @samp{`@var{commands}`},
16738 and it has most of the problems listed under @code{`@var{commands}`}.
16740 This construct can be
16741 nested while this is impossible to do portably with back quotes.
16742 Although it is almost universally supported, unfortunately Solaris 10
16743 and earlier releases lack it:
16745 @example
16746 $ @kbd{showrev -c /bin/sh | grep version}
16747 Command version: SunOS 5.10 Generic 142251-02 Sep 2010
16748 $ @kbd{echo $(echo blah)}
16749 syntax error: `(' unexpected
16750 @end example
16752 @noindent
16753 nor does IRIX 6.5's Bourne shell:
16754 @example
16755 $ @kbd{uname -a}
16756 IRIX firebird-image 6.5 07151432 IP22
16757 $ @kbd{echo $(echo blah)}
16758 $(echo blah)
16759 @end example
16761 If you do use @samp{$(@var{commands})}, make sure that the commands
16762 do not start with a parenthesis, as that would cause confusion with
16763 a different notation @samp{$((@var{expression}))} that in modern
16764 shells is an arithmetic expression not a command.  To avoid the
16765 confusion, insert a space between the two opening parentheses.
16767 Avoid @var{commands} that contain unbalanced parentheses in
16768 here-documents, comments, or case statement patterns, as many shells
16769 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
16770 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16772 @example
16773 echo $(case x in x) echo hello;; esac)
16774 @end example
16777 @item $((@var{expression}))
16778 @cindex @code{$((@var{expression}))}
16779 Arithmetic expansion is not portable as some shells (most
16780 notably Solaris 10 @command{/bin/sh}) don't support it.
16782 Among shells that do support @samp{$(( ))}, not all of them obey the
16783 Posix rule that octal and hexadecimal constants must be recognized:
16785 @example
16786 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
16788 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
16790 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
16792 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16793 pdksh:  010 + 0x10 : bad number `0x10'
16794 $ @kbd{pdksh -c 'echo $(( 010 ))'}
16796 @end example
16798 When it is available, using arithmetic expansion provides a noticeable
16799 speedup in script execution; but testing for support requires
16800 @command{eval} to avoid syntax errors.  The following construct is used
16801 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16802 arguments are provided in decimal and without a leading zero, and all
16803 operators are properly quoted and appear as distinct arguments:
16805 @example
16806 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16807   eval 'func_arith ()
16808   @{
16809     func_arith_result=$(( $* ))
16810   @}'
16811 else
16812   func_arith ()
16813   @{
16814     func_arith_result=`expr "$@@"`
16815   @}
16817 func_arith 1 + 1
16818 foo=$func_arith_result
16819 @end example
16822 @item ^
16823 @cindex @code{^} quoting
16824 Always quote @samp{^}, otherwise traditional shells such as
16825 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
16827 @end table
16830 @node Assignments
16831 @section Assignments
16832 @cindex Shell assignments
16834 When setting several variables in a row, be aware that the order of the
16835 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
16836 gives @samp{1} with Solaris 10 @command{/bin/sh}, but @samp{2} with Bash.
16837 You must use
16838 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
16840 Don't rely on the following to find @file{subdir/program}:
16842 @example
16843 PATH=subdir$PATH_SEPARATOR$PATH program
16844 @end example
16846 @noindent
16847 as this does not work with Zsh 3.0.6.  Use something like this
16848 instead:
16850 @example
16851 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
16852 @end example
16854 Don't rely on the exit status of an assignment: Ash 0.2 does not change
16855 the status and propagates that of the last statement:
16857 @example
16858 $ @kbd{false || foo=bar; echo $?}
16860 $ @kbd{false || foo=`:`; echo $?}
16862 @end example
16864 @noindent
16865 and to make things even worse, QNX 4.25 just sets the exit status
16866 to 0 in any case:
16868 @example
16869 $ @kbd{foo=`exit 1`; echo $?}
16871 @end example
16873 To assign default values, follow this algorithm:
16875 @enumerate
16876 @item
16877 If the default value is a literal and does not contain any closing
16878 brace, use:
16880 @example
16881 : "$@{var='my literal'@}"
16882 @end example
16884 @item
16885 If the default value contains no closing brace, has to be expanded, and
16886 the variable being initialized is not intended to be IFS-split
16887 (i.e., it's not a list), then use:
16889 @example
16890 : $@{var="$default"@}
16891 @end example
16893 @item
16894 If the default value contains no closing brace, has to be expanded, and
16895 the variable being initialized is intended to be IFS-split (i.e., it's a list),
16896 then use:
16898 @example
16899 var=$@{var="$default"@}
16900 @end example
16902 @item
16903 If the default value contains a closing brace, then use:
16905 @example
16906 test $@{var+y@} || var="has a '@}'"
16907 @end example
16908 @end enumerate
16910 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
16911 doubt, just use the last form.  @xref{Shell Substitutions}, items
16912 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
16913 for the rationale.
16915 @node Parentheses
16916 @section Parentheses in Shell Scripts
16917 @cindex Shell parentheses
16919 Beware of two opening parentheses in a row, as many shell
16920 implementations treat them specially, and Posix says that a portable
16921 script cannot use @samp{((} outside the @samp{$((} form used for shell
16922 arithmetic.  In traditional shells, @samp{((cat))} behaves like
16923 @samp{(cat)}; but many shells, including
16924 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
16925 expression equivalent to @samp{let "cat"}, and may or may not report an
16926 error when they detect that @samp{cat} is not a number.  As another
16927 example, @samp{pdksh} 5.2.14 does not treat the following code
16928 as a traditional shell would:
16930 @example
16931 if ((true) || false); then
16932   echo ok
16934 @end example
16936 @noindent
16937 To work around this problem, insert a space between the two opening
16938 parentheses.  There is a similar problem and workaround with
16939 @samp{$((}; see @ref{Shell Substitutions}.
16941 @node Slashes
16942 @section Slashes in Shell Scripts
16943 @cindex Shell slashes
16945 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
16946 arguments that contain two trailing slashes:
16948 @example
16949 $ @kbd{echo / // /// //// .// //.}
16950 / / // /// ./ //.
16951 $ @kbd{x=//}
16952 $ @kbd{eval "echo \$x"}
16954 $ @kbd{set -x}
16955 $ @kbd{echo abc | tr -t ab //}
16956 + echo abc
16957 + tr -t ab /
16959 @end example
16961 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
16962 variable is empty and the second double-quote is followed by a word that
16963 begins and ends with slash:
16965 @example
16966 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
16968 + echo //ouch/
16969 //ouch/
16970 @end example
16972 However, our understanding is that patches are available, so perhaps
16973 it's not worth worrying about working around these horrendous bugs.
16975 @node Special Shell Variables
16976 @section Special Shell Variables
16977 @cindex Shell variables
16978 @cindex Special shell variables
16980 Some shell variables should not be used, since they can have a deep
16981 influence on the behavior of the shell.  In order to recover a sane
16982 behavior from the shell, some variables should be unset; M4sh takes
16983 care of this and provides fallback values, whenever needed, to cater
16984 for a very old @file{/bin/sh} that does not support @command{unset}.
16985 (@pxref{Portable Shell, , Portable Shell Programming}).
16987 As a general rule, shell variable names containing a lower-case letter
16988 are safe; you can define and use these variables without worrying about
16989 their effect on the underlying system, and without worrying about
16990 whether the shell changes them unexpectedly.  (The exception is the
16991 shell variable @code{status}, as described below.)
16993 Here is a list of names that are known to cause trouble.  This list is
16994 not exhaustive, but you should be safe if you avoid the name
16995 @code{status} and names containing only upper-case letters and
16996 underscores.
16998 @c Alphabetical order, case insensitive, `A' before `a'.
16999 @table @code
17000 @item ?
17001 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
17002 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
17003 correctly in shell functions (@pxref{Shell Functions}) or in traps
17004 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
17005 @samp{$?} to zero after an empty command.
17007 @example
17008 $ @kbd{bash -c 'false; $empty; echo $?'}
17010 $ @kbd{zsh -c 'false; $empty; echo $?'}
17012 @end example
17014 @item _
17015 @evindex _
17016 Many shells reserve @samp{$_} for various purposes, e.g., the name of
17017 the last command executed.
17019 @item BIN_SH
17020 @evindex BIN_SH
17021 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
17022 the standard shell conform to Posix.
17024 @item CDPATH
17025 @evindex CDPATH
17026 When this variable is set it specifies a list of directories to search
17027 when invoking @code{cd} with a relative file name that did not start
17028 with @samp{./} or @samp{../}.  Posix
17029 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
17030 is used successfully, @code{cd} prints the resulting absolute
17031 file name.  Unfortunately this output can break idioms like
17032 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
17033 Also, many shells do not conform to this part of Posix; for
17034 example, @command{zsh} prints the result only if a directory name
17035 other than @file{.} was chosen from @env{CDPATH}.
17037 In practice the shells that have this problem also support
17038 @command{unset}, so you can work around the problem as follows:
17040 @example
17041 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
17042 @end example
17044 You can also avoid output by ensuring that your directory name is
17045 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
17047 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
17048 possible, so you need not worry about this problem in those scripts.
17050 @item CLICOLOR_FORCE
17051 @evindex CLICOLOR_FORCE
17052 When this variable is set, some implementations of tools like
17053 @command{ls} attempt to add color to their output via terminal escape
17054 sequences, even when the output is not directed to a terminal, and can
17055 thus cause spurious failures in scripts.  Configure scripts use M4sh,
17056 which automatically unsets this variable.
17058 @item DUALCASE
17059 @evindex DUALCASE
17060 In the MKS shell, case statements and file name generation are
17061 case-insensitive unless @env{DUALCASE} is nonzero.
17062 Autoconf-generated scripts export this variable when they start up.
17064 @item ENV
17065 @itemx MAIL
17066 @itemx MAILPATH
17067 @itemx PS1
17068 @itemx PS2
17069 @itemx PS4
17070 @evindex ENV
17071 @evindex MAIL
17072 @evindex MAILPATH
17073 @evindex PS1
17074 @evindex PS2
17075 @evindex PS4
17076 These variables should not matter for shell scripts, since they are
17077 supposed to affect only interactive shells.  However, at least one
17078 shell (the pre-3.0 UWIN Korn shell) gets confused about
17079 whether it is interactive, which means that (for example) a @env{PS1}
17080 with a side effect can unexpectedly modify @samp{$?}.  To work around
17081 this bug, M4sh scripts (including @file{configure} scripts) do something
17082 like this:
17084 @example
17085 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
17086 PS1='$ '
17087 PS2='> '
17088 PS4='+ '
17089 @end example
17091 @noindent
17092 (actually, there is some complication due to bugs in @command{unset};
17093 @pxref{unset, , Limitations of Shell Builtins}).
17095 @item FPATH
17096 @evindex FPATH
17097 The Korn shell uses @env{FPATH} to find shell functions, so avoid
17098 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
17099 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
17100 to find whether a command exists, since they might report the wrong
17101 result if @env{FPATH} is also set.
17103 @item GREP_OPTIONS
17104 @evindex GREP_OPTIONS
17105 When this variable is set, some implementations of @command{grep} honor
17106 these options, even if the options include direction to enable colored
17107 output via terminal escape sequences, and the result can cause spurious
17108 failures when the output is not directed to a terminal.  Configure
17109 scripts use M4sh, which automatically unsets this variable.
17111 @item IFS
17112 @evindex IFS
17113 Long ago, shell scripts inherited @env{IFS} from the environment,
17114 but this caused many problems so modern shells ignore any environment
17115 settings for @env{IFS}.
17117 Don't set the first character of @env{IFS} to backslash.  Indeed,
17118 Bourne shells use the first character (backslash) when joining the
17119 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
17120 backslash escapes, so you can end up with backspace and other strange
17121 characters.
17123 The proper value for @env{IFS} (in regular code, not when performing
17124 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
17125 especially important, as it is used to join the arguments in @samp{$*};
17126 however, note that traditional shells, but also bash-2.04, fail to adhere
17127 to this and join with a space anyway.
17129 M4sh guarantees that @env{IFS} will have the default value at the
17130 beginning of a script, and many macros within autoconf rely on this
17131 setting.  It is okay to use blocks of shell code that temporarily change
17132 the value of @env{IFS} in order to split on another character, but
17133 remember to restore it before expanding further macros.
17135 Unsetting @code{IFS} instead of resetting it to the default sequence
17136 is not suggested, since code that tries to save and restore the
17137 variable's value will incorrectly reset it to an empty value, thus
17138 disabling field splitting:
17140 @example
17141 unset IFS
17142 # default separators used for field splitting
17144 save_IFS=$IFS
17145 IFS=:
17146 # ...
17147 IFS=$save_IFS
17148 # no field splitting performed
17149 @end example
17151 @item LANG
17152 @itemx LC_ALL
17153 @itemx LC_COLLATE
17154 @itemx LC_CTYPE
17155 @itemx LC_MESSAGES
17156 @itemx LC_MONETARY
17157 @itemx LC_NUMERIC
17158 @itemx LC_TIME
17159 @evindex LANG
17160 @evindex LC_ALL
17161 @evindex LC_COLLATE
17162 @evindex LC_CTYPE
17163 @evindex LC_MESSAGES
17164 @evindex LC_MONETARY
17165 @evindex LC_NUMERIC
17166 @evindex LC_TIME
17168 You should set all these variables to @samp{C} because so much
17169 configuration code assumes the C locale and Posix requires that locale
17170 environment variables be set to @samp{C} if the C locale is desired;
17171 @file{configure} scripts and M4sh do that for you.
17172 Export these variables after setting them.
17174 @c  However, some older, nonstandard
17175 @c  systems (notably SCO) break if locale environment variables
17176 @c  are set to @samp{C}, so when running on these systems
17177 @c  Autoconf-generated scripts unset the variables instead.
17179 @item LANGUAGE
17180 @evindex LANGUAGE
17182 @env{LANGUAGE} is not specified by Posix, but it is a GNU
17183 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
17184 should set it too.
17186 @item LC_ADDRESS
17187 @itemx LC_IDENTIFICATION
17188 @itemx LC_MEASUREMENT
17189 @itemx LC_NAME
17190 @itemx LC_PAPER
17191 @itemx LC_TELEPHONE
17192 @evindex LC_ADDRESS
17193 @evindex LC_IDENTIFICATION
17194 @evindex LC_MEASUREMENT
17195 @evindex LC_NAME
17196 @evindex LC_PAPER
17197 @evindex LC_TELEPHONE
17199 These locale environment variables are GNU extensions.  They
17200 are treated like their Posix brethren (@env{LC_COLLATE},
17201 etc.)@: as described above.
17203 @item LINENO
17204 @evindex LINENO
17205 Most modern shells provide the current line number in @code{LINENO}.
17206 Its value is the line number of the beginning of the current command.
17207 M4sh, and hence Autoconf, attempts to execute @command{configure} with
17208 a shell that supports @code{LINENO}.  If no such shell is available, it
17209 attempts to implement @code{LINENO} with a Sed prepass that replaces each
17210 instance of the string @code{$LINENO} (not followed by an alphanumeric
17211 character) with the line's number.  In M4sh scripts you should execute
17212 @code{AS_LINENO_PREPARE} so that these workarounds are included in
17213 your script; configure scripts do this automatically in @code{AC_INIT}.
17215 You should not rely on @code{LINENO} within @command{eval} or shell
17216 functions, as the behavior differs in practice.  The presence of a
17217 quoted newline within simple commands can alter which line number is
17218 used as the starting point for @code{$LINENO} substitutions within that
17219 command.  Also, the possibility of the Sed prepass means that you should
17220 not rely on @code{$LINENO} when quoted, when in here-documents, or when
17221 line continuations are used.  Subshells should be OK, though.  In the
17222 following example, lines 1, 9, and 14 are portable, but the other
17223 instances of @code{$LINENO} do not have deterministic values:
17225 @example
17226 @group
17227 $ @kbd{cat lineno}
17228 echo 1. $LINENO
17229 echo "2. $LINENO
17230 3. $LINENO"
17231 cat <<EOF
17232 5. $LINENO
17233 6. $LINENO
17234 7. \$LINENO
17236 ( echo 9. $LINENO )
17237 eval 'echo 10. $LINENO'
17238 eval 'echo 11. $LINENO
17239 echo 12. $LINENO'
17240 echo 13. '$LINENO'
17241 echo 14. $LINENO '
17242 15.' $LINENO
17243 f () @{ echo $1 $LINENO;
17244 echo $1 $LINENO @}
17245 f 18.
17246 echo 19. \
17247 $LINENO
17248 @end group
17249 @group
17250 $ @kbd{bash-3.2 ./lineno}
17251 1. 1
17252 2. 3
17253 3. 3
17254 5. 4
17255 6. 4
17256 7. $LINENO
17257 9. 9
17258 10. 10
17259 11. 12
17260 12. 13
17261 13. $LINENO
17262 14. 14
17263 15. 14
17264 18. 16
17265 18. 17
17266 19. 19
17267 @end group
17268 @group
17269 $ @kbd{zsh-4.3.4 ./lineno}
17270 1. 1
17271 2. 2
17272 3. 2
17273 5. 4
17274 6. 4
17275 7. $LINENO
17276 9. 9
17277 10. 1
17278 11. 1
17279 12. 2
17280 13. $LINENO
17281 14. 14
17282 15. 14
17283 18. 0
17284 18. 1
17285 19. 19
17286 @end group
17287 @group
17288 $ @kbd{pdksh-5.2.14 ./lineno}
17289 1. 1
17290 2. 2
17291 3. 2
17292 5. 4
17293 6. 4
17294 7. $LINENO
17295 9. 9
17296 10. 0
17297 11. 0
17298 12. 0
17299 13. $LINENO
17300 14. 14
17301 15. 14
17302 18. 16
17303 18. 17
17304 19. 19
17305 @end group
17306 @group
17307 $ @kbd{sed '=' <lineno |}
17308 > @kbd{  sed '}
17309 > @kbd{    N}
17310 > @kbd{    s,$,-,}
17311 > @kbd{    t loop}
17312 > @kbd{    :loop}
17313 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
17314 > @kbd{    t loop}
17315 > @kbd{    s,-$,,}
17316 > @kbd{    s,^[0-9]*\n,,}
17317 > @kbd{  ' |}
17318 > @kbd{  sh}
17319 1. 1
17320 2. 2
17321 3. 3
17322 5. 5
17323 6. 6
17324 7. \7
17325 9. 9
17326 10. 10
17327 11. 11
17328 12. 12
17329 13. 13
17330 14. 14
17331 15. 15
17332 18. 16
17333 18. 17
17334 19. 20
17335 @end group
17336 @end example
17338 In particular, note that @file{config.status} (and any other subsidiary
17339 script created by @code{AS_INIT_GENERATED}) might report line numbers
17340 relative to the parent script as a result of the potential Sed pass.
17342 @item NULLCMD
17343 @evindex NULLCMD
17344 When executing the command @samp{>foo}, @command{zsh} executes
17345 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
17346 compatibility mode and the @command{zsh} version is newer
17347 than 3.1.6-dev-18.  If you are using an older @command{zsh}
17348 and forget to set @env{NULLCMD},
17349 your script might be suspended waiting for data on its standard input.
17351 @item options
17352 @evindex options
17353 For @command{zsh} 4.3.10, @env{options} is treated as an associative
17354 array even after @code{emulate sh}, so it should not be used.
17356 @item PATH_SEPARATOR
17357 @evindex PATH_SEPARATOR
17358 On DJGPP systems, the @env{PATH_SEPARATOR} environment
17359 variable can be set to either @samp{:} or @samp{;} to control the path
17360 separator Bash uses to set up certain environment variables (such as
17361 @env{PATH}).  You can set this variable to @samp{;} if you want
17362 @command{configure} to use @samp{;} as a separator; this might be useful
17363 if you plan to use non-Posix shells to execute files.  @xref{File System
17364 Conventions}, for more information about @code{PATH_SEPARATOR}.
17366 @item POSIXLY_CORRECT
17367 @evindex POSIXLY_CORRECT
17368 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
17369 (even empty) causes programs to try harder to conform to Posix.
17370 Autoconf does not directly manipulate this variable, but @command{bash}
17371 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
17372 running in Posix mode.  Therefore, take care when exporting or unsetting
17373 this variable, so as not to change whether @command{bash} is in Posix
17374 mode.
17376 @example
17377 $ @kbd{bash --posix -c 'set -o | grep posix}
17378 > @kbd{unset POSIXLY_CORRECT}
17379 > @kbd{set -o | grep posix'}
17380 posix           on
17381 posix           off
17382 @end example
17384 @item PWD
17385 @evindex PWD
17386 Posix 1003.1-2001 requires that @command{cd} and
17387 @command{pwd} must update the @env{PWD} environment variable to point
17388 to the logical name of the current directory, but traditional shells
17389 do not support this.  This can cause confusion if one shell instance
17390 maintains @env{PWD} but a subsidiary and different shell does not know
17391 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
17392 points to the wrong directory.  Use @samp{`pwd`} rather than
17393 @samp{$PWD}.
17395 @item RANDOM
17396 @evindex RANDOM
17397 Many shells provide @code{RANDOM}, a variable that returns a different
17398 integer each time it is used.  Most of the time, its value does not
17399 change when it is not used, but on IRIX 6.5 the value changes all
17400 the time.  This can be observed by using @command{set}.  It is common
17401 practice to use @code{$RANDOM} as part of a file name, but code
17402 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
17404 @item status
17405 @evindex status
17406 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
17407 hence read-only.  Do not use it.
17408 @end table
17410 @node Shell Functions
17411 @section Shell Functions
17412 @cindex Shell Functions
17414 Nowadays, it is difficult to find a shell that does not support
17415 shell functions at all.  However, some differences should be expected.
17417 When declaring a shell function, you must include whitespace between the
17418 @samp{)} after the function name and the start of the compound
17419 expression, to avoid upsetting @command{ksh}.  While it is possible to
17420 use any compound command, most scripts use @samp{@{@dots{}@}}.
17422 @example
17423 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
17425 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
17426 ksh: syntax error at line 1: `@}' unexpected
17427 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
17429 @end example
17431 Inside a shell function, you should not rely on the error status of a
17432 subshell if the last command of that subshell was @code{exit} or
17433 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
17434 find a shell that does not exhibit the bug, zsh might be the only shell
17435 present on the user's machine.
17437 Likewise, the state of @samp{$?} is not reliable when entering a shell
17438 function.  This has the effect that using a function as the first
17439 command in a @command{trap} handler can cause problems.
17441 @example
17442 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17445 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17448 @end example
17450 DJGPP bash 2.04 has a bug in that @command{return} from a
17451 shell function which also used a command substitution causes a
17452 segmentation fault.  To work around the issue, you can use
17453 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
17454 in the execution flow of the function (@pxref{Common Shell Constructs}).
17456 Not all shells treat shell functions as simple commands impacted by
17457 @samp{set -e}, for example with Solaris 10 @command{/bin/sh}:
17459 @example
17460 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17461 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17462 oops
17463 @end example
17465 Shell variables and functions may share the same namespace, for example
17466 with Solaris 10 @command{/bin/sh}:
17468 @example
17469 $ @kbd{f () @{ :; @}; f=; f}
17470 f: not found
17471 @end example
17473 @noindent
17474 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
17475 uses the prefix @samp{as_fn_} for its functions.
17477 Handling of positional parameters and shell options varies among shells.
17478 For example, Korn shells reset and restore trace output (@samp{set -x})
17479 and other options upon function entry and exit.  Inside a function,
17480 IRIX sh sets @samp{$0} to the function name.
17482 It is not portable to pass temporary environment variables to shell
17483 functions.  Solaris 10 @command{/bin/sh} does not see the variable.
17484 Meanwhile, not all shells follow the Posix rule that the assignment must
17485 affect the current environment in the same manner as special built-ins.
17487 @example
17488 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17489 @result{}
17490 @result{}
17491 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17492 @result{}1
17493 @result{}
17494 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
17495 @result{}1
17496 @result{}1
17497 @end example
17499 Some ancient Bourne shell variants with function support did not reset
17500 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
17501 arguments of the script were lost after the first function invocation.
17502 It is probably not worth worrying about these shells any more.
17504 With AIX sh, a @command{trap} on 0 installed in a shell function
17505 triggers at function exit rather than at script exit.  @xref{trap, ,
17506 Limitations of Shell Builtins}.
17508 @node Limitations of Builtins
17509 @section Limitations of Shell Builtins
17510 @cindex Shell builtins
17511 @cindex Limitations of shell builtins
17513 No, no, we are serious: some shells do have limitations!  :)
17515 You should always keep in mind that any builtin or command may support
17516 options, and therefore differ in behavior with arguments
17517 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
17518 can give unexpected results when @code{word} starts with a dash.  It is
17519 often possible to avoid this problem using @samp{echo "x$word"}, taking
17520 the @samp{x} into account later in the pipe.  Many of these limitations
17521 can be worked around using M4sh (@pxref{Programming in M4sh}).
17523 @c This table includes things like `@command{test} (files)', so we can't
17524 @c use @table @command.
17525 @table @asis
17526 @item @command{.}
17527 @c --------------
17528 @prindex @command{.}
17529 Use @command{.} only with regular files (use @samp{test -f}).  Bash
17530 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
17531 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
17532 some shells, including bash 3.2, implicitly append the current directory
17533 to this @env{PATH} search, even though Posix forbids it.  So if you want
17534 to use @command{.} on a file @file{foo} in the current directory, you
17535 must use @samp{. ./foo}.
17537 Not all shells gracefully handle syntax errors within a sourced file.
17538 On one extreme, some non-interactive shells abort the entire script.  On
17539 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17540 syntax error.
17542 @example
17543 $ @kbd{echo 'fi' > syntax}
17544 $ @kbd{bash -c '. ./syntax; echo $?'}
17545 ./syntax: line 1: syntax error near unexpected token `fi'
17546 ./syntax: line 1: `fi'
17548 $ @kbd{ash -c '. ./syntax; echo $?'}
17549 ./syntax: 1: Syntax error: "fi" unexpected
17550 $ @kbd{zsh -c '. ./syntax; echo $?'}
17551 ./syntax:1: parse error near `fi'
17553 @end example
17555 @item @command{!}
17556 @c --------------
17557 @prindex @command{!}
17558 The Unix version 7 shell did not support
17559 negating the exit status of commands with @command{!}, and this feature
17560 is still absent from some shells (e.g., Solaris 10 @command{/bin/sh}).
17561 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17562 bugs when using @command{!}:
17564 @example
17565 $ @kbd{sh -c '! : | :'; echo $?}
17567 $ @kbd{ash -c '! : | :'; echo $?}
17569 $ @kbd{sh -c '! @{ :; @}'; echo $?}
17571 $ @kbd{ash -c '! @{ :; @}'; echo $?}
17572 @{: not found
17573 Syntax error: "@}" unexpected
17575 @end example
17577 Shell code like this:
17579 @example
17580 if ! cmp file1 file2 >/dev/null 2>&1; then
17581   echo files differ or trouble
17583 @end example
17585 is therefore not portable in practice.  Typically it is easy to rewrite
17586 such code, e.g.:
17588 @example
17589 cmp file1 file2 >/dev/null 2>&1 ||
17590   echo files differ or trouble
17591 @end example
17593 More generally, one can always rewrite @samp{! @var{command}} as:
17595 @example
17596 if @var{command}; then (exit 1); else :; fi
17597 @end example
17600 @item @command{@{...@}}
17601 @c --------------------
17602 @prindex @command{@{...@}}
17603 Bash 3.2 (and earlier versions) sometimes does not properly set
17604 @samp{$?} when failing to write redirected output of a compound command.
17605 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17606 not occur with @samp{(@dots{})}.  For example:
17608 @example
17609 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17610 bash: line 1: /bad: Permission denied
17612 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17613 bash: line 1: /bad: Permission denied
17615 @end example
17617 To work around the bug, prepend @samp{:;}:
17619 @example
17620 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17621 bash: line 1: /bad: Permission denied
17623 @end example
17625 Posix requires a syntax error if a brace list has no contents.  However,
17626 not all shells obey this rule; and on shells where empty lists are
17627 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
17628 ensure that a brace list is never empty.
17630 @example
17631 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17632 bash: line 1: syntax error near unexpected token `@}'
17633 bash: line 1: `false; @{ @}; echo $?'
17635 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
17637 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
17639 @end example
17642 @item @command{break}
17643 @c ------------------
17644 @prindex @command{break}
17645 The use of @samp{break 2} etc.@: is safe.
17648 @anchor{case}
17649 @item @command{case}
17650 @c -----------------
17651 @prindex @command{case}
17652 You don't need to quote the argument; no splitting is performed.
17654 You don't need the final @samp{;;}, but you should use it.
17656 Posix requires support for @code{case} patterns with opening
17657 parentheses like this:
17659 @example
17660 case $file_name in
17661   (*.c) echo "C source code";;
17662 esac
17663 @end example
17665 @noindent
17666 but the @code{(} in this example is not portable to a few obsolescent Bourne
17667 shell implementations, which is a pity for those of us using tools that
17668 rely on balanced parentheses.  For instance, with Solaris 10
17669 @command{/bin/sh}:
17671 @example
17672 $ @kbd{case foo in (foo) echo foo;; esac}
17673 @error{}syntax error: `(' unexpected
17674 @end example
17676 @noindent
17677 The leading @samp{(} can be omitted safely.  Unfortunately, there are
17678 contexts where unbalanced parentheses cause other problems, such as when
17679 using a syntax-highlighting editor that searches for the balancing
17680 counterpart, or more importantly, when using a case statement as an
17681 underquoted argument to an Autoconf macro.  @xref{Balancing
17682 Parentheses}, for trade-offs involved in various styles of dealing with
17683 unbalanced @samp{)}.
17685 Zsh handles pattern fragments derived from parameter expansions or
17686 command substitutions as though quoted:
17688 @example
17689 $ pat=\?; case aa in ?$pat) echo match;; esac
17690 $ pat=\?; case a? in ?$pat) echo match;; esac
17691 match
17692 @end example
17694 @noindent
17695 Because of a bug in its @code{fnmatch}, Bash fails to properly
17696 handle backslashes in character classes:
17698 @example
17699 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17700 bash-2.02$
17701 @end example
17703 @noindent
17704 This is extremely unfortunate, since you are likely to use this code to
17705 handle Posix or MS-DOS absolute file names.  To work around this
17706 bug, always put the backslash first:
17708 @example
17709 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17711 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17713 @end example
17715 Many Bourne shells cannot handle closing brackets in character classes
17716 correctly.
17718 Some shells also have problems with backslash escaping in case you do not want
17719 to match the backslash: both a backslash and the escaped character match this
17720 pattern.  To work around this, specify the character class in a variable, so
17721 that quote removal does not apply afterwards, and the special characters don't
17722 have to be backslash-escaped:
17724 @example
17725 $ @kbd{case '\' in [\<]) echo OK;; esac}
17727 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17729 @end example
17731 Even with this, Solaris @command{ksh} matches a backslash if the set
17732 contains any
17733 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17735 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
17736 a closing parenthesis if not specified in a character class:
17738 @example
17739 $ @kbd{case foo in *\)*) echo fail ;; esac}
17740 fail
17741 $ @kbd{case foo in *')'*) echo fail ;; esac}
17742 fail
17743 @end example
17745 Some shells, such as Ash 0.3.8, are confused by an empty
17746 @code{case}/@code{esac}:
17748 @example
17749 ash-0.3.8 $ @kbd{case foo in esac;}
17750 @error{}Syntax error: ";" unexpected (expecting ")")
17751 @end example
17753 Posix requires @command{case} to give an exit status of 0 if no cases
17754 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
17755 rule.  Meanwhile, it is unclear whether a case that matches, but
17756 contains no statements, must also change the exit status to 0.  The M4sh
17757 macro @code{AS_CASE} works around these inconsistencies.
17759 @example
17760 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
17762 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17764 @end example
17767 @item @command{cd}
17768 @c ---------------
17769 @prindex @command{cd}
17770 Posix 1003.1-2001 requires that @command{cd} must support
17771 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17772 with @option{-L} being the default.  However, traditional shells do
17773 not support these options, and their @command{cd} command has the
17774 @option{-P} behavior.
17776 Portable scripts should assume neither option is supported, and should
17777 assume neither behavior is the default.  This can be a bit tricky,
17778 since the Posix default behavior means that, for example,
17779 @samp{ls ..} and @samp{cd ..} may refer to different directories if
17780 the current logical directory is a symbolic link.  It is safe to use
17781 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17782 Also, Autoconf-generated scripts check for this problem when computing
17783 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17784 so it is safe to @command{cd} to these variables.
17786 Posix states that behavior is undefined if @command{cd} is given an
17787 explicit empty argument.  Some shells do nothing, some change to the
17788 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
17789 the shell rather than returning an error.  Unfortunately, this means
17790 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
17791 than @samp{cd $var} (at least the latter is well-behaved in all shells
17792 at changing to @env{HOME}, although this is probably not what you wanted
17793 in a script).  You should check that a directory name was supplied
17794 before trying to change locations.
17796 @xref{Special Shell Variables}, for portability problems involving
17797 @command{cd} and the @env{CDPATH} environment variable.
17798 Also please see the discussion of the @command{pwd} command.
17801 @anchor{echo}
17802 @item @command{echo}
17803 @c -----------------
17804 @prindex @command{echo}
17805 The simple @command{echo} is probably the most surprising source of
17806 portability troubles.  It is not possible to use @samp{echo} portably
17807 unless both options and escape sequences are omitted.  Don't expect any
17808 option.
17810 Do not use backslashes in the arguments, as there is no consensus on
17811 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
17812 Solaris 10 outputs 2,
17813 but Bash and Zsh (in @command{sh} emulation mode) output 1.
17814 The problem is truly @command{echo}: all the shells
17815 understand @samp{'\n'} as the string composed of a backslash and an
17816 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
17817 mess up the internal state of ksh88 on AIX 6.1 so that it will print
17818 the first character @samp{s} only, followed by a newline, and then
17819 entirely drop the output of the next echo in a command substitution.
17821 Because of these problems, do not pass a string containing arbitrary
17822 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
17823 only if you know that @var{foo}'s value cannot contain backslashes and
17824 cannot start with @samp{-}.
17826 Normally, @command{printf} is safer and easier to use than @command{echo}
17827 and @command{echo -n}.  Thus, you should use @command{printf "%s\n"}
17828 instead of @command{echo}, and similarly use @command{printf %s} instead
17829 of @command{echo -n}.
17831 Older scripts, written before @command{printf} was portable,
17832 sometimes used a here-document as a safer alternative to @command{echo},
17833 like this:
17835 @example
17836 cat <<EOF
17837 $foo
17839 @end example
17842 @item @command{eval}
17843 @c -----------------
17844 @prindex @command{eval}
17845 The @command{eval} command is useful in limited circumstances, e.g.,
17846 using commands like @samp{eval table_$key=\$value} and @samp{eval
17847 value=table_$key} to simulate a hash table when the key is known to be
17848 alphanumeric.
17850 You should also be wary of common bugs in @command{eval} implementations.
17851 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
17852 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
17853 4.2.5), the arguments of @samp{eval} are evaluated in a context where
17854 @samp{$?} is 0, so they exhibit behavior like this:
17856 @example
17857 $ @kbd{false; eval 'echo $?'}
17859 @end example
17861 The correct behavior here is to output a nonzero value,
17862 but portable scripts should not rely on this.
17864 You should not rely on @code{LINENO} within @command{eval}.
17865 @xref{Special Shell Variables}.
17867 Note that, even though these bugs are easily avoided,
17868 @command{eval} is tricky to use on arbitrary arguments.
17869 It is obviously unwise to use @samp{eval $cmd} if the string value of
17870 @samp{cmd} was derived from an untrustworthy source.  But even if the
17871 string value is valid, @samp{eval $cmd} might not work as intended,
17872 since it causes field splitting and file name expansion to occur twice,
17873 once for the @command{eval} and once for the command itself.  It is
17874 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
17875 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
17876 equivalent of @samp{cat test;.c} if there happens to be a file named
17877 @file{test;.c} in the current directory; and this in turn
17878 mistakenly attempts to invoke @command{cat} on the file @file{test} and
17879 then execute the command @command{.c}.  To avoid this problem, use
17880 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
17882 However, suppose that you want to output the text of the evaluated
17883 command just before executing it.  Assuming the previous example,
17884 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
17885 this output doesn't show the user that @samp{test;.c} is the actual name
17886 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
17887 works on this example, but it fails with @samp{cmd='cat foo >bar'},
17888 since it mistakenly replaces the contents of @file{bar} by the
17889 string @samp{cat foo}.  No simple, general, and portable solution to
17890 this problem is known.
17892 @item @command{exec}
17893 @c -----------------
17894 @prindex @command{exec}
17895 Posix describes several categories of shell built-ins.  Special
17896 built-ins (such as @command{exit}) must impact the environment of the
17897 current shell, and need not be available through @command{exec}.  All
17898 other built-ins are regular, and must not propagate variable assignments
17899 to the environment of the current shell.  However, the group of regular
17900 built-ins is further distinguished by commands that do not require a
17901 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
17902 are offered as a more efficient version of something that must still be
17903 found in a @env{PATH} search (such as @command{echo}).  Posix is not
17904 clear on whether @command{exec} must work with the list of 17 utilities
17905 that are invoked without a @env{PATH} search, and many platforms lack an
17906 executable for some of those built-ins:
17908 @example
17909 $ @kbd{sh -c 'exec cd /tmp'}
17910 sh: line 0: exec: cd: not found
17911 @end example
17913 All other built-ins that provide utilities specified by Posix must have
17914 a counterpart executable that exists on @env{PATH}, although Posix
17915 allows @command{exec} to use the built-in instead of the executable.
17916 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
17918 @example
17919 $ @kbd{bash -c 'pwd --version' | head -n1}
17920 bash: line 0: pwd: --: invalid option
17921 pwd: usage: pwd [-LP]
17922 $ @kbd{bash -c 'exec pwd --version' | head -n1}
17923 pwd (GNU coreutils) 6.10
17924 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
17925 pdksh: pwd: --: unknown option
17926 @end example
17928 When it is desired to avoid a regular shell built-in, the workaround is
17929 to use some other forwarding command, such as @command{env} or
17930 @command{nice}, that will ensure a path search:
17932 @example
17933 $ @kbd{pdksh -c 'exec true --version' | head -n1}
17934 $ @kbd{pdksh -c 'nice true --version' | head -n1}
17935 true (GNU coreutils) 6.10
17936 $ @kbd{pdksh -c 'env true --version' | head -n1}
17937 true (GNU coreutils) 6.10
17938 @end example
17940 @item @command{exit}
17941 @c -----------------
17942 @prindex @command{exit}
17943 The default value of @command{exit} is supposed to be @code{$?};
17944 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17945 perform @samp{exit 0}.
17947 @example
17948 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17949 fail
17950 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17951 fail
17952 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17953 bash-2.04$
17954 @end example
17956 Using @samp{exit $?} restores the expected behavior.
17958 Some shell scripts, such as those generated by @command{autoconf}, use a
17959 trap to clean up before exiting.  If the last shell command exited with
17960 nonzero status, the trap also exits with nonzero status so that the
17961 invoker can tell that an error occurred.
17963 Unfortunately, in some shells, such as Solaris 10 @command{/bin/sh}, an exit
17964 trap ignores the @code{exit} command's argument.  In these shells, a trap
17965 cannot determine whether it was invoked by plain @code{exit} or by
17966 @code{exit 1}.  Instead of calling @code{exit} directly, use the
17967 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
17970 @anchor{export}
17971 @item @command{export}
17972 @c -------------------
17973 @prindex @command{export}
17974 The builtin @command{export} dubs a shell variable @dfn{environment
17975 variable}.  Each update of exported variables corresponds to an update
17976 of the environment variables.  Conversely, each environment variable
17977 received by the shell when it is launched should be imported as a shell
17978 variable marked as exported.
17980 Alas, many shells, such as Solaris 10 @command{/bin/sh},
17981 IRIX 6.3, IRIX 5.2,
17982 AIX 4.1.5, and Digital Unix 4.0, forget to
17983 @command{export} the environment variables they receive.  As a result,
17984 two variables coexist: the environment variable and the shell
17985 variable.  The following code demonstrates this failure:
17987 @example
17988 #!/bin/sh
17989 echo $FOO
17990 FOO=bar
17991 echo $FOO
17992 exec /bin/sh $0
17993 @end example
17995 @noindent
17996 when run with @samp{FOO=foo} in the environment, these shells print
17997 alternately @samp{foo} and @samp{bar}, although they should print only
17998 @samp{foo} and then a sequence of @samp{bar}s.
18000 Therefore you should @command{export} again each environment variable
18001 that you update; the export can occur before or after the assignment.
18003 Posix is not clear on whether the @command{export} of an undefined
18004 variable causes the variable to be defined with the value of an empty
18005 string, or merely marks any future definition of a variable by that name
18006 for export.  Various shells behave differently in this regard:
18008 @example
18009 $ @kbd{sh -c 'export foo; env | grep foo'}
18010 $ @kbd{ash -c 'export foo; env | grep foo'}
18011 foo=
18012 @end example
18014 Posix requires @command{export} to honor assignments made as arguments,
18015 but older shells do not support this, including @command{/bin/sh} in
18016 Solaris 10.  Portable scripts should separate assignments and exports
18017 into different statements.
18019 @example
18020 $ @kbd{bash -c 'export foo=bar; echo $foo'}
18022 $ @kbd{/bin/sh -c 'export foo=bar; echo $foo'}
18023 /bin/sh: foo=bar: is not an identifier
18024 $ @kbd{/bin/sh -c 'export foo; foo=bar; echo $foo'}
18026 @end example
18028 Posix requires @command{export} to work with any arbitrary value for the
18029 contents of the variable being exported, as long as the total size of
18030 the environment combined with arguments doesn't exceed @code{ARG_MAX}
18031 when executing a child process.  However, some shells have extensions
18032 that involve interpreting some environment values specially, regardless
18033 of the variable name.  We currently know of one case: all versions of
18034 Bash released prior to 27 September 2014 interpret an environment
18035 variable with an initial content substring of @code{() @{} as an
18036 exported function definition (this is the ``Shellshock'' remote
18037 execution bug, CVE-2014-6271 and friends, where it was possible to
18038 exploit the function parser to cause remote code execution on child bash
18039 startup; newer versions of Bash use special environment variable
18040 @emph{names} instead of values to implement the same feature).
18042 There may be entries inherited into the environment that are not valid
18043 as shell variable names; Posix states that processes should be tolerant
18044 of these names.  Some shells such as @command{dash} do this by removing
18045 those names from the environment at startup, while others such as
18046 @command{bash} hide the entry from shell access but still pass it on to
18047 child processes.  While you can set such names using @command{env} for a
18048 direct child process, you cannot rely on them being preserved through an
18049 intermediate pass through the shell.
18051 @item @command{false}
18052 @c ------------------
18053 @prindex @command{false}
18054 Don't expect @command{false} to exit with status 1: in native
18055 Solaris @file{/bin/false} exits with status 255.
18058 @item @command{for}
18059 @c ----------------
18060 @prindex @command{for}
18061 To loop over positional arguments, use:
18063 @example
18064 for arg
18066   echo "$arg"
18067 done
18068 @end example
18070 @noindent
18071 You may @emph{not} leave the @code{do} on the same line as @code{for},
18072 since some shells improperly grok:
18074 @example
18075 for arg; do
18076   echo "$arg"
18077 done
18078 @end example
18080 If you want to explicitly refer to the positional arguments, given the
18081 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
18083 @example
18084 for arg in $@{1+"$@@"@}; do
18085   echo "$arg"
18086 done
18087 @end example
18089 @noindent
18090 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
18091 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
18092 item @samp{$@@}, for more.
18094 Posix requires support for a @command{for} loop with no list after
18095 @code{in}.  However, Solaris 10 @command{/bin/sh} treats that as a syntax
18096 error.  It is possible to work around this by providing any shell word
18097 that expands to nothing, or by ignoring an obvious sentinel.
18099 @example
18100 $ @kbd{/bin/sh -c 'for a in $empty; do echo hi; done'}
18101 $ @kbd{/bin/sh -c 'for a in ; do echo hi; done'}
18102 /bin/sh: syntax error at line 1: `;' unexpected
18103 @end example
18105 This syntax problem is most frequently encountered in code that goes
18106 through several layers of expansion, such as an m4 macro or makefile
18107 variable used as a list body, where the first layer of expansion (m4 or
18108 make) can end up expanding to nothing in the version handed to the
18109 shell.  In the makefile context, one common workaround is to use a shell
18110 variable rather than a make variable as the source of the list.
18112 @example
18113 $ @kbd{cat Makefile}
18114 list =
18115 bad:
18116         @@for arg in $(list); do echo $$arg; done
18117 good:
18118         @@list='$(list)'; for arg in $$list; do echo $$arg; done
18119 $ @kbd{make bad 2&>1 | head -n1}
18120 sh: syntax error at line 1: `;' unexpected
18121 $ @kbd{make bad list='a b'}
18124 $ @kbd{make good}
18125 $ @kbd{make good list='a b'}
18128 @end example
18130 In Solaris 10 @command{/bin/sh}, when the list of arguments of a
18131 @command{for} loop starts with @emph{unquoted} tokens looking like
18132 variable assignments, the loop is not executed on those tokens:
18134 @example
18135 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
18138 @end example
18140 @noindent
18141 Thankfully, quoting the assignment-like tokens, or starting the list
18142 with other tokens (including unquoted variable expansion that results in
18143 an assignment-like result), avoids the problem, so it is easy to work
18144 around:
18146 @example
18147 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
18149 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
18152 @end example
18154 @anchor{if}
18155 @item @command{if}
18156 @c ---------------
18157 @prindex @command{if}
18158 Using @samp{!} is not portable.  Instead of:
18160 @example
18161 if ! cmp -s file file.new; then
18162   mv file.new file
18164 @end example
18166 @noindent
18167 use:
18169 @example
18170 if cmp -s file file.new; then :; else
18171   mv file.new file
18173 @end example
18175 @noindent
18176 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
18177 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
18178 of conditionals:
18180 @example
18181 AS_IF([cmp -s file file.new], [], [mv file.new file])
18182 @end example
18184 This is especially useful in other M4 macros, where the @dfn{then} and
18185 @dfn{else} branches might be macro arguments.
18187 Some very old shells did not reset the exit status from an @command{if}
18188 with no @command{else}:
18190 @example
18191 $ @kbd{if (exit 42); then true; fi; echo $?}
18193 @end example
18195 @noindent
18196 whereas a proper shell should have printed @samp{0}.  But this is no
18197 longer a portability problem; any shell that supports functions gets it
18198 correct.  However, it explains why some makefiles have lengthy
18199 constructs:
18201 @example
18202 if test -f "$file"; then
18203   install "$file" "$dest"
18204 else
18205   :
18207 @end example
18210 @item @command{printf}
18211 @c ------------------
18212 @prindex @command{printf}
18213 A format string starting with a @samp{-} can cause problems.
18214 Bash interprets it as an option and
18215 gives an error.  And @samp{--} to mark the end of options is not good
18216 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
18217 literally as the format string.  Putting the @samp{-} in a @samp{%c}
18218 or @samp{%s} is probably easiest:
18220 @example
18221 printf %s -foo
18222 @end example
18224 AIX 7.2 @command{sh} mishandles octal escapes in multi-byte locales by
18225 treating them as characters instead of bytes.  For example, in a locale
18226 using the UTF-8 encoding, @samp{printf '\351'} outputs the two bytes C3,
18227 A9 (the UTF-8 encoding for U+00E9) instead of the desired single byte E9.
18228 To work around the bug, use the C locale.
18230 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
18232 @example
18233 $ @kbd{printf '\045'}
18234 bash: printf: `%': missing format character
18235 @end example
18237 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
18238 example, @file{/usr/bin/printf} is buggy, so when using
18239 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
18240 core.
18242 Since @command{printf} is not always a shell builtin, there is a
18243 potential speed penalty for using @code{printf '%s\n'} as a replacement
18244 for an @command{echo} that does not interpret @samp{\} or leading
18245 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
18246 -r --} for this role instead.
18248 @xref{echo, , Limitations of Shell Builtins}, for a discussion of
18249 portable alternatives to both @command{printf} and @command{echo}.
18252 @item @command{pwd}
18253 @c ----------------
18254 @prindex @command{pwd}
18255 With modern shells, plain @command{pwd} outputs a ``logical''
18256 directory name, some of whose components may be symbolic links.  These
18257 directory names are in contrast to ``physical'' directory names, whose
18258 components are all directories.
18260 Posix 1003.1-2001 requires that @command{pwd} must support
18261 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
18262 with @option{-L} being the default.  However, traditional shells do
18263 not support these options, and their @command{pwd} command has the
18264 @option{-P} behavior.
18266 Portable scripts should assume neither option is supported, and should
18267 assume neither behavior is the default.  Also, on many hosts
18268 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
18269 does not require this behavior and portable scripts should not rely on
18272 Typically it's best to use plain @command{pwd}.  On modern hosts this
18273 outputs logical directory names, which have the following advantages:
18275 @itemize @bullet
18276 @item
18277 Logical names are what the user specified.
18278 @item
18279 Physical names may not be portable from one installation
18280 host to another due to network file system gymnastics.
18281 @item
18282 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
18283 some parent directory, but plain @command{pwd} cannot fail for this
18284 reason.
18285 @end itemize
18287 Also please see the discussion of the @command{cd} command.
18290 @item @command{read}
18291 @c -----------------
18292 @prindex @command{read}
18293 No options are portable, not even support @option{-r} (Solaris 10
18294 @command{/bin/sh} for example).  Tru64/OSF 5.1 @command{sh} treats
18295 @command{read} as a special built-in, so it may exit if input is
18296 redirected from a non-existent or unreadable file.
18299 @anchor{set}
18300 @item @command{set}
18301 @c ----------------
18302 @prindex @command{set}
18303 With the FreeBSD 6.0 shell, the @command{set} command (without
18304 any options) does not sort its output.
18306 The @command{set} builtin faces the usual problem with arguments
18307 starting with a
18308 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
18309 the end of the options (any argument after @option{--} is a parameter,
18310 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
18311 10 @command{/bin/sh}) simply stop option
18312 processing as soon as a non-option argument is found.  Therefore, use
18313 @samp{dummy} or simply @samp{x} to end the option processing, and use
18314 @command{shift} to pop it out:
18316 @example
18317 set x $my_list; shift
18318 @end example
18320 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
18321 longer requires support for this command, and in traditional shells
18322 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
18323 makes scripts harder to debug.
18325 Some nonstandard shells do not recognize more than one option
18326 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
18327 better to combine them:
18329 @example
18330 set -ex
18331 @end example
18333 @cindex @command{set -e}
18334 The @option{-e} option has historically been under-specified, with enough
18335 ambiguities to cause numerous differences across various shell
18336 implementations; see for example
18337 @uref{https://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
18338 or @uref{https://www.austingroupbugs.net/@/view.php?id=52, this link},
18339 documenting a change to Posix 2008 to match @command{ksh88} behavior.
18340 Note that mixing @code{set -e} and shell functions is asking for surprises:
18342 @example
18343 set -e
18344 doit()
18346   rm file
18347   echo one
18349 doit || echo two
18350 @end example
18352 @noindent
18353 According to the recommendation, @samp{one} should always be output
18354 regardless of whether the @command{rm} failed, because it occurs within
18355 the body of the shell function @samp{doit} invoked on the left side of
18356 @samp{||}, where the effects of @samp{set -e} are not enforced.
18357 Likewise, @samp{two} should never be printed, since the failure of
18358 @command{rm} does not abort the function, such that the status of
18359 @samp{doit} is 0.
18361 The BSD shell has had several problems with the @option{-e}
18362 option.  Older versions of the BSD
18363 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
18364 @samp{case} when @option{-e} was in effect, causing the shell to exit
18365 unexpectedly in some cases.  This was particularly a problem with
18366 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
18367 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
18368 wrapper works around the bug (@pxref{Failure in Make Rules}).
18370 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
18371 wrongly exit with @option{-e} if the last command within a compound
18372 statement fails and is guarded by an @samp{&&} only.  For example:
18374 @example
18375 #! /bin/sh
18376 set -e
18377 foo=''
18378 test -n "$foo" && exit 1
18379 echo one
18380 if :; then
18381   test -n "$foo" && exit 1
18382   echo two
18383   test -n "$foo" && exit 1
18385 echo three
18386 @end example
18388 @noindent
18389 does not print @samp{three}.  One workaround is to change the last
18390 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
18391 "$foo"; then exit 1; fi} instead.  Another possibility is to warn BSD
18392 users not to use @samp{sh -e}.
18394 When @samp{set -e} is in effect, a failed command substitution in
18395 Solaris 10 @command{/bin/sh} cannot be ignored, even with @samp{||}.
18397 @example
18398 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
18399 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
18402 @end example
18404 @noindent
18405 Moreover, a command substitution, successful or not, causes this shell to
18406 exit from a failing outer command even in presence of an @samp{&&} list:
18408 @example
18409 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
18411 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
18413 @end example
18415 Portable scripts should not use @samp{set -e} if @command{trap} is used
18416 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
18417 sometimes enters the trap handler with the exit status of the command
18418 prior to the one that triggered the errexit handler:
18420 @example
18421 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
18423 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
18425 @end example
18427 @noindent
18428 Thus, when writing a script in M4sh, rather than trying to rely on
18429 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
18430 statement where it is desirable to abort on failure.
18432 @cindex @command{set -b}
18433 @cindex @command{set -m}
18434 Job control is not provided by all shells, so the use of @samp{set -m}
18435 or @samp{set -b} must be done with care.  When using @command{zsh} in
18436 native mode, asynchronous notification (@samp{set -b}) is enabled by
18437 default, and using @samp{emulate sh} to switch to Posix mode does not
18438 clear this setting (although asynchronous notification has no impact
18439 unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
18440 earlier have a bug where job control can be manipulated in interactive
18441 shells, but not in subshells or scripts.  Furthermore, some shells, like
18442 @command{pdksh}, fail to treat subshells as interactive, even though the
18443 parent shell was.
18445 @example
18446 $ @kbd{echo $ZSH_VERSION}
18447 4.3.10
18448 $ @kbd{set -m; echo $?}
18450 $ @kbd{zsh -c 'set -m; echo $?'}
18451 set: can't change option: -m
18452 $ @kbd{(set -m); echo $?}
18453 set: can't change option: -m
18455 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
18458 @end example
18460 @cindex @command{set -n}
18461 Use of @command{set -n} (typically via @command{sh -n script}) to
18462 validate a script is not foolproof.  Modern @command{ksh93} tries to be
18463 helpful by informing you about better syntax, but switching the script
18464 to use the suggested syntax in order to silence the warnings would
18465 render the script no longer portable to older shells:
18467 @example
18468 $ @kbd{ksh -nc '``'}
18469 ksh: warning: line 1: `...` obsolete, use $(...)
18471 @end example
18473 Furthermore, on ancient hosts, such as SunOS 4, @command{sh -n} could go
18474 into an infinite loop; even with that bug fixed, Solaris 8
18475 @command{/bin/sh} takes extremely long to parse large scripts.  Autoconf
18476 itself uses @command{sh -n} within its testsuite to check that correct
18477 scripts were generated, but only after first probing for other shell
18478 features (such as @code{test $@{BASH_VERSION+y@}}) that indicate
18479 a reasonably fast and working implementation.
18481 @item @command{shift}
18482 @c ------------------
18483 @prindex @command{shift}
18484 Not only is @command{shift}ing a bad idea when there is nothing left to
18485 shift, but in addition it is not portable: the shell of MIPS
18486 RISC/OS 4.52 refuses to do it.
18488 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
18489 it is also absent in many pre-Posix shells.
18492 @item @command{source}
18493 @c -------------------
18494 @prindex @command{source}
18495 This command is not portable, as Posix does not require it; use
18496 @command{.} instead.
18499 @item @command{test}
18500 @c -----------------
18501 @prindex @command{test}
18502 The @code{test} program is the way to perform many file and string
18503 tests.  It is often invoked by the alternate name @samp{[}, but using
18504 that name in Autoconf code is asking for trouble since it is an M4 quote
18505 character.
18507 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
18508 present in all implementations, and have been marked obsolete by Posix
18509 2008.  This is because there are inherent ambiguities in using them.
18510 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
18511 check whether two strings are both non-empty, but if @samp{$1} is the
18512 literal @samp{!}, then some implementations of @command{test} treat it
18513 as a negation of the unary operator @option{-a}.
18515 Thus, portable uses of @command{test} should never have more than four
18516 arguments, and scripts should use shell constructs like @samp{&&} and
18517 @samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
18518 statement, keep in mind that they have equal precedence, so it is often
18519 better to parenthesize even when this is redundant.  For example:
18521 @smallexample
18522 # Not portable:
18523 test "X$a" = "X$b" -a \
18524   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
18526 # Portable:
18527 test "X$a" = "X$b" &&
18528   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
18529 @end smallexample
18531 @command{test} does not process options like most other commands do; for
18532 example, it does not recognize the @option{--} argument as marking the
18533 end of options.
18535 It is safe to use @samp{!} as a @command{test} operator.  For example,
18536 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
18537 -d foo; @dots{}} is not.
18540 @item @command{test} (files)
18541 @c -------------------------
18542 To enable @command{configure} scripts to support cross-compilation, they
18543 shouldn't do anything that tests features of the build system instead of
18544 the host system.  But occasionally you may find it necessary to check
18545 whether some arbitrary file exists.  To do so, use @samp{test -f},
18546 @samp{test -r}, or @samp{test -x}.  Do not use @samp{test -e}, because
18547 Solaris 10 @command{/bin/sh}
18548 lacks it.  To test for symbolic links on systems that have them, use
18549 @samp{test -h} rather than @samp{test -L}; either form conforms to
18550 Posix 1003.1-2001, but older shells like Solaris 8
18551 @code{/bin/sh} support only @option{-h}.
18553 For historical reasons, Posix reluctantly allows implementations of
18554 @samp{test -x} that will succeed for the root user, even if no execute
18555 permissions are present.  Furthermore, shells do not all agree on
18556 whether Access Control Lists should affect @samp{test -r}, @samp{test
18557 -w}, and @samp{test -x}; some shells base test results strictly on the
18558 current user id compared to file owner and mode, as if by
18559 @code{stat(2)}; while other shells base test results on whether the
18560 current user has the given right, even if that right is only granted by
18561 an ACL, as if by @code{faccessat(2)}.  Furthermore, there is a classic
18562 time of check to time of use race between any use of @command{test}
18563 followed by operating on the just-checked file.  Therefore, it is a good
18564 idea to write scripts that actually attempt an operation, and are
18565 prepared for the resulting failure if permission is denied, rather than
18566 trying to avoid an operation based solely on whether @command{test}
18567 guessed that it might not be permitted.
18569 @item @command{test} (strings)
18570 @c ---------------------------
18571 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
18572 not null, but this usage is not portable to traditional platforms like
18573 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
18574 @samp{-n}.  However, it @emph{is} portable to test if a variable is set
18575 to a non-empty value, by using @samp{test $@{var+y@}}, since all known
18576 implementations properly distinguish between no arguments and a
18577 known-safe string of @samp{y}.
18579 Posix also says that @samp{test ! "@var{string}"},
18580 @samp{test -n "@var{string}"} and
18581 @samp{test -z "@var{string}"} work with any string, but many
18582 shells (such as Solaris 10, AIX 3.2, UNICOS 10.0.0.6,
18583 Digital Unix 4, etc.)@: get confused if
18584 @var{string} looks like an operator:
18586 @example
18587 $ @kbd{test -n =}
18588 test: argument expected
18589 $ @kbd{test ! -n}
18590 test: argument expected
18591 $ @kbd{test -z ")"; echo $?}
18593 @end example
18595 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
18596 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
18597 strings, but in practice this is not true for troublesome strings that
18598 look like operators or parentheses, or that begin with @samp{-}.
18600 It is best to protect such strings with a leading @samp{X}, e.g.,
18601 @samp{test "X@var{string}" != X} rather than @samp{test -n
18602 "@var{string}"} or @samp{test ! "@var{string}"}.
18604 It is common to find variations of the following idiom:
18606 @example
18607 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
18608   @var{action}
18609 @end example
18611 @noindent
18612 to take an action when a token matches a given pattern.  Such constructs
18613 should be avoided by using:
18615 @example
18616 case $ac_feature in
18617   *[!-a-zA-Z0-9_]*) @var{action};;
18618 esac
18619 @end example
18621 If the pattern is a complicated regular expression that cannot be
18622 expressed as a shell pattern, use something like this instead:
18624 @example
18625 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
18626   @var{action}
18627 @end example
18629 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
18630 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
18631 @samp{@var{foo}} contains backslashes.
18634 @anchor{trap}
18635 @item @command{trap}
18636 @c -----------------
18637 @prindex @command{trap}
18638 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
18639 trap 0, i.e., have the @command{trap} run when the script ends (either via an
18640 explicit @command{exit}, or the end of the script).  The trap for 0 should be
18641 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
18642 will invoke the trap at the end of this function.
18644 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
18645 specified signals to their default values, but many common shells (e.g.,
18646 Solaris 10 @command{/bin/sh}) misinterpret this and attempt to execute a
18647 ``command'' named @command{-} when the specified conditions arise.
18648 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18649 reset traps, as this is supported by a larger set of shells, but there
18650 are still shells like @command{dash} that mistakenly try to execute
18651 @command{1} instead of resetting the traps.  Therefore, there is no
18652 portable workaround, except for @samp{trap - 0}, for which
18653 @samp{trap '' 0} is a portable substitute.
18655 Although Posix is not absolutely clear on this point, it is widely
18656 admitted that when entering the trap @samp{$?} should be set to the exit
18657 status of the last command run before the trap.  The ambiguity can be
18658 summarized as: ``when the trap is launched by an @command{exit}, what is
18659 the @emph{last} command run: that before @command{exit}, or
18660 @command{exit} itself?''
18662 Bash considers @command{exit} to be the last command, while Zsh and
18663 Solaris 10 @command{/bin/sh} consider that when the trap is run it is
18664 @emph{still} in the @command{exit}, hence it is the previous exit status
18665 that the trap receives:
18667 @example
18668 $ @kbd{cat trap.sh}
18669 trap 'echo $?' 0
18670 (exit 42); exit 0
18671 $ @kbd{zsh trap.sh}
18673 $ @kbd{bash trap.sh}
18675 @end example
18677 The portable solution is then simple: when you want to @samp{exit 42},
18678 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18679 set the exit status to 42 for Zsh, and the second to trigger the trap
18680 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
18681 @code{AS_EXIT}.
18683 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18684 reset to 0 by empty lines if the code is inside @command{trap}.
18686 @example
18687 $ @kbd{trap 'false}
18689 echo $?' 0
18690 $ @kbd{exit}
18692 @end example
18694 @noindent
18695 Fortunately, this bug only affects @command{trap}.
18697 Several shells fail to execute an exit trap that is defined inside a
18698 subshell, when the last command of that subshell is not a builtin.  A
18699 workaround is to use @samp{exit $?} as the shell builtin.
18701 @example
18702 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18704 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18705 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18707 @end example
18709 @noindent
18710 Likewise, older implementations of @command{bash} failed to preserve
18711 @samp{$?} across an exit trap consisting of a single cleanup command.
18713 @example
18714 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
18716 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
18718 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
18720 @end example
18722 Be aware that a trap can be called from any number of places in your
18723 script, and therefore the trap handler should not make assumptions about
18724 shell state.  For some examples, if your script temporarily modifies
18725 @env{IFS}, then the trap should include an initialization back to its
18726 typical value of space-tab-newline (autoconf does this for generated
18727 @file{configure} files).  Likewise, if your script changes the current
18728 working directory at some point after the trap is installed, then your
18729 trap cannot assume which directory it is in, and should begin by
18730 changing directories to an absolute path if that is important to the
18731 cleanup efforts (autotest does this for generated @file{testsuite}
18732 files).
18734 @item @command{true}
18735 @c -----------------
18736 @prindex @command{true}
18737 @c Info cannot handle `:' in index entries.
18738 @c @prindex @command{:}
18739 Don't worry: as far as we know @command{true} is portable.
18740 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18741 portable shell community tends to prefer using @command{:}.  This has a
18742 funny side effect: when asked whether @command{false} is more portable
18743 than @command{true} Alexandre Oliva answered:
18745 @quotation
18746 In a sense, yes, because if it doesn't exist, the shell will produce an
18747 exit status of failure, which is correct for @command{false}, but not
18748 for @command{true}.
18749 @end quotation
18751 Remember that even though @samp{:} ignores its arguments, it still takes
18752 time to compute those arguments.  It is a good idea to use double quotes
18753 around any arguments to @samp{:} to avoid time spent in field splitting
18754 and file name expansion.
18757 @anchor{unset}
18758 @item @command{unset}
18759 @c ------------------
18760 @prindex @command{unset}
18761 In some nonconforming shells (e.g., Solaris 10 @command{/bin/ksh} and
18762 @command{/usr/xpg4/bin/sh}, NetBSD 5.99.43 sh, or Bash 2.05a),
18763 @code{unset FOO} fails when @code{FOO} is not set.  This can interfere
18764 with @code{set -e} operation.  You can use
18766 @smallexample
18767 FOO=; unset FOO
18768 @end smallexample
18770 @noindent
18771 if you are not sure that @code{FOO} is set.
18773 A few ancient shells lack @command{unset} entirely.  For some variables
18774 such as @code{PS1}, you can use a neutralizing value instead:
18776 @smallexample
18777 PS1='$ '
18778 @end smallexample
18780 Usually, shells that do not support @command{unset} need less effort to
18781 make the environment sane, so for example is not a problem if you cannot
18782 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
18783 @code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18784 So, you should do something like
18786 @smallexample
18787 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18788 @end smallexample
18790 @noindent
18791 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
18792 @ref{export, , Limitations of Builtins}, for
18793 the case of environment variables.
18795 @item @command{wait}
18796 @c -----------------
18797 @prindex @command{wait}
18798 The exit status of @command{wait} is not always reliable.
18799 @end table
18801 @node Limitations of Usual Tools
18802 @section Limitations of Usual Tools
18803 @cindex Limitations of usual tools
18805 The small set of tools you can expect to find on any machine can still
18806 include some limitations you should be aware of.
18808 @comment Between this list and the list of builtins above, we should
18809 @comment mention all the tools in GNU Coding Standards ``Utilities in
18810 @comment Makefiles''.
18812 @c This table includes things like `@command{expr} (|)', so we can't
18813 @c use @table @command.
18814 @table @asis
18815 @anchor{awk}
18816 @item @command{awk}
18817 @c ----------------
18818 @prindex @command{awk}
18819 Don't leave white space before the opening parenthesis in a user function call.
18820 Posix does not allow this and GNU Awk rejects it:
18822 @example
18823 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18824         BEGIN @{ die () @}'}
18825 gawk: cmd. line:2:         BEGIN @{ die () @}
18826 gawk: cmd. line:2:                      ^ parse error
18827 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18828         BEGIN @{ die() @}'}
18829 Aaaaarg!
18830 @end example
18832 Posix says that if a program contains only @samp{BEGIN} actions, and
18833 contains no instances of @code{getline}, then the program merely
18834 executes the actions without reading input.  However, traditional Awk
18835 implementations (such as Solaris 10 @command{awk}) read and discard
18836 input in this case.  Portable scripts can redirect input from
18837 @file{/dev/null} to work around the problem.  For example:
18839 @example
18840 awk 'BEGIN @{print "hello world"@}' </dev/null
18841 @end example
18843 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
18844 @samp{$1}) retain their value from the last record read, if no
18845 intervening @samp{getline} occurred.  However, some implementations
18846 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
18847 @samp{awk}) reset these variables.  A workaround is to use an
18848 intermediate variable prior to the @samp{END} block.  For example:
18850 @example
18851 $ @kbd{cat end.awk}
18852 @{ tmp = $1 @}
18853 END @{ print "a", $1, $NF, "b", tmp @}
18854 $ @kbd{echo 1 | awk -f end.awk}
18855 a   b 1
18856 $ @kbd{echo 1 | gawk -f end.awk}
18857 a 1 1 b 1
18858 @end example
18860 If you want your program to be deterministic, don't depend on @code{for}
18861 on arrays:
18863 @example
18864 $ @kbd{cat for.awk}
18865 END @{
18866   arr["foo"] = 1
18867   arr["bar"] = 1
18868   for (i in arr)
18869     print i
18871 $ @kbd{gawk -f for.awk </dev/null}
18874 $ @kbd{nawk -f for.awk </dev/null}
18877 @end example
18879 Some Awk implementations, such as HP-UX 11.0's native one,
18880 mishandle anchors:
18882 @example
18883 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
18884 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
18886 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
18887 xfoo
18888 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
18890 @end example
18892 @noindent
18893 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
18894 or use a simple test to reject such implementations.
18896 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
18897 after @code{%u}:
18899 @example
18900 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
18901 0 0
18902 @end example
18904 AIX version 5.2 has an arbitrary limit of 399 on the
18905 length of regular expressions and literal strings in an Awk program.
18907 Traditional Awk implementations derived from Unix version 7, such as
18908 Solaris @command{/bin/awk}, have many limitations and do not
18909 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
18910 Programs}) finds you an Awk that doesn't have these problems, but if
18911 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
18912 address them.  For more detailed descriptions, see @ref{Language
18913 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
18915 Traditional Awk does not support multidimensional arrays or user-defined
18916 functions.
18918 Traditional Awk does not support the @option{-v} option.  You can use
18919 assignments after the program instead, e.g., @code{$AWK '@{print v
18920 $1@}' v=x}; however, don't forget that such assignments are not
18921 evaluated until they are encountered (e.g., after any @code{BEGIN}
18922 action).
18924 Traditional Awk does not support the keywords @code{delete} or @code{do}.
18926 Traditional Awk does not support the expressions
18927 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
18928 or @code{@var{a}^=@var{b}}.
18930 Traditional Awk does not support the predefined @code{CONVFMT} or
18931 @code{ENVIRON} variables.
18933 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
18934 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
18935 @code{sqrt}, and @code{substr}.
18937 Traditional Awk @code{getline} is not at all compatible with Posix;
18938 avoid it.
18940 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
18941 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
18943 In code portable to both traditional and modern Awk, @code{FS} must be a
18944 string containing just one ordinary character, and similarly for the
18945 field-separator argument to @code{split}.
18947 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
18948 implementations, like Tru64's, split the input even if you don't refer
18949 to any field in the script, to circumvent this problem, set @samp{FS}
18950 to an unusual character and use @code{split}.
18952 Traditional Awk has a limit of at most 99 bytes in a number formatted by
18953 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
18954 dumps core.
18956 The original version of Awk had a limit of at most 99 bytes per
18957 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
18958 per run of non-special characters in a @code{printf} format, but these
18959 bugs have been fixed on all practical hosts that we know of.
18961 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
18962 of at most 3070 bytes.
18964 @item @command{basename}
18965 @c ---------------------
18966 @prindex @command{basename}
18967 Not all hosts have a working @command{basename}.
18968 You can use @command{expr} instead.
18970 @c AS_BASENAME is to be replaced by a better API.
18971 @ignore
18972 Not all hosts have a working @command{basename}, and you should instead
18973 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
18974 @command{expr} if you need to strip a suffix.  For example:
18976 @example
18977 a=`basename "$aname"`       # This is not portable.
18978 a=`AS_BASENAME(["$aname"])` # This is more portable.
18980 # This is not portable.
18981 c=`basename "$cname" .c`
18983 # This is more portable.
18984 c=`AS_BASENAME(["$cname"])`
18985 case $c in
18986 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
18987 esac
18988 @end example
18989 @end ignore
18992 @item @command{cat}
18993 @c ----------------
18994 @prindex @command{cat}
18995 Don't rely on any option.
18998 @item @command{cc}
18999 @c ---------------
19000 @prindex @command{cc}
19001 The command @samp{cc -c foo.c} traditionally produces an object file
19002 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
19003 with @option{-o} to specify a different object file name, but
19004 Posix does not require this combination and a few compilers
19005 lack support for it.  @xref{C Compiler}, for how GNU Make
19006 tests for this feature with @code{AC_PROG_CC_C_O}.
19008 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
19009 (such as CDS on Reliant Unix) leave a @file{foo.o}.
19011 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
19012 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
19013 nothing.
19015 The default executable, produced by @samp{cc foo.c}, can be
19017 @itemize
19018 @item @file{a.out} -- usual Posix convention.
19019 @item @file{b.out} -- i960 compilers (including @command{gcc}).
19020 @item @file{a.exe} -- DJGPP port of @command{gcc}.
19021 @item @file{a_out.exe} -- GNV @command{cc} wrapper for DEC C on OpenVMS.
19022 @item @file{foo.exe} -- various MS-DOS compilers.
19023 @end itemize
19025 The C compiler's traditional name is @command{cc}, but other names like
19026 @command{gcc} are common.  Posix 1003.1-2001 and 1003.1-2008 specify the
19027 name @command{c99}, but older Posix editions specified
19028 @command{c89}, future POSIX standards will likely specify
19029 @command{c11}, and anyway these standard names are rarely used in
19030 practice.  Typically the C compiler is invoked from makefiles that use
19031 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
19032 compiler name.
19034 @item @command{chgrp}
19035 @itemx @command{chown}
19036 @c -------------------
19037 @prindex @command{chgrp}
19038 @prindex @command{chown}
19039 It is not portable to change a file's group to a group that the owner
19040 does not belong to.
19042 @item @command{chmod}
19043 @c ------------------
19044 @prindex @command{chmod}
19045 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
19046 instead, for two reasons.  First, plain @option{-w} does not necessarily
19047 make the file unwritable, since it does not affect mode bits that
19048 correspond to bits in the file mode creation mask.  Second,
19049 Posix says that the @option{-w} might be interpreted as an
19050 implementation-specific option, not as a mode; Posix suggests
19051 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
19052 @samp{--} does not work on some older hosts.
19055 @item @command{cmp}
19056 @c ----------------
19057 @prindex @command{cmp}
19058 @command{cmp} performs a raw data comparison of two files, while
19059 @command{diff} compares two text files.  Therefore, if you might compare
19060 DOS files, even if only checking whether two files are different, use
19061 @command{diff} to avoid spurious differences due to differences of
19062 newline encoding.
19065 @item @command{cp}
19066 @c ---------------
19067 @prindex @command{cp}
19068 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
19069 obsolescent and its behavior on special files is implementation-defined.
19070 Use @option{-R} instead.  On GNU hosts the two options
19071 are equivalent, but on Solaris hosts (for example) @code{cp -r}
19072 reads from pipes instead of replicating them.  AIX 5.3 @code{cp -R} may
19073 corrupt its own memory with some directory hierarchies and error out or
19074 dump core:
19076 @example
19077 @kbd{mkdir -p 12345678/12345678/12345678/12345678}
19078 @kbd{touch 12345678/12345678/x}
19079 @kbd{cp -R 12345678 t}
19080 cp: 0653-440 12345678/12345678/: name too long.
19081 @end example
19083 Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
19084 trailing slashes at the end of nonexistent destination directories.  To
19085 avoid this problem, omit the trailing slashes.  For example, use
19086 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
19087 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
19089 The @option{-f} option is portable nowadays.
19091 @cindex timestamp resolution
19092 Traditionally, file timestamps had 1-second resolution, and @samp{cp
19093 -p} copied the timestamps exactly.  However, many modern file systems
19094 have timestamps with 1-nanosecond resolution.  Unfortunately, some older
19095 @samp{cp -p} implementations truncate timestamps when copying files,
19096 which can cause the destination file to appear to be older than the
19097 source.  The exact amount of truncation depends on the resolution of
19098 the system calls that @command{cp} uses.  Traditionally this was
19099 @code{utime}, which has 1-second resolution.  Less-ancient @command{cp}
19100 implementations such as GNU Core Utilities 5.0.91 (2003) use
19101 @code{utimes}, which has 1-microsecond resolution.  Modern
19102 implementations such as GNU Core Utilities 6.12 (2008) can set timestamps to
19103 the full nanosecond resolution, using the modern system calls
19104 @code{futimens} and @code{utimensat} when they are available.  As of
19105 2011, though, many platforms do not yet fully support these new system
19106 calls.
19108 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
19109 ownerships.  But whether it actually does copy ownerships or not is a
19110 system dependent policy decision implemented by the kernel.  If the
19111 kernel allows it then it happens.  If the kernel does not allow it then
19112 it does not happen.  It is not something @command{cp} itself has control
19113 over.
19115 In Unix System V any user can chown files to any other user, and System
19116 V also has a non-sticky @file{/tmp}.  That probably derives from the
19117 heritage of System V in a business environment without hostile users.
19118 BSD changed this
19119 to be a more secure model where only root can @command{chown} files and
19120 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
19121 of BSD in a campus environment.
19123 GNU/Linux and Solaris by default follow BSD, but
19124 can be configured to allow a System V style @command{chown}.  On the
19125 other hand, HP-UX follows System V, but can
19126 be configured to use the modern security model and disallow
19127 @command{chown}.  Since it is an administrator-configurable parameter
19128 you can't use the name of the kernel as an indicator of the behavior.
19132 @item @command{date}
19133 @c -----------------
19134 @prindex @command{date}
19135 Some versions of @command{date} do not recognize special @samp{%} directives,
19136 and unfortunately, instead of complaining, they just pass them through,
19137 and exit with success:
19139 @example
19140 $ @kbd{uname -a}
19141 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
19142 $ @kbd{date "+%s"}
19144 @end example
19147 @item @command{diff}
19148 @c -----------------
19149 @prindex @command{diff}
19150 Option @option{-u} is nonportable.
19152 Some implementations, such as Tru64's, fail when comparing to
19153 @file{/dev/null}.  Use an empty file instead.
19156 @item @command{dirname}
19157 @c --------------------
19158 @prindex @command{dirname}
19159 Not all hosts have a working @command{dirname}, and you should instead
19160 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
19162 @example
19163 dir=`dirname "$file"`       # This is not portable.
19164 dir=`AS_DIRNAME(["$file"])` # This is more portable.
19165 @end example
19168 @item @command{egrep}
19169 @c ------------------
19170 @prindex @command{egrep}
19171 Posix 1003.1-2001 no longer requires @command{egrep},
19172 but many hosts do not yet support the Posix
19173 replacement @code{grep -E}.  Also, some traditional implementations do
19174 not work on long input lines.  To work around these problems, invoke
19175 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
19177 Portable extended regular expressions should use @samp{\} only to escape
19178 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
19179 is not portable, even though it typically matches @samp{@}}.
19181 The empty alternative is not portable.  Use @samp{?} instead.  For
19182 instance with Digital Unix v5.0:
19184 @example
19185 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
19186 |foo
19187 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
19188 bar|
19189 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
19191 |bar
19192 @end example
19194 @command{$EGREP} also suffers the limitations of @command{grep}
19195 (@pxref{grep, , Limitations of Usual Tools}).
19197 @item @command{expr}
19198 @c -----------------
19199 @prindex @command{expr}
19200 Not all implementations obey the Posix rule that @samp{--} separates
19201 options from arguments; likewise, not all implementations provide the
19202 extension to Posix that the first argument can be treated as part of a
19203 valid expression rather than an invalid option if it begins with
19204 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
19205 @samp{$var} might be a negative number, to keep @command{expr} from
19206 interpreting it as an option.
19208 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
19209 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
19210 misinterpreting @var{word}.
19212 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
19214 @item @command{expr} (@samp{|})
19215 @prindex @command{expr} (@samp{|})
19216 You can use @samp{|}.  Although Posix does require that @samp{expr
19217 ''} return the empty string, it does not specify the result when you
19218 @samp{|} together the empty string (or zero) with the empty string.  For
19219 example:
19221 @example
19222 expr '' \| ''
19223 @end example
19225 Posix 1003.2-1992 returns the empty string
19226 for this case, but traditional Unix returns @samp{0} (Solaris is
19227 one such example).  In Posix 1003.1-2001, the specification was
19228 changed to match traditional Unix's behavior (which is
19229 bizarre, but it's too late to fix this).  Please note that the same
19230 problem does arise when the empty string results from a computation,
19231 as in:
19233 @example
19234 expr bar : foo \| foo : bar
19235 @end example
19237 @noindent
19238 Avoid this portability problem by avoiding the empty string.
19241 @item @command{expr} (@samp{:})
19242 @c ----------------------------
19243 @prindex @command{expr}
19244 Portable @command{expr} regular expressions should use @samp{\} to
19245 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
19246 For example, alternation, @samp{\|}, is common but Posix does not
19247 require its support, so it should be avoided in portable scripts.
19248 Similarly, @samp{\+} and @samp{\?} should be avoided.
19250 Portable @command{expr} regular expressions should not begin with
19251 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
19252 not needed anyway.
19254 On the other hand, the behavior of the @samp{$} anchor is not portable
19255 on multi-line strings.  Posix is ambiguous whether the anchor applies to
19256 each line, as was done in older versions of the GNU Core Utilities, or
19257 whether it applies only to the end of the overall string, as in
19258 Coreutils 6.0 and most other implementations.
19260 @example
19261 $ @kbd{baz='foo}
19262 > @kbd{bar'}
19263 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
19265 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
19267 @end example
19269 The Posix standard is ambiguous as to whether
19270 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
19271 In practice, it outputs the empty string on most platforms, but portable
19272 scripts should not assume this.  For instance, the QNX 4.25 native
19273 @command{expr} returns @samp{0}.
19275 One might think that a way to get a uniform behavior would be to use
19276 the empty string as a default value:
19278 @example
19279 expr a : '\(b\)' \| ''
19280 @end example
19282 @noindent
19283 Unfortunately this behaves exactly as the original expression; see the
19284 @command{expr} (@samp{|}) entry for more information.
19286 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
19287 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
19288 @command{expr} to fail if the matched substring is longer than 120
19289 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
19290 @command{expr} fails.  Nowadays this is of practical importance only for
19291 the rare installer who mistakenly puts @file{/usr/ucb} before
19292 @file{/usr/bin} in @env{PATH}.
19294 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
19295 some cases.  For example, the command
19296 @example
19297 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
19298 @end example
19300 @noindent
19301 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
19302 This particular case can be worked around by substituting @samp{[^--]}
19303 for @samp{[^-]}.
19305 Don't leave, there is some more!
19307 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
19308 the empty string, has a funny behavior in its exit status: it's always 1
19309 when parentheses are used!
19311 @example
19312 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
19313 0: 1
19314 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
19315 1: 0
19317 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
19318 1: a
19319 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
19320 1: 0
19321 @end example
19323 @noindent
19324 In practice this can be a big problem if you are ready to catch failures
19325 of @command{expr} programs with some other method (such as using
19326 @command{sed}), since you may get twice the result.  For instance
19328 @example
19329 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
19330 @end example
19332 @noindent
19333 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25.  A
19334 simple workaround consists of testing @command{expr} and using a variable
19335 set to @command{expr} or to @command{false} according to the result.
19337 Tru64 @command{expr} incorrectly treats the result as a number, if it
19338 can be interpreted that way:
19340 @example
19341 $ @kbd{expr 00001 : '.*\(...\)'}
19343 @end example
19345 On HP-UX 11, @command{expr} only supports a single
19346 sub-expression.
19348 @example
19349 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
19350 expr: More than one '\(' was used.
19351 @end example
19354 @item @command{fgrep}
19355 @c ------------------
19356 @prindex @command{fgrep}
19357 Posix 1003.1-2001 no longer requires @command{fgrep},
19358 but many hosts do not yet support the Posix
19359 replacement @code{grep -F}.  Also, some traditional implementations do
19360 not work on long input lines.  To work around these problems, invoke
19361 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
19363 Tru64/OSF 5.1 @command{fgrep} does not match an empty pattern.
19366 @item @command{find}
19367 @c -----------------
19368 @prindex @command{find}
19369 The @option{-maxdepth} option seems to be GNU specific.
19370 Tru64 v5.1, NetBSD 1.5 and Solaris @command{find}
19371 commands do not understand it.
19373 The replacement of @samp{@{@}} is guaranteed only if the argument is
19374 exactly @emph{@{@}}, not if it's only a part of an argument.  For
19375 instance on DU, and HP-UX 10.20 and HP-UX 11:
19377 @example
19378 $ @kbd{touch foo}
19379 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
19380 @{@}-@{@}
19381 @end example
19383 @noindent
19384 while GNU @command{find} reports @samp{./foo-./foo}.
19387 @anchor{grep}
19388 @item @command{grep}
19389 @c -----------------
19390 @prindex @command{grep}
19391 Portable scripts can rely on the @command{grep} options @option{-c},
19392 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
19393 options.  For example, don't use @option{-w}, as Posix does not require
19394 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
19395 portable scripts should not combine @option{-c} with @option{-l},
19396 as Posix does not allow this.
19398 Some of the options required by Posix are not portable in practice.
19399 Don't use @samp{grep -q} to suppress output, because many @command{grep}
19400 implementations (e.g., Solaris) do not support @option{-q}.
19401 Don't use @samp{grep -s} to suppress output either, because Posix
19402 says @option{-s} does not suppress output, only some error messages;
19403 also, the @option{-s} option of traditional @command{grep} behaved
19404 like @option{-q} does in most modern implementations.  Instead,
19405 redirect the standard output and standard error (in case the file
19406 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
19407 status of @code{grep} to determine whether it found a match.
19409 The QNX4 implementation fails to count lines with @code{grep -c '$'},
19410 but works with @code{grep -c '^'}.  Other alternatives for counting
19411 lines are to use @code{sed -n '$='} or @code{wc -l}.
19413 Some traditional @command{grep} implementations do not work on long
19414 input lines.  On AIX the default @code{grep} silently truncates long
19415 lines on the input before matching.
19417 Also, many implementations do not support multiple regexps
19418 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
19419 or honor only the last pattern (e.g., IRIX 6.5 and NeXT).  To
19420 work around these problems, invoke @code{AC_PROG_GREP} and then use
19421 @code{$GREP}.
19423 Another possible workaround for the multiple @option{-e} problem is to
19424 separate the patterns by newlines, for example:
19426 @example
19427 grep 'foo
19428 bar' in.txt
19429 @end example
19431 @noindent
19432 except that this fails with traditional @command{grep}
19433 implementations and with OpenBSD 3.8 @command{grep}.
19435 Traditional @command{grep} implementations (e.g., Solaris) do not
19436 support the @option{-E} or @option{-F} options.  To work around these
19437 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
19438 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
19439 willing to require support for Posix @command{grep}, your script should
19440 not use both @option{-E} and @option{-F}, since Posix does not allow
19441 this combination.
19443 Portable @command{grep} regular expressions should use @samp{\} only to
19444 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
19445 alternation, @samp{\|}, is common but Posix does not require its
19446 support in basic regular expressions, so it should be avoided in
19447 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
19448 Similarly, the following escape sequences should also be avoided:
19449 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
19450 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
19452 Posix does not specify the behavior of @command{grep} on binary files.
19453 An example where this matters is using BSD @command{grep} to
19454 search text that includes embedded ANSI escape sequences for
19455 colored output to terminals (@samp{\033[m} is the sequence to restore
19456 normal output); the behavior depends on whether input is seekable:
19458 @example
19459 $ @kbd{printf 'esc\033[mape\n' > sample}
19460 $ @kbd{grep . sample}
19461 Binary file sample matches
19462 $ @kbd{cat sample | grep .}
19463 escape
19464 @end example
19467 @item @command{join}
19468 @c -----------------
19469 @prindex @command{join}
19470 Solaris 8 @command{join} has bugs when the second operand is standard
19471 input, and when standard input is a pipe.  For example, the following
19472 shell script causes Solaris 8 @command{join} to loop forever:
19474 @example
19475 cat >file <<'EOF'
19476 1 x
19477 2 y
19479 cat file | join file -
19480 @end example
19482 Use @samp{join - file} instead.
19484 On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
19485 @command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
19486 the workaround is to use @command{join -a1 file1 file2} instead.
19488 @item @command{ln}
19489 @c ---------------
19490 @prindex @command{ln}
19491 The @option{-f} option is portable nowadays.
19493 @cindex Symbolic links
19494 Symbolic links are not available on some systems; use @samp{$(LN_S)} as
19495 a portable substitute.
19497 For versions of the DJGPP before 2.04,
19498 @command{ln} emulates symbolic links
19499 to executables by generating a stub that in turn calls the real
19500 program.  This feature also works with nonexistent files like in the
19501 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
19502 which attempts to call @file{file.exe} if run.  But this feature only
19503 works for executables, so @samp{cp -p} is used instead for these
19504 systems.  DJGPP versions 2.04 and later have full support
19505 for symbolic links.
19508 @item @command{ls}
19509 @c ---------------
19510 @prindex @command{ls}
19511 @cindex Listing directories
19512 The portable options are @option{-acdilrtu}.  Current practice is for
19513 @option{-l} to output both owner and group, even though ancient versions
19514 of @command{ls} omitted the group.
19516 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
19517 to standard output if @file{foo} did not exist.  Hence a shell command
19518 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
19519 was equivalent to @samp{sources='*.c not found'} in the absence of
19520 @samp{.c} files.  This is no longer a practical problem, since current
19521 @command{ls} implementations send diagnostics to standard error.
19523 The behavior of @command{ls} on a directory that is being concurrently
19524 modified is not always predictable, because of a data race where cached
19525 information returned by @code{readdir} does not match the current
19526 directory state.  In fact, MacOS 10.5 has an intermittent bug where
19527 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
19528 once if other files were added or removed from the directory immediately
19529 prior to the @command{ls} call.  Since @command{ls} already sorts its
19530 output, the duplicate entries can be avoided by piping the results
19531 through @code{uniq}.
19533 @anchor{mkdir}
19534 @item @command{mkdir}
19535 @c ------------------
19536 @prindex @command{mkdir}
19537 @cindex Making directories
19538 No @command{mkdir} option is portable to older systems.  Instead of
19539 @samp{mkdir -p @var{file-name}}, you should use
19540 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
19541 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
19543 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
19544 go-w -p @var{dir}}, often leads to trouble.  FreeBSD
19545 @command{mkdir} incorrectly attempts to change the permissions of
19546 @var{dir} even if it already exists.  HP-UX 11.23 and
19547 IRIX 6.5 @command{mkdir} often assign the wrong permissions to
19548 any newly-created parents of @var{dir}.
19550 Posix does not clearly specify whether @samp{mkdir -p foo}
19551 should succeed when @file{foo} is a symbolic link to an already-existing
19552 directory.  The GNU Core Utilities 5.1.0 @command{mkdir}
19553 succeeds, but Solaris @command{mkdir} fails.
19555 Traditional @code{mkdir -p} implementations suffer from race conditions.
19556 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
19557 at the same time, both processes might detect that @file{a} is missing,
19558 one might create @file{a}, then the other might try to create @file{a}
19559 and fail with a @code{File exists} diagnostic.  The GNU Core
19560 Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
19561 NetBSD 2.0.2, and OpenBSD 2.4 are known to be
19562 race-free when two processes invoke @code{mkdir -p} simultaneously, but
19563 earlier versions are vulnerable.  Solaris @command{mkdir} is still
19564 vulnerable as of Solaris 10, and other traditional Unix systems are
19565 probably vulnerable too.  This possible race is harmful in parallel
19566 builds when several Make rules call @code{mkdir -p} to
19567 construct directories.  You may use
19568 @code{install-sh -d} as a safe replacement, provided this script is
19569 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
19570 OK, but copies from older versions are vulnerable.
19573 @item @command{mkfifo}
19574 @itemx @command{mknod}
19575 @c -------------------
19576 @prindex @command{mkfifo}
19577 @prindex @command{mknod}
19578 The GNU Coding Standards state that @command{mknod} is safe to use on
19579 platforms where it has been tested to exist; but it is generally portable
19580 only for creating named FIFOs, since device numbers are
19581 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
19582 testsuites.  Posix states that behavior is unspecified when opening a
19583 named FIFO for both reading and writing; on at least Cygwin, this
19584 results in failure on any attempt to read or write to that file
19585 descriptor.
19587 @item @command{mktemp}
19588 @c -------------------
19589 @prindex @command{mktemp}
19590 @cindex Creating temporary files
19591 Shell scripts can use temporary files safely with @command{mktemp}, but
19592 it does not exist on all systems.  A portable way to create a safe
19593 temporary file name is to create a temporary directory with mode 700 and
19594 use a file inside this directory.  Both methods prevent attackers from
19595 gaining control, though @command{mktemp} is far less likely to fail
19596 gratuitously under attack.
19598 Here is sample code to create a new temporary directory @samp{$dir} safely:
19600 @example
19601 # Create a temporary directory $dir in $TMPDIR (default /tmp).
19602 # Use mktemp if possible; otherwise fall back on mkdir,
19603 # with $RANDOM to make collisions less likely.
19604 : "$@{TMPDIR:=/tmp@}"
19606   dir=`
19607     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
19608   ` &&
19609   test -d "$dir"
19610 @} || @{
19611   dir=$TMPDIR/foo$$-$RANDOM
19612 @c $$ restore font-lock
19613   (umask 077 && mkdir "$dir")
19614 @} || exit $?
19615 @end example
19618 @item @command{mv}
19619 @c ---------------
19620 @prindex @command{mv}
19621 @cindex Moving open files
19622 The only portable options are @option{-f} and @option{-i}.
19624 Moving individual files between file systems is portable (it was in Unix
19625 version 6),
19626 but it is not always atomic: when doing @samp{mv new existing}, there's
19627 a critical section where neither the old nor the new version of
19628 @file{existing} actually exists.
19630 On some systems moving files from @file{/tmp} can sometimes cause
19631 undesirable (but perfectly valid) warnings, even if you created these
19632 files.  This is because @file{/tmp} belongs to a group that ordinary
19633 users are not members of, and files created in @file{/tmp} inherit
19634 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
19635 a diagnostic without failing:
19637 @smallexample
19638 $ @kbd{touch /tmp/foo}
19639 $ @kbd{mv /tmp/foo .}
19640 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
19641 $ @kbd{echo $?}
19643 $ @kbd{ls foo}
19645 @end smallexample
19647 @noindent
19648 This annoying behavior conforms to Posix, unfortunately.
19650 Moving directories across mount points is not portable, use @command{cp}
19651 and @command{rm}.
19653 DOS variants cannot rename or remove open files, and do not
19654 support commands like @samp{mv foo bar >foo}, even though this is
19655 perfectly portable among Posix hosts.
19658 @item @command{od}
19659 @c ---------------
19660 @prindex @command{od}
19662 In Mac OS X 10.3, @command{od} does not support the
19663 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
19664 @option{-t}, or the XSI option, @option{-s}.  The only
19665 supported Posix option is @option{-v}, and the only supported
19666 XSI options are those in @option{-bcdox}.  The BSD
19667 @command{hexdump} program can be used instead.
19669 This problem no longer exists in Mac OS X 10.4.3.
19672 @item @command{rm}
19673 @c ---------------
19674 @prindex @command{rm}
19675 The @option{-f} and @option{-r} options are portable.
19677 It is not portable to invoke @command{rm} without options or operands.
19678 On the other hand, Posix now requires @command{rm -f} to silently
19679 succeed when there are no operands (useful for constructs like
19680 @command{rm -rf $filelist} without first checking if @samp{$filelist}
19681 was empty).  But this was not always portable; at least NetBSD
19682 @command{rm} built before 2008 would fail with a diagnostic.
19684 A file might not be removed even if its parent directory is writable
19685 and searchable.  Many Posix hosts cannot remove a mount point, a named
19686 stream, a working directory, or a last link to a file that is being
19687 executed.
19689 DOS variants cannot rename or remove open files, and do not
19690 support commands like @samp{rm foo >foo}, even though this is
19691 perfectly portable among Posix hosts.
19693 @item @command{rmdir}
19694 @c ------------------
19695 @prindex @command{rmdir}
19696 Just as with @command{rm}, some platforms refuse to remove a working
19697 directory.
19699 @anchor{sed}
19700 @item @command{sed}
19701 @c ----------------
19702 @prindex @command{sed}
19703 Patterns should not include the separator (unless escaped), even as part
19704 of a character class.  In conformance with Posix, the Cray
19705 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
19706 Even when escaped, patterns should not include separators that are also
19707 used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
19708 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19709 before evaluating the basic regular expression.
19711 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
19712 not require support for empty patterns, and Unicos 9 @command{sed} rejects
19713 them.
19715 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
19717 Sed scripts should not use branch labels longer than 7 characters and
19718 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
19719 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
19720 48 labels, which cannot be circumvented by using more than one script
19721 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
19722 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
19723 about 6000 bytes for the internal representation of commands.
19725 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
19726 NetBSD 1.4.2's, incorrectly try to interpret the second
19727 @samp{;} as a command:
19729 @example
19730 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
19731 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
19732 @end example
19734 Some @command{sed} implementations have a buffer limited to 4000 bytes,
19735 and this limits the size of input lines, output lines, and internal
19736 buffers that can be processed portably.  Likewise,
19737 not all @command{sed} implementations can handle embedded @code{NUL} or
19738 a missing trailing newline.
19740 Remember that ranges within a bracket expression of a regular expression
19741 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19742 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19743 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19744 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19745 than to rely on @samp{[A-Z]}.
19747 Additionally, Posix states that regular expressions are only
19748 well-defined on characters.  Unfortunately, there exist platforms such
19749 as MacOS X 10.5 where not all 8-bit byte values are valid characters,
19750 even though that platform has a single-byte @samp{C} locale.  And Posix
19751 allows the existence of a multi-byte @samp{C} locale, although that does
19752 not yet appear to be a common implementation.  At any rate, it means
19753 that not all bytes will be matched by the regular expression @samp{.}:
19755 @example
19756 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
19758 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
19760 @end example
19762 Portable @command{sed} regular expressions should use @samp{\} only to escape
19763 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
19764 alternation, @samp{\|}, is common but Posix does not require its
19765 support, so it should be avoided in portable scripts.  Solaris
19766 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19767 deletes only lines that contain the literal string @samp{a|b}.
19768 Similarly, @samp{\+} and @samp{\?} should be avoided.
19770 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19772 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
19773 quite portable to current hosts, but was not supported by some ancient
19774 @command{sed} implementations like SVR3.
19776 Some @command{sed} implementations, e.g., Solaris, restrict the special
19777 role of the asterisk @samp{*} to one-character regular expressions and
19778 back-references, and the special role of interval expressions
19779 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19780 to one-character regular expressions.  This may lead to unexpected behavior:
19782 @example
19783 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19784 x2x4
19785 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19787 @end example
19789 The @option{-e} option is mostly portable.
19790 However, its argument
19791 cannot start with @samp{a}, @samp{c}, or @samp{i},
19792 as this runs afoul of a Tru64 5.1 bug.
19793 Also, its argument cannot be empty, as this fails on AIX 5.3.
19794 Some people prefer to use @samp{-e}:
19796 @example
19797 sed -e '@var{command-1}' \
19798     -e '@var{command-2}'
19799 @end example
19801 @noindent
19802 as opposed to the equivalent:
19804 @example
19805 sed '
19806   @var{command-1}
19807   @var{command-2}
19809 @end example
19811 @noindent
19812 The following usage is sometimes equivalent:
19814 @example
19815 sed '@var{command-1};@var{command-2}'
19816 @end example
19818 but Posix says that this use of a semicolon has undefined effect if
19819 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
19820 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
19821 should use semicolon only with simple scripts that do not use these
19822 verbs.
19824 Posix up to the 2008 revision requires the argument of the @option{-e}
19825 option to be a syntactically complete script.  GNU @command{sed} allows
19826 to pass multiple script fragments, each as argument of a separate
19827 @option{-e} option, that are then combined, with newlines between the
19828 fragments, and a future Posix revision may allow this as well.  This
19829 approach is not portable with script fragments ending in backslash; for
19830 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
19831 don't allow splitting in this case:
19833 @example
19834 $ @kbd{echo a | sed -n -e 'i\}
19835 @kbd{0'}
19837 $ @kbd{echo a | sed -n -e 'i\' -e 0}
19838 Unrecognized command: 0
19839 @end example
19841 @noindent
19842 In practice, however, this technique of joining fragments
19843 through @option{-e} works for multiple @command{sed} functions within
19844 @samp{@{} and @samp{@}}, even if that is not specified by Posix:
19846 @example
19847 @c The quote around the closing brace silences interactive zsh.
19848 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
19850 @end example
19852 Commands inside @{ @} brackets are further restricted.  Posix 2008 says that
19853 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
19854 each command must be followed immediately by a newline, without any
19855 intervening blanks or semicolons.  The closing bracket must be alone on
19856 a line, other than white space preceding or following it.  However, a
19857 future version of Posix may standardize the use of addresses within brackets.
19859 Contrary to yet another urban legend, you may portably use @samp{&} in
19860 the replacement part of the @code{s} command to mean ``what was
19861 matched''.  All descendants of Unix version 7 @command{sed}
19862 (at least; we
19863 don't have first hand experience with older @command{sed} implementations) have
19864 supported it.
19866 Posix requires that you must not have any white space between
19867 @samp{!} and the following command.  It is OK to have blanks between
19868 the address and the @samp{!}.  For instance, on Solaris:
19870 @example
19871 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
19872 @error{}Unrecognized command: /bar/ ! p
19873 $ @kbd{echo "foo" | sed -n '/bar/! p'}
19874 @error{}Unrecognized command: /bar/! p
19875 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
19877 @end example
19879 Posix also says that you should not combine @samp{!} and @samp{;}.  If
19880 you use @samp{!}, it is best to put it on a command that is delimited by
19881 newlines rather than @samp{;}.
19883 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
19884 @samp{w} commands be followed by exactly one space before their argument.
19885 On the other hand, no white space is allowed between @samp{:} and the
19886 subsequent label name.
19888 If a sed script is specified on the command line and ends in an
19889 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
19890 should be followed by a newline.  Otherwise some @command{sed}
19891 implementations (e.g., OpenBSD 3.9) do not append a newline to the
19892 inserted text.
19894 Many @command{sed} implementations (e.g., MacOS X 10.4,
19895 OpenBSD 3.9, Solaris 10
19896 @command{/usr/ucb/sed}) strip leading white space from the text of
19897 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
19898 work around this incompatibility with Posix:
19900 @example
19901 $ @kbd{echo flushleft | sed 'a\}
19902 > @kbd{   indented}
19903 > @kbd{'}
19904 flushleft
19905 indented
19906 $ @kbd{echo foo | sed 'a\}
19907 > @kbd{\   indented}
19908 > @kbd{'}
19909 flushleft
19910    indented
19911 @end example
19913 Posix requires that with an empty regular expression, the last non-empty
19914 regular expression from either an address specification or substitution
19915 command is applied.  However, busybox 1.6.1 complains when using a
19916 substitution command with a replacement containing a back-reference to
19917 an empty regular expression; the workaround is repeating the regular
19918 expression.
19920 @example
19921 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
19922 sed: No previous regexp.
19923 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
19925 @end example
19927 Portable scripts should be aware of the inconsistencies and options for
19928 handling word boundaries, as these are not specified by POSIX.
19930 @example
19931                 \<      \b      [[:<:]]
19932 Solaris 10      yes     no      no
19933 Solaris XPG4    yes     no      error
19934 NetBSD 5.1      no      no      yes
19935 FreeBSD 9.1     no      no      yes
19936 GNU             yes     yes     error
19937 busybox         yes     yes     error
19938 @end example
19940 @item @command{sed} (@samp{t})
19941 @c ---------------------------
19942 @prindex @command{sed} (@samp{t})
19943 Some old systems have @command{sed} that ``forget'' to reset their
19944 @samp{t} flag when starting a new cycle.  For instance on MIPS
19945 RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
19946 script (the line numbers are not actual part of the texts):
19948 @example
19949 s/keep me/kept/g  # a
19950 t end             # b
19951 s/.*/deleted/g    # c
19952 :end              # d
19953 @end example
19955 @noindent
19958 @example
19959 delete me         # 1
19960 delete me         # 2
19961 keep me           # 3
19962 delete me         # 4
19963 @end example
19965 @noindent
19966 you get
19968 @example
19969 deleted
19970 delete me
19971 kept
19972 deleted
19973 @end example
19975 @noindent
19976 instead of
19978 @example
19979 deleted
19980 deleted
19981 kept
19982 deleted
19983 @end example
19985 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
19986 flag, and the output is produced.  When processing
19987 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
19988 fails to match, but @command{sed} is not supposed to clear the @samp{t}
19989 flag when a substitution fails.  Command (b) sees that the flag is set,
19990 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
19991 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
19992 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
19993 Finally, since the flag is clear, line 4 is processed properly.
19995 There are two things one should remember about @samp{t} in @command{sed}.
19996 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
19997 succeeded, not only the immediately preceding substitution.  Therefore,
19998 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
19999 line, to reset the @samp{t} flag where needed.
20001 Secondly, you cannot rely on @command{sed} to clear the flag at each new
20002 cycle.
20004 One portable implementation of the script above is:
20006 @example
20007 t clear
20008 :clear
20009 s/keep me/kept/g
20010 t end
20011 s/.*/deleted/g
20012 :end
20013 @end example
20015 @item @command{sleep}
20016 @c ------------------
20017 @prindex @command{sleep}
20018 Using @command{sleep} is generally portable.  However, remember that
20019 adding a @command{sleep} to work around timestamp issues, with a minimum
20020 granularity of one second, doesn't scale well for parallel builds on
20021 modern machines with sub-second process completion.
20023 @item @command{sort}
20024 @c -----------------
20025 @prindex @command{sort}
20026 Remember that sort order is influenced by the current locale.  Inside
20027 @file{configure}, the C locale is in effect, but in Makefile snippets,
20028 you may need to specify @code{LC_ALL=C sort}.
20030 @item @command{tar}
20031 @c ----------------
20032 @prindex @command{tar}
20033 There are multiple file formats for @command{tar}; if you use Automake,
20034 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
20035 level of portability to use.
20037 @anchor{touch}
20038 @item @command{touch}
20039 @c ------------------
20040 @prindex @command{touch}
20041 @cindex timestamp resolution
20042 If you specify the desired timestamp (e.g., with the @option{-r}
20043 option), older @command{touch} implementations use the @code{utime} or
20044 @code{utimes} system call, which can result in the same kind of
20045 timestamp truncation problems that @samp{cp -p} has.
20047 On ancient BSD systems, @command{touch} or any command that
20048 results in an empty file does not update the timestamps, so use a
20049 command like @command{echo} as a workaround.
20050 Also,
20051 GNU @command{touch} 3.16r (and presumably all before that)
20052 fails to work on SunOS 4.1.3 when the empty file is on an
20053 NFS-mounted 4.2 volume.
20054 However, these problems are no longer of practical concern.
20056 @item @command{tr}
20057 @c ---------------
20058 @prindex @command{tr}
20059 @cindex carriage return, deleting
20060 @cindex newline, deleting
20061 @cindex deleting carriage return
20062 Not all versions of @command{tr} handle all backslash character escapes.
20063 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
20064 Solaris contains more modern @command{tr} in other locations.
20065 Using octal escapes is more portable for carriage returns, since
20066 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
20067 literal carriage returns in scripts causes a number of other problems.
20068 But for other characters, like newline, using octal escapes ties the
20069 operation to ASCII, so it is better to use literal characters.
20071 @example
20072 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
20074 light
20075 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
20076 moonlight
20077 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
20078 moonlight
20079 $ @kbd{nl='}
20080 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
20081 moonlight
20082 @end example
20084 Not all versions of @command{tr} recognize direct ranges of characters: at
20085 least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
20086 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in Posix
20087 transliterate to themselves).
20089 @example
20090 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
20091 HAZy FAntAZy
20092 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
20093 HAZY FANTAZY
20094 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
20095 HAZY FANTAZY
20096 @end example
20098 When providing two arguments, be sure the second string is at least as
20099 long as the first.
20101 @example
20102 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
20104 $ @kbd{echo abc | coreutils/tr bc d}
20106 @end example
20108 Posix requires @command{tr} to operate on binary files.  But at least
20109 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
20110 @code{NUL} in the input prior to doing any translation.  When using
20111 @command{tr} to process a binary file that may contain @code{NUL} bytes,
20112 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
20113 @command{/usr/xpg6/bin/tr} if that is available.
20115 @example
20116 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
20117  61 62
20118 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
20119  61 62
20120 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
20121  61 00 62
20122 @end example
20124 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
20125 octal escape for @code{NUL}.
20127 @example
20128 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
20129  61 62 63
20130 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
20131  61 00 64
20132 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
20133  61 00 64
20134 @end example
20136 @end table
20139 @node Portable Make
20140 @chapter Portable Make Programming
20141 @prindex @command{make}
20142 @cindex Limitations of @command{make}
20144 Writing portable makefiles is an art.  Since a makefile's commands are
20145 executed by the shell, you must consider the shell portability issues
20146 already mentioned.  However, other issues are specific to @command{make}
20147 itself.
20149 @menu
20150 * $< in Ordinary Make Rules::   $< in ordinary rules
20151 * Failure in Make Rules::       Failing portably in rules
20152 * Special Chars in Names::      Special Characters in Macro Names
20153 * Backslash-Newline-Empty::     Empty lines after backslash-newline
20154 * Backslash-Newline Comments::  Spanning comments across line boundaries
20155 * Long Lines in Makefiles::     Line length limitations
20156 * Macros and Submakes::         @code{make macro=value} and submakes
20157 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
20158 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
20159 * Parallel Make::               Parallel @command{make} quirks
20160 * Comments in Make Rules::      Other problems with Make comments
20161 * Newlines in Make Rules::      Using literal newlines in rules
20162 * Comments in Make Macros::     Other problems with Make comments in macros
20163 * Trailing whitespace in Make Macros::  Macro substitution problems
20164 * Command-line Macros and whitespace::  Whitespace trimming of values
20165 * obj/ and Make::               Don't name a subdirectory @file{obj}
20166 * make -k Status::              Exit status of @samp{make -k}
20167 * VPATH and Make::              @code{VPATH} woes
20168 * Single Suffix Rules::         Single suffix rules and separated dependencies
20169 * Timestamps and Make::         Sub-second timestamp resolution
20170 @end menu
20172 @node $< in Ordinary Make Rules
20173 @section @code{$<} in Ordinary Make Rules
20175 Posix says that the @samp{$<} construct in makefiles can be
20176 used only in inference rules and in the @samp{.DEFAULT} rule; its
20177 meaning in ordinary rules is unspecified.  Solaris @command{make}
20178 for instance replaces it with the empty string.  OpenBSD (3.0 and
20179 later) @command{make} diagnoses these uses and errors out.
20181 @node Failure in Make Rules
20182 @section Failure in Make Rules
20184 Posix 2008 requires that @command{make} must invoke each command with
20185 the equivalent of a @samp{sh -e -c} subshell, which causes the
20186 subshell to exit immediately if a subsidiary simple-command fails,
20187 although not all @command{make} implementations have historically
20188 followed this rule.  For
20189 example, the command @samp{touch T; rm -f U} may attempt to
20190 remove @file{U} even if the @command{touch} fails, although this is not
20191 permitted with Posix make.  One way to work around failures in simple
20192 commands is to reword them so that they always succeed, e.g., @samp{touch
20193 T || :; rm -f U}.
20194 However, even this approach can run into common bugs in BSD
20195 implementations of the @option{-e} option of @command{sh} and
20196 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
20197 are worried
20198 about porting to buggy BSD shells it may be simpler to migrate
20199 complicated @command{make} actions into separate scripts.
20201 @node Special Chars in Names
20202 @section Special Characters in Make Macro Names
20204 Posix limits macro names to nonempty strings containing only
20205 ASCII letters and digits, @samp{.}, and @samp{_}.  Many
20206 @command{make} implementations allow a wider variety of characters, but
20207 portable makefiles should avoid them.  It is portable to start a name
20208 with a special character, e.g., @samp{$(.FOO)}.
20210 Some ancient @command{make} implementations don't support leading
20211 underscores in macro names.  An example is NEWS-OS 4.2R.
20213 @example
20214 $ @kbd{cat Makefile}
20215 _am_include = #
20216 _am_quote =
20217 all:; @@echo this is test
20218 $ @kbd{make}
20219 Make: Must be a separator on rules line 2.  Stop.
20220 $ @kbd{cat Makefile2}
20221 am_include = #
20222 am_quote =
20223 all:; @@echo this is test
20224 $ @kbd{make -f Makefile2}
20225 this is test
20226 @end example
20228 @noindent
20229 However, this problem is no longer of practical concern.
20231 @node Backslash-Newline-Empty
20232 @section Backslash-Newline Before Empty Lines
20234 A bug in Bash 2.03 can cause problems if a Make rule contains a
20235 backslash-newline followed by line that expands to nothing.
20236 For example, on Solaris 8:
20238 @example
20239 SHELL = /bin/bash
20240 EMPTY =
20241 foo:
20242         touch foo \
20243         $(EMPTY)
20244 @end example
20246 @noindent
20247 executes
20249 @example
20250 /bin/bash -c 'touch foo \
20252 @end example
20254 @noindent
20255 which fails with a syntax error, due to the Bash bug.  To avoid this
20256 problem, avoid nullable macros in the last line of a multi-line command.
20258 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
20259 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
20260 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
20261 On some versions of HP-UX, @command{make} reads multiple newlines
20262 following a backslash, continuing to the next non-empty line.  For
20263 example,
20265 @example
20266 FOO = one \
20268 BAR = two
20270 test:
20271         : FOO is "$(FOO)"
20272         : BAR is "$(BAR)"
20273 @end example
20275 @noindent
20276 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
20277 sensibly let a backslash continue only to the immediately following
20278 line.
20280 @node Backslash-Newline Comments
20281 @section Backslash-Newline in Make Comments
20283 According to Posix, Make comments start with @code{#}
20284 and continue until an unescaped newline is reached.
20286 @example
20287 $ @kbd{cat Makefile}
20288 # A = foo \
20289       bar \
20290       baz
20292 all:
20293         @@echo ok
20294 $ @kbd{make}   # GNU make
20296 @end example
20298 @noindent
20299 However this is not always the case.  Some implementations
20300 discard everything from @code{#} through the end of the line, ignoring any
20301 trailing backslash.
20303 @example
20304 $ @kbd{pmake}  # BSD make
20305 "Makefile", line 3: Need an operator
20306 Fatal errors encountered -- cannot continue
20307 @end example
20309 @noindent
20310 Therefore, if you want to comment out a multi-line definition, prefix each
20311 line with @code{#}, not only the first.
20313 @example
20314 # A = foo \
20315 #     bar \
20316 #     baz
20317 @end example
20319 @node Long Lines in Makefiles
20320 @section Long Lines in Makefiles
20322 Tru64 5.1's @command{make} has been reported to crash when given a
20323 makefile with lines longer than around 20 kB.  Earlier versions are
20324 reported to exit with @code{Line too long} diagnostics.
20326 @node Macros and Submakes
20327 @section @code{make macro=value} and Submakes
20329 A command-line variable definition such as @code{foo=bar} overrides any
20330 definition of @code{foo} in a makefile.  Some @command{make}
20331 implementations (such as GNU @command{make}) propagate this
20332 override to subsidiary invocations of @command{make}.  Some other
20333 implementations do not pass the substitution along to submakes.
20335 @example
20336 $ @kbd{cat Makefile}
20337 foo = foo
20338 one:
20339         @@echo $(foo)
20340         $(MAKE) two
20341 two:
20342         @@echo $(foo)
20343 $ @kbd{make foo=bar}            # GNU make 3.79.1
20345 make two
20346 make[1]: Entering directory `/home/adl'
20348 make[1]: Leaving directory `/home/adl'
20349 $ @kbd{pmake foo=bar}           # BSD make
20351 pmake two
20353 @end example
20355 You have a few possibilities if you do want the @code{foo=bar} override
20356 to propagate to submakes.  One is to use the @option{-e}
20357 option, which causes all environment variables to have precedence over
20358 the makefile macro definitions, and declare foo as an environment
20359 variable:
20361 @example
20362 $ @kbd{env foo=bar make -e}
20363 @end example
20365 The @option{-e} option is propagated to submakes automatically,
20366 and since the environment is inherited between @command{make}
20367 invocations, the @code{foo} macro is overridden in
20368 submakes as expected.
20370 This syntax (@code{foo=bar make -e}) is portable only when used
20371 outside of a makefile, for instance from a script or from the
20372 command line.  When run inside a @command{make} rule, GNU
20373 @command{make} 3.80 and prior versions forget to propagate the
20374 @option{-e} option to submakes.
20376 Moreover, using @option{-e} could have unexpected side effects if your
20377 environment contains some other macros usually defined by the
20378 makefile.  (See also the note about @code{make -e} and @code{SHELL}
20379 below.)
20381 If you can foresee all macros that a user might want to override, then
20382 you can propagate them to submakes manually, from your makefile:
20384 @example
20385 foo = foo
20386 one:
20387         @@echo $(foo)
20388         $(MAKE) foo=$(foo) two
20389 two:
20390         @@echo $(foo)
20391 @end example
20393 Another way to propagate a variable to submakes in a portable way is to
20394 expand an extra variable in every invocation of @samp{$(MAKE)} within
20395 your makefile:
20397 @example
20398 foo = foo
20399 one:
20400         @@echo $(foo)
20401         $(MAKE) $(SUBMAKEFLAGS) two
20402 two:
20403         @@echo $(foo)
20404 @end example
20406 Users must be aware that this technique is in use to take advantage of
20407 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
20408 allows any macro to be overridden.  Makefiles generated by
20409 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
20410 on the command lines of submakes (@pxref{Subdirectories, , Automake,
20411 automake, GNU Automake}).
20413 @node The Make Macro MAKEFLAGS
20414 @section The Make Macro MAKEFLAGS
20415 @cindex @code{MAKEFLAGS} and @command{make}
20416 @cindex @command{make} and @code{MAKEFLAGS}
20418 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
20419 current and recursive invocations of make, but allows implementations
20420 several formats for the variable.  It is tricky to parse
20421 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
20422 or @option{-k} for continued execution are in effect.  For example, you
20423 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
20424 contains single-letter options, since in the Cygwin version of
20425 GNU @command{make} it is either @option{--unix} or
20426 @option{--win32} with the second word containing single-letter options.
20428 @example
20429 $ @kbd{cat Makefile}
20430 all:
20431         @@echo MAKEFLAGS = $(MAKEFLAGS)
20432 $ @kbd{make}
20433 MAKEFLAGS = --unix
20434 $ @kbd{make -k}
20435 MAKEFLAGS = --unix -k
20436 @end example
20438 @node The Make Macro SHELL
20439 @section The Make Macro @code{SHELL}
20440 @cindex @code{SHELL} and @command{make}
20441 @cindex @command{make} and @code{SHELL}
20443 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
20444 macro to spawn shell processes and execute Make rules.  This
20445 is a builtin macro supplied by @command{make}, but it can be modified
20446 by a makefile or by a command-line argument.
20448 Not all @command{make} implementations define this @code{SHELL} macro.
20449 Tru64
20450 @command{make} is an example; this implementation always uses
20451 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
20452 your makefiles.  If you use Autoconf, do
20454 @example
20455 SHELL = @@SHELL@@
20456 @end example
20458 @noindent
20459 If you use Automake, this is done for you.
20461 Do not force @code{SHELL = /bin/sh} because that is not correct
20462 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
20463 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
20464 Additionally, DJGPP lacks @code{/bin/sh}, and when its
20465 GNU @command{make} port sees such a setting it enters a
20466 special emulation mode where features like pipes and redirections are
20467 emulated on top of DOS's @command{command.com}.  Unfortunately this
20468 emulation is incomplete; for instance it does not handle command
20469 substitutions.  Using @code{@@SHELL@@} means that your makefile will
20470 benefit from the same improved shell, such as @command{bash} or
20471 @command{ksh}, that was discovered during @command{configure}, so that
20472 you aren't fighting two different sets of shell bugs between the two
20473 contexts.
20475 Posix-compliant @command{make} should never acquire the value of
20476 $(SHELL) from the environment, even when @code{make -e} is used
20477 (otherwise, think about what would happen to your rules if
20478 @code{SHELL=/bin/tcsh}).
20480 However not all @command{make} implementations have this exception.
20481 For instance it's not surprising that Tru64 @command{make} doesn't
20482 protect @code{SHELL}, since it doesn't use it.
20484 @example
20485 $ @kbd{cat Makefile}
20486 SHELL = /bin/sh
20487 FOO = foo
20488 all:
20489         @@echo $(SHELL)
20490         @@echo $(FOO)
20491 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
20492 /bin/tcsh
20494 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
20495 /bin/sh
20497 @end example
20499 Conversely, @command{make} is not supposed to export any changes to the
20500 macro @code{SHELL} to child processes.  Again, many implementations
20501 break this rule:
20503 @example
20504 $ @kbd{cat Makefile}
20505 all:
20506         @@echo $(SHELL)
20507         @@printenv SHELL
20508 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
20509 /bin/ksh
20510 /bin/ksh
20511 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
20512 /bin/ksh
20514 @end example
20516 @node Parallel Make
20517 @section Parallel Make
20518 @cindex Parallel @command{make}
20520 Support for parallel execution in @command{make} implementation varies.
20521 Generally, using GNU make is your best bet.
20523 When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
20524 reuse the same shell for multiple commands within one recipe.  This can
20525 have various unexpected consequences.  For example, changes of directories
20526 or variables persist between recipes, so that:
20528 @example
20529 all:
20530         @@var=value; cd /; pwd; echo $$var; echo $$$$
20531         @@pwd; echo $$var; echo $$$$
20532 @end example
20534 @noindent
20535 may output the following with @code{make -j1}, at least on NetBSD up to
20536 5.1 and FreeBSD up to 8.2:
20538 @example
20540 value
20541 32235
20543 value
20544 32235
20545 @end example
20547 @noindent
20548 while without @option{-j1}, or with @option{-B}, the output looks less
20549 surprising:
20551 @example
20553 value
20554 32238
20555 /tmp
20557 32239
20558 @end example
20560 @noindent
20561 Another consequence is that, if one command in a recipe uses @code{exit 0}
20562 to indicate a successful exit, the shell will be gone and the remaining
20563 commands of this recipe will not be executed.
20565 The BSD @command{make} implementations, when run in parallel mode,
20566 will also pass the @command{Makefile} recipes to the shell through
20567 its standard input, thus making it unusable from the recipes:
20569 @example
20570 $ @kbd{cat Makefile}
20571 read:
20572         @@read line; echo LINE: $$line
20573 @c $$ @c restore font-lock
20574 $ @kbd{echo foo | make read}
20575 LINE: foo
20576 $ @kbd{echo foo | make -j1 read} # NetBSD 5.1 and FreeBSD 8.2
20577 LINE:
20578 @end example
20580 @noindent
20581 Moreover, when FreeBSD @command{make} (up at least to 8.2) is run in
20582 parallel mode, it implements the @code{@@} and @code{-} ``recipe
20583 modifiers'' by dynamically modifying the active shell flags.  This
20584 behavior has the effects of potentially clobbering the exit status
20585 of recipes silenced with the @code{@@} modifier if they also unset
20586 the @option{errexit} shell flag, and of mangling the output in
20587 unexpected ways:
20589 @example
20590 $ @kbd{cat Makefile}
20592         @@echo $$-; set +e; false
20594         -echo $$-; false; echo set -
20595 $ @kbd{make a; echo status: $?}
20596 ehBc
20597 *** Error code 1
20598 status: 1
20599 $ @kbd{make -j1 a; echo status: $?}
20601 status: 0
20602 $ @kbd{make b}
20603 echo $-; echo set -
20605 set -
20606 $ @kbd{make -j1 b}
20607 echo $-; echo hvB
20608 @end example
20610 @noindent
20611 You can avoid all these issues by using the @option{-B} option to enable
20612 compatibility semantics.  However, that will effectively also disable
20613 all parallelism as that will cause prerequisites to be updated in the
20614 order they are listed in a rule.
20616 Some make implementations (among them, FreeBSD @command{make}, NetBSD
20617 @command{make}, and Solaris @command{dmake}), when invoked with a
20618 @option{-j@var{N}} option, connect the standard output and standard
20619 error of all their child processes to pipes or temporary regular
20620 files.  This can lead to subtly different semantics in the behavior
20621 of the spawned processes.  For example, even if the @command{make}
20622 standard output is connected to a tty, the recipe command will not be:
20624 @example
20625 $ @kbd{cat Makefile}
20626 all:
20627         @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
20628 $ @kbd{make -j 2} # FreeBSD 8.2 make
20629 Is not a tty
20630 $ @kbd{make -j 2} # NetBSD 5.1 make
20631 --- all ---
20632 Is not a tty
20633 $ @kbd{dmake -j 2} # Solaris 10 dmake
20634 @var{hostname} --> 1 job
20635 @var{hostname} --> Job output
20636 Is not a tty
20637 @end example
20639 @noindent
20640 On the other hand:
20642 @example
20643 $ @kbd{make -j 2} # GNU make, Heirloom make
20644 Is a tty
20645 @end example
20647 @noindent
20648 The above examples also show additional status output produced in parallel
20649 mode for targets being updated by Solaris @command{dmake} and NetBSD
20650 @command{make} (but @emph{not} by FreeBSD @command{make}).
20652 Furthermore, parallel runs of those @command{make} implementations will
20653 route standard error from commands that they spawn into their own
20654 standard output, and may remove leading whitespace from output lines.
20657 @node Comments in Make Rules
20658 @section Comments in Make Rules
20659 @cindex Comments in @file{Makefile} rules
20660 @cindex @file{Makefile} rules and comments
20662 Never put comments in a rule.
20664 Some @command{make} treat anything starting with a tab as a command for
20665 the current rule, even if the tab is immediately followed by a @code{#}.
20666 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
20667 makefile runs @code{# foo} through the shell.
20669 @example
20670 all:
20671         # foo
20672 @end example
20674 As a workaround, you can use the @command{:} no-op command with a string
20675 argument that gets ignored:
20677 @example
20678 all:
20679         : "foo"
20680 @end example
20682 Conversely, if you want to use the @samp{#} character in some command,
20683 you can only do so by expanding it inside a rule (@pxref{Comments in
20684 Make Macros}).  So for example, if @samp{COMMENT_CHAR} is substituted by
20685 @command{config.status} as @samp{#}, then the following substitutes
20686 @samp{@@COMMENT_CHAR@@} in a generated header:
20688 @example
20689 foo.h: foo.h.in
20690         sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
20691             $(srcdir)/foo.h.in > $@@
20692 @end example
20694 The funny shell quoting avoids a substitution at @command{config.status}
20695 run time of the left-hand side of the @command{sed} @samp{s} command.
20697 @node Newlines in Make Rules
20698 @section Newlines in Make Rules
20699 @cindex Newlines in @file{Makefile} rules
20700 @cindex @file{Makefile} rules and newlines
20702 In shell scripts, newlines can be used inside string literals.  But in
20703 the shell statements of @file{Makefile} rules, this is not possible:
20704 A newline not preceded by a backslash is a separator between shell
20705 statements.  Whereas a newline that is preceded by a backslash becomes
20706 part of the shell statement according to POSIX, but gets replaced,
20707 together with the backslash that precedes it, by a space in GNU
20708 @command{make} 3.80 and older.  So, how can a newline be used in a string
20709 literal?
20711 The trick is to set up a shell variable that contains a newline:
20713 @example
20714 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"
20715 @end example
20717 For example, in order to create a multi-line @samp{sed} expression that
20718 inserts a blank line after every line of a file, this code can be used:
20720 @example
20721 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"; \
20722 sed -e "s/\$$/\\$$@{nl@}/" < input > output
20723 @end example
20725 @node Comments in Make Macros
20726 @section Comments in Make Macros
20727 @cindex Comments in @file{Makefile} macros
20728 @cindex @file{Makefile} macros and comments
20730 Avoid putting comments in macro values as far as possible.  Posix
20731 specifies that the text starting from the @samp{#} sign until the end of
20732 the line is to be ignored, which has the unfortunate effect of
20733 disallowing them even within quotes.  Thus, the following might lead to
20734 a syntax error at compile time:
20736 @example
20737 CPPFLAGS = "-DCOMMENT_CHAR='#'"
20738 @end example
20740 @noindent
20741 as @samp{CPPFLAGS} may be expanded to @samp{"-DCOMMENT_CHAR='}.
20743 Most @command{make} implementations disregard this and treat single and
20744 double quotes specially here.  Also, GNU @command{make} lets you put
20745 @samp{#} into a macro value by escaping it with a backslash, i.e.,
20746 @samp{\#}.  However, neither of these usages are portable.
20747 @xref{Comments in Make Rules}, for a portable alternative.
20749 Even without quoting involved, comments can have surprising effects,
20750 because the whitespace before them is part of the variable value:
20752 @example
20753 foo = bar # trailing comment
20754 print: ; @@echo "$(foo)."
20755 @end example
20757 @noindent
20758 prints @samp{bar .}, which is usually not intended, and can expose
20759 @command{make} bugs as described below.
20761 @node Trailing whitespace in Make Macros
20762 @section Trailing whitespace in Make Macros
20763 @cindex whitespace in @file{Makefile} macros
20764 @cindex @file{Makefile} macros and whitespace
20766 GNU @command{make} 3.80 mistreats trailing whitespace in macro
20767 substitutions and appends another spurious suffix:
20769 @example
20770 empty =
20771 foo = bar $(empty)
20772 print: ; @@echo $(foo:=.test)
20773 @end example
20775 @noindent
20776 prints @samp{bar.test .test}.
20778 BSD and Solaris @command{make} implementations do not honor trailing
20779 whitespace in macro definitions as Posix requires:
20781 @example
20782 foo = bar # Note the space after "bar".
20783 print: ; @@echo $(foo)t
20784 @end example
20786 @noindent
20787 prints @samp{bart} instead of @samp{bar t}.  To work around this, you
20788 can use a helper macro as in the previous example.
20791 @node Command-line Macros and whitespace
20792 @section Command-line Macros and whitespace
20793 @cindex whitespace in command-line macros
20794 @cindex command-line, macros set on
20795 @cindex environment, macros set from
20797 Some @command{make} implementations may strip trailing whitespace off
20798 of macros set on the command line in addition to leading whitespace.
20799 Further, some may strip leading whitespace off of macros set from
20800 environment variables:
20802 @example
20803 $ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
20804   foo=' f f ' make -f - bar=' b b '}
20805 x f f xb b x  # AIX, BSD, GNU make
20806 xf f xb b x   # HP-UX, IRIX, Tru64/OSF make
20807 x f f xb bx   # Solaris make
20808 @end example
20811 @node obj/ and Make
20812 @section The @file{obj/} Subdirectory and Make
20813 @cindex @file{obj/}, subdirectory
20814 @cindex BSD @command{make} and @file{obj/}
20816 Never name one of your subdirectories @file{obj/} if you don't like
20817 surprises.
20819 If an @file{obj/} directory exists, BSD @command{make} enters it
20820 before reading the makefile.  Hence the makefile in the
20821 current directory is not read.
20823 @example
20824 $ @kbd{cat Makefile}
20825 all:
20826         echo Hello
20827 $ @kbd{cat obj/Makefile}
20828 all:
20829         echo World
20830 $ @kbd{make}      # GNU make
20831 echo Hello
20832 Hello
20833 $ @kbd{pmake}     # BSD make
20834 echo World
20835 World
20836 @end example
20838 @node make -k Status
20839 @section Exit Status of @code{make -k}
20840 @cindex @code{make -k}
20842 Do not rely on the exit status of @code{make -k}.  Some implementations
20843 reflect whether they encountered an error in their exit status; other
20844 implementations always succeed.
20846 @example
20847 $ @kbd{cat Makefile}
20848 all:
20849         false
20850 $ @kbd{make -k; echo exit status: $?}    # GNU make
20851 false
20852 make: *** [all] Error 1
20853 exit status: 2
20854 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
20855 false
20856 *** Error code 1 (continuing)
20857 exit status: 0
20858 @end example
20860 @node VPATH and Make
20861 @section @code{VPATH} and Make
20862 @cindex @code{VPATH}
20864 Posix does not specify the semantics of @code{VPATH}.  Typically,
20865 @command{make} supports @code{VPATH}, but its implementation is not
20866 consistent.
20868 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
20869 portable to recent-enough popular implementations of @command{make}, but
20870 to keep the resulting makefiles portable, a package's makefile
20871 prototypes must take the following issues into account.  These issues
20872 are complicated and are often poorly understood, and installers who use
20873 @code{VPATH} should expect to find many bugs in this area.  If you use
20874 @code{VPATH}, the simplest way to avoid these portability bugs is to
20875 stick with GNU @command{make}, since it is the most
20876 commonly-used @command{make} among Autoconf users.
20878 Here are some known issues with some @code{VPATH}
20879 implementations.
20881 @menu
20882 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
20883 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
20884 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
20885 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
20886 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
20887 * Make Target Lookup::          More details about @code{VPATH} lookup
20888 @end menu
20890 @node Variables listed in VPATH
20891 @subsection Variables listed in @code{VPATH}
20892 @cindex @code{VPATH} and variables
20893 @cindex variables and @code{VPATH}
20895 Do not set @code{VPATH} to the value of another variable, for example
20896 @samp{VPATH = $(srcdir)}, because some ancient versions of
20897 @command{make} do not do variable substitutions on the value of
20898 @code{VPATH}.  For example, use this
20900 @example
20901 srcdir = @@srcdir@@
20902 VPATH = @@srcdir@@
20903 @end example
20905 @noindent
20906 rather than @samp{VPATH = $(srcdir)}.  Note that with GNU
20907 Automake, there is no need to set this yourself.
20909 @node VPATH and Double-colon
20910 @subsection @code{VPATH} and Double-colon Rules
20911 @cindex @code{VPATH} and double-colon rules
20912 @cindex double-colon rules and @code{VPATH}
20914 With ancient versions of Sun @command{make},
20915 any assignment to @code{VPATH} causes @command{make} to execute only
20916 the first set of double-colon rules.
20917 However, this problem is no longer of practical concern.
20919 @node $< in Explicit Rules
20920 @subsection @code{$<} Not Supported in Explicit Rules
20921 @cindex explicit rules, @code{$<}, and @code{VPATH}
20922 @cindex @code{$<}, explicit rules, and @code{VPATH}
20923 @cindex @code{VPATH}, explicit rules, and @code{$<}
20925 Using @code{$<} in explicit rules is not portable.
20926 The prerequisite file must be named explicitly in the rule.  If you want
20927 to find the prerequisite via a @code{VPATH} search, you have to code the
20928 whole thing manually.  @xref{Build Directories}.
20930 @node Automatic Rule Rewriting
20931 @subsection Automatic Rule Rewriting
20932 @cindex @code{VPATH} and automatic rule rewriting
20933 @cindex automatic rule rewriting and @code{VPATH}
20935 Some @command{make} implementations, such as Solaris and Tru64,
20936 search for prerequisites in @code{VPATH} and
20937 then rewrite each occurrence as a plain word in the rule.
20938 For instance:
20940 @example
20941 # This isn't portable to GNU make.
20942 VPATH = ../pkg/src
20943 f.c: if.c
20944         cp if.c f.c
20945 @end example
20947 @noindent
20948 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
20949 found in @file{../pkg/src}.
20951 However, this rule leads to real problems in practice.  For example, if
20952 the source directory contains an ordinary file named @file{test} that is
20953 used in a dependency, Solaris @command{make} rewrites commands like
20954 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
20955 @dots{}}, which is typically undesirable.  In fact, @command{make} is
20956 completely unaware of shell syntax used in the rules, so the VPATH
20957 rewrite can potentially apply to @emph{any} whitespace-separated word
20958 in a rule, including shell variables, functions, and keywords.
20960 @example
20961 $ @kbd{mkdir build}
20962 $ @kbd{cd build}
20963 $ @kbd{cat > Makefile <<'END'}
20964 VPATH = ..
20965 all: arg func for echo
20966         func () @{ for arg in "$$@@"; do echo $$arg; done; @}; \
20967         func "hello world"
20969 $ @kbd{touch ../arg ../func ../for ../echo}
20970 $ @kbd{make}
20971 ../func () @{ ../for ../arg in "$@@"; do ../echo $arg; done; @}; \
20972 ../func "hello world"
20973 sh: syntax error at line 1: `do' unexpected
20974 *** Error code 2
20975 @end example
20977 @noindent
20978 To avoid this problem, portable makefiles should never mention a source
20979 file or dependency whose name is that of a shell keyword like @file{for}
20980 or @file{until}, a shell command like @command{cat} or @command{gcc} or
20981 @command{test}, or a shell function or variable used in the corresponding
20982 @command{Makefile} recipe.
20984 Because of these problems GNU @command{make} and many other @command{make}
20985 implementations do not rewrite commands, so portable makefiles should
20986 search @code{VPATH} manually.  It is tempting to write this:
20988 @smallexample
20989 # This isn't portable to Solaris make.
20990 VPATH = ../pkg/src
20991 f.c: if.c
20992         cp `test -f if.c || echo $(VPATH)/`if.c f.c
20993 @end smallexample
20995 @noindent
20996 However, the ``prerequisite rewriting'' still applies here.  So if
20997 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
20998 execute
21000 @smallexample
21001 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
21002 @end smallexample
21004 @noindent
21005 which reduces to
21007 @example
21008 cp if.c f.c
21009 @end example
21011 @noindent
21012 and thus fails.  Oops.
21014 A simple workaround, and good practice anyway, is to use @samp{$?} and
21015 @samp{$@@} when possible:
21017 @smallexample
21018 VPATH = ../pkg/src
21019 f.c: if.c
21020         cp $? $@@
21021 @end smallexample
21023 @noindent
21024 but this does not generalize well to commands with multiple
21025 prerequisites.  A more general workaround is to rewrite the rule so that
21026 the prerequisite @file{if.c} never appears as a plain word.  For
21027 example, these three rules would be safe, assuming @file{if.c} is in
21028 @file{../pkg/src} and the other files are in the working directory:
21030 @smallexample
21031 VPATH = ../pkg/src
21032 f.c: if.c f1.c
21033         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
21034 g.c: if.c g1.c
21035         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
21036 h.c: if.c h1.c
21037         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
21038 @end smallexample
21040 Things get worse when your prerequisites are in a macro.
21042 @example
21043 VPATH = ../pkg/src
21044 HEADERS = f.h g.h h.h
21045 install-HEADERS: $(HEADERS)
21046         for i in $(HEADERS); do \
21047           $(INSTALL) -m 644 \
21048             `test -f $$i || echo $(VPATH)/`$$i \
21049             $(DESTDIR)$(includedir)/$$i; \
21050 @c $$ restore font-lock
21051         done
21052 @end example
21054 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
21055 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
21056 where @code{f.h} and @code{g.h} are plain words and are hence
21057 subject to @code{VPATH} adjustments.
21059 If the three files are in @file{../pkg/src}, the rule is run as:
21061 @example
21062 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
21063   install -m 644 \
21064      `test -f $i || echo ../pkg/src/`$i \
21065      /usr/local/include/$i; \
21066 done
21067 @end example
21069 where the two first @command{install} calls fail.  For instance,
21070 consider the @code{f.h} installation:
21072 @example
21073 install -m 644 \
21074   `test -f ../pkg/src/f.h || \
21075     echo ../pkg/src/ \
21076   `../pkg/src/f.h \
21077   /usr/local/include/../pkg/src/f.h;
21078 @end example
21080 @noindent
21081 It reduces to:
21083 @example
21084 install -m 644 \
21085   ../pkg/src/f.h \
21086   /usr/local/include/../pkg/src/f.h;
21087 @end example
21089 Note that the manual @code{VPATH} search did not cause any problems here;
21090 however this command installs @file{f.h} in an incorrect directory.
21092 Trying to quote @code{$(HEADERS)} in some way, as we did for
21093 @code{foo.c} a few makefiles ago, does not help:
21095 @example
21096 install-HEADERS: $(HEADERS)
21097         headers='$(HEADERS)'; \
21098         for i in $$headers; do \
21099           $(INSTALL) -m 644 \
21100             `test -f $$i || echo $(VPATH)/`$$i \
21101             $(DESTDIR)$(includedir)/$$i; \
21102         done
21103 @end example
21105 Now, @code{headers='$(HEADERS)'} macro-expands to:
21107 @example
21108 headers='f.h g.h h.h'
21109 @end example
21111 @noindent
21112 but @code{g.h} is still a plain word.  (As an aside, the idiom
21113 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
21114 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
21115 syntax error on @code{for i in;}.)
21117 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
21119 @example
21120 VPATH = ../pkg/src
21121 HEADERS = f.h g.h h.h
21122 install-HEADERS: $(HEADERS)
21123         headers='$(HEADERS)'; \
21124         for i in $$headers; do \
21125           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
21126           $(INSTALL) -m 644 \
21127             `test -f $$i || echo $(VPATH)/`$$i \
21128             $(DESTDIR)$(includedir)/$$i; \
21129 @c $$ restore font-lock
21130         done
21131 @end example
21133 Automake does something similar.  However the above hack works only if
21134 the files listed in @code{HEADERS} are in the current directory or a
21135 subdirectory; they should not be in an enclosing directory.  If we had
21136 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
21137 build with Tru64 @command{make}.  The reason is that not only does
21138 Tru64 @command{make} rewrite dependencies, but it also simplifies
21139 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
21140 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
21141 a leading @file{../pkg/src/} component.
21143 The following example makes the behavior of Tru64 @command{make}
21144 more apparent.
21146 @example
21147 $ @kbd{cat Makefile}
21148 VPATH = sub
21149 all: ../foo
21150         echo ../foo
21151 $ @kbd{ls}
21152 Makefile foo
21153 $ @kbd{make}
21154 echo foo
21156 @end example
21158 @noindent
21159 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
21160 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
21161 directory does not even exist, this just means that the simplification
21162 occurred before the file was checked for.)
21164 For the record here is how SunOS 4 @command{make} behaves on this
21165 example.
21167 @smallexample
21168 $ @kbd{make}
21169 make: Fatal error: Don't know how to make target `../foo'
21170 $ @kbd{mkdir sub}
21171 $ @kbd{make}
21172 echo sub/../foo
21173 sub/../foo
21174 @end smallexample
21177 @node Tru64 Directory Magic
21178 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
21179 @cindex @code{VPATH} and prerequisite directories
21180 @cindex prerequisite directories and @code{VPATH}
21182 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
21183 @command{make} creates it in the current directory.
21185 @example
21186 $ @kbd{mkdir -p foo/bar build}
21187 $ @kbd{cd build}
21188 $ @kbd{cat >Makefile <<END
21189 VPATH = ..
21190 all: foo/bar
21191 END}
21192 $ @kbd{make}
21193 mkdir foo
21194 mkdir foo/bar
21195 @end example
21197 This can yield unexpected results if a rule uses a manual @code{VPATH}
21198 search as presented before.
21200 @example
21201 VPATH = ..
21202 all : foo/bar
21203         command `test -d foo/bar || echo ../`foo/bar
21204 @end example
21206 The above @command{command} is run on the empty @file{foo/bar}
21207 directory that was created in the current directory.
21209 @node Make Target Lookup
21210 @subsection Make Target Lookup
21211 @cindex @code{VPATH}, resolving target pathnames
21213 GNU @command{make} uses a complex algorithm to decide when it
21214 should use files found via a @code{VPATH} search.  @xref{Search
21215 Algorithm, , How Directory Searches are Performed, make, The GNU Make
21216 Manual}.
21218 If a target needs to be rebuilt, GNU @command{make} discards the
21219 file name found during the @code{VPATH} search for this target, and
21220 builds the file locally using the file name given in the makefile.
21221 If a target does not need to be rebuilt, GNU @command{make} uses the
21222 file name found during the @code{VPATH} search.
21224 Other @command{make} implementations, like NetBSD @command{make}, are
21225 easier to describe: the file name found during the @code{VPATH} search
21226 is used whether the target needs to be rebuilt or not.  Therefore
21227 new files are created locally, but existing files are updated at their
21228 @code{VPATH} location.
21230 OpenBSD and FreeBSD @command{make}, however,
21231 never perform a
21232 @code{VPATH} search for a dependency that has an explicit rule.
21233 This is extremely annoying.
21235 When attempting a @code{VPATH} build for an autoconfiscated package
21236 (e.g., @code{mkdir build && cd build && ../configure}), this means
21238 @command{make} builds everything locally in the @file{build}
21239 directory, while BSD @command{make} builds new files locally and
21240 updates existing files in the source directory.
21242 @example
21243 $ @kbd{cat Makefile}
21244 VPATH = ..
21245 all: foo.x bar.x
21246 foo.x bar.x: newer.x
21247         @@echo Building $@@
21248 $ @kbd{touch ../bar.x}
21249 $ @kbd{touch ../newer.x}
21250 $ @kbd{make}        # GNU make
21251 Building foo.x
21252 Building bar.x
21253 $ @kbd{pmake}       # NetBSD make
21254 Building foo.x
21255 Building ../bar.x
21256 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21257 Building foo.x
21258 Building bar.x
21259 $ @kbd{tmake}       # Tru64 make
21260 Building foo.x
21261 Building bar.x
21262 $ @kbd{touch ../bar.x}
21263 $ @kbd{make}        # GNU make
21264 Building foo.x
21265 $ @kbd{pmake}       # NetBSD make
21266 Building foo.x
21267 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21268 Building foo.x
21269 Building bar.x
21270 $ @kbd{tmake}       # Tru64 make
21271 Building foo.x
21272 Building bar.x
21273 @end example
21275 Note how NetBSD @command{make} updates @file{../bar.x} in its
21276 VPATH location, and how FreeBSD, OpenBSD, and Tru64
21277 @command{make} always
21278 update @file{bar.x}, even when @file{../bar.x} is up to date.
21280 Another point worth mentioning is that once GNU @command{make} has
21281 decided to ignore a @code{VPATH} file name (e.g., it ignored
21282 @file{../bar.x} in the above example) it continues to ignore it when
21283 the target occurs as a prerequisite of another rule.
21285 The following example shows that GNU @command{make} does not look up
21286 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
21287 because it ignored the @code{VPATH} result of @file{bar.x} while running
21288 the @code{bar.x: newer.x} rule.
21290 @example
21291 $ @kbd{cat Makefile}
21292 VPATH = ..
21293 all: bar.y
21294 bar.x: newer.x
21295         @@echo Building $@@
21296 .SUFFIXES: .x .y
21297 .x.y:
21298         cp $< $@@
21299 $ @kbd{touch ../bar.x}
21300 $ @kbd{touch ../newer.x}
21301 $ @kbd{make}        # GNU make
21302 Building bar.x
21303 cp bar.x bar.y
21304 cp: cannot stat `bar.x': No such file or directory
21305 make: *** [bar.y] Error 1
21306 $ @kbd{pmake}       # NetBSD make
21307 Building ../bar.x
21308 cp ../bar.x bar.y
21309 $ @kbd{rm bar.y}
21310 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21311 echo Building bar.x
21312 cp bar.x bar.y
21313 cp: cannot stat `bar.x': No such file or directory
21314 *** Error code 1
21315 $ @kbd{tmake}       # Tru64 make
21316 Building bar.x
21317 cp: bar.x: No such file or directory
21318 *** Exit 1
21319 @end example
21321 Note that if you drop away the command from the @code{bar.x: newer.x}
21322 rule, GNU @command{make} magically starts to work: it
21323 knows that @code{bar.x} hasn't been updated, therefore it doesn't
21324 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
21325 uses.  Tru64 also works, but FreeBSD and OpenBSD
21326 still don't.
21328 @example
21329 $ @kbd{cat Makefile}
21330 VPATH = ..
21331 all: bar.y
21332 bar.x: newer.x
21333 .SUFFIXES: .x .y
21334 .x.y:
21335         cp $< $@@
21336 $ @kbd{touch ../bar.x}
21337 $ @kbd{touch ../newer.x}
21338 $ @kbd{make}        # GNU make
21339 cp ../bar.x bar.y
21340 $ @kbd{rm bar.y}
21341 $ @kbd{pmake}       # NetBSD make
21342 cp ../bar.x bar.y
21343 $ @kbd{rm bar.y}
21344 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21345 cp bar.x bar.y
21346 cp: cannot stat `bar.x': No such file or directory
21347 *** Error code 1
21348 $ @kbd{tmake}       # Tru64 make
21349 cp ../bar.x bar.y
21350 @end example
21352 It seems the sole solution that would please every @command{make}
21353 implementation is to never rely on @code{VPATH} searches for targets.
21354 In other words, @code{VPATH} should be reserved to sources that are not built.
21357 @node Single Suffix Rules
21358 @section Single Suffix Rules and Separated Dependencies
21359 @cindex Single Suffix Inference Rule
21360 @cindex Rule, Single Suffix Inference
21361 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
21362 (@samp{.from.to:}), but which @emph{destination} suffix is empty
21363 (@samp{.from:}).
21365 @cindex Separated Dependencies
21366 @dfn{Separated dependencies} simply refers to listing the prerequisite
21367 of a target, without defining a rule.  Usually one can list on the one
21368 hand side, the rules, and on the other hand side, the dependencies.
21370 Solaris @command{make} does not support separated dependencies for
21371 targets defined by single suffix rules:
21373 @example
21374 $ @kbd{cat Makefile}
21375 .SUFFIXES: .in
21376 foo: foo.in
21377 .in:
21378         cp $< $@@
21379 $ @kbd{touch foo.in}
21380 $ @kbd{make}
21381 $ @kbd{ls}
21382 Makefile  foo.in
21383 @end example
21385 @noindent
21386 while GNU Make does:
21388 @example
21389 $ @kbd{gmake}
21390 cp foo.in foo
21391 $ @kbd{ls}
21392 Makefile  foo       foo.in
21393 @end example
21395 Note it works without the @samp{foo: foo.in} dependency.
21397 @example
21398 $ @kbd{cat Makefile}
21399 .SUFFIXES: .in
21400 .in:
21401         cp $< $@@
21402 $ @kbd{make foo}
21403 cp foo.in foo
21404 @end example
21406 @noindent
21407 and it works with double suffix inference rules:
21409 @example
21410 $ @kbd{cat Makefile}
21411 foo.out: foo.in
21412 .SUFFIXES: .in .out
21413 .in.out:
21414         cp $< $@@
21415 $ @kbd{make}
21416 cp foo.in foo.out
21417 @end example
21419 As a result, in such a case, you have to write target rules.
21421 @node Timestamps and Make
21422 @section Timestamp Resolution and Make
21423 @cindex timestamp resolution
21424 Traditionally, file timestamps had 1-second resolution, and
21425 @command{make} used those timestamps to determine whether one file was
21426 newer than the other.  However, many modern file systems have
21427 timestamps with 1-nanosecond resolution.  Some @command{make}
21428 implementations look at the entire timestamp; others ignore the
21429 fractional part, which can lead to incorrect results.  Normally this
21430 is not a problem, but in some extreme cases you may need to use tricks
21431 like @samp{sleep 1} to work around timestamp truncation bugs.
21433 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
21434 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
21435 Tools}).  Hence you should be wary of rules like this:
21437 @example
21438 dest: src
21439         cp -p src dest
21440 @end example
21442 as @file{dest} often appears to be older than @file{src} after the
21443 timestamp is truncated, and this can cause @command{make} to do
21444 needless rework the next time it is invoked.  To work around this
21445 problem, you can use a timestamp file, e.g.:
21447 @example
21448 dest-stamp: src
21449         cp -p src dest
21450         date >dest-stamp
21451 @end example
21453 Apart from timestamp resolution, there are also differences in handling
21454 equal timestamps.  HP-UX @command{make} updates targets if it has the
21455 same timestamp as one of its prerequisites, in violation of Posix rules.
21457 This can cause spurious rebuilds for repeated runs of @command{make}.
21458 This in turn can cause @command{make} to fail if it tries to rebuild
21459 generated files in a possibly read-only source tree with tools not
21460 present on the end-user machine.  Use GNU @command{make} instead.
21464 @c ======================================== Portable C and C++ Programming
21466 @node Portable C and C++
21467 @chapter Portable C and C++ Programming
21468 @cindex Portable C and C++ programming
21470 C and C++ programs often use low-level features of the underlying
21471 system, and therefore are often more difficult to make portable to other
21472 platforms.
21474 Several standards have been developed to help make your programs more
21475 portable.  If you write programs with these standards in mind, you can
21476 have greater confidence that your programs work on a wide variety
21477 of systems.
21478 @ifhtml
21479 @uref{https://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
21480 Standards Supported by GCC}
21481 @end ifhtml
21482 @ifnothtml
21483 @xref{Standards, , Language Standards Supported by
21484 GCC, gcc, Using the GNU Compiler Collection
21485 (GCC)},
21486 @end ifnothtml
21487 for a list of C-related standards.  Many programs also assume the
21488 @uref{https://@/en.wikipedia.org/@/wiki/@/POSIX, Posix standard}.
21490 Some old code is written to be portable to K&R C, which predates any C
21491 standard.  K&R C compilers are no longer of practical interest, though,
21492 and the rest of section assumes at least C89, the first C standard.
21494 Program portability is a huge topic, and this section can only briefly
21495 introduce common pitfalls.  @xref{System Portability, , Portability
21496 between System Types, standards, The GNU Coding Standards}, for
21497 more information.
21499 @menu
21500 * Varieties of Unportability::  How to make your programs unportable
21501 * Integer Overflow::            When integers get too large
21502 * Preprocessor Arithmetic::     @code{#if} expression problems
21503 * Null Pointers::               Properties of null pointers
21504 * Buffer Overruns::             Subscript errors and the like
21505 * Volatile Objects::            @code{volatile} and signals
21506 * Floating Point Portability::  Portable floating-point arithmetic
21507 * Exiting Portably::            Exiting and the exit status
21508 @end menu
21510 @node Varieties of Unportability
21511 @section Varieties of Unportability
21512 @cindex portability
21514 Autoconf tests and ordinary programs often need to test what is allowed
21515 on a system, and therefore they may need to deliberately exceed the
21516 boundaries of what the standards allow, if only to see whether an
21517 optional feature is present.  When you write such a program, you should
21518 keep in mind the difference between constraints, unspecified behavior,
21519 and undefined behavior.
21521 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
21522 example constraint is that C programs must not declare a bit-field with
21523 negative width.  Tests can therefore reliably assume that programs with
21524 negative-width bit-fields are rejected by a compiler that conforms
21525 to the standard.
21527 @dfn{Unspecified behavior} is valid behavior, where the standard allows
21528 multiple possibilities.  For example, the order of evaluation of
21529 function arguments is unspecified.  Some unspecified behavior is
21530 @dfn{implementation-defined}, i.e., documented by the implementation,
21531 but since Autoconf tests cannot read the documentation they cannot
21532 distinguish between implementation-defined and other unspecified
21533 behavior.  It is common for Autoconf tests to probe implementations to
21534 determine otherwise-unspecified behavior.
21536 @dfn{Undefined behavior} is invalid behavior, where the standard allows
21537 the implementation to do anything it pleases.  For example,
21538 dereferencing a null pointer leads to undefined behavior.  If possible,
21539 test programs should avoid undefined behavior, since a program with
21540 undefined behavior might succeed on a test that should fail.
21542 The above rules apply to programs that are intended to conform to the
21543 standard.  However, strictly-conforming programs are quite rare, since
21544 the standards are so limiting.  A major goal of Autoconf is to support
21545 programs that use implementation features not described by the standard,
21546 and it is fairly common for test programs to violate the above rules, if
21547 the programs work well enough in practice.
21549 @node Integer Overflow
21550 @section Integer Overflow
21551 @cindex integer overflow
21552 @cindex overflow, signed integer
21553 @cindex signed integer overflow
21554 @cindex wraparound arithmetic
21556 In practice many portable C programs assume that signed integer overflow wraps
21557 around reliably using two's complement arithmetic.  Yet the C standard
21558 says that program behavior is undefined on overflow, and in a few cases
21559 C programs do not work on some modern implementations because their
21560 overflows do not wrap around as their authors expected.  Conversely, in
21561 signed integer remainder, the C standard requires overflow
21562 behavior that is commonly not implemented.
21564 @menu
21565 * Integer Overflow Basics::     Why integer overflow is a problem
21566 * Signed Overflow Examples::    Examples of code assuming wraparound
21567 * Optimization and Wraparound::  Optimizations that break uses of wraparound
21568 * Signed Overflow Advice::      Practical advice for signed overflow issues
21569 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
21570 @end menu
21572 @node Integer Overflow Basics
21573 @subsection Basics of Integer Overflow
21574 @cindex integer overflow
21575 @cindex overflow, signed integer
21576 @cindex signed integer overflow
21577 @cindex wraparound arithmetic
21579 In languages like C, unsigned integer overflow reliably wraps around;
21580 e.g., @code{UINT_MAX + 1} yields zero.
21581 This is guaranteed by the C standard and is
21582 portable in practice, unless you specify aggressive,
21583 nonstandard optimization options
21584 suitable only for special applications.
21586 In contrast, the C standard says that signed integer overflow leads to
21587 undefined behavior where a program can do anything, including dumping
21588 core or overrunning a buffer.  The misbehavior can even precede the
21589 overflow.  Such an overflow can occur during addition, subtraction,
21590 multiplication, division, and left shift.
21592 Despite this requirement of the standard, many C programs and Autoconf
21593 tests assume that signed integer overflow silently wraps around modulo a
21594 power of two, using two's complement arithmetic, so long as you cast the
21595 resulting value to a signed integer type or store it into a signed
21596 integer variable.  If you use conservative optimization flags, such
21597 programs are generally portable to the vast majority of modern
21598 platforms, with a few exceptions discussed later.
21600 For historical reasons the C standard also allows implementations with
21601 ones' complement or signed magnitude arithmetic, but it is safe to
21602 assume two's complement nowadays.
21604 Also, overflow can occur when converting an out-of-range value to a
21605 signed integer type.  Here a standard implementation must define what
21606 happens, but this might include raising an exception.  In practice all
21607 known implementations support silent wraparound in this case, so you need
21608 not worry about other possibilities.
21610 @node Signed Overflow Examples
21611 @subsection Examples of Code Assuming Wraparound Overflow
21612 @cindex integer overflow
21613 @cindex overflow, signed integer
21614 @cindex signed integer overflow
21615 @cindex wraparound arithmetic
21617 There has long been a tension between what the C standard requires for
21618 signed integer overflow, and what C programs commonly assume.  The
21619 standard allows aggressive optimizations based on assumptions that
21620 overflow never occurs, but many practical C programs rely on overflow
21621 wrapping around.  These programs do not conform to the standard, but
21622 they commonly work in practice because compiler writers are
21623 understandably reluctant to implement optimizations that would break
21624 many programs, unless perhaps a user specifies aggressive optimization.
21626 The C Standard says that if a program has signed integer overflow its
21627 behavior is undefined, and the undefined behavior can even precede the
21628 overflow.  To take an extreme example:
21630 @c Inspired by Robert Dewar's example in
21631 @c <https://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
21632 @example
21633 if (password == expected_password)
21634   allow_superuser_privileges ();
21635 else if (counter++ == INT_MAX)
21636   abort ();
21637 else
21638   printf ("%d password mismatches\n", counter);
21639 @end example
21641 @noindent
21642 If the @code{int} variable @code{counter} equals @code{INT_MAX},
21643 @code{counter++} must overflow and the behavior is undefined, so the C
21644 standard allows the compiler to optimize away the test against
21645 @code{INT_MAX} and the @code{abort} call.
21646 Worse, if an earlier bug in the program lets the compiler deduce that
21647 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
21648 the C standard allows the compiler to optimize away the password test
21649 and generate code that allows superuser privileges unconditionally.
21651 Despite this requirement by the standard, it has long been common for C
21652 code to assume wraparound arithmetic after signed overflow, and all
21653 known practical C implementations support some C idioms that assume
21654 wraparound signed arithmetic, even if the idioms do not conform
21655 strictly to the standard.  If your code looks like the following
21656 examples it will almost surely work with real-world compilers.
21658 Here is an example derived from the 7th Edition Unix implementation of
21659 @code{atoi} (1979-01-10):
21661 @example
21662 char *p;
21663 int f, n;
21664 @dots{}
21665 while (*p >= '0' && *p <= '9')
21666   n = n * 10 + *p++ - '0';
21667 return (f ? -n : n);
21668 @end example
21670 @noindent
21671 Even if the input string is in range, on most modern machines this has
21672 signed overflow when computing the most negative integer (the @code{-n}
21673 overflows) or a value near an extreme integer (the first @code{+}
21674 overflows).
21676 Here is another example, derived from the 7th Edition implementation of
21677 @code{rand} (1979-01-10).  Here the programmer expects both
21678 multiplication and addition to wrap on overflow:
21680 @example
21681 static long int randx = 1;
21682 @dots{}
21683 randx = randx * 1103515245 + 12345;
21684 return (randx >> 16) & 077777;
21685 @end example
21687 In the following example, derived from the GNU C Library 2.5
21688 implementation of @code{mktime} (2006-09-09), the code assumes
21689 wraparound arithmetic in @code{+} to detect signed overflow:
21691 @example
21692 time_t t, t1, t2;
21693 int sec_requested, sec_adjustment;
21694 @dots{}
21695 t1 = t + sec_requested;
21696 t2 = t1 + sec_adjustment;
21697 if (((t1 < t) != (sec_requested < 0))
21698     | ((t2 < t1) != (sec_adjustment < 0)))
21699   return -1;
21700 @end example
21702 If your code looks like these examples, it is probably safe even though
21703 it does not strictly conform to the C standard.  This might lead one to
21704 believe that one can generally assume wraparound on overflow, but that
21705 is not always true, as can be seen in the next section.
21707 @node Optimization and Wraparound
21708 @subsection Optimizations That Break Wraparound Arithmetic
21709 @cindex loop induction
21711 Compilers sometimes generate code that is incompatible with wraparound
21712 integer arithmetic.  A simple example is an algebraic simplification: a
21713 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
21714 because it assumes that @code{i * 2000} does not overflow.  The
21715 translation is not equivalent to the original when overflow occurs:
21716 e.g., in the typical case of 32-bit signed two's complement wraparound
21717 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
21718 the original expression returns @minus{}2147483 but the optimized
21719 version returns the mathematically correct value 2147484.
21721 More subtly, loop induction optimizations often exploit the undefined
21722 behavior of signed overflow.  Consider the following contrived function
21723 @code{sumc}:
21725 @example
21727 sumc (int lo, int hi)
21729   int sum = 0;
21730   int i;
21731   for (i = lo; i <= hi; i++)
21732     sum ^= i * 53;
21733   return sum;
21735 @end example
21737 @noindent
21738 To avoid multiplying by 53 each time through the loop, an optimizing
21739 compiler might internally transform @code{sumc} to the equivalent of the
21740 following:
21742 @example
21744 transformed_sumc (int lo, int hi)
21746   int sum = 0;
21747   int hic = hi * 53;
21748   int ic;
21749   for (ic = lo * 53; ic <= hic; ic += 53)
21750     sum ^= ic;
21751   return sum;
21753 @end example
21755 @noindent
21756 This transformation is allowed by the C standard, but it is invalid for
21757 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
21758 overflow in computing expressions like @code{hi * 53} can cause the
21759 expression @code{i <= hi} to yield a different value from the
21760 transformed expression @code{ic <= hic}.
21762 For this reason, compilers that use loop induction and similar
21763 techniques often do not support reliable wraparound arithmetic when a
21764 loop induction variable like @code{ic} is involved.  Since loop
21765 induction variables are generated by the compiler, and are not visible
21766 in the source code, it is not always trivial to say whether the problem
21767 affects your code.
21769 Hardly any code actually depends on wraparound arithmetic in cases like
21770 these, so in practice these loop induction optimizations are almost
21771 always useful.  However, edge cases in this area can cause problems.
21772 For example:
21774 @example
21775 int j;
21776 for (j = 1; 0 < j; j *= 2)
21777   test (j);
21778 @end example
21780 @noindent
21781 Here, the loop attempts to iterate through all powers of 2 that
21782 @code{int} can represent, but the C standard allows a compiler to
21783 optimize away the comparison and generate an infinite loop,
21784 under the argument that behavior is undefined on overflow.  As of this
21785 writing this optimization is not done by any production version of
21786 GCC with @option{-O2}, but it might be performed by other
21787 compilers, or by more aggressive GCC optimization options,
21788 and the GCC developers have not decided whether it will
21789 continue to work with GCC and @option{-O2}.
21791 @node Signed Overflow Advice
21792 @subsection Practical Advice for Signed Overflow Issues
21793 @cindex integer overflow
21794 @cindex overflow, signed integer
21795 @cindex signed integer overflow
21796 @cindex wraparound arithmetic
21798 Ideally the safest approach is to avoid signed integer overflow
21799 entirely.  For example, instead of multiplying two signed integers, you
21800 can convert them to unsigned integers, multiply the unsigned values,
21801 then test whether the result is in signed range.
21803 Rewriting code in this way will be inconvenient, though, particularly if
21804 the signed values might be negative.  Also, it may hurt
21805 performance.  Using unsigned arithmetic to check for overflow is
21806 particularly painful to do portably and efficiently when dealing with an
21807 integer type like @code{uid_t} whose width and signedness vary from
21808 platform to platform.
21810 Furthermore, many C applications pervasively assume wraparound behavior
21811 and typically it is not easy to find and remove all these assumptions.
21812 Hence it is often useful to maintain nonstandard code that assumes
21813 wraparound on overflow, instead of rewriting the code.  The rest of this
21814 section attempts to give practical advice for this situation.
21816 If your code wants to detect signed integer overflow in @code{sum = a +
21817 b}, it is generally safe to use an expression like @code{(sum < a) != (b
21818 < 0)}.
21820 If your code uses a signed loop index, make sure that the index cannot
21821 overflow, along with all signed expressions derived from the index.
21822 Here is a contrived example of problematic code with two instances of
21823 overflow.
21825 @example
21826 for (i = INT_MAX - 10; i <= INT_MAX; i++)
21827   if (i + 1 < 0)
21828     @{
21829       report_overflow ();
21830       break;
21831     @}
21832 @end example
21834 @noindent
21835 Because of the two overflows, a compiler might optimize away or
21836 transform the two comparisons in a way that is incompatible with the
21837 wraparound assumption.
21839 If your code uses an expression like @code{(i * 2000) / 1000} and you
21840 actually want the multiplication to wrap around on overflow, use
21841 unsigned arithmetic
21842 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
21844 If your code assumes wraparound behavior and you want to insulate it
21845 against any GCC optimizations that would fail to support that
21846 behavior, you should use GCC's @option{-fwrapv} option, which
21847 causes signed overflow to wrap around reliably (except for division and
21848 remainder, as discussed in the next section).
21850 If you need to port to platforms where signed integer overflow does not
21851 reliably wrap around (e.g., due to hardware overflow checking, or to
21852 highly aggressive optimizations), you should consider debugging with
21853 GCC's @option{-ftrapv} option, which causes signed overflow to
21854 raise an exception.
21856 @node Signed Integer Division
21857 @subsection Signed Integer Division and Integer Overflow
21858 @cindex division, integer
21860 Overflow in signed
21861 integer division is not always harmless: for example, on CPUs of the
21862 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
21863 which by default terminates the program.  Worse, taking the remainder
21864 of these two values typically yields the same signal on these CPUs,
21865 even though the C standard requires @code{INT_MIN % -1} to yield zero
21866 because the expression does not overflow.
21868 @node Preprocessor Arithmetic
21869 @section Preprocessor Arithmetic
21870 @cindex preprocessor arithmetic
21872 In C99 and later, preprocessor arithmetic, used for @code{#if}
21873 expressions, must
21874 be evaluated as if all signed values are of type @code{intmax_t} and all
21875 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
21876 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
21877 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
21878 @code{long long int}.  Also, some older preprocessors mishandle
21879 constants ending in @code{LL}.  To work around these problems, you can
21880 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
21881 @code{configure}-time rather than at @code{#if}-time.
21883 @node Null Pointers
21884 @section Properties of Null Pointers
21885 @cindex null pointers
21887 Most modern hosts reliably fail when you attempt to dereference a null
21888 pointer.
21890 On almost all modern hosts, null pointers use an all-bits-zero internal
21891 representation, so you can reliably use @code{memset} with 0 to set all
21892 the pointers in an array to null values.
21894 If @code{p} is a null pointer to an object type, the C expression
21895 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
21896 the standard says that it has undefined behavior.
21898 @node Buffer Overruns
21899 @section Buffer Overruns and Subscript Errors
21900 @cindex buffer overruns
21902 Buffer overruns and subscript errors are the most common dangerous
21903 errors in C programs.  They result in undefined behavior because storing
21904 outside an array typically modifies storage that is used by some other
21905 object, and most modern systems lack runtime checks to catch these
21906 errors.  Programs should not rely on buffer overruns being caught.
21908 There is one exception to the usual rule that a portable program cannot
21909 address outside an array.  In C, it is valid to compute the address just
21910 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
21911 so long as you do not dereference the resulting pointer.  But it is not
21912 valid to compute the address just before an object, e.g., @code{&a[-1]};
21913 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
21914 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
21915 reliable in general, and it is usually easy enough to avoid the
21916 potential portability problem, e.g., by allocating an extra unused array
21917 element at the start or end.
21919 @uref{https://@/www.valgrind.org/, Valgrind} can catch many overruns.
21920 GCC users might also consider using the @option{-fsanitize=} options
21921 to catch overruns.
21922 @xref{Instrumentation Options, , Program Instrumentation Options,
21923       gcc, Using the GNU Compiler Collection (GCC)}.
21925 Buffer overruns are usually caused by off-by-one errors, but there are
21926 more subtle ways to get them.
21928 Using @code{int} values to index into an array or compute array sizes
21929 causes problems on typical 64-bit hosts where an array index might
21930 be @math{2^{31}} or larger.  Index values of type @code{size_t} avoid this
21931 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
21932 are signed, and are wide enough in practice.
21934 If you add or multiply two numbers to calculate an array size, e.g.,
21935 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
21936 multiplication overflows.
21938 Many implementations of the @code{alloca} function silently misbehave
21939 and can generate buffer overflows if given sizes that are too large.
21940 The size limits are implementation dependent, but are at least 4000
21941 bytes on all platforms that we know about.
21943 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
21944 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
21945 portable code should not use them unless the inputs are known to be
21946 within certain limits.  The time-related functions can overflow their
21947 buffers if given timestamps out of range (e.g., a year less than -999
21948 or greater than 9999).  Time-related buffer overflows cannot happen with
21949 recent-enough versions of the GNU C library, but are possible
21950 with other
21951 implementations.  The @code{gets} function is the worst, since it almost
21952 invariably overflows its buffer when presented with an input line larger
21953 than the buffer.
21955 @node Volatile Objects
21956 @section Volatile Objects
21957 @cindex volatile objects
21959 The keyword @code{volatile} is often misunderstood in portable code.
21960 Its use inhibits some memory-access optimizations, but programmers often
21961 wish that it had a different meaning than it actually does.
21963 @code{volatile} was designed for code that accesses special objects like
21964 memory-mapped device registers whose contents spontaneously change.
21965 Such code is inherently low-level, and it is difficult to specify
21966 portably what @code{volatile} means in these cases.  The C standard
21967 says, ``What constitutes an access to an object that has
21968 volatile-qualified type is implementation-defined,'' so in theory each
21969 implementation is supposed to fill in the gap by documenting what
21970 @code{volatile} means for that implementation.  In practice, though,
21971 this documentation is usually absent or incomplete.
21973 One area of confusion is the distinction between objects defined with
21974 volatile types, and volatile lvalues.  From the C standard's point of
21975 view, an object defined with a volatile type has externally visible
21976 behavior.  You can think of such objects as having little oscilloscope
21977 probes attached to them, so that the user can observe some properties of
21978 accesses to them, just as the user can observe data written to output
21979 files.  However, the standard does not make it clear whether users can
21980 observe accesses by volatile lvalues to ordinary objects.  For example:
21982 @example
21983 /* Declare and access a volatile object.
21984    Accesses to X are "visible" to users.  */
21985 static int volatile x;
21986 x = 1;
21988 /* Access two ordinary objects via a volatile lvalue.
21989    It's not clear whether accesses to *P are "visible".  */
21990 int y;
21991 int *z = malloc (sizeof (int));
21992 int volatile *p;
21993 p = &y;
21994 *p = 1;
21995 p = z;
21996 *p = 1;
21997 @end example
21999 Programmers often wish that @code{volatile} meant ``Perform the memory
22000 access here and now, without merging several memory accesses, without
22001 changing the memory word size, and without reordering.''  But the C
22002 standard does not require this.  For objects defined with a volatile
22003 type, accesses must be done before the next sequence point; but
22004 otherwise merging, reordering, and word-size change is allowed.  Worse,
22005 it is not clear from the standard whether volatile lvalues provide more
22006 guarantees in general than nonvolatile lvalues, if the underlying
22007 objects are ordinary.
22009 Even when accessing objects defined with a volatile type,
22010 the C standard allows only
22011 extremely limited signal handlers: in C99 the behavior is undefined if a signal
22012 handler reads any non-local object, or writes to any non-local object
22013 whose type is not @code{sig_atomic_t volatile}, or calls any standard
22014 library function other than @code{abort}, @code{signal}, and
22015 @code{_Exit}.  Hence C compilers need not worry about a signal handler
22016 disturbing ordinary computation.  C11 and Posix allow some additional
22017 behavior in a portable signal handler, but are still quite restrictive.
22019 Some C implementations allow memory-access optimizations within each
22020 translation unit, such that actual behavior agrees with the behavior
22021 required by the standard only when calling a function in some other
22022 translation unit, and a signal handler acts like it was called from a
22023 different translation unit.  The C99 standard hints that in these
22024 implementations, objects referred to by signal handlers ``would require
22025 explicit specification of @code{volatile} storage, as well as other
22026 implementation-defined restrictions.''  But unfortunately even for this
22027 special case these other restrictions are often not documented well.
22028 This area was significantly changed in C11, and eventually implementations
22029 will probably head in the C11 direction, but this will take some time.
22030 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
22031 GNU Compiler Collection (GCC)}, for some
22032 restrictions imposed by GCC.  @xref{Defining Handlers, ,
22033 Defining Signal Handlers, libc, The GNU C Library}, for some
22034 restrictions imposed by the GNU C library.  Restrictions
22035 differ on other platforms.
22037 If possible, it is best to use a signal handler that fits within the
22038 limits imposed by the C and Posix standards.
22040 If this is not practical, you can try the following rules of thumb.  A
22041 signal handler should access only volatile lvalues, preferably lvalues
22042 that refer to objects defined with a volatile type, and should not
22043 assume that the accessed objects have an internally consistent state
22044 if they are larger than a machine word.  Furthermore, installers
22045 should employ compilers and compiler options that are commonly used
22046 for building operating system kernels, because kernels often need more
22047 from @code{volatile} than the C Standard requires, and installers who
22048 compile an application in a similar environment can sometimes benefit
22049 from the extra constraints imposed by kernels on compilers.
22050 Admittedly we are hand-waving somewhat here, as there are few
22051 guarantees in this area; the rules of thumb may help to fix some bugs
22052 but there is a good chance that they will not fix them all.
22054 For @code{volatile}, C++ has the same problems that C does.
22055 Multithreaded applications have even more problems with @code{volatile},
22056 but they are beyond the scope of this section.
22058 The bottom line is that using @code{volatile} typically hurts
22059 performance but should not hurt correctness.  In some cases its use
22060 does help correctness, but these cases are often so poorly understood
22061 that all too often adding @code{volatile} to a data structure merely
22062 alleviates some symptoms of a bug while not fixing the bug in general.
22064 @node Floating Point Portability
22065 @section Floating Point Portability
22066 @cindex floating point
22068 Almost all modern systems use IEEE-754 floating point, and it is safe to
22069 assume IEEE-754 in most portable code these days.  For more information,
22070 please see David Goldberg's classic paper
22071 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
22072 Scientist Should Know About Floating-Point Arithmetic}.
22074 @node Exiting Portably
22075 @section Exiting Portably
22076 @cindex exiting portably
22078 A C or C++ program can exit with status @var{N} by returning
22079 @var{N} from the @code{main} function.  Portable programs are supposed
22080 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
22081 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
22082 fail by exiting with status 1, and test programs that assume Posix can
22083 fail by exiting with status values from 1 through 255.  Programs on
22084 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
22085 status when @code{main} returned nonzero, but ancient systems like these
22086 are no longer of practical concern.
22088 A program can also exit with status @var{N} by passing @var{N} to the
22089 @code{exit} function, and a program can fail by calling the @code{abort}
22090 function.  If a program is specialized to just some platforms, it can fail
22091 by calling functions specific to those platforms, e.g., @code{_exit}
22092 (Posix).  However, like other functions, an exit
22093 function should be declared, typically by including a header.  For
22094 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
22095 either directly or via the default includes (@pxref{Default Includes}).
22097 A program can fail due to undefined behavior such as dereferencing a null
22098 pointer, but this is not recommended as undefined behavior allows an
22099 implementation to do whatever it pleases and this includes exiting
22100 successfully.
22103 @c ================================================== Manual Configuration
22105 @node Manual Configuration
22106 @chapter Manual Configuration
22108 A few kinds of features can't be guessed automatically by running test
22109 programs.  For example, the details of the object-file format, or
22110 special options that need to be passed to the compiler or linker.
22111 Autoconf provides a uniform method for handling unguessable features,
22112 by giving each operating system a @dfn{canonical system type}, also
22113 known as a @dfn{canonical name} or @dfn{target triplet}.
22115 @prindex @command{config.guess}
22116 @prindex @command{config.sub}
22118 If you use any of the macros described in this chapter, you must
22119 distribute the helper scripts @command{config.guess} and
22120 @command{config.sub} along with your source code.  Some Autoconf macros
22121 use these macros internally, so you may need to distribute these scripts
22122 even if you do not use any of these macros yourself.  @xref{Input}, for
22123 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
22124 to control in which directory @command{configure} looks for helper
22125 scripts, and where to get the scripts from.
22127 @menu
22128 * Specifying Target Triplets::  Specifying target triplets
22129 * Canonicalizing::              Getting the canonical system type
22130 * Using System Type::           What to do with the system type
22131 @end menu
22133 @node Specifying Target Triplets
22134 @section Specifying target triplets
22135 @cindex System type
22136 @cindex Target triplet
22137 @c This node used to be named Specifying Names.  The @anchor allows old
22138 @c links to still work.
22139 @anchor{Specifying Names}
22141 Autoconf-generated
22142 @command{configure} scripts can make decisions based on a canonical name
22143 for the system type, or @dfn{target triplet}, which has the form:
22144 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
22145 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
22147 @command{configure} can usually guess the canonical name for the type of
22148 system it's running on.  To do so it runs a script called
22149 @command{config.guess}, which infers the name using the @code{uname}
22150 command or symbols predefined by the C preprocessor.
22152 Alternately, the user can specify the system type with command line
22153 arguments to @command{configure} (@pxref{System Type}.  Doing so is
22154 necessary when
22155 cross-compiling.  In the most complex case of cross-compiling, three
22156 system types are involved.  The options to specify them are:
22158 @table @option
22159 @item --build=@var{build-type}
22160 the type of system on which the package is being configured and
22161 compiled.  It defaults to the result of running @command{config.guess}.
22162 Specifying a @var{build-type} that differs from @var{host-type} enables
22163 cross-compilation mode.
22165 @item --host=@var{host-type}
22166 the type of system on which the package runs.  By default it is the
22167 same as the build machine.  The tools that get used to build and
22168 manipulate binaries will, by default, all be prefixed with
22169 @code{@var{host-type}-}, such as @code{@var{host-type}-gcc},
22170 @code{@var{host-type}-g++}, @code{@var{host-type}-ar}, and
22171 @code{@var{host-type}-nm}.  If the binaries produced by these tools can
22172 be executed by the build system, the configure script will make use of
22173 it in @code{AC_RUN_IFELSE} invocations; otherwise, cross-compilation
22174 mode is enabled.  Specifying a @var{host-type} that differs
22175 from @var{build-type}, when @var{build-type} was also explicitly
22176 specified, equally enables cross-compilation mode.
22178 @item --target=@var{target-type}
22179 the type of system for which any compiler tools in the package
22180 produce code (rarely needed).  By default, it is the same as host.
22181 @end table
22183 If you mean to override the result of @command{config.guess} but
22184 still produce binaries for the build machine, use @option{--build},
22185 not @option{--host}.
22187 So, for example, to produce binaries for 64-bit MinGW, use a command
22188 like this:
22190 @example
22191 ./configure --host=x86_64-w64-mingw64
22192 @end example
22194 If your system has the ability to execute MinGW binaries but you don't
22195 want to make use of this feature and instead prefer cross-compilation
22196 guesses, use a command like this:
22198 @example
22199 ./configure --build=x86_64-pc-linux-gnu --host=x86_64-w64-mingw64
22200 @end example
22202 @noindent
22203 Note that if you do not specify @option{--host}, @command{configure}
22204 fails if it can't run the code generated by the specified compiler.  For
22205 example, configuring as follows fails:
22207 @example
22208 ./configure CC=x86_64-w64-mingw64-gcc
22209 @end example
22211 When cross-compiling, @command{configure} will warn about any tools
22212 (compilers, linkers, assemblers) whose name is not prefixed with the
22213 host type.  This is an aid to users performing cross-compilation.
22214 Continuing the example above, if a cross-compiler named @command{cc} is
22215 used with a native @command{pkg-config}, then libraries found by
22216 @command{pkg-config} will likely cause subtle build failures; but using
22217 the names @command{x86_64-w64-mingw64-gcc} and
22218 @command{x86_64-w64-mingw64-pkg-config}
22219 avoids any confusion.  Avoiding the warning is as simple as creating the
22220 correct symlinks naming the cross tools.
22222 @cindex @command{config.sub}
22223 @command{configure} recognizes short aliases for many system types; for
22224 example, @samp{decstation} can be used instead of
22225 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
22226 @command{config.sub} to canonicalize system type aliases.
22228 This section deliberately omits the description of the obsolete
22229 interface; see @ref{Hosts and Cross-Compilation}.
22232 @node Canonicalizing
22233 @section Getting the Canonical System Type
22234 @cindex System type
22235 @cindex Canonical system type
22237 The following macros make the system type available to @command{configure}
22238 scripts.
22240 @ovindex build_alias
22241 @ovindex host_alias
22242 @ovindex target_alias
22244 The variables @samp{build_alias}, @samp{host_alias}, and
22245 @samp{target_alias} are always exactly the arguments of @option{--build},
22246 @option{--host}, and @option{--target}; in particular, they are left empty
22247 if the user did not use them, even if the corresponding
22248 @code{AC_CANONICAL} macro was run.  Any configure script may use these
22249 variables anywhere.  These are the variables that should be used when in
22250 interaction with the user.
22252 If you need to recognize some special environments based on their system
22253 type, run the following macros to get canonical system names.  These
22254 variables are not set before the macro call.
22256 @defmac AC_CANONICAL_BUILD
22257 @acindex{CANONICAL_BUILD}
22258 @ovindex build
22259 @ovindex build_cpu
22260 @ovindex build_vendor
22261 @ovindex build_os
22262 Compute the canonical build-system type variable, @code{build}, and its
22263 three individual parts @code{build_cpu}, @code{build_vendor}, and
22264 @code{build_os}.
22266 If @option{--build} was specified, then @code{build} is the
22267 canonicalization of @code{build_alias} by @command{config.sub},
22268 otherwise it is determined by the shell script @command{config.guess}.
22269 @end defmac
22271 @defmac AC_CANONICAL_HOST
22272 @acindex{CANONICAL_HOST}
22273 @ovindex host
22274 @ovindex host_cpu
22275 @ovindex host_vendor
22276 @ovindex host_os
22277 Compute the canonical host-system type variable, @code{host}, and its
22278 three individual parts @code{host_cpu}, @code{host_vendor}, and
22279 @code{host_os}.
22281 If @option{--host} was specified, then @code{host} is the
22282 canonicalization of @code{host_alias} by @command{config.sub},
22283 otherwise it defaults to @code{build}.
22284 @end defmac
22286 @defmac AC_CANONICAL_TARGET
22287 @acindex{CANONICAL_TARGET}
22288 @ovindex target
22289 @ovindex target_cpu
22290 @ovindex target_vendor
22291 @ovindex target_os
22292 Compute the canonical target-system type variable, @code{target}, and its
22293 three individual parts @code{target_cpu}, @code{target_vendor}, and
22294 @code{target_os}.
22296 If @option{--target} was specified, then @code{target} is the
22297 canonicalization of @code{target_alias} by @command{config.sub},
22298 otherwise it defaults to @code{host}.
22299 @end defmac
22301 Note that there can be artifacts due to the backward compatibility
22302 code.  @xref{Hosts and Cross-Compilation}, for more.
22304 @node Using System Type
22305 @section Using the System Type
22307 In @file{configure.ac} the system type is generally used by one or more
22308 @code{case} statements to select system-specifics.  Shell wildcards can
22309 be used to match a group of system types.
22311 For example, an extra assembler code object file could be chosen, giving
22312 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
22313 following would be used in a makefile to add the object to a
22314 program or library.
22316 @example
22317 AS_CASE([$host],
22318   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
22319   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
22320   [CYCLE_OBJ=""]
22322 AC_SUBST([CYCLE_OBJ])
22323 @end example
22325 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
22326 to select variant source files, for example optimized code for some
22327 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
22328 so some runtime capability checks may be necessary too.
22330 @example
22331 case $host in
22332   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
22333   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
22334   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
22335 esac
22336 @end example
22338 The host system type can also be used to find cross-compilation tools
22339 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
22341 The above examples all show @samp{$host}, since this is where the code
22342 is going to run.  Only rarely is it necessary to test @samp{$build}
22343 (which is where the build is being done).
22345 Whenever you're tempted to use @samp{$host} it's worth considering
22346 whether some sort of probe would be better.  New system types come along
22347 periodically or previously missing features are added.  Well-written
22348 probes can adapt themselves to such things, but hard-coded lists of
22349 names can't.  Here are some guidelines,
22351 @itemize @bullet
22352 @item
22353 Availability of libraries and library functions should always be checked
22354 by probing.
22355 @item
22356 Variant behavior of system calls is best identified with runtime tests
22357 if possible, but bug workarounds or obscure difficulties might have to
22358 be driven from @samp{$host}.
22359 @item
22360 Assembler code is inevitably highly CPU-specific and is best selected
22361 according to @samp{$host_cpu}.
22362 @item
22363 Assembler variations like underscore prefix on globals or ELF versus
22364 COFF type directives are however best determined by probing, perhaps
22365 even examining the compiler output.
22366 @end itemize
22368 @samp{$target} is for use by a package creating a compiler or similar.
22369 For ordinary packages it's meaningless and should not be used.  It
22370 indicates what the created compiler should generate code for, if it can
22371 cross-compile.  @samp{$target} generally selects various hard-coded CPU
22372 and system conventions, since usually the compiler or tools under
22373 construction themselves determine how the target works.
22376 @c ===================================================== Site Configuration.
22378 @node Site Configuration
22379 @chapter Site Configuration
22381 @command{configure} scripts support several kinds of local configuration
22382 decisions.  There are ways for users to specify where external software
22383 packages are, include or exclude optional features, install programs
22384 under modified names, and set default values for @command{configure}
22385 options.
22387 @menu
22388 * Help Formatting::             Customizing @samp{configure --help}
22389 * External Software::           Working with other optional software
22390 * Package Options::             Selecting optional features
22391 * Pretty Help Strings::         Formatting help string
22392 * Option Checking::             Controlling checking of @command{configure} options
22393 * Site Details::                Configuring site details
22394 * Transforming Names::          Changing program names when installing
22395 * Site Defaults::               Giving @command{configure} local defaults
22396 @end menu
22398 @node Help Formatting
22399 @section Controlling Help Output
22401 Users consult @samp{configure --help} to learn of configuration
22402 decisions specific to your package.  By default, @command{configure}
22403 breaks this output into sections for each type of option; within each
22404 section, help strings appear in the order @file{configure.ac} defines
22405 them:
22407 @example
22408 Optional Features:
22409   @dots{}
22410   --enable-bar            include bar
22412 Optional Packages:
22413   @dots{}
22414   --with-foo              use foo
22415 @end example
22417 @defmac AC_PRESERVE_HELP_ORDER
22418 @acindex{PRESERVE_HELP_ORDER}
22420 Request an alternate @option{--help} format, in which options of all
22421 types appear together, in the order defined.  Call this macro before any
22422 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
22424 @example
22425 Optional Features and Packages:
22426   @dots{}
22427   --enable-bar            include bar
22428   --with-foo              use foo
22429 @end example
22431 @end defmac
22433 @node External Software
22434 @section Working With External Software
22435 @cindex External software
22437 Some packages require, or can optionally use, other software packages
22438 that are already installed.  The user can give @command{configure}
22439 command line options to specify which such external software to use.
22440 The options have one of these forms:
22442 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22443 @c awful.
22444 @example
22445 --with-@var{package}@r{[}=@var{arg}@r{]}
22446 --without-@var{package}
22447 @end example
22449 For example, @option{--with-gnu-ld} means work with the GNU linker
22450 instead of some other linker.  @option{--with-x} means work with The X
22451 Window System.
22453 The user can give an argument by following the package name with
22454 @samp{=} and the argument.  Giving an argument of @samp{no} is for
22455 packages that are used by default; it says to @emph{not} use the
22456 package.  An argument that is neither @samp{yes} nor @samp{no} could
22457 include a name or number of a version of the other package, to specify
22458 more precisely which other package this program is supposed to work
22459 with.  If no argument is given, it defaults to @samp{yes}.
22460 @option{--without-@var{package}} is equivalent to
22461 @option{--with-@var{package}=no}.
22463 Normally @command{configure} scripts complain about
22464 @option{--with-@var{package}} options that they do not support.
22465 @xref{Option Checking}, for details, and for how to override the
22466 defaults.
22468 For each external software package that may be used, @file{configure.ac}
22469 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
22470 user asked to use it.  Whether each package is used or not by default,
22471 and which arguments are valid, is up to you.
22473 @anchor{AC_ARG_WITH}
22474 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
22475   @ovar{action-if-given}, @ovar{action-if-not-given})
22476 @acindex{ARG_WITH}
22477 If the user gave @command{configure} the option @option{--with-@var{package}}
22478 or @option{--without-@var{package}}, run shell commands
22479 @var{action-if-given}.  If neither option was given, run shell commands
22480 @var{action-if-not-given}.  The name @var{package} indicates another
22481 software package that this program should work with.  It should consist
22482 only of alphanumeric characters, dashes, plus signs, and dots.
22484 The option's argument is available to the shell commands
22485 @var{action-if-given} in the shell variable @code{withval}, which is
22486 actually just the value of the shell variable named
22487 @code{with_@var{package}}, with any non-alphanumeric characters in
22488 @var{package} changed into @samp{_}.  You may use that variable instead,
22489 if you wish.
22491 Note that @var{action-if-not-given} is not expanded until the point that
22492 @code{AC_ARG_WITH} was expanded.  If you need the value of
22493 @code{with_@var{package}} set to a default value by the time argument
22494 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22495 diversion (@pxref{m4_divert_text}) (if done as an argument to
22496 @code{AC_ARG_WITH}, also provide non-diverted text to avoid a shell
22497 syntax error).
22499 The argument @var{help-string} is a description of the option that
22500 looks like this:
22501 @example
22502   --with-readline         support fancy command line editing
22503 @end example
22505 @noindent
22506 @var{help-string} may be more than one line long, if more detail is
22507 needed.  Just make sure the columns line up in @samp{configure
22508 --help}.  Avoid tabs in the help string.  The easiest way to provide the
22509 proper leading whitespace is to format your @var{help-string} with the macro
22510 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22512 The following example shows how to use the @code{AC_ARG_WITH} macro in
22513 a common situation.  You want to let the user decide whether to enable
22514 support for an external library (e.g., the readline library); if the user
22515 specified neither @option{--with-readline} nor @option{--without-readline},
22516 you want to enable support for readline only if the library is available
22517 on the system.
22519 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22520 @example
22521 AC_ARG_WITH([readline],
22522   [AS_HELP_STRING([--with-readline],
22523     [support fancy command line editing @@<:@@default=check@@:>@@])],
22524   [],
22525   [: m4_divert_text([DEFAULTS], [with_readline=check])])
22527 LIBREADLINE=
22528 AS_IF([test "x$with_readline" != xno],
22529   [AC_CHECK_LIB([readline], [main],
22530     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22531      AC_DEFINE([HAVE_LIBREADLINE], [1],
22532                [Define if you have libreadline])
22533     ],
22534     [if test "x$with_readline" != xcheck; then
22535        AC_MSG_FAILURE(
22536          [--with-readline was given, but test for readline failed])
22537      fi
22538     ], -lncurses)])
22539 @end example
22541 The next example shows how to use @code{AC_ARG_WITH} to give the user the
22542 possibility to enable support for the readline library, in case it is still
22543 experimental and not well tested, and is therefore disabled by default.
22545 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22546 @example
22547 AC_ARG_WITH([readline],
22548   [AS_HELP_STRING([--with-readline],
22549     [enable experimental support for readline])],
22550   [],
22551   [with_readline=no])
22553 LIBREADLINE=
22554 AS_IF([test "x$with_readline" != xno],
22555   [AC_CHECK_LIB([readline], [main],
22556     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22557      AC_DEFINE([HAVE_LIBREADLINE], [1],
22558                [Define if you have libreadline])
22559     ],
22560     [AC_MSG_FAILURE(
22561        [--with-readline was given, but test for readline failed])],
22562     [-lncurses])])
22563 @end example
22565 The last example shows how to use @code{AC_ARG_WITH} to give the user the
22566 possibility to disable support for the readline library, given that it is
22567 an important feature and that it should be enabled by default.
22569 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22570 @example
22571 AC_ARG_WITH([readline],
22572   [AS_HELP_STRING([--without-readline],
22573     [disable support for readline])],
22574   [],
22575   [with_readline=yes])
22577 LIBREADLINE=
22578 AS_IF([test "x$with_readline" != xno],
22579   [AC_CHECK_LIB([readline], [main],
22580     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22581      AC_DEFINE([HAVE_LIBREADLINE], [1],
22582                [Define if you have libreadline])
22583     ],
22584     [AC_MSG_FAILURE(
22585        [readline test failed (--without-readline to disable)])],
22586     [-lncurses])])
22587 @end example
22589 These three examples can be easily adapted to the case where
22590 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
22591 @ref{Package Options}).
22592 @end defmac
22594 @node Package Options
22595 @section Choosing Package Options
22596 @cindex Package options
22597 @cindex Options, package
22599 If a software package has optional compile-time features, the user can
22600 give @command{configure} command line options to specify whether to
22601 compile them.  The options have one of these forms:
22603 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22604 @c awful.
22605 @example
22606 --enable-@var{feature}@r{[}=@var{arg}@r{]}
22607 --disable-@var{feature}
22608 @end example
22610 These options allow users to choose which optional features to build and
22611 install.  @option{--enable-@var{feature}} options should never make a
22612 feature behave differently or cause one feature to replace another.
22613 They should only cause parts of the program to be built rather than left
22614 out.
22616 The user can give an argument by following the feature name with
22617 @samp{=} and the argument.  Giving an argument of @samp{no} requests
22618 that the feature @emph{not} be made available.  A feature with an
22619 argument looks like @option{--enable-debug=stabs}.  If no argument is
22620 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
22621 equivalent to @option{--enable-@var{feature}=no}.
22623 Normally @command{configure} scripts complain about
22624 @option{--enable-@var{package}} options that they do not support.
22625 @xref{Option Checking}, for details, and for how to override the
22626 defaults.
22628 For each optional feature, @file{configure.ac} should call
22629 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
22630 to include it.  Whether each feature is included or not by default, and
22631 which arguments are valid, is up to you.
22633 @anchor{AC_ARG_ENABLE}
22634 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
22635   @ovar{action-if-given}, @ovar{action-if-not-given})
22636 @acindex{ARG_ENABLE}
22637 If the user gave @command{configure} the option
22638 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
22639 shell commands @var{action-if-given}.  If neither option was given, run
22640 shell commands @var{action-if-not-given}.  The name @var{feature}
22641 indicates an optional user-level facility.  It should consist only of
22642 alphanumeric characters, dashes, plus signs, and dots.
22644 The option's argument is available to the shell commands
22645 @var{action-if-given} in the shell variable @code{enableval}, which is
22646 actually just the value of the shell variable named
22647 @code{enable_@var{feature}}, with any non-alphanumeric characters in
22648 @var{feature} changed into @samp{_}.  You may use that variable instead,
22649 if you wish.  The @var{help-string} argument is like that of
22650 @code{AC_ARG_WITH} (@pxref{External Software}).
22652 Note that @var{action-if-not-given} is not expanded until the point that
22653 @code{AC_ARG_ENABLE} was expanded.  If you need the value of
22654 @code{enable_@var{feature}} set to a default value by the time argument
22655 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22656 diversion (@pxref{m4_divert_text}) (if done as an argument to
22657 @code{AC_ARG_ENABLE}, also provide non-diverted text to avoid a shell
22658 syntax error).
22660 You should format your @var{help-string} with the macro
22661 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22663 See the examples suggested with the definition of @code{AC_ARG_WITH}
22664 (@pxref{External Software}) to get an idea of possible applications of
22665 @code{AC_ARG_ENABLE}.
22666 @end defmac
22668 @node Pretty Help Strings
22669 @section Making Your Help Strings Look Pretty
22670 @cindex Help strings
22672 Properly formatting the @samp{help strings} which are used in
22673 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
22674 (@pxref{Package Options}) can be challenging.  Specifically, you want
22675 your own @samp{help strings} to line up in the appropriate columns of
22676 @samp{configure --help} just like the standard Autoconf @samp{help
22677 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
22679 @anchor{AS_HELP_STRING}
22680 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
22681   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
22682 @asindex{HELP_STRING}
22684 Expands into a help string that looks pretty when the user executes
22685 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
22686 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
22687 Options}).  The following example makes this clearer.
22689 @example
22690 AC_ARG_WITH([foo],
22691   [AS_HELP_STRING([--with-foo],
22692      [use foo (default is no)])],
22693   [use_foo=$withval],
22694   [use_foo=no])
22695 @end example
22697 Then the last few lines of @samp{configure --help} appear like
22698 this:
22700 @example
22701 --enable and --with options recognized:
22702   --with-foo              use foo (default is no)
22703 @end example
22705 Macro expansion is performed on the first argument.  However, the second
22706 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
22707 list of text to be reformatted, and is not subject to macro expansion.
22708 Since it is not expanded, it should not be double quoted.
22709 @xref{Autoconf Language}, for a more detailed explanation.
22711 The @code{AS_HELP_STRING} macro is particularly helpful when the
22712 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
22713 arguments, as shown in the following example.  Be aware that
22714 @var{left-hand-side} may not expand to unbalanced quotes,
22715 although quadrigraphs can be used.
22717 @example
22718 AC_DEFUN([MY_ARG_WITH],
22719   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
22720      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
22721                      [use $1 (default is $2)])],
22722      [use_[]$1=$withval],
22723      [use_[]$1=$2])])
22724 MY_ARG_WITH([a_b], [no])
22725 @end example
22726 @noindent
22727 Here, the last few lines of @samp{configure --help} will include:
22729 @example
22730 --enable and --with options recognized:
22731   --with-a-b              use a_b (default is no)
22732 @end example
22734 The parameters @var{indent-column} and @var{wrap-column} were introduced
22735 in Autoconf 2.62.  Generally, they should not be specified; they exist
22736 for fine-tuning of the wrapping.
22737 @example
22738 AS_HELP_STRING([--option], [description of option])
22739 @result{}  --option                description of option
22740 AS_HELP_STRING([--option], [description of option], [15], [30])
22741 @result{}  --option     description of
22742 @result{}               option
22743 @end example
22744 @end defmac
22747 @node Option Checking
22748 @section Controlling Checking of @command{configure} Options
22749 @cindex Options, Package
22751 The @command{configure} script checks its command-line options against a
22752 list of known options, like @option{--help} or @option{--config-cache}.
22753 An unknown option ordinarily indicates a mistake by the user and
22754 @command{configure} halts with an error.  However, by default unknown
22755 @option{--with-@var{package}} and @option{--enable-@var{feature}}
22756 options elicit only a warning, to support configuring entire source
22757 trees.
22759 Source trees often contain multiple packages with a top-level
22760 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
22761 (@pxref{Subdirectories}).  Because the packages generally support
22762 different @option{--with-@var{package}} and
22763 @option{--enable-@var{feature}} options, the GNU Coding
22764 Standards say they must accept unrecognized options without halting.
22765 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
22766 automatically disables the warnings.
22768 This default behavior may be modified in two ways.  First, the installer
22769 can invoke @code{configure --disable-option-checking} to disable
22770 these warnings, or invoke @code{configure --enable-option-checking=fatal}
22771 options to turn them into fatal errors, respectively.  Second, the
22772 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
22774 @defmac AC_DISABLE_OPTION_CHECKING
22775 @acindex{DISABLE_OPTION_CHECKING}
22777 By default, disable warnings related to any unrecognized
22778 @option{--with-@var{package}} or @option{--enable-@var{feature}}
22779 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
22781 The installer can override this behavior by passing
22782 @option{--enable-option-checking} (enable warnings) or
22783 @option{--enable-option-checking=fatal} (enable errors) to
22784 @command{configure}.
22785 @end defmac
22788 @node Site Details
22789 @section Configuring Site Details
22790 @cindex Site details
22792 Some software packages require complex site-specific information.  Some
22793 examples are host names to use for certain services, company names, and
22794 email addresses to contact.  Since some configuration scripts generated
22795 by Metaconfig ask for such information interactively, people sometimes
22796 wonder how to get that information in Autoconf-generated configuration
22797 scripts, which aren't interactive.
22799 Such site configuration information should be put in a file that is
22800 edited @emph{only by users}, not by programs.  The location of the file
22801 can either be based on the @code{prefix} variable, or be a standard
22802 location such as the user's home directory.  It could even be specified
22803 by an environment variable.  The programs should examine that file at
22804 runtime, rather than at compile time.  Runtime configuration is more
22805 convenient for users and makes the configuration process simpler than
22806 getting the information while configuring.  @xref{Directory Variables, ,
22807 Variables for Installation Directories, standards, The GNU Coding
22808 Standards}, for more information on where to put data files.
22810 @node Transforming Names
22811 @section Transforming Program Names When Installing
22812 @cindex Transforming program names
22813 @cindex Program names, transforming
22815 Autoconf supports changing the names of programs when installing them.
22816 In order to use these transformations, @file{configure.ac} must call the
22817 macro @code{AC_ARG_PROGRAM}.
22819 @defmac AC_ARG_PROGRAM
22820 @acindex{ARG_PROGRAM}
22821 @ovindex program_transform_name
22822 Place in output variable @code{program_transform_name} a sequence of
22823 @code{sed} commands for changing the names of installed programs.
22825 If any of the options described below are given to @command{configure},
22826 program names are transformed accordingly.  Otherwise, if
22827 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
22828 is given, the target type followed by a dash is used as a prefix.
22829 Otherwise, no program name transformation is done.
22830 @end defmac
22832 @menu
22833 * Transformation Options::      @command{configure} options to transform names
22834 * Transformation Examples::     Sample uses of transforming names
22835 * Transformation Rules::        Makefile uses of transforming names
22836 @end menu
22838 @node Transformation Options
22839 @subsection Transformation Options
22841 You can specify name transformations by giving @command{configure} these
22842 command line options:
22844 @table @option
22845 @item --program-prefix=@var{prefix}
22846 prepend @var{prefix} to the names;
22848 @item --program-suffix=@var{suffix}
22849 append @var{suffix} to the names;
22851 @item --program-transform-name=@var{expression}
22852 perform @code{sed} substitution @var{expression} on the names.
22853 @end table
22855 @node Transformation Examples
22856 @subsection Transformation Examples
22858 These transformations are useful with programs that can be part of a
22859 cross-compilation development environment.  For example, a
22860 cross-assembler running on x86-64 configured with
22861 @option{--target=aarch64-linux-gnu} is normally installed as
22862 @file{aarch64-linux-gnu-as}, rather than @file{as}, which could be confused
22863 with a native x86-64 assembler.
22865 You can force a program name to begin with @file{g}, if you don't want
22866 GNU programs installed on your system to shadow other programs with
22867 the same name.  For example, if you configure GNU @code{diff} with
22868 @option{--program-prefix=g}, then when you run @samp{make install} it is
22869 installed as @file{/usr/local/bin/gdiff}.
22871 As a more sophisticated example, you could use
22873 @example
22874 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
22875 @end example
22876 @noindent
22878 to prepend @samp{g} to most of the program names in a source tree,
22879 excepting those like @code{gdb} that already have one and those like
22880 @code{less} and @code{lesskey} that aren't GNU programs.  (That is
22881 assuming that you have a source tree containing those programs that is
22882 set up to use this feature.)
22884 One way to install multiple versions of some programs simultaneously is
22885 to append a version number to the name of one or both.  For example, if
22886 you want to keep Autoconf version 1 around for awhile, you can configure
22887 Autoconf version 2 using @option{--program-suffix=2} to install the
22888 programs as @file{/usr/local/bin/autoconf2},
22889 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
22890 that only the binaries are renamed, therefore you'd have problems with
22891 the library files which might overlap.
22893 @node Transformation Rules
22894 @subsection Transformation Rules
22896 Here is how to use the variable @code{program_transform_name} in a
22897 @file{Makefile.in}:
22899 @example
22900 PROGRAMS = cp ls rm
22901 transform = @@program_transform_name@@
22902 install:
22903         for p in $(PROGRAMS); do \
22904           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
22905                                               sed '$(transform)'`; \
22906         done
22908 uninstall:
22909         for p in $(PROGRAMS); do \
22910           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
22911 @c $$ restore font-lock
22912         done
22913 @end example
22915 It is guaranteed that @code{program_transform_name} is never empty, and
22916 that there are no useless separators.  Therefore you may safely embed
22917 @code{program_transform_name} within a sed program using @samp{;}:
22919 @example
22920 transform = @@program_transform_name@@
22921 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
22922 @end example
22924 Whether to do the transformations on documentation files (Texinfo or
22925 @code{man}) is a tricky question; there seems to be no perfect answer,
22926 due to the several reasons for name transforming.  Documentation is not
22927 usually particular to a specific architecture, and Texinfo files do not
22928 conflict with system documentation.  But they might conflict with
22929 earlier versions of the same files, and @code{man} pages sometimes do
22930 conflict with system documentation.  As a compromise, it is probably
22931 best to do name transformations on @code{man} pages but not on Texinfo
22932 manuals.
22934 @node Site Defaults
22935 @section Setting Site Defaults
22936 @cindex Site defaults
22937 @cindex config.site
22939 Autoconf-generated @command{configure} scripts allow your site to provide
22940 default values for some configuration values.  You do this by creating
22941 site- and system-wide initialization files.
22943 @evindex CONFIG_SITE
22944 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
22945 uses its value as the name of a shell script to read; it is recommended
22946 that this be an absolute file name.  Otherwise, it
22947 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
22948 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
22949 settings in machine-specific files override those in machine-independent
22950 ones in case of conflict.
22952 Site files can be arbitrary shell scripts, but only certain kinds of
22953 code are really appropriate to be in them.  Because @command{configure}
22954 reads any cache file after it has read any site files, a site file can
22955 define a default cache file to be shared between all Autoconf-generated
22956 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
22957 you set a default cache file in a site file, it is a good idea to also
22958 set the output variable @code{CC} in that site file, because the cache
22959 file is only valid for a particular compiler, but many systems have
22960 several available.
22962 You can examine or override the value set by a command line option to
22963 @command{configure} in a site file; options set shell variables that have
22964 the same names as the options, with any dashes turned into underscores.
22965 The exceptions are that @option{--without-} and @option{--disable-} options
22966 are like giving the corresponding @option{--with-} or @option{--enable-}
22967 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
22968 sets the variable @code{cache_file} to the value @samp{localcache};
22969 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
22970 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
22971 variable @code{prefix} to the value @samp{/usr}; etc.
22973 Site files are also good places to set default values for other output
22974 variables, such as @code{CFLAGS}, if you need to give them non-default
22975 values: anything you would normally do, repetitively, on the command
22976 line.  If you use non-default values for @var{prefix} or
22977 @var{exec_prefix} (wherever you locate the site file), you can set them
22978 in the site file if you specify it with the @code{CONFIG_SITE}
22979 environment variable.
22981 You can set some cache values in the site file itself.  Doing this is
22982 useful if you are cross-compiling, where it is impossible to check features
22983 that require running a test program.  You could ``prime the cache'' by
22984 setting those values correctly for that system in
22985 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
22986 variables you need to set, see the documentation of the respective
22987 Autoconf macro.  If the variables or their semantics are undocumented,
22988 you may need to look for shell variables with @samp{_cv_} in their names
22989 in the affected @command{configure} scripts, or in the Autoconf M4
22990 source code for those macros; but in that case, their name or semantics
22991 may change in a future Autoconf version.
22993 The cache file is careful to not override any variables set in the site
22994 files.  Similarly, you should not override command-line options in the
22995 site files.  Your code should check that variables such as @code{prefix}
22996 and @code{cache_file} have their default values (as set near the top of
22997 @command{configure}) before changing them.
22999 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
23000 command @samp{configure --prefix=/usr/share/local/gnu} would read this
23001 file (if @code{CONFIG_SITE} is not set to a different file).
23003 @example
23004 # /usr/share/local/gnu/share/config.site for configure
23006 # Change some defaults.
23007 test "$prefix" = NONE && prefix=/usr/share/local/gnu
23008 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
23009 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
23010 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
23011 test "$runstatedir" = '$@{localstatedir@}/run' && runstatedir=/run
23013 # Give Autoconf 2.x generated configure scripts a shared default
23014 # cache file for feature test results, architecture-specific.
23015 if test "$cache_file" = /dev/null; then
23016   cache_file="$prefix/var/config.cache"
23017   # A cache file is only valid for one C compiler.
23018   CC=gcc
23020 @end example
23022 @c Leave this use of "File system" rendered as one word, but
23023 @c slightly obfuscated so as not to trigger the syntax-check prohibition.
23024 @cindex File@/system Hierarchy Standard
23025 @cindex FHS
23027 Another use of @file{config.site} is for priming the directory variables
23028 @c "File system", but slightly obfuscated, as above.
23029 in a manner consistent with the File@/system Hierarchy Standard
23030 (FHS).  Once the following file is installed at
23031 @file{/usr/share/config.site}, a user can execute simply
23032 @code{./configure --prefix=/usr} to get all the directories chosen in
23033 the locations recommended by FHS.
23035 @example
23036 # /usr/share/config.site for FHS defaults when installing below /usr,
23037 # and the respective settings were not changed on the command line.
23038 if test "$prefix" = /usr; then
23039   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
23040   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
23041   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
23043 @end example
23045 @cindex @file{lib64}
23046 @cindex 64-bit libraries
23047 Likewise, on platforms where 64-bit libraries are built by default, then
23048 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
23049 it is appropriate to install @file{/usr/local/@/share/config.site}:
23051 @example
23052 # /usr/local/share/config.site for platforms that prefer
23053 # the directory /usr/local/lib64 over /usr/local/lib.
23054 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
23055 @end example
23058 @c ============================================== Running configure Scripts.
23060 @node Running configure Scripts
23061 @chapter Running @command{configure} Scripts
23062 @cindex @command{configure}
23064 Below are instructions on how to configure a package that uses a
23065 @command{configure} script, suitable for inclusion as an @file{INSTALL}
23066 file in the package.  A plain-text version of @file{INSTALL} which you
23067 may use comes with Autoconf.
23069 @menu
23070 * Basic Installation::          Instructions for typical cases
23071 * Compilers and Options::       Selecting compilers and optimization
23072 * Multiple Architectures::      Compiling for multiple architectures at once
23073 * Installation Names::          Installing in different directories
23074 * Optional Features::           Selecting optional features
23075 * Particular Systems::          Particular systems
23076 * System Type::                 Specifying the system type
23077 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
23078 * Defining Variables::          Specifying the compiler etc.
23079 * configure Invocation::        Changing how @command{configure} runs
23080 @end menu
23082 @set autoconf
23083 @include install.texi
23086 @c ============================================== config.status Invocation
23088 @node config.status Invocation
23089 @chapter config.status Invocation
23090 @cindex @command{config.status}
23092 The @command{configure} script creates a file named @file{config.status},
23093 which actually configures, @dfn{instantiates}, the template files.  It
23094 also records the configuration options that were specified when the
23095 package was last configured in case reconfiguring is needed.
23097 Synopsis:
23098 @example
23099 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
23100 @end example
23102 It configures each @var{tag}; if none are specified, all the templates
23103 are instantiated.  A @var{tag} refers to a file or other tag associated
23104 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
23105 macro (@pxref{Configuration Actions}).  The files must be specified
23106 without their dependencies, as in
23108 @example
23109 ./config.status foobar
23110 @end example
23112 @noindent
23115 @example
23116 ./config.status foobar:foo.in:bar.in
23117 @end example
23119 The supported options are:
23121 @table @option
23122 @item --help
23123 @itemx -h
23124 Print a summary of the command line options, the list of the template
23125 files, and exit.
23127 @item --version
23128 @itemx -V
23129 Print the version number of Autoconf and the configuration settings,
23130 and exit.
23132 @item --config
23133 Print the configuration settings in reusable way, quoted for the shell,
23134 and exit.  For example, for a debugging build that otherwise reuses the
23135 configuration from a different build directory @var{build-dir} of a
23136 package in @var{src-dir}, you could use the following:
23138 @example
23139 args=`@var{build-dir}/config.status --config`
23140 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
23141 @end example
23143 @noindent
23144 Note that it may be necessary to override a @option{--srcdir} setting
23145 that was saved in the configuration, if the arguments are used in a
23146 different build directory.
23148 @item --silent
23149 @itemx --quiet
23150 @itemx -q
23151 Do not print progress messages.
23153 @item --debug
23154 @itemx -d
23155 Don't remove the temporary files.
23157 @item --file=@var{file}[:@var{template}]
23158 Require that @var{file} be instantiated as if
23159 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
23160 @var{file} and @var{template} may be @samp{-} in which case the standard
23161 output and/or standard input, respectively, is used.  If a
23162 @var{template} file name is relative, it is first looked for in the build
23163 tree, and then in the source tree.  @xref{Configuration Actions}, for
23164 more details.
23166 This option and the following ones provide one way for separately
23167 distributed packages to share the values computed by @command{configure}.
23168 Doing so can be useful if some of the packages need a superset of the
23169 features that one of them, perhaps a common library, does.  These
23170 options allow a @file{config.status} file to create files other than the
23171 ones that its @file{configure.ac} specifies, so it can be used for a
23172 different package, or for extracting a subset of values.  For example,
23174 @example
23175 echo '@@CC@@' | ./config.status --file=-
23176 @end example
23178 @noindent
23179 provides the value of @code{@@CC@@} on standard output.
23181 @item --header=@var{file}[:@var{template}]
23182 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
23184 @item --recheck
23185 Ask @file{config.status} to update itself and exit (no instantiation).
23186 This option is useful if you change @command{configure}, so that the
23187 results of some tests might be different from the previous run.  The
23188 @option{--recheck} option reruns @command{configure} with the same arguments
23189 you used before, plus the @option{--no-create} option, which prevents
23190 @command{configure} from running @file{config.status} and creating
23191 @file{Makefile} and other files, and the @option{--no-recursion} option,
23192 which prevents @command{configure} from running other @command{configure}
23193 scripts in subdirectories.  (This is so other Make rules can
23194 run @file{config.status} when it changes; @pxref{Automatic Remaking},
23195 for an example).
23196 @end table
23198 @file{config.status} checks several optional environment variables that
23199 can alter its behavior:
23201 @anchor{CONFIG_SHELL}
23202 @defvar CONFIG_SHELL
23203 @evindex CONFIG_SHELL
23204 The shell with which to run @command{configure}.  It must be
23205 Bourne-compatible, and the absolute name of the shell should be passed.
23206 The default is a shell that supports @code{LINENO} if available, and
23207 @file{/bin/sh} otherwise.
23208 @end defvar
23210 @defvar CONFIG_STATUS
23211 @evindex CONFIG_STATUS
23212 The file name to use for the shell script that records the
23213 configuration.  The default is @file{./config.status}.  This variable is
23214 useful when one package uses parts of another and the @command{configure}
23215 scripts shouldn't be merged because they are maintained separately.
23216 @end defvar
23218 You can use @file{./config.status} in your makefiles.  For example, in
23219 the dependencies given above (@pxref{Automatic Remaking}),
23220 @file{config.status} is run twice when @file{configure.ac} has changed.
23221 If that bothers you, you can make each run only regenerate the files for
23222 that rule:
23223 @example
23224 @group
23225 config.h: stamp-h
23226 stamp-h: config.h.in config.status
23227         ./config.status config.h
23228         echo > stamp-h
23230 Makefile: Makefile.in config.status
23231         ./config.status Makefile
23232 @end group
23233 @end example
23235 The calling convention of @file{config.status} has changed; see
23236 @ref{Obsolete config.status Use}, for details.
23239 @c =================================================== Obsolete Constructs
23241 @node Obsolete Constructs
23242 @chapter Obsolete Constructs
23243 @cindex Obsolete constructs
23245 Autoconf changes, and throughout the years some constructs have been
23246 obsoleted.  Most of the changes involve the macros, but in some cases
23247 the tools themselves, or even some concepts, are now considered
23248 obsolete.
23250 You may completely skip this chapter if you are new to Autoconf.  Its
23251 intention is mainly to help maintainers updating their packages by
23252 understanding how to move to more modern constructs.
23254 @menu
23255 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
23256 * acconfig Header::             Additional entries in @file{config.h.in}
23257 * autoupdate Invocation::       Automatic update of @file{configure.ac}
23258 * Obsolete Macros::             Backward compatibility macros
23259 * Autoconf 1::                  Tips for upgrading your files
23260 * Autoconf 2.13::               Some fresher tips
23261 @end menu
23263 @node Obsolete config.status Use
23264 @section Obsolete @file{config.status} Invocation
23266 @file{config.status} now supports arguments to specify the files to
23267 instantiate; see @ref{config.status Invocation}, for more details.
23268 Before, environment variables had to be used.
23270 @defvar CONFIG_COMMANDS
23271 @evindex CONFIG_COMMANDS
23272 The tags of the commands to execute.  The default is the arguments given
23273 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
23274 @file{configure.ac}.
23275 @end defvar
23277 @defvar CONFIG_FILES
23278 @evindex CONFIG_FILES
23279 The files in which to perform @samp{@@@var{variable}@@} substitutions.
23280 The default is the arguments given to @code{AC_OUTPUT} and
23281 @code{AC_CONFIG_FILES} in @file{configure.ac}.
23282 @end defvar
23284 @defvar CONFIG_HEADERS
23285 @evindex CONFIG_HEADERS
23286 The files in which to substitute C @code{#define} statements.  The
23287 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
23288 macro was not called, @file{config.status} ignores this variable.
23289 @end defvar
23291 @defvar CONFIG_LINKS
23292 @evindex CONFIG_LINKS
23293 The symbolic links to establish.  The default is the arguments given to
23294 @code{AC_CONFIG_LINKS}; if that macro was not called,
23295 @file{config.status} ignores this variable.
23296 @end defvar
23298 In @ref{config.status Invocation}, using this old interface, the example
23299 would be:
23301 @example
23302 @group
23303 config.h: stamp-h
23304 stamp-h: config.h.in config.status
23305         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
23306           CONFIG_HEADERS=config.h ./config.status
23307         echo > stamp-h
23309 Makefile: Makefile.in config.status
23310         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
23311           CONFIG_FILES=Makefile ./config.status
23312 @end group
23313 @end example
23315 @noindent
23316 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
23317 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
23318 for @code{CONFIG_COMMANDS}, etc.)
23321 @node acconfig Header
23322 @section @file{acconfig.h}
23324 @cindex @file{acconfig.h}
23325 @cindex @file{config.h.top}
23326 @cindex @file{config.h.bot}
23328 In order to produce @file{config.h.in}, @command{autoheader} needs to
23329 build or to find templates for each symbol.  Modern releases of Autoconf
23330 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
23331 Macros}), but in older releases a file, @file{acconfig.h}, contained the
23332 list of needed templates.  @command{autoheader} copied comments and
23333 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
23334 the current directory, if present.  This file used to be mandatory if
23335 you @code{AC_DEFINE} any additional symbols.
23337 Modern releases of Autoconf also provide @code{AH_TOP} and
23338 @code{AH_BOTTOM} if you need to prepend/append some information to
23339 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
23340 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
23341 @command{autoheader} copies the lines before the line containing
23342 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
23343 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
23344 @command{autoheader} copies the lines after that line to the end of the
23345 file it generates.  Either or both of those strings may be omitted.  An
23346 even older alternate way to produce the same effect in ancient versions
23347 of Autoconf is to create the files @file{@var{file}.top} (typically
23348 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
23349 directory.  If they exist, @command{autoheader} copies them to the
23350 beginning and end, respectively, of its output.
23352 In former versions of Autoconf, the files used in preparing a software
23353 package for distribution were:
23354 @example
23355 @group
23356 configure.ac --.   .------> autoconf* -----> configure
23357                +---+
23358 [aclocal.m4] --+   `---.
23359 [acsite.m4] ---'       |
23360                        +--> [autoheader*] -> [config.h.in]
23361 [acconfig.h] ----.     |
23362                  +-----'
23363 [config.h.top] --+
23364 [config.h.bot] --'
23365 @end group
23366 @end example
23368 Using only the @code{AH_} macros, @file{configure.ac} should be
23369 self-contained, and should not depend upon @file{acconfig.h} etc.
23372 @node autoupdate Invocation
23373 @section Using @command{autoupdate} to Modernize @file{configure.ac}
23374 @cindex @command{autoupdate}
23376 The @command{autoupdate} program updates a @file{configure.ac} file that
23377 calls Autoconf macros by their old names to use the current macro names.
23378 In version 2 of Autoconf, most of the macros were renamed to use a more
23379 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
23380 description of the new scheme.  Although the old names still work
23381 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
23382 new names), you can make your @file{configure.ac} files more readable
23383 and make it easier to use the current Autoconf documentation if you
23384 update them to use the new macro names.
23386 @evindex SIMPLE_BACKUP_SUFFIX
23387 If given no arguments, @command{autoupdate} updates @file{configure.ac},
23388 backing up the original version with the suffix @file{~} (or the value
23389 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
23390 set).  If you give @command{autoupdate} an argument, it reads that file
23391 instead of @file{configure.ac} and writes the updated file to the
23392 standard output.
23394 @noindent
23395 @command{autoupdate} accepts the following options:
23397 @table @option
23398 @item --help
23399 @itemx -h
23400 Print a summary of the command line options and exit.
23402 @item --version
23403 @itemx -V
23404 Print the version number of Autoconf and exit.
23406 @item --verbose
23407 @itemx -v
23408 Report processing steps.
23410 @item --debug
23411 @itemx -d
23412 Don't remove the temporary files.
23414 @item --force
23415 @itemx -f
23416 Force the update even if the file has not changed.  Disregard the cache.
23418 @item --include=@var{dir}
23419 @itemx -I @var{dir}
23420 Also look for input files in @var{dir}.  Multiple invocations accumulate.
23421 Directories are browsed from last to first.
23423 @item --prepend-include=@var{dir}
23424 @itemx -B @var{dir}
23425 Prepend directory @var{dir} to the search path.  This is used to include
23426 the language-specific files before any third-party macros.
23427 @end table
23429 @node Obsolete Macros
23430 @section Obsolete Macros
23432 Several macros are obsoleted in Autoconf, for various reasons (typically
23433 they failed to quote properly, couldn't be extended for more recent
23434 issues, etc.).  They are still supported, but deprecated: their use
23435 should be avoided.
23437 During the jump from Autoconf version 1 to version 2, most of the
23438 macros were renamed to use a more uniform and descriptive naming scheme,
23439 but their signature did not change.  @xref{Macro Names}, for a
23440 description of the new naming scheme.  Below, if there is just the mapping
23441 from old names to new names for these macros, the reader is invited to
23442 refer to the definition of the new macro for the signature and the
23443 description.
23445 @defmac AC_AIX
23446 @acindex{AIX}
23447 @cvindex _ALL_SOURCE
23448 This macro is a platform-specific subset of
23449 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23450 @end defmac
23452 @defmac AC_ALLOCA
23453 @acindex{ALLOCA}
23454 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
23455 @end defmac
23457 @defmac AC_ARG_ARRAY
23458 @acindex{ARG_ARRAY}
23459 Removed because of limited usefulness.
23460 @end defmac
23462 @defmac AC_C_CROSS
23463 @acindex{C_CROSS}
23464 This macro is obsolete; it does nothing.
23465 @end defmac
23467 @defmac AC_C_LONG_DOUBLE
23468 @acindex{C_LONG_DOUBLE}
23469 @cvindex HAVE_LONG_DOUBLE
23470 If the C compiler supports a working @code{long double} type with more
23471 range or precision than the @code{double} type, define
23472 @code{HAVE_LONG_DOUBLE}.
23474 You should use @code{AC_TYPE_LONG_DOUBLE} or
23475 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23476 @end defmac
23478 @defmac AC_CANONICAL_SYSTEM
23479 @acindex{CANONICAL_SYSTEM}
23480 Determine the system type and set output variables to the names of the
23481 canonical system types.  @xref{Canonicalizing}, for details about the
23482 variables this macro sets.
23484 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
23485 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
23486 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
23487 other macros (@pxref{Canonicalizing}).
23488 @end defmac
23490 @defmac AC_CHAR_UNSIGNED
23491 @acindex{CHAR_UNSIGNED}
23492 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
23493 @end defmac
23495 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
23496 @acindex{CHECK_TYPE}
23497 Autoconf, up to 2.13, used to provide this version of
23498 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
23499 it is a member of the @code{CHECK} clan, it does
23500 more than just checking.  Secondly, missing types are defined
23501 using @code{#define}, not @code{typedef}, and this can lead to
23502 problems in the case of pointer types.
23504 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
23505 @ref{Generic Types}, for the description of the current macro.
23507 If the type @var{type} is not defined, define it to be the C (or C++)
23508 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
23510 This macro is equivalent to:
23512 @example
23513 AC_CHECK_TYPE([@var{type}], [],
23514   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
23515      [Define to `@var{default}'
23516       if <sys/types.h> does not define.])])
23517 @end example
23519 In order to keep backward compatibility, the two versions of
23520 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
23522 @enumerate
23523 @item
23524 If there are three or four arguments, the modern version is used.
23526 @item
23527 If the second argument appears to be a C or C++ type, then the
23528 obsolete version is used.  This happens if the argument is a C or C++
23529 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
23530 followed by one of @samp{[(* } and then by a string of zero or more
23531 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
23533 @item
23534 If the second argument is spelled with the alphabet of valid C and C++
23535 types, the user is warned and the modern version is used.
23537 @item
23538 Otherwise, the modern version is used.
23539 @end enumerate
23541 @noindent
23542 You are encouraged either to use a valid builtin type, or to use the
23543 equivalent modern code (see above), or better yet, to use
23544 @code{AC_CHECK_TYPES} together with
23546 @example
23547 #ifndef HAVE_LOFF_T
23548 typedef loff_t off_t;
23549 #endif
23550 @end example
23551 @end defmac
23552 @c end of AC_CHECK_TYPE
23554 @defmac AC_CHECKING (@var{feature-description})
23555 @acindex{CHECKING}
23556 Same as
23558 @example
23559 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
23560 @end example
23562 @noindent
23563 @xref{AC_MSG_NOTICE}.
23564 @end defmac
23566 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
23567   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
23568 @acindex{COMPILE_CHECK}
23569 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
23570 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
23571 addition that it prints @samp{checking for @var{echo-text}} to the
23572 standard output first, if @var{echo-text} is non-empty.  Use
23573 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
23574 messages (@pxref{Printing Messages}).
23575 @end defmac
23577 @defmac AC_CONST
23578 @acindex{CONST}
23579 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
23580 @end defmac
23582 @defmac AC_CROSS_CHECK
23583 @acindex{CROSS_CHECK}
23584 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
23585 @code{:-)}.
23586 @end defmac
23588 @defmac AC_CYGWIN
23589 @acindex{CYGWIN}
23590 @evindex CYGWIN
23591 Check for the Cygwin environment in which case the shell variable
23592 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
23593 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
23594 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
23596 @example
23597 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
23598 case $host_os in
23599   *cygwin* ) CYGWIN=yes;;
23600          * ) CYGWIN=no;;
23601 esac
23602 @end example
23604 Beware that the variable @env{CYGWIN} has a special meaning when
23605 running Cygwin, and should not be changed.  That's yet another reason
23606 not to use this macro.
23607 @end defmac
23609 @defmac AC_DECL_SYS_SIGLIST
23610 @acindex{DECL_SYS_SIGLIST}
23611 @cvindex SYS_SIGLIST_DECLARED
23612 Same as:
23614 @example
23615 AC_CHECK_DECLS([sys_siglist], [], [],
23616 [#include <signal.h>
23617 /* NetBSD declares sys_siglist in unistd.h.  */
23618 #ifdef HAVE_UNISTD_H
23619 # include <unistd.h>
23620 #endif
23622 @end example
23624 @noindent
23625 @xref{AC_CHECK_DECLS}.
23626 @end defmac
23628 @defmac AC_DECL_YYTEXT
23629 @acindex{DECL_YYTEXT}
23630 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23631 @end defmac
23633 @defmac AC_DIAGNOSE (@var{category}, @var{message})
23634 @acindex{DIAGNOSE}
23635 Replaced by @code{m4_warn} (@pxref{m4_warn}).
23636 @end defmac
23638 @defmac AC_DIR_HEADER
23639 @acindex{DIR_HEADER}
23640 @cvindex DIRENT
23641 @cvindex SYSNDIR
23642 @cvindex SYSDIR
23643 @cvindex NDIR
23644 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
23645 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
23646 (@pxref{AC_HEADER_DIRENT}),
23647 but defines a different set of C preprocessor macros to indicate which
23648 header file is found:
23650 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
23651 @item Header            @tab Old Symbol     @tab New Symbol
23652 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
23653 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
23654 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
23655 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
23656 @end multitable
23657 @end defmac
23659 @defmac AC_DYNIX_SEQ
23660 @acindex{DYNIX_SEQ}
23661 If on DYNIX/ptx, add @option{-lseq} to output variable
23662 @code{LIBS}.  This macro used to be defined as
23664 @example
23665 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
23666 @end example
23668 @noindent
23669 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
23670 @end defmac
23672 @defmac AC_EXEEXT
23673 @acindex{EXEEXT}
23674 @ovindex EXEEXT
23675 Defined the output variable @code{EXEEXT} based on the output of the
23676 compiler, which is now done automatically.  Typically set to empty
23677 string if Posix and @samp{.exe} if a DOS variant.
23678 @end defmac
23680 @defmac AC_EMXOS2
23681 @acindex{EMXOS2}
23682 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
23683 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
23684 check the nature of the host is using @code{AC_CANONICAL_HOST}
23685 (@pxref{Canonicalizing}).
23686 @end defmac
23688 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
23689   @ovar{action-if-not-given})
23690 @acindex{ENABLE}
23691 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
23692 support providing a help string (@pxref{AC_ARG_ENABLE}).
23693 @end defmac
23695 @defmac AC_ERROR
23696 @acindex{ERROR}
23697 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
23698 @end defmac
23700 @defmac AC_FATAL (@var{message})
23701 @acindex{FATAL}
23702 Replaced by @code{m4_fatal} (@pxref{m4_fatal}).
23703 @end defmac
23705 @defmac AC_FIND_X
23706 @acindex{FIND_X}
23707 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
23708 @end defmac
23710 @defmac AC_FIND_XTRA
23711 @acindex{FIND_XTRA}
23712 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
23713 @end defmac
23715 @defmac AC_FOREACH
23716 @acindex{FOREACH}
23717 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
23718 @end defmac
23720 @defmac AC_FUNC_CHECK
23721 @acindex{FUNC_CHECK}
23722 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
23723 @end defmac
23725 @anchor{AC_FUNC_SETVBUF_REVERSED}
23726 @defmac AC_FUNC_SETVBUF_REVERSED
23727 @acindex{FUNC_SETVBUF_REVERSED}
23728 @cvindex SETVBUF_REVERSED
23729 @c @fuindex setvbuf
23730 @prindex @code{setvbuf}
23731 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
23732 the buffering type as its second argument and the buffer pointer as the
23733 third, instead of the other way around, and defined
23734 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
23735 were those based on SVR2, which became obsolete in 1987, and the macro
23736 is no longer needed.
23737 @end defmac
23739 @defmac AC_FUNC_WAIT3
23740 @acindex{FUNC_WAIT3}
23741 @cvindex HAVE_WAIT3
23742 @c @fuindex wait3
23743 @prindex @code{wait3}
23744 If @code{wait3} is found and fills in the contents of its third argument
23745 (a @samp{struct rusage *}), which HP-UX does not do, define
23746 @code{HAVE_WAIT3}.
23748 These days portable programs should use @code{waitpid}, not
23749 @code{wait3}, as @code{wait3} has been removed from Posix.
23750 @end defmac
23752 @defmac AC_GCC_TRADITIONAL
23753 @acindex{GCC_TRADITIONAL}
23754 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
23755 @end defmac
23757 @defmac AC_GETGROUPS_T
23758 @acindex{GETGROUPS_T}
23759 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
23760 @end defmac
23762 @defmac AC_GETLOADAVG
23763 @acindex{GETLOADAVG}
23764 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
23765 @end defmac
23767 @defmac AC_GNU_SOURCE
23768 @acindex{GNU_SOURCE}
23769 @cvindex _GNU_SOURCE
23770 This macro is a platform-specific subset of
23771 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23772 @end defmac
23774 @defmac AC_HAVE_FUNCS
23775 @acindex{HAVE_FUNCS}
23776 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
23777 @end defmac
23779 @defmac AC_HAVE_HEADERS
23780 @acindex{HAVE_HEADERS}
23781 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
23782 @end defmac
23784 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
23785   @ovar{action-if-not-found}, @ovar{other-libraries})
23786 @acindex{HAVE_LIBRARY}
23787 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
23788 @var{function} argument of @code{main}.  In addition, @var{library} can
23789 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
23790 all of those cases, the compiler is passed @option{-lfoo}.  However,
23791 @var{library} cannot be a shell variable; it must be a literal name.
23792 @xref{AC_CHECK_LIB}.
23793 @end defmac
23795 @defmac AC_HAVE_POUNDBANG
23796 @acindex{HAVE_POUNDBANG}
23797 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
23798 @end defmac
23800 @defmac AC_HEADER_CHECK
23801 @acindex{HEADER_CHECK}
23802 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
23803 @end defmac
23805 @defmac AC_HEADER_EGREP
23806 @acindex{HEADER_EGREP}
23807 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
23808 @end defmac
23810 @anchor{AC_HEADER_TIME}
23811 @defmac AC_HEADER_TIME
23812 @acindex{HEADER_TIME}
23813 @cvindex TIME_WITH_SYS_TIME
23814 @hdrindex{time.h}
23815 @hdrindex{sys/time.h}
23816 @caindex header_time
23817 This macro used to check whether it was possible to include
23818 @file{time.h} and @file{sys/time.h} in the same source file,
23819 defining @code{TIME_WITH_SYS_TIME} if so.
23821 Nowadays, it is equivalent to @samp{AC_CHECK_HEADERS([sys/time.h])},
23822 although it does still define @code{TIME_WITH_SYS_TIME} for
23823 compatibility's sake.  @file{time.h} is universally present, and the
23824 systems on which @file{sys/time.h} conflicted with @file{time.h} are
23825 obsolete.
23826 @end defmac
23828 @defmac AC_HELP_STRING
23829 @acindex{HELP_STRING}
23830 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
23831 @end defmac
23833 @defmac AC_INIT (@var{unique-file-in-source-dir})
23834 @acindex{INIT}
23835 Formerly @code{AC_INIT} used to have a single argument, and was
23836 equivalent to:
23838 @example
23839 AC_INIT
23840 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
23841 @end example
23842 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
23843 @end defmac
23845 @defmac AC_INLINE
23846 @acindex{INLINE}
23847 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
23848 @end defmac
23850 @defmac AC_INT_16_BITS
23851 @acindex{INT_16_BITS}
23852 @cvindex INT_16_BITS
23853 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
23854 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
23855 @end defmac
23857 @defmac AC_IRIX_SUN
23858 @acindex{IRIX_SUN}
23859 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
23860 @code{LIBS}.  If you were using it to get @code{getmntent}, use
23861 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
23862 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
23863 getpwnam)}.  Up to Autoconf 2.13, it used to be
23865 @example
23866 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
23867 @end example
23869 @noindent
23870 now it is defined as
23872 @example
23873 AC_FUNC_GETMNTENT
23874 AC_CHECK_LIB([sun], [getpwnam])
23875 @end example
23877 @noindent
23878 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
23879 @end defmac
23881 @defmac AC_ISC_POSIX
23882 @acindex{ISC_POSIX}
23883 @ovindex LIBS
23884 This macro adds @option{-lcposix} to output variable @code{LIBS} if
23885 necessary for Posix facilities.  Sun dropped support for the obsolete
23886 INTERACTIVE Systems Corporation Unix on 2006-07-23.  New programs
23887 need not use this macro.  It is implemented as
23888 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
23889 @end defmac
23891 @defmac AC_LANG_C
23892 @acindex{LANG_C}
23893 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
23894 @end defmac
23896 @defmac AC_LANG_CPLUSPLUS
23897 @acindex{LANG_CPLUSPLUS}
23898 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
23899 @end defmac
23901 @defmac AC_LANG_FORTRAN77
23902 @acindex{LANG_FORTRAN77}
23903 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
23904 @end defmac
23906 @defmac AC_LANG_RESTORE
23907 @acindex{LANG_RESTORE}
23908 Select the @var{language} that is saved on the top of the stack, as set
23909 by @code{AC_LANG_SAVE}, remove it from the stack, and call
23910 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
23911 preferred way to change languages.
23912 @end defmac
23914 @defmac AC_LANG_SAVE
23915 @acindex{LANG_SAVE}
23916 Remember the current language (as set by @code{AC_LANG}) on a stack.
23917 The current language does not change.  @code{AC_LANG_PUSH} is preferred
23918 (@pxref{AC_LANG_PUSH}).
23919 @end defmac
23921 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
23922 @acindex{LINK_FILES}
23923 This is an obsolete version of @code{AC_CONFIG_LINKS}
23924 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
23926 @example
23927 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
23928               host.h            object.h)
23929 @end example
23931 @noindent
23934 @example
23935 AC_CONFIG_LINKS([host.h:config/$machine.h
23936                 object.h:config/$obj_format.h])
23937 @end example
23938 @end defmac
23940 @defmac AC_LN_S
23941 @acindex{LN_S}
23942 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
23943 @end defmac
23945 @defmac AC_LONG_64_BITS
23946 @acindex{LONG_64_BITS}
23947 @cvindex LONG_64_BITS
23948 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
23949 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
23950 (@pxref{AC_CHECK_SIZEOF}).
23951 @end defmac
23953 @defmac AC_LONG_DOUBLE
23954 @acindex{LONG_DOUBLE}
23955 If the C compiler supports a working @code{long double} type with more
23956 range or precision than the @code{double} type, define
23957 @code{HAVE_LONG_DOUBLE}.
23959 You should use @code{AC_TYPE_LONG_DOUBLE} or
23960 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23961 @end defmac
23963 @defmac AC_LONG_FILE_NAMES
23964 @acindex{LONG_FILE_NAMES}
23965 Replaced by
23966 @example
23967 AC_SYS_LONG_FILE_NAMES
23968 @end example
23969 @noindent
23970 @xref{AC_SYS_LONG_FILE_NAMES}.
23971 @end defmac
23973 @defmac AC_MAJOR_HEADER
23974 @acindex{MAJOR_HEADER}
23975 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
23976 @end defmac
23978 @defmac AC_MEMORY_H
23979 @acindex{MEMORY_H}
23980 @cvindex NEED_MEMORY_H
23981 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
23982 defined in @file{memory.h}.  Today it is equivalent to
23983 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
23984 your code to get the @code{mem} functions from @file{string.h} instead.
23985 @end defmac
23987 @defmac AC_MINGW32
23988 @acindex{MINGW32}
23989 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
23990 environment and sets @code{MINGW32}.  Don't use this macro, the
23991 dignified means to check the nature of the host is using
23992 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23993 @end defmac
23995 @defmac AC_MINIX
23996 @acindex{MINIX}
23997 @cvindex _MINIX
23998 @cvindex _POSIX_SOURCE
23999 @cvindex _POSIX_1_SOURCE
24000 This macro is a platform-specific subset of
24001 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
24002 @end defmac
24004 @defmac AC_MINUS_C_MINUS_O
24005 @acindex{MINUS_C_MINUS_O}
24006 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
24007 @end defmac
24009 @defmac AC_MMAP
24010 @acindex{MMAP}
24011 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
24012 @end defmac
24014 @defmac AC_MODE_T
24015 @acindex{MODE_T}
24016 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
24017 @end defmac
24019 @defmac AC_OBJEXT
24020 @acindex{OBJEXT}
24021 @ovindex OBJEXT
24022 Defined the output variable @code{OBJEXT} based on the output of the
24023 compiler, after .c files have been excluded.  Typically set to @samp{o}
24024 if Posix, @samp{obj} if a DOS variant.
24025 Now the compiler checking macros handle
24026 this automatically.
24027 @end defmac
24029 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
24030 @acindex{OBSOLETE}
24031 Make M4 print a message to the standard error output warning that
24032 @var{this-macro-name} is obsolete, and giving the file and line number
24033 where it was called.  @var{this-macro-name} should be the name of the
24034 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
24035 it is printed at the end of the warning message; for example, it can be
24036 a suggestion for what to use instead of @var{this-macro-name}.
24038 For instance
24040 @example
24041 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
24042 @end example
24044 @noindent
24045 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
24046 services to the user (@pxref{AU_DEFUN}).
24047 @end defmac
24049 @defmac AC_OFF_T
24050 @acindex{OFF_T}
24051 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
24052 @end defmac
24054 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
24055 @acindex{OUTPUT}
24056 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
24057 interface is equivalent to:
24059 @example
24060 @group
24061 AC_CONFIG_FILES(@var{file}@dots{})
24062 AC_CONFIG_COMMANDS([default],
24063                    @var{extra-cmds}, @var{init-cmds})
24064 AC_OUTPUT
24065 @end group
24066 @end example
24068 @noindent
24069 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
24070 @end defmac
24072 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
24073 @acindex{OUTPUT_COMMANDS}
24074 Specify additional shell commands to run at the end of
24075 @file{config.status}, and shell commands to initialize any variables
24076 from @command{configure}.  This macro may be called multiple times.  It is
24077 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
24079 Here is an unrealistic example:
24081 @example
24082 fubar=27
24083 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
24084                    [fubar=$fubar])
24085 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
24086                    [echo init bit])
24087 @end example
24089 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
24090 additional key, an important difference is that
24091 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
24092 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
24093 can safely be given macro calls as arguments:
24095 @example
24096 AC_CONFIG_COMMANDS(foo, [my_FOO()])
24097 @end example
24099 @noindent
24100 Conversely, where one level of quoting was enough for literal strings
24101 with @code{AC_OUTPUT_COMMANDS}, you need two with
24102 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
24104 @example
24105 @group
24106 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
24107 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
24108 @end group
24109 @end example
24110 @end defmac
24112 @defmac AC_PID_T
24113 @acindex{PID_T}
24114 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
24115 @end defmac
24117 @defmac AC_PREFIX
24118 @acindex{PREFIX}
24119 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
24120 @end defmac
24122 @defmac AC_PROG_CC_C89
24123 @acindex{PROG_CC_C89}
24124 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
24125 @end defmac
24127 @defmac AC_PROG_CC_C99
24128 @acindex{PROG_CC_C99}
24129 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
24130 @end defmac
24132 @defmac AC_PROG_CC_STDC
24133 @acindex{PROG_CC_STDC}
24134 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
24135 @end defmac
24137 @defmac AC_PROGRAMS_CHECK
24138 @acindex{PROGRAMS_CHECK}
24139 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
24140 @end defmac
24142 @defmac AC_PROGRAMS_PATH
24143 @acindex{PROGRAMS_PATH}
24144 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
24145 @end defmac
24147 @defmac AC_PROGRAM_CHECK
24148 @acindex{PROGRAM_CHECK}
24149 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
24150 @end defmac
24152 @defmac AC_PROGRAM_EGREP
24153 @acindex{PROGRAM_EGREP}
24154 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
24155 @end defmac
24157 @defmac AC_PROGRAM_PATH
24158 @acindex{PROGRAM_PATH}
24159 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
24160 @end defmac
24162 @defmac AC_REMOTE_TAPE
24163 @acindex{REMOTE_TAPE}
24164 Removed because of limited usefulness.
24165 @end defmac
24167 @defmac AC_RESTARTABLE_SYSCALLS
24168 @acindex{RESTARTABLE_SYSCALLS}
24169 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
24170 these days portable programs should use @code{sigaction} with
24171 @code{SA_RESTART} if they want restartable system calls.  They should
24172 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
24173 system call is restartable is a dynamic issue, not a configuration-time
24174 issue.
24175 @end defmac
24177 @defmac AC_RETSIGTYPE
24178 @acindex{RETSIGTYPE}
24179 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
24180 is obsolete when assuming C89 or better.
24181 @end defmac
24183 @defmac AC_RSH
24184 @acindex{RSH}
24185 Removed because of limited usefulness.
24186 @end defmac
24188 @defmac AC_SCO_INTL
24189 @acindex{SCO_INTL}
24190 @ovindex LIBS
24191 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
24192 macro used to do this:
24194 @example
24195 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
24196 @end example
24198 @noindent
24199 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
24200 @end defmac
24202 @defmac AC_SETVBUF_REVERSED
24203 @acindex{SETVBUF_REVERSED}
24204 Replaced by
24205 @example
24206 AC_FUNC_SETVBUF_REVERSED
24207 @end example
24208 @noindent
24209 @xref{AC_FUNC_SETVBUF_REVERSED}.
24210 @end defmac
24212 @defmac AC_SET_MAKE
24213 @acindex{SET_MAKE}
24214 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
24215 @end defmac
24217 @defmac AC_SIZEOF_TYPE
24218 @acindex{SIZEOF_TYPE}
24219 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
24220 @end defmac
24222 @defmac AC_SIZE_T
24223 @acindex{SIZE_T}
24224 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
24225 @end defmac
24227 @defmac AC_STAT_MACROS_BROKEN
24228 @acindex{STAT_MACROS_BROKEN}
24229 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
24230 @end defmac
24232 @defmac AC_STDC_HEADERS
24233 @acindex{STDC_HEADERS}
24234 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}), which
24235 is itself obsolete.  Nowadays it is safe to assume the facilities of C90
24236 exist.
24237 @end defmac
24239 @defmac AC_STRCOLL
24240 @acindex{STRCOLL}
24241 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
24242 @end defmac
24244 @defmac AC_STRUCT_ST_BLKSIZE
24245 @acindex{STRUCT_ST_BLKSIZE}
24246 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
24247 @cvindex HAVE_ST_BLKSIZE
24248 If @code{struct stat} contains an @code{st_blksize} member, define
24249 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
24250 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
24251 the future.  This macro is obsoleted, and should be replaced by
24253 @example
24254 AC_CHECK_MEMBERS([struct stat.st_blksize])
24255 @end example
24256 @noindent
24257 @xref{AC_CHECK_MEMBERS}.
24258 @end defmac
24260 @defmac AC_STRUCT_ST_RDEV
24261 @acindex{STRUCT_ST_RDEV}
24262 @cvindex HAVE_ST_RDEV
24263 @cvindex HAVE_STRUCT_STAT_ST_RDEV
24264 If @code{struct stat} contains an @code{st_rdev} member, define
24265 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
24266 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
24267 in the future.  Actually, even the new macro is obsolete and should be
24268 replaced by:
24269 @example
24270 AC_CHECK_MEMBERS([struct stat.st_rdev])
24271 @end example
24272 @noindent
24273 @xref{AC_CHECK_MEMBERS}.
24274 @end defmac
24276 @defmac AC_ST_BLKSIZE
24277 @acindex{ST_BLKSIZE}
24278 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24279 @end defmac
24281 @defmac AC_ST_BLOCKS
24282 @acindex{ST_BLOCKS}
24283 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
24284 @end defmac
24286 @defmac AC_ST_RDEV
24287 @acindex{ST_RDEV}
24288 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24289 @end defmac
24291 @defmac AC_SYS_RESTARTABLE_SYSCALLS
24292 @acindex{SYS_RESTARTABLE_SYSCALLS}
24293 @cvindex HAVE_RESTARTABLE_SYSCALLS
24294 If the system automatically restarts a system call that is interrupted
24295 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
24296 not check whether system calls are restarted in general---it checks whether a
24297 signal handler installed with @code{signal} (but not @code{sigaction})
24298 causes system calls to be restarted.  It does not check whether system calls
24299 can be restarted when interrupted by signals that have no handler.
24301 These days portable programs should use @code{sigaction} with
24302 @code{SA_RESTART} if they want restartable system calls.  They should
24303 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
24304 system call is restartable is a dynamic issue, not a configuration-time
24305 issue.
24306 @end defmac
24308 @defmac AC_SYS_SIGLIST_DECLARED
24309 @acindex{SYS_SIGLIST_DECLARED}
24310 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
24311 name is obsolete, as the same functionality is now achieved via
24312 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
24313 @end defmac
24315 @defmac AC_TEST_CPP
24316 @acindex{TEST_CPP}
24317 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
24318 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
24319 @end defmac
24321 @defmac AC_TEST_PROGRAM
24322 @acindex{TEST_PROGRAM}
24323 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
24324 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
24325 @end defmac
24327 @defmac AC_TIMEZONE
24328 @acindex{TIMEZONE}
24329 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
24330 @end defmac
24332 @defmac AC_TIME_WITH_SYS_TIME
24333 @acindex{TIME_WITH_SYS_TIME}
24334 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}), which is
24335 itself obsolete; nowadays one need only do
24336 @samp{AC_CHECK_HEADERS([sys/time.h])}.
24337 @end defmac
24339 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
24340   @ovar{action-if-true}, @ovar{action-if-false})
24341 @acindex{TRY_COMPILE}
24342 Same as:
24344 @example
24345 AC_COMPILE_IFELSE(
24346   [AC_LANG_PROGRAM([[@var{includes}]],
24347      [[@var{function-body}]])],
24348   [@var{action-if-true}],
24349   [@var{action-if-false}])
24350 @end example
24352 @noindent
24353 @xref{Running the Compiler}.
24355 This macro double quotes both @var{includes} and @var{function-body}.
24357 For C and C++, @var{includes} is any @code{#include} statements needed
24358 by the code in @var{function-body} (@var{includes} is ignored if
24359 the currently selected language is Fortran or Fortran 77).  The compiler
24360 and compilation flags are determined by the current language
24361 (@pxref{Language Choice}).
24362 @end defmac
24364 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
24365 @acindex{TRY_CPP}
24366 Same as:
24368 @example
24369 AC_PREPROC_IFELSE(
24370   [AC_LANG_SOURCE([[@var{input}]])],
24371   [@var{action-if-true}],
24372   [@var{action-if-false}])
24373 @end example
24375 @noindent
24376 @xref{Running the Preprocessor}.
24378 This macro double quotes the @var{input}.
24379 @end defmac
24381 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
24382   @ovar{action-if-true}, @ovar{action-if-false})
24383 @acindex{TRY_LINK}
24384 Same as:
24386 @example
24387 AC_LINK_IFELSE(
24388   [AC_LANG_PROGRAM([[@var{includes}]],
24389      [[@var{function-body}]])],
24390   [@var{action-if-true}],
24391   [@var{action-if-false}])
24392 @end example
24394 @noindent
24395 @xref{Running the Linker}.
24397 This macro double quotes both @var{includes} and @var{function-body}.
24399 Depending on the current language (@pxref{Language Choice}), create a
24400 test program to see whether a function whose body consists of
24401 @var{function-body} can be compiled and linked.  If the file compiles
24402 and links successfully, run shell commands @var{action-if-found},
24403 otherwise run @var{action-if-not-found}.
24405 This macro double quotes both @var{includes} and @var{function-body}.
24407 For C and C++, @var{includes} is any @code{#include} statements needed
24408 by the code in @var{function-body} (@var{includes} is ignored if
24409 the currently selected language is Fortran or Fortran 77).  The compiler
24410 and compilation flags are determined by the current language
24411 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
24412 @code{LIBS} are used for linking.
24413 @end defmac
24415 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
24416   @ovar{action-if-not-found})
24417 @acindex{TRY_LINK_FUNC}
24418 This macro is equivalent to
24419 @example
24420 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
24421   [@var{action-if-found}], [@var{action-if-not-found}])
24422 @end example
24423 @noindent
24424 @xref{Running the Linker}.
24425 @end defmac
24427 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
24428   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
24429 @acindex{TRY_RUN}
24430 Same as:
24432 @example
24433 AC_RUN_IFELSE(
24434   [AC_LANG_SOURCE([[@var{program}]])],
24435   [@var{action-if-true}],
24436   [@var{action-if-false}],
24437   [@var{action-if-cross-compiling}])
24438 @end example
24440 @noindent
24441 @xref{Runtime}.
24442 @end defmac
24444 @anchor{AC_TYPE_SIGNAL}
24445 @defmac AC_TYPE_SIGNAL
24446 @acindex{TYPE_SIGNAL}
24447 @cvindex RETSIGTYPE
24448 @hdrindex{signal.h}
24449 If @file{signal.h} declares @code{signal} as returning a pointer to a
24450 function returning @code{void}, define @code{RETSIGTYPE} to be
24451 @code{void}; otherwise, define it to be @code{int}.  These days, it is
24452 portable to assume C89, and that signal handlers return @code{void},
24453 without needing to use this macro or @code{RETSIGTYPE}.
24455 When targeting older K&R C, it is possible to define signal handlers as
24456 returning type @code{RETSIGTYPE}, and omit a return statement:
24458 @example
24459 @group
24460 RETSIGTYPE
24461 hup_handler ()
24463 @dots{}
24465 @end group
24466 @end example
24467 @end defmac
24469 @defmac AC_UID_T
24470 @acindex{UID_T}
24471 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
24472 @end defmac
24474 @defmac AC_UNISTD_H
24475 @acindex{UNISTD_H}
24476 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}),
24477 which is one of the tests done as a side effect by
24478 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), so usually
24479 unnecessary to write explicitly.
24480 @end defmac
24482 @defmac AC_USG
24483 @acindex{USG}
24484 @cvindex USG
24485 Define @code{USG} if the BSD string functions (@code{bcopy},
24486 @code{bzero}, @code{index}, @code{rindex}, etc) are @emph{not} defined
24487 in @file{strings.h}.  Modern code should assume @file{string.h} exists
24488 and should use the ISO C string functions (@code{memmove}, @code{memset},
24489 @code{strchr}, @code{strrchr}, etc) unconditionally.
24491 @file{strings.h} may be the only header that declares @code{strcasecmp},
24492 @code{strncasecmp}, and @code{ffs}.  @code{AC_INCLUDES_DEFAULT} checks
24493 for it (@pxref{Default Includes}); test @code{HAVE_STRINGS_H}.
24494 @end defmac
24496 @defmac AC_UTIME_NULL
24497 @acindex{UTIME_NULL}
24498 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
24499 @end defmac
24501 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
24502 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
24503 If the cache file is inconsistent with the current host, target and
24504 build system types, it used to execute @var{cmd} or print a default
24505 error message.  This is now handled by default.
24506 @end defmac
24508 @defmac AC_VERBOSE (@var{result-description})
24509 @acindex{VERBOSE}
24510 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
24511 @end defmac
24513 @defmac AC_VFORK
24514 @acindex{VFORK}
24515 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
24516 @end defmac
24518 @defmac AC_VPRINTF
24519 @acindex{VPRINTF}
24520 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
24521 @end defmac
24523 @defmac AC_WAIT3
24524 @acindex{WAIT3}
24525 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
24526 portable programs should use @code{waitpid}, not @code{wait3}, as
24527 @code{wait3} has been removed from Posix.
24528 @end defmac
24530 @defmac AC_WARN
24531 @acindex{WARN}
24532 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
24533 @end defmac
24535 @defmac AC_WARNING (@var{message})
24536 @acindex{WARNING}
24537 Replaced by @code{m4_warn} (@pxref{m4_warn}).
24538 @end defmac
24540 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
24541   @ovar{action-if-not-given})
24542 @acindex{WITH}
24543 This is an obsolete version of @code{AC_ARG_WITH} that does not
24544 support providing a help string (@pxref{AC_ARG_WITH}).
24545 @end defmac
24547 @defmac AC_WORDS_BIGENDIAN
24548 @acindex{WORDS_BIGENDIAN}
24549 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
24550 @end defmac
24552 @defmac AC_XENIX_DIR
24553 @acindex{XENIX_DIR}
24554 @ovindex LIBS
24555 This macro used to add @option{-lx} to output variable @code{LIBS} if on
24556 Xenix.  Also, if @file{dirent.h} is being checked for, added
24557 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
24558 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
24559 running XENIX on which you should not depend:
24561 @example
24562 AC_MSG_CHECKING([for Xenix])
24563 AC_EGREP_CPP([yes],
24564 [#if defined M_XENIX && !defined M_UNIX
24565   yes
24566 #endif],
24567              [AC_MSG_RESULT([yes]); XENIX=yes],
24568              [AC_MSG_RESULT([no]); XENIX=])
24569 @end example
24570 @noindent
24571 Don't use this macro, the dignified means to check the nature of the
24572 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24573 @end defmac
24575 @defmac AC_YYTEXT_POINTER
24576 @acindex{YYTEXT_POINTER}
24577 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
24578 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
24579 @end defmac
24581 @node Autoconf 1
24582 @section Upgrading From Version 1
24583 @cindex Upgrading autoconf
24584 @cindex Autoconf upgrading
24586 Autoconf version 2 is mostly backward compatible with version 1.
24587 However, it introduces better ways to do some things, and doesn't
24588 support some of the ugly things in version 1.  So, depending on how
24589 sophisticated your @file{configure.ac} files are, you might have to do
24590 some manual work in order to upgrade to version 2.  This chapter points
24591 out some problems to watch for when upgrading.  Also, perhaps your
24592 @command{configure} scripts could benefit from some of the new features in
24593 version 2; the changes are summarized in the file @file{NEWS} in the
24594 Autoconf distribution.
24596 @menu
24597 * Changed File Names::          Files you might rename
24598 * Changed Makefiles::           New things to put in @file{Makefile.in}
24599 * Changed Macros::              Macro calls you might replace
24600 * Changed Results::             Changes in how to check test results
24601 * Changed Macro Writing::       Better ways to write your own macros
24602 @end menu
24604 @node Changed File Names
24605 @subsection Changed File Names
24607 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
24608 in a particular package's source directory), you must rename it to
24609 @file{acsite.m4}.  @xref{autoconf Invocation}.
24611 If you distribute @file{install.sh} with your package, rename it to
24612 @file{install-sh} so @command{make} builtin rules don't inadvertently
24613 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
24614 looks for the script under both names, but it is best to use the new name.
24616 If you were using @file{config.h.top}, @file{config.h.bot}, or
24617 @file{acconfig.h}, you still can, but you have less clutter if you
24618 use the @code{AH_} macros.  @xref{Autoheader Macros}.
24620 @node Changed Makefiles
24621 @subsection Changed Makefiles
24623 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
24624 your @file{Makefile.in} files, so they can take advantage of the values
24625 of those variables in the environment when @command{configure} is run.
24626 Doing this isn't necessary, but it's a convenience for users.
24628 Also add @samp{@@configure_input@@} in a comment to each input file for
24629 @code{AC_OUTPUT}, so that the output files contain a comment saying
24630 they were produced by @command{configure}.  Automatically selecting the
24631 right comment syntax for all the kinds of files that people call
24632 @code{AC_OUTPUT} on became too much work.
24634 Add @file{config.log} and @file{config.cache} to the list of files you
24635 remove in @code{distclean} targets.
24637 If you have the following in @file{Makefile.in}:
24639 @example
24640 prefix = /usr/local
24641 exec_prefix = $(prefix)
24642 @end example
24644 @noindent
24645 you must change it to:
24647 @example
24648 prefix = @@prefix@@
24649 exec_prefix = @@exec_prefix@@
24650 @end example
24652 @noindent
24653 The old behavior of replacing those variables without @samp{@@}
24654 characters around them has been removed.
24656 @node Changed Macros
24657 @subsection Changed Macros
24659 Many of the macros were renamed in Autoconf version 2.  You can still
24660 use the old names, but the new ones are clearer, and it's easier to find
24661 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
24662 new names for the old macros.  Use the @command{autoupdate} program to
24663 convert your @file{configure.ac} to using the new macro names.
24664 @xref{autoupdate Invocation}.
24666 Some macros have been superseded by similar ones that do the job better,
24667 but are not call-compatible.  If you get warnings about calling obsolete
24668 macros while running @command{autoconf}, you may safely ignore them, but
24669 your @command{configure} script generally works better if you follow
24670 the advice that is printed about what to replace the obsolete macros with.  In
24671 particular, the mechanism for reporting the results of tests has
24672 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
24673 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
24674 looks better if you switch to @code{AC_MSG_CHECKING} and
24675 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
24676 in conjunction with cache variables.  @xref{Caching Results}.
24680 @node Changed Results
24681 @subsection Changed Results
24683 If you were checking the results of previous tests by examining the
24684 shell variable @code{DEFS}, you need to switch to checking the values of
24685 the cache variables for those tests.  @code{DEFS} no longer exists while
24686 @command{configure} is running; it is only created when generating output
24687 files.  This difference from version 1 is because properly quoting the
24688 contents of that variable turned out to be too cumbersome and
24689 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
24690 Variable Names}.
24692 For example, here is a @file{configure.ac} fragment written for Autoconf
24693 version 1:
24695 @example
24696 AC_HAVE_FUNCS(syslog)
24697 case "$DEFS" in
24698 *-DHAVE_SYSLOG*) ;;
24699 *) # syslog is not in the default libraries.  See if it's in some other.
24700   saved_LIBS="$LIBS"
24701   for lib in bsd socket inet; do
24702     AC_CHECKING(for syslog in -l$lib)
24703     LIBS="-l$lib $saved_LIBS"
24704     AC_HAVE_FUNCS(syslog)
24705     case "$DEFS" in
24706     *-DHAVE_SYSLOG*) break ;;
24707     *) ;;
24708     esac
24709     LIBS="$saved_LIBS"
24710   done ;;
24711 esac
24712 @end example
24714 Here is a way to write it for version 2:
24716 @example
24717 AC_CHECK_FUNCS([syslog])
24718 if test "x$ac_cv_func_syslog" = xno; then
24719   # syslog is not in the default libraries.  See if it's in some other.
24720   for lib in bsd socket inet; do
24721     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
24722       LIBS="-l$lib $LIBS"; break])
24723   done
24725 @end example
24727 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
24728 backslashes before quotes, you need to remove them.  It now works
24729 predictably, and does not treat quotes (except back quotes) specially.
24730 @xref{Setting Output Variables}.
24732 All of the Boolean shell variables set by Autoconf macros now use
24733 @samp{yes} for the true value.  Most of them use @samp{no} for false,
24734 though for backward compatibility some use the empty string instead.  If
24735 you were relying on a shell variable being set to something like 1 or
24736 @samp{t} for true, you need to change your tests.
24738 @node Changed Macro Writing
24739 @subsection Changed Macro Writing
24741 When defining your own macros, you should now use @code{AC_DEFUN}
24742 instead of @code{define}.  @code{AC_DEFUN} automatically calls
24743 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
24744 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
24745 messages on the screen.  There's no actual harm in continuing to use the
24746 older way, but it's less convenient and attractive.  @xref{Macro
24747 Definitions}.
24749 You probably looked at the macros that came with Autoconf as a guide for
24750 how to do things.  It would be a good idea to take a look at the new
24751 versions of them, as the style is somewhat improved and they take
24752 advantage of some new features.
24754 If you were doing tricky things with undocumented Autoconf internals
24755 (macros, variables, diversions), check whether you need to change
24756 anything to account for changes that have been made.  Perhaps you can
24757 even use an officially supported technique in version 2 instead of
24758 kludging.  Or perhaps not.
24760 To speed up your locally written feature tests, add caching to them.
24761 See whether any of your tests are of general enough usefulness to
24762 encapsulate them into macros that you can share.
24765 @node Autoconf 2.13
24766 @section Upgrading From Version 2.13
24767 @cindex Upgrading autoconf
24768 @cindex Autoconf upgrading
24770 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
24771 suits this section@enddots{}
24773 @quotation
24774 Autoconf version 2.50 is mostly backward compatible with version 2.13.
24775 However, it introduces better ways to do some things, and doesn't
24776 support some of the ugly things in version 2.13.  So, depending on how
24777 sophisticated your @file{configure.ac} files are, you might have to do
24778 some manual work in order to upgrade to version 2.50.  This chapter
24779 points out some problems to watch for when upgrading.  Also, perhaps
24780 your @command{configure} scripts could benefit from some of the new
24781 features in version 2.50; the changes are summarized in the file
24782 @file{NEWS} in the Autoconf distribution.
24783 @end quotation
24785 @menu
24786 * Changed Quotation::           Broken code which used to work
24787 * New Macros::                  Interaction with foreign macros
24788 * Hosts and Cross-Compilation::  Bugward compatibility kludges
24789 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
24790 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
24791 @end menu
24793 @node Changed Quotation
24794 @subsection Changed Quotation
24796 The most important changes are invisible to you: the implementation of
24797 most macros have completely changed.  This allowed more factorization of
24798 the code, better error messages, a higher uniformity of the user's
24799 interface etc.  Unfortunately, as a side effect, some construct which
24800 used to (miraculously) work might break starting with Autoconf 2.50.
24801 The most common culprit is bad quotation.
24803 For instance, in the following example, the message is not properly
24804 quoted:
24806 @example
24807 AC_INIT
24808 AC_CHECK_HEADERS(foo.h, ,
24809   AC_MSG_ERROR(cannot find foo.h, bailing out))
24810 AC_OUTPUT
24811 @end example
24813 @noindent
24814 Autoconf 2.13 simply ignores it:
24816 @example
24817 $ @kbd{autoconf-2.13; ./configure --silent}
24818 creating cache ./config.cache
24819 configure: error: cannot find foo.h
24821 @end example
24823 @noindent
24824 while Autoconf 2.50 produces a broken @file{configure}:
24826 @example
24827 $ @kbd{autoconf-2.50; ./configure --silent}
24828 configure: error: cannot find foo.h
24829 ./configure: exit: bad non-numeric arg `bailing'
24830 ./configure: exit: bad non-numeric arg `bailing'
24832 @end example
24834 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
24835 too!
24837 @example
24838 AC_INIT([Example], [1.0], [bug-example@@example.org])
24839 AC_CHECK_HEADERS([foo.h], [],
24840   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
24841 AC_OUTPUT
24842 @end example
24844 Many many (and many more) Autoconf macros were lacking proper quotation,
24845 including no less than@dots{} @code{AC_DEFUN} itself!
24847 @example
24848 $ @kbd{cat configure.in}
24849 AC_DEFUN([AC_PROG_INSTALL],
24850 [# My own much better version
24852 AC_INIT
24853 AC_PROG_INSTALL
24854 AC_OUTPUT
24855 $ @kbd{autoconf-2.13}
24856 autoconf: Undefined macros:
24857 ***BUG in Autoconf--please report*** AC_FD_MSG
24858 ***BUG in Autoconf--please report*** AC_EPI
24859 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
24860 configure.in:5:AC_PROG_INSTALL
24861 $ @kbd{autoconf-2.50}
24863 @end example
24866 @node New Macros
24867 @subsection New Macros
24869 @cindex undefined macro
24870 @cindex @code{_m4_divert_diversion}
24872 While Autoconf was relatively dormant in the late 1990s, Automake
24873 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
24874 in 2001, Autoconf provided
24875 versions of these macros, integrated in the @code{AC_} namespace,
24876 instead of @code{AM_}.  But in order to ease the upgrading via
24877 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
24879 Unfortunately older versions of Automake (e.g., Automake 1.4)
24880 did not quote the names of these macros.
24881 Therefore, when @command{m4} finds something like
24882 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
24883 @code{AM_TYPE_PTRDIFF_T} is
24884 expanded, replaced with its Autoconf definition.
24886 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
24887 complains, in its own words:
24889 @example
24890 $ @kbd{cat configure.ac}
24891 AC_INIT([Example], [1.0], [bug-example@@example.org])
24892 AM_TYPE_PTRDIFF_T
24893 $ @kbd{aclocal-1.4}
24894 $ @kbd{autoconf}
24895 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
24896 aclocal.m4:17: the top level
24897 autom4te: m4 failed with exit status: 1
24899 @end example
24901 Modern versions of Automake no longer define most of these
24902 macros, and properly quote the names of the remaining macros.
24903 If you must use an old Automake, do not depend upon macros from Automake
24904 as it is simply not its job
24905 to provide macros (but the one it requires itself):
24907 @example
24908 $ @kbd{cat configure.ac}
24909 AC_INIT([Example], [1.0], [bug-example@@example.org])
24910 AM_TYPE_PTRDIFF_T
24911 $ @kbd{rm aclocal.m4}
24912 $ @kbd{autoupdate}
24913 autoupdate: `configure.ac' is updated
24914 $ @kbd{cat configure.ac}
24915 AC_INIT([Example], [1.0], [bug-example@@example.org])
24916 AC_CHECK_TYPES([ptrdiff_t])
24917 $ @kbd{aclocal-1.4}
24918 $ @kbd{autoconf}
24920 @end example
24923 @node Hosts and Cross-Compilation
24924 @subsection Hosts and Cross-Compilation
24925 @cindex Cross compilation
24927 Based on the experience of compiler writers, and after long public
24928 debates, many aspects of the cross-compilation chain have changed:
24930 @itemize @minus
24931 @item
24932 the relationship between the build, host, and target architecture types,
24934 @item
24935 the command line interface for specifying them to @command{configure},
24937 @item
24938 the variables defined in @command{configure},
24940 @item
24941 the enabling of cross-compilation mode.
24942 @end itemize
24944 @sp 1
24946 The relationship between build, host, and target have been cleaned up:
24947 the chain of default is now simply: target defaults to host, host to
24948 build, and build to the result of @command{config.guess}.  Nevertheless,
24949 in order to ease the transition from 2.13 to 2.50, the following
24950 transition scheme is implemented.  @emph{Do not rely on it}, as it will
24951 be completely disabled in a couple of releases (we cannot keep it, as it
24952 proves to cause more problems than it cures).
24954 They all default to the result of running @command{config.guess}, unless
24955 you specify either @option{--build} or @option{--host}.  In this case,
24956 the default becomes the system type you specified.  If you specify both,
24957 and they're different, @command{configure} enters cross compilation
24958 mode, so it doesn't run any tests that require execution.
24960 Hint: if you mean to override the result of @command{config.guess},
24961 prefer @option{--build} over @option{--host}.
24963 @sp 1
24965 For backward compatibility, @command{configure} accepts a system
24966 type as an option by itself.  Such an option overrides the
24967 defaults for build, host, and target system types.  The following
24968 configure statement configures a cross toolchain that runs on
24969 NetBSD/alpha but generates code for GNU Hurd/sparc,
24970 which is also the build platform.
24972 @example
24973 ./configure --host=alpha-netbsd sparc-gnu
24974 @end example
24976 @sp 1
24978 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
24979 and @code{target} had a different semantics before and after the
24980 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
24981 @option{--build} is strictly copied into @code{build_alias}, and is left
24982 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
24983 set to the canonicalized build type.  To ease the transition, before,
24984 its contents is the same as that of @code{build_alias}.  Do @emph{not}
24985 rely on this broken feature.
24987 For consistency with the backward compatibility scheme exposed above,
24988 when @option{--host} is specified but @option{--build} isn't, the build
24989 system is assumed to be the same as @option{--host}, and
24990 @samp{build_alias} is set to that value.  Eventually, this
24991 historically incorrect behavior will go away.
24993 @sp 1
24995 The former scheme to enable cross-compilation proved to cause more harm
24996 than good, in particular, it used to be triggered too easily, leaving
24997 regular end users puzzled in front of cryptic error messages.
24998 @command{configure} could even enter cross-compilation mode only
24999 because the compiler was not functional.  This is mainly because
25000 @command{configure} used to try to detect cross-compilation, instead of
25001 waiting for an explicit flag from the user.
25003 Now, @command{configure} enters cross-compilation mode if and only if
25004 @option{--host} is passed.
25006 That's the short documentation.  To ease the transition between 2.13 and
25007 its successors, a more complicated scheme is implemented.  @emph{Do not
25008 rely on the following}, as it will be removed in the near future.
25010 If you specify @option{--host}, but not @option{--build}, when
25011 @command{configure} performs the first compiler test it tries to run
25012 an executable produced by the compiler.  If the execution fails, it
25013 enters cross-compilation mode.  This is fragile.  Moreover, by the time
25014 the compiler test is performed, it may be too late to modify the
25015 build-system type: other tests may have already been performed.
25016 Therefore, whenever you specify @option{--host}, be sure to specify
25017 @option{--build} too.
25019 @example
25020 ./configure --build=x86_64-pc-linux-gnu --host=x86_64-w64-mingw64
25021 @end example
25023 @noindent
25024 enters cross-compilation mode.  The former interface, which
25025 consisted in setting the compiler to a cross-compiler without informing
25026 @command{configure} is obsolete.  For instance, @command{configure}
25027 fails if it can't run the code generated by the specified compiler if you
25028 configure as follows:
25030 @example
25031 ./configure CC=x86_64-w64-mingw64-gcc
25032 @end example
25035 @node AC_LIBOBJ vs LIBOBJS
25036 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
25038 Up to Autoconf 2.13, the replacement of functions was triggered via the
25039 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
25040 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
25041 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
25043 This change is mandated by the unification of the GNU Build System
25044 components.  In particular, the various fragile techniques used to parse
25045 a @file{configure.ac} are all replaced with the use of traces.  As a
25046 consequence, any action must be traceable, which obsoletes critical
25047 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
25048 and it can even be handled gracefully (read, ``without your having to
25049 change something'').
25051 There were two typical uses of @code{LIBOBJS}: asking for a replacement
25052 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
25054 @sp 1
25056 As for function replacement, the fix is immediate: use
25057 @code{AC_LIBOBJ}.  For instance:
25059 @example
25060 LIBOBJS="$LIBOBJS fnmatch.o"
25061 LIBOBJS="$LIBOBJS malloc.$ac_objext"
25062 @end example
25064 @noindent
25065 should be replaced with:
25067 @example
25068 AC_LIBOBJ([fnmatch])
25069 AC_LIBOBJ([malloc])
25070 @end example
25072 @sp 1
25074 @ovindex LIBOBJDIR
25075 When used with Automake 1.10 or newer, a suitable value for
25076 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
25077 can be referenced from any @file{Makefile.am}.  Even without Automake,
25078 arranging for @code{LIBOBJDIR} to be set correctly enables
25079 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
25080 The @code{LIBOBJDIR} feature is experimental.
25083 @node AC_ACT_IFELSE vs AC_TRY_ACT
25084 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
25085 @c the anchor keeps the old node name, to try to avoid breaking links
25086 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
25088 @acindex{@var{ACT}_IFELSE}
25089 @acindex{TRY_@var{ACT}}
25090 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
25091 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
25092 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
25093 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
25094 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
25095 @code{AC_TRY_RUN}.  The motivations where:
25096 @itemize @minus
25097 @item
25098 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
25099 quoting their arguments;
25101 @item
25102 the combinatorial explosion is solved by decomposing on the one hand the
25103 generation of sources, and on the other hand executing the program;
25105 @item
25106 this scheme helps supporting more languages than plain C and C++.
25107 @end itemize
25109 In addition to the change of syntax, the philosophy has changed too:
25110 while emphasis was put on speed at the expense of accuracy, today's
25111 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
25112 expense of speed.
25115 As a perfect example of what is @emph{not} to be done, here is how to
25116 find out whether a header file contains a particular declaration, such
25117 as a typedef, a structure, a structure member, or a function.  Use
25118 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
25119 header file; on some systems the symbol might be defined in another
25120 header file that the file you are checking includes.
25122 As a (bad) example, here is how you should not check for C preprocessor
25123 symbols, either defined by header files or predefined by the C
25124 preprocessor: using @code{AC_EGREP_CPP}:
25126 @example
25127 @group
25128 AC_EGREP_CPP(yes,
25129 [#ifdef _AIX
25130   yes
25131 #endif
25132 ], is_aix=yes, is_aix=no)
25133 @end group
25134 @end example
25136 The above example, properly written would (i) use
25137 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
25139 @example
25140 @group
25141 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
25142 [[#ifndef _AIX
25143  error: This isn't AIX!
25144 #endif
25145 ]])],
25146                    [is_aix=yes],
25147                    [is_aix=no])
25148 @end group
25149 @end example
25152 @c ============================= Generating Test Suites with Autotest
25154 @node Using Autotest
25155 @chapter Generating Test Suites with Autotest
25157 @cindex Autotest
25159 @display
25160 @strong{N.B.: This section describes a feature which is still
25161 stabilizing.  Although we believe that Autotest is useful as-is, this
25162 documentation describes an interface which might change in the future:
25163 do not depend upon Autotest without subscribing to the Autoconf mailing
25164 lists.}
25165 @end display
25167 It is paradoxical that portable projects depend on nonportable tools
25168 to run their test suite.  Autoconf by itself is the paragon of this
25169 problem: although it aims at perfectly portability, up to 2.13 its
25170 test suite was using DejaGNU, a rich and complex testing
25171 framework, but which is far from being standard on Posix systems.
25172 Worse yet, it was likely to be missing on the most fragile platforms,
25173 the very platforms that are most likely to torture Autoconf and
25174 exhibit deficiencies.
25176 To circumvent this problem, many package maintainers have developed their
25177 own testing framework, based on simple shell scripts whose sole outputs
25178 are exit status values describing whether the test succeeded.  Most of
25179 these tests share common patterns, and this can result in lots of
25180 duplicated code and tedious maintenance.
25182 Following exactly the same reasoning that yielded to the inception of
25183 Autoconf, Autotest provides a test suite generation framework, based on
25184 M4 macros building a portable shell script.  The suite itself is
25185 equipped with automatic logging and tracing facilities which greatly
25186 diminish the interaction with bug reporters, and simple timing reports.
25188 Autoconf itself has been using Autotest for years, and we do attest that
25189 it has considerably improved the strength of the test suite and the
25190 quality of bug reports.  Other projects are known to use some generation
25191 of Autotest, such as Bison, GNU Wdiff, GNU Tar, each of
25192 them with different needs, and this usage has validated Autotest as a general
25193 testing framework.
25195 Nonetheless, compared to DejaGNU, Autotest is inadequate for
25196 interactive tool testing, which is probably its main limitation.
25198 @menu
25199 * Using an Autotest Test Suite::  Autotest and the user
25200 * Writing Testsuites::          Autotest macros
25201 * testsuite Invocation::        Running @command{testsuite} scripts
25202 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
25203 @end menu
25205 @node Using an Autotest Test Suite
25206 @section Using an Autotest Test Suite
25208 @menu
25209 * testsuite Scripts::           The concepts of Autotest
25210 * Autotest Logs::               Their contents
25211 @end menu
25213 @node testsuite Scripts
25214 @subsection @command{testsuite} Scripts
25216 @cindex @command{testsuite}
25218 Generating testing or validation suites using Autotest is rather easy.
25219 The whole validation suite is held in a file to be processed through
25220 @command{autom4te}, itself using GNU M4 under the hood, to
25221 produce a stand-alone Bourne shell script which then gets distributed.
25222 Neither @command{autom4te} nor GNU M4 are needed at
25223 the installer's end.
25225 @cindex test group
25226 Each test of the validation suite should be part of some test group.  A
25227 @dfn{test group} is a sequence of interwoven tests that ought to be
25228 executed together, usually because one test in the group creates data
25229 files that a later test in the same group needs to read.  Complex test
25230 groups make later debugging more tedious.  It is much better to
25231 keep only a few tests per test group.  Ideally there is only one test
25232 per test group.
25234 For all but the simplest packages, some file such as @file{testsuite.at}
25235 does not fully hold all test sources, as these are often easier to
25236 maintain in separate files.  Each of these separate files holds a single
25237 test group, or a sequence of test groups all addressing some common
25238 functionality in the package.  In such cases, @file{testsuite.at}
25239 merely initializes the validation suite, and sometimes does elementary
25240 health checking, before listing include statements for all other test
25241 files.  The special file @file{package.m4}, containing the
25242 identification of the package, is automatically included if found.
25244 A convenient alternative consists in moving all the global issues
25245 (local Autotest macros, elementary health checking, and @code{AT_INIT}
25246 invocation) into the file @code{local.at}, and making
25247 @file{testsuite.at} be a simple list of @code{m4_include}s of sub test
25248 suites.  In such case, generating the whole test suite or pieces of it
25249 is only a matter of choosing the @command{autom4te} command line
25250 arguments.
25252 The validation scripts that Autotest produces are by convention called
25253 @command{testsuite}.  When run, @command{testsuite} executes each test
25254 group in turn, producing only one summary line per test to say if that
25255 particular test succeeded or failed.  At end of all tests, summarizing
25256 counters get printed.  One debugging directory is left for each test
25257 group which failed, if any: such directories are named
25258 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
25259 the test group, and they include:
25261 @itemize @bullet
25262 @item a debugging script named @file{run} which reruns the test in
25263 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
25264 of debugging scripts has the purpose of easing the chase for bugs.
25266 @item all the files created with @code{AT_DATA}
25268 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
25270 @item a log of the run, named @file{testsuite.log}
25271 @end itemize
25273 In the ideal situation, none of the tests fail, and consequently no
25274 debugging directory is left behind for validation.
25276 It often happens in practice that individual tests in the validation
25277 suite need to get information coming out of the configuration process.
25278 Some of this information, common for all validation suites, is provided
25279 through the file @file{atconfig}, automatically created by
25280 @code{AC_CONFIG_TESTDIR}.  For configuration information which your
25281 testing environment specifically needs, you might prepare an optional
25282 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
25283 The configuration process produces @file{atconfig} and @file{atlocal}
25284 out of these two input files, and these two produced files are
25285 automatically read by the @file{testsuite} script.
25287 Here is a diagram showing the relationship between files.
25289 @noindent
25290 Files used in preparing a software package for distribution:
25292 @example
25293                 [package.m4] -->.
25294                                  \
25295 subfile-1.at ->.  [local.at] ---->+
25296     ...         \                  \
25297 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
25298     ...         /
25299 subfile-n.at ->'
25300 @end example
25302 @noindent
25303 Files used in configuring a software package:
25305 @example
25306                                      .--> atconfig
25307                                     /
25308 [atlocal.in] -->  config.status* --<
25309                                     \
25310                                      `--> [atlocal]
25311 @end example
25313 @noindent
25314 Files created during test suite execution:
25316 @example
25317 atconfig -->.                    .--> testsuite.log
25318              \                  /
25319               >-- testsuite* --<
25320              /                  \
25321 [atlocal] ->'                    `--> [testsuite.dir]
25322 @end example
25325 @node Autotest Logs
25326 @subsection Autotest Logs
25328 When run, the test suite creates a log file named after itself, e.g., a
25329 test suite named @command{testsuite} creates @file{testsuite.log}.  It
25330 contains a lot of information, usually more than maintainers actually
25331 need, but therefore most of the time it contains all that is needed:
25333 @table @asis
25334 @item command line arguments
25335 A bad but unfortunately widespread habit consists of
25336 setting environment variables before the command, such as in
25337 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
25338 know this change, hence (i) it cannot report it to you, and (ii)
25339 it cannot preserve the value of @code{CC} for subsequent runs.
25340 Autoconf faced exactly the same problem, and solved it by asking
25341 users to pass the variable definitions as command line arguments.
25342 Autotest requires this rule, too, but has no means to enforce it; the log
25343 then contains a trace of the variables that were changed by the user.
25345 @item @file{ChangeLog} excerpts
25346 The topmost lines of all the @file{ChangeLog} files found in the source
25347 hierarchy.  This is especially useful when bugs are reported against
25348 development versions of the package, since the version string does not
25349 provide sufficient information to know the exact state of the sources
25350 the user compiled.  Of course, this relies on the use of a
25351 @file{ChangeLog}.
25353 @item build machine
25354 Running a test suite in a cross-compile environment is not an easy task,
25355 since it would mean having the test suite run on a machine @var{build},
25356 while running programs on a machine @var{host}.  It is much simpler to
25357 run both the test suite and the programs on @var{host}, but then, from
25358 the point of view of the test suite, there remains a single environment,
25359 @var{host} = @var{build}.  The log contains relevant information on the
25360 state of the @var{build} machine, including some important environment
25361 variables.
25362 @c FIXME: How about having an M4sh macro to say `hey, log the value
25363 @c of `@dots{}'?  This would help both Autoconf and Autotest.
25365 @item tested programs
25366 The absolute file name and answers to @option{--version} of the tested
25367 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
25369 @item configuration log
25370 The contents of @file{config.log}, as created by @command{configure},
25371 are appended.  It contains the configuration flags and a detailed report
25372 on the configuration itself.
25373 @end table
25376 @node Writing Testsuites
25377 @section Writing @file{testsuite.at}
25379 The @file{testsuite.at} is a Bourne shell script making use of special
25380 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
25381 its beginning followed by one call to @code{m4_include} per source file
25382 for tests.  Each such included file, or the remainder of
25383 @file{testsuite.at} if include files are not used, contain a sequence of
25384 test groups.  Each test group begins with a call to @code{AT_SETUP},
25385 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
25386 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
25387 groups can be categorized by a call to @code{AT_BANNER}.
25389 All of the public Autotest macros have all-uppercase names in the
25390 namespace @samp{^AT_} to prevent them from accidentally conflicting with
25391 other text; Autoconf also reserves the namespace @samp{^_AT_} for
25392 internal macros.  All shell variables used in the testsuite for internal
25393 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
25394 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
25395 makes use of the file system namespace @samp{^at-}.
25397 Since Autoconf is built on top of M4sugar (@pxref{Programming in
25398 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
25399 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
25400 @emph{should not use} the namespace of a package that does not own the
25401 macro or shell code you are writing.
25403 @defmac AT_INIT (@ovar{name})
25404 @atindex{INIT}
25405 @c FIXME: Not clear, plus duplication of the information.
25406 Initialize Autotest.  Giving a @var{name} to the test suite is
25407 encouraged if your package includes several test suites.  Before this
25408 macro is called, @code{AT_PACKAGE_STRING} and
25409 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
25410 information about the testsuite to the user.  Typically, these macros
25411 are provided by a file @file{package.m4} built by @command{make}
25412 (@pxref{Making testsuite Scripts}), in order to inherit the package
25413 name, version, and bug reporting address from @file{configure.ac}.
25414 @end defmac
25416 @defmac AT_COPYRIGHT (@var{copyright-notice})
25417 @atindex{COPYRIGHT}
25418 @cindex Copyright Notice
25419 State that, in addition to the Free Software Foundation's copyright on
25420 the Autotest macros, parts of your test suite are covered by
25421 @var{copyright-notice}.
25423 The @var{copyright-notice} shows up in both the head of
25424 @command{testsuite} and in @samp{testsuite --version}.
25425 @end defmac
25427 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
25428   @ovar{action-if-given}, @ovar{action-if-not-given})
25429 @atindex{ARG_OPTION}
25430 @vrindex at_arg_@var{option}
25431 Accept options from the space-separated list @var{options}, a list that
25432 has leading dashes removed from the options.  Long options will be
25433 prefixed with @samp{--}, single-character options with @samp{-}.  The
25434 first word in this list is the primary @var{option}, any others are
25435 assumed to be short-hand aliases.  The variable associated with it
25436 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
25437 with underscores.
25439 If the user passes @option{--@var{option}} to the @command{testsuite},
25440 the variable will be set to @samp{:}.  If the user does not pass the
25441 option, or passes @option{--no-@var{option}}, then the variable will be
25442 set to @samp{false}.
25444 @vrindex at_optarg
25445 @vrindex at_optarg_@var{option}
25446 @var{action-if-given} is run each time the option is encountered; here,
25447 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
25448 appropriate.  @code{at_optarg} is actually just a copy of
25449 @code{at_arg_@var{option}}.
25451 @var{action-if-not-given} will be run once after option parsing is
25452 complete and if no option from @var{options} was used.
25454 @var{help-text} is added to the end of the list of options shown in
25455 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25457 It is recommended that you use a package-specific prefix to @var{options}
25458 names in order to avoid clashes with future Autotest built-in options.
25459 @end defmac
25461 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
25462   @ovar{action-if-given}, @ovar{action-if-not-given})
25463 @atindex{ARG_OPTION_ARG}
25464 @vrindex at_arg_@var{option}
25465 Accept options with arguments from the space-separated list
25466 @var{options}, a list that has leading dashes removed from the options.
25467 Long options will be prefixed with @samp{--}, single-character options
25468 with @samp{-}.  The first word in this list is the primary @var{option},
25469 any others are assumed to be short-hand aliases.  The variable associated
25470 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
25471 replaced with underscores.
25473 If the user passes @option{--@var{option}=@var{arg}} or
25474 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
25475 variable will be set to @samp{@var{arg}}.
25477 @vrindex at_optarg
25478 @var{action-if-given} is run each time the option is encountered; here,
25479 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
25480 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
25482 @var{action-if-not-given} will be run once after option parsing is
25483 complete and if no option from @var{options} was used.
25485 @var{help-text} is added to the end of the list of options shown in
25486 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25488 It is recommended that you use a package-specific prefix to @var{options}
25489 names in order to avoid clashes with future Autotest built-in options.
25490 @end defmac
25492 @defmac AT_COLOR_TESTS
25493 @atindex{COLOR_TESTS}
25494 Enable colored test results by default when the output is connected to
25495 a terminal.
25496 @end defmac
25498 @defmac AT_TESTED (@var{executables})
25499 @atindex{TESTED}
25500 Log the file name and answer to @option{--version} of each program in
25501 space-separated list @var{executables}.  Several invocations register
25502 new executables, in other words, don't fear registering one program
25503 several times.
25505 Autotest test suites rely on @env{PATH} to find the tested program.
25506 This avoids the need to generate absolute names of the various tools, and
25507 makes it possible to test installed programs.  Therefore, knowing which
25508 programs are being exercised is crucial to understanding problems in
25509 the test suite itself, or its occasional misuses.  It is a good idea to
25510 also subscribe foreign programs you depend upon, to avoid incompatible
25511 diagnostics.
25513 @var{executables} is implicitly wrapped in shell double quotes, but it
25514 will still use shell variable expansion (@samp{$}), command substitution
25515 (@samp{`}), and backslash escaping (@samp{\}).  In particular, the
25516 @env{EXEEXT} variable is available if it is passed to the testsuite
25517 via @file{atlocal} or @file{atconfig}.
25518 @end defmac
25520 @sp 1
25522 @defmac AT_BANNER (@var{test-category-name})
25523 @atindex{BANNER}
25524 This macro identifies the start of a category of related test groups.
25525 When the resulting @file{testsuite} is invoked with more than one test
25526 group to run, its output will include a banner containing
25527 @var{test-category-name} prior to any tests run from that category.  The
25528 banner should be no more than about 40 or 50 characters.  A blank banner
25529 indicates uncategorized tests; an empty line will be inserted after
25530 tests from an earlier category, effectively ending that category.
25531 @end defmac
25533 @defmac AT_SETUP (@var{test-group-name})
25534 @atindex{SETUP}
25535 This macro starts a group of related tests, all to be executed in the
25536 same subshell.  It accepts a single argument, which holds a few words
25537 (no more than about 30 or 40 characters) quickly describing the purpose
25538 of the test group being started.  @var{test-group-name} must not expand
25539 to unbalanced quotes, although quadrigraphs can be used.
25540 @end defmac
25542 @defmac AT_KEYWORDS (@var{keywords})
25543 @atindex{KEYWORDS}
25544 Associate the space-separated list of @var{keywords} to the enclosing
25545 test group.  This makes it possible to run ``slices'' of the test suite.
25546 For instance, if some of your test groups exercise some @samp{foo}
25547 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
25548 @samp{./testsuite -k foo} to run exclusively these test groups.  The
25549 @var{test-group-name} of the test group is automatically recorded to
25550 @code{AT_KEYWORDS}.
25552 Several invocations within a test group accumulate new keywords.  In
25553 other words, don't fear registering the same keyword several times in a
25554 test group.
25555 @end defmac
25557 @defmac AT_CAPTURE_FILE (@var{file})
25558 @atindex{CAPTURE_FILE}
25559 If the current test group fails, log the contents of @var{file}.
25560 Several identical calls within one test group have no additional effect.
25561 @end defmac
25563 @defmac AT_FAIL_IF (@var{shell-condition})
25564 @atindex{FAIL_IF}
25565 Make the test group fail and skip the rest of its execution, if
25566 @var{shell-condition} is true.  @var{shell-condition} is a shell expression
25567 such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
25568 will be executed and may still cause the test group to be skipped.
25569 You can instantiate this macro many times from within the same test group.
25571 You should use this macro only for very simple failure conditions.  If the
25572 @var{shell-condition} could emit any kind of output you should instead
25573 use @command{AT_CHECK} like
25574 @example
25575 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
25576 @end example
25577 @noindent
25578 so that such output is properly recorded in the @file{testsuite.log}
25579 file.
25580 @end defmac
25582 @defmac AT_SKIP_IF (@var{shell-condition})
25583 @atindex{SKIP_IF}
25584 Determine whether the test should be skipped because it requires
25585 features that are unsupported on the machine under test.
25586 @var{shell-condition} is a shell expression such as a @code{test}
25587 command.  Tests before @command{AT_SKIP_IF} will be executed
25588 and may still cause the test group to fail.  You can instantiate this
25589 macro many times from within the same test group.
25591 You should use this macro only for very simple skip conditions.  If the
25592 @var{shell-condition} could emit any kind of output you should instead
25593 use @command{AT_CHECK} like
25594 @example
25595 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
25596 @end example
25597 @noindent
25598 so that such output is properly recorded in the @file{testsuite.log}
25599 file.
25600 @end defmac
25602 @defmac AT_XFAIL_IF (@var{shell-condition})
25603 @atindex{XFAIL_IF}
25604 Determine whether the test is expected to fail because it is a known
25605 bug (for unsupported features, you should skip the test).
25606 @var{shell-condition} is a shell expression such as a @code{test}
25607 command; you can instantiate this macro many times from within the
25608 same test group, and one of the conditions is enough to turn
25609 the test into an expected failure.
25610 @end defmac
25612 @defmac AT_CLEANUP
25613 @atindex{CLEANUP}
25614 End the current test group.
25615 @end defmac
25617 @sp 1
25619 @defmac AT_DATA (@var{file}, @var{contents})
25620 @defmacx AT_DATA_UNQUOTED (@var{file}, @var{contents})
25621 @atindex{DATA}
25622 Initialize an input data @var{file} with given @var{contents}.  Of
25623 course, the @var{contents} have to be properly quoted between square
25624 brackets to protect against included commas or spurious M4
25625 expansion.  @var{contents} must be empty or end with a newline.
25626 @var{file} must
25627 be a single shell word that expands into a single file name.
25629 The difference between @code{AT_DATA} and @code{AT_DATA_UNQUOTED} is
25630 that only the latter performs shell variable expansion (@samp{$}),
25631 command substitution (@samp{`}), and backslash escaping (@samp{\})
25632 on @var{contents}.
25633 @end defmac
25635 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25636   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25637 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25638   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25639 @atindex{CHECK}
25640 @atindex{CHECK_UNQUOTED}
25641 @vrindex at_status
25642 Execute a test by performing given shell @var{commands} in a subshell.
25643 @var{commands} is output as-is, so shell expansions are honored.  These
25644 commands should normally exit with @var{status}, while producing expected
25645 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
25646 unexpected status 77, then the rest of the test group is skipped.  If
25647 @var{commands} exit with unexpected status 99, then the test group is
25648 immediately failed.  Otherwise, if this test fails, run shell commands
25649 @var{run-if-fail} or, if this test passes, run shell commands
25650 @var{run-if-pass}, both inside the current shell execution environment.
25651 At the beginning of @var{run-if-fail} and @var{run-if-pass}, the status of
25652 @var{commands} is available in the @code{at_status} shell variable.
25654 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25656 If @var{status} is the literal @samp{ignore}, then the corresponding
25657 exit status is not checked, except for the special cases of 77 (skip)
25658 and 99 (hard failure).  The existence of hard failures allows one to
25659 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
25660 feature has not yet been implemented, but to still distinguish between
25661 gracefully handling the missing feature and dumping core.  A hard
25662 failure also inhibits post-test actions in @var{run-if-fail}.
25664 If the value of the @var{stdout} or @var{stderr} parameter is one of the
25665 literals in the following table, then the test treats the output
25666 according to the rules of that literal.  Otherwise, the value of the
25667 parameter is treated as text that must exactly match the output given by
25668 @var{commands} on standard output and standard error (including an empty
25669 parameter for no output); any differences are captured in the testsuite
25670 log and the test is failed (unless an unexpected exit status of 77
25671 skipped the test instead).  The difference between @code{AT_CHECK} and
25672 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
25673 expansion (@samp{$}), command substitution (@samp{`}), and backslash
25674 escaping (@samp{\}) on comparison text given in the @var{stdout} and
25675 @var{stderr} arguments; if the text includes a trailing newline, this
25676 would be the same as if it were specified via an unquoted
25677 here-document.  (However, there is no difference in the interpretation
25678 of @var{commands}).
25680 @table @samp
25681 @item ignore
25682 The content of the output is ignored, but still captured in the test
25683 group log (if the testsuite is run with the @option{-v} option, the test
25684 group log is displayed as the test is run; if the test group later
25685 fails, the test group log is also copied into the overall testsuite
25686 log).  This action is valid for both @var{stdout} and @var{stderr}.
25688 @item ignore-nolog
25689 The content of the output is ignored, and nothing is captured in the log
25690 files.  If @var{commands} are likely to produce binary output (including
25691 long lines) or large amounts of output, then logging the output can make
25692 it harder to locate details related to subsequent tests within the
25693 group, and could potentially corrupt terminal display of a user running
25694 @command{testsuite -v}.
25696 @item stdout
25697 For the @var{stdout} parameter, capture the content of standard output
25698 to both the file @file{stdout} and the test group log.  Subsequent
25699 commands in the test group can then post-process the file.  This action
25700 is often used when it is desired to use @command{grep} to look for a
25701 substring in the output, or when the output must be post-processed to
25702 normalize error messages into a common form.
25704 @item stderr
25705 Like @samp{stdout}, except that it only works for the @var{stderr}
25706 parameter, and the standard error capture file will be named
25707 @file{stderr}.
25709 @item stdout-nolog
25710 @itemx stderr-nolog
25711 Like @samp{stdout} or @samp{stderr}, except that the captured output is
25712 not duplicated into the test group log.  This action is particularly
25713 useful for an intermediate check that produces large amounts of data,
25714 which will be followed by another check that filters down to the
25715 relevant data, as it makes it easier to locate details in the log.
25717 @item expout
25718 For the @var{stdout} parameter, compare standard output contents with
25719 the previously created file @file{expout}, and list any differences in
25720 the testsuite log.
25722 @item experr
25723 Like @samp{expout}, except that it only works for the @var{stderr}
25724 parameter, and the standard error contents are compared with
25725 @file{experr}.
25726 @end table
25727 @end defmac
25729 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
25730   @ovar{run-if-fail}, @ovar{run-if-pass})
25731 @atindex{CHECK_EUNIT}
25732 Initialize and execute an Erlang module named @var{module} that performs
25733 tests following the @var{test-spec} EUnit test specification.
25734 @var{test-spec} must be a valid EUnit test specification, as defined in
25735 the @uref{https://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
25736 Reference Manual}.  @var{erlflags} are optional command-line options
25737 passed to the Erlang interpreter to execute the test Erlang module.
25738 Typically, @var{erlflags} defines at least the paths to directories
25739 containing the compiled Erlang modules under test, as @samp{-pa path1
25740 path2 ...}.
25742 For example, the unit tests associated with Erlang module @samp{testme},
25743 which compiled code is in subdirectory @file{src}, can be performed
25744 with:
25746 @example
25747 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
25748                [-pa "$@{abs_top_builddir@}/src"])
25749 @end example
25751 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25753 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
25754 must be defined as the path of the Erlang interpreter, the path of the
25755 Erlang compiler, and the command-line flags to pass to the compiler,
25756 respectively.  Those variables should be configured in
25757 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
25758 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
25759 variables are automatically defined in the testsuite.  If @code{ERL} or
25760 @code{ERLC} is not defined, the test group is skipped.
25762 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
25763 be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
25764 an invalid EUnit test specification, the test group fails.  Otherwise,
25765 if the EUnit test passes, shell commands @var{run-if-pass} are executed
25766 or, if the EUnit test fails, shell commands @var{run-if-fail} are
25767 executed and the test group fails.
25769 Only the generated test Erlang module is automatically compiled and
25770 executed.  If @var{test-spec} involves testing other Erlang modules,
25771 e.g. module @samp{testme} in the example above, those modules must be
25772 already compiled.
25774 If the testsuite is run in verbose mode and with the @option{--verbose} option,
25775 EUnit is also run in verbose mode to output more details about
25776 individual unit tests.
25777 @end defmac
25780 @node testsuite Invocation
25781 @section Running @command{testsuite} Scripts
25782 @cindex @command{testsuite}
25784 Autotest test suites support the following options:
25786 @table @option
25787 @item --help
25788 @itemx -h
25789 Display the list of options and exit successfully.
25791 @item --version
25792 @itemx -V
25793 Display the version of the test suite and exit successfully.
25795 @item --directory=@var{dir}
25796 @itemx -C @var{dir}
25797 Change the current directory to @var{dir} before creating any files.
25798 Useful for running the testsuite in a subdirectory from a top-level
25799 Makefile.
25801 @item --jobs@r{[}=@var{n}@r{]}
25802 @itemx -j@ovar{n}
25803 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
25804 run all given tests in parallel.  Note that there should be no space
25805 before the argument to @option{-j}, as @option{-j @var{number}} denotes
25806 the separate arguments @option{-j} and @option{@var{number}}, see below.
25808 In parallel mode, the standard input device of the testsuite script is
25809 not available to commands inside a test group.  Furthermore, banner
25810 lines are not printed, and the summary line for each test group is
25811 output after the test group completes.  Summary lines may appear
25812 unordered.  If verbose and trace output are enabled (see below), they
25813 may appear intermixed from concurrently running tests.
25815 Parallel mode requires the @command{mkfifo} command to work, and will be
25816 silently disabled otherwise.
25818 @item --clean
25819 @itemx -c
25820 Remove all the files the test suite might have created and exit.  Meant
25821 for @code{clean} Make targets.
25823 @item --list
25824 @itemx -l
25825 List all the tests (or only the selection), including their possible
25826 keywords.
25827 @end table
25829 @sp 1
25831 By default all tests are performed (or described with @option{--list})
25832 silently in the default environment, but the environment, set of tests,
25833 and verbosity level can be tuned:
25835 @table @samp
25836 @item @var{variable}=@var{value}
25837 Set the environment @var{variable} to @var{value}.  Use this rather
25838 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
25839 different environment.
25841 @cindex @code{AUTOTEST_PATH}
25842 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
25843 to @env{PATH}.  Relative directory names (not starting with
25844 @samp{/}) are considered to be relative to the top level of the
25845 package being built.  All directories are made absolute, first
25846 starting from the top level @emph{build} tree, then from the
25847 @emph{source} tree.  For instance @samp{./testsuite
25848 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
25849 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
25850 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
25851 @env{PATH}.
25853 @item @var{number}
25854 @itemx @var{number}-@var{number}
25855 @itemx @var{number}-
25856 @itemx -@var{number}
25857 Add the corresponding test groups, with obvious semantics, to the
25858 selection.
25860 @item --keywords=@var{keywords}
25861 @itemx -k @var{keywords}
25862 Add to the selection the test groups with title or keywords (arguments
25863 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
25864 of the comma separated list @var{keywords}, case-insensitively.  Use
25865 @samp{!} immediately before the keyword to invert the selection for this
25866 keyword.  By default, the keywords match whole words; enclose them in
25867 @samp{.*} to also match parts of words.
25869 For example, running
25871 @example
25872 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
25873 @end example
25875 @noindent
25876 selects all tests tagged @samp{autoupdate} @emph{and} with tags
25877 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
25878 etc.), while
25880 @example
25881 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
25882 @end example
25884 @noindent
25885 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
25886 containing @samp{FUNC}.
25888 @item --errexit
25889 @itemx -e
25890 If any test fails, immediately abort testing.  This implies
25891 @option{--debug}: post test group clean up, and top-level logging
25892 are inhibited.  This option is meant for the full test
25893 suite, it is not really useful for generated debugging scripts.
25894 If the testsuite is run in parallel mode using @option{--jobs},
25895 then concurrently running tests will finish before exiting.
25897 @item --verbose
25898 @itemx -v
25899 Force more verbosity in the detailed output of what is being done.  This
25900 is the default for debugging scripts.
25902 @item --color
25903 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
25904 Enable colored test results.  Without an argument, or with @samp{always},
25905 test results will be colored.  With @samp{never}, color mode is turned
25906 off.  Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
25907 the testsuite author, or the argument @samp{auto} is given, then test
25908 results are colored if standard output is connected to a terminal.
25910 @item --debug
25911 @itemx -d
25912 Do not remove the files after a test group was performed---but they are
25913 still removed @emph{before}, therefore using this option is sane when
25914 running several test groups.  Create debugging scripts.  Do not
25915 overwrite the top-level
25916 log (in order to preserve a supposedly existing full log file).  This is
25917 the default for debugging scripts, but it can also be useful to debug
25918 the testsuite itself.
25920 @item --recheck
25921 Add to the selection all test groups that failed or passed unexpectedly
25922 during the last non-debugging test run.
25924 @item --trace
25925 @itemx -x
25926 Trigger shell tracing of the test groups.
25927 @end table
25929 Besides these options accepted by every Autotest testsuite, the
25930 testsuite author might have added package-specific options
25931 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
25932 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
25933 the package documentation for details.
25936 @node Making testsuite Scripts
25937 @section Making @command{testsuite} Scripts
25939 For putting Autotest into movement, you need some configuration and
25940 makefile machinery.  We recommend, at least if your package uses deep or
25941 shallow hierarchies, that you use @file{tests/} as the name of the
25942 directory holding all your tests and their makefile.  Here is a
25943 check list of things to do, followed by an example, taking into
25944 consideration whether you are also using Automake.
25946 @itemize @minus
25948 @item
25949 @cindex @file{package.m4}
25950 @atindex{PACKAGE_STRING}
25951 @atindex{PACKAGE_BUGREPORT}
25952 @atindex{PACKAGE_NAME}
25953 @atindex{PACKAGE_TARNAME}
25954 @atindex{PACKAGE_VERSION}
25955 @atindex{PACKAGE_URL}
25956 Make sure to create the file @file{package.m4}, which defines the
25957 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
25958 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
25959 address to which bug reports should be sent.  For sake of completeness,
25960 we suggest that you also define @code{AT_PACKAGE_NAME},
25961 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
25962 @code{AT_PACKAGE_URL}.
25963 @xref{Initializing configure}, for a description of these variables.
25964 Be sure to distribute @file{package.m4} and to put it into the source
25965 hierarchy: the test suite ought to be shipped!  See below for an example.
25967 @item
25968 Invoke @code{AC_CONFIG_TESTDIR} in your @file{configure.ac}.
25970 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvarv{test-path, directory})
25971 @acindex{CONFIG_TESTDIR}
25972 An Autotest test suite is to be configured in @var{directory}.  This
25973 macro causes @file{@var{directory}/atconfig} to be created by
25974 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
25975 @var{test-path} (@pxref{testsuite Invocation}).
25976 @end defmac
25978 @item
25979 Still within @file{configure.ac}, as appropriate, ensure that some
25980 @code{AC_CONFIG_FILES} command includes substitution for
25981 @file{tests/atlocal}.
25983 @item
25984 Also within your @file{configure.ac}, arrange for the @code{AUTOM4TE}
25985 variable to be set.
25987 @item
25988 The appropriate @file{Makefile} should be modified so the validation in
25989 your package is triggered by @samp{make check}.
25990 @end itemize
25992 The following example demonstrates the above checklist, first by
25993 assuming that you are using Automake (see below for tweaks to make to
25994 get the same results without Automake).  Begin by adding the following
25995 lines to your @file{configure.ac}:
25997 @example
25998 # Initialize the test suite.
25999 AC_CONFIG_TESTDIR([tests])
26000 AC_CONFIG_FILES([tests/Makefile tests/atlocal])
26001 AM_MISSING_PROG([AUTOM4TE], [autom4te])
26002 @end example
26004 Next, add the following lines to your @file{tests/Makefile.am}, in order
26005 to link @samp{make check} with a validation suite.
26007 @example
26008 # The ':;' works around a Bash 3.2 bug when the output is not writable.
26009 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
26010         :;@{ \
26011           echo '# Signature of the current package.' && \
26012           echo 'm4_define([AT_PACKAGE_NAME],' && \
26013           echo '  [$(PACKAGE_NAME)])' && \
26014           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
26015           echo '  [$(PACKAGE_TARNAME)])' && \
26016           echo 'm4_define([AT_PACKAGE_VERSION],' && \
26017           echo '  [$(PACKAGE_VERSION)])' && \
26018           echo 'm4_define([AT_PACKAGE_STRING],' && \
26019           echo '  [$(PACKAGE_STRING)])' && \
26020           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
26021           echo '  [$(PACKAGE_BUGREPORT)])'; \
26022           echo 'm4_define([AT_PACKAGE_URL],' && \
26023           echo '  [$(PACKAGE_URL)])'; \
26024         @} >'$(srcdir)/package.m4'
26026 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
26027 TESTSUITE = $(srcdir)/testsuite
26029 check-local: atconfig atlocal $(TESTSUITE)
26030         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
26032 installcheck-local: atconfig atlocal $(TESTSUITE)
26033         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
26034           $(TESTSUITEFLAGS)
26036 clean-local:
26037         test ! -f '$(TESTSUITE)' || \
26038          $(SHELL) '$(TESTSUITE)' --clean
26040 AUTOTEST = $(AUTOM4TE) --language=autotest
26041 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
26042         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
26043         mv $@@.tmp $@@
26044 @end example
26046 Note that the built testsuite is distributed; this is necessary because
26047 users might not have Autoconf installed, and thus would not be able to
26048 rebuild it.  Likewise, the use of Automake's @code{AM_MISSING_PROG} will
26049 arrange for the definition of @code{$AUTOM4TE} within the Makefile to
26050 provide the user with
26051 a nicer error message if they modify a source file to the testsuite, and
26052 accidentally trigger the rebuild rules.
26054 You might want to list explicitly the dependencies, i.e., the list of
26055 the files @file{testsuite.at} includes.
26057 If you don't use Automake, you should make the following tweaks.  In
26058 your @file{configure.ac}, replace the @code{AM_MISSING_PROG} line above
26059 with @code{AC_PATH_PROG([AUTOM4TE], [autom4te], [false])}.  You are
26060 welcome to also try using the @command{missing} script from the Automake
26061 project instead of @command{false}, to try to get a nicer error message
26062 when the user modifies prerequisites but did not have Autoconf
26063 installed, but at that point you may be better off using Automake.
26064 Then, take the code suggested above for @file{tests/@/Makefile.am} and
26065 place it in your @file{tests/@/Makefile.in} instead.  Add code to your
26066 @file{tests/@/Makefile.in} to ensure that @code{$(EXTRA_DIST)} files are
26067 distributed, as well as adding the following additional lines to prepare
26068 the set of needed Makefile variables:
26070 @example
26071 subdir = tests
26072 PACKAGE_NAME = @@PACKAGE_NAME@@
26073 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
26074 PACKAGE_VERSION = @@PACKAGE_VERSION@@
26075 PACKAGE_STRING = @@PACKAGE_STRING@@
26076 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
26077 PACKAGE_URL = @@PACKAGE_URL@@
26078 AUTOM4TE = @@AUTOM4TE@@
26080 atconfig: $(top_builddir)/config.status
26081         cd $(top_builddir) && \
26082            $(SHELL) ./config.status $(subdir)/$@@
26084 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
26085         cd $(top_builddir) && \
26086            $(SHELL) ./config.status $(subdir)/$@@
26087 @end example
26089 Using the above example (with or without Automake), and assuming you
26090 were careful to not initialize @samp{TESTSUITEFLAGS} within your
26091 makefile, you can now fine-tune test suite execution at runtime by
26092 altering this variable, for example:
26094 @example
26095 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
26096 @end example
26100 @c =============================== Frequent Autoconf Questions, with answers
26102 @node FAQ
26103 @chapter Frequent Autoconf Questions, with answers
26105 Several questions about Autoconf come up occasionally.  Here some of them
26106 are addressed.
26108 @menu
26109 * Distributing::                Distributing @command{configure} scripts
26110 * Why GNU M4::                  Why not use the standard M4?
26111 * Bootstrapping::               Autoconf and GNU M4 require each other?
26112 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
26113 * Defining Directories::        Passing @code{datadir} to program
26114 * Autom4te Cache::              What is it?  Can I remove it?
26115 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
26116 * Expanded Before Required::    Expanded Before Required
26117 * Debugging::                   Debugging @command{configure} scripts
26118 @end menu
26120 @node Distributing
26121 @section Distributing @command{configure} Scripts
26122 @cindex License
26124 @display
26125 What are the restrictions on distributing @command{configure}
26126 scripts that Autoconf generates?  How does that affect my
26127 programs that use them?
26128 @end display
26130 There are no restrictions on how the configuration scripts that Autoconf
26131 produces may be distributed or used.  In Autoconf version 1, they were
26132 covered by the GNU General Public License.  We still encourage
26133 software authors to distribute their work under terms like those of the
26134 GPL, but doing so is not required to use Autoconf.
26136 Of the other files that might be used with @command{configure},
26137 @file{config.h.in} is under whatever copyright you use for your
26138 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
26139 exception to the GPL when they are used with an Autoconf-generated
26140 @command{configure} script, which permits you to distribute them under the
26141 same terms as the rest of your package.  @file{install-sh} is from the X
26142 Consortium and is not copyrighted.
26144 @node Why GNU M4
26145 @section Why Require GNU M4?
26147 @display
26148 Why does Autoconf require GNU M4?
26149 @end display
26151 Many M4 implementations have hard-coded limitations on the size and
26152 number of macros that Autoconf exceeds.  They also lack several
26153 builtin macros that it would be difficult to get along without in a
26154 sophisticated application like Autoconf, including:
26156 @example
26157 m4_builtin
26158 m4_indir
26159 m4_bpatsubst
26160 __file__
26161 __line__
26162 @end example
26164 Autoconf requires version 1.4.6 or later of GNU M4.
26166 Since only software maintainers need to use Autoconf, and since GNU
26167 M4 is simple to configure and install, it seems reasonable to require
26168 GNU M4 to be installed also.  Many maintainers of GNU and
26169 other free software already have most of the GNU utilities
26170 installed, since they prefer them.
26172 @node Bootstrapping
26173 @section How Can I Bootstrap?
26174 @cindex Bootstrap
26176 @display
26177 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
26178 @command{configure} script, how do I bootstrap?  It seems like a chicken
26179 and egg problem!
26180 @end display
26182 This is a misunderstanding.  Although GNU M4 does come with a
26183 @command{configure} script produced by Autoconf, Autoconf is not required
26184 in order to run the script and install GNU M4.  Autoconf is only
26185 required if you want to change the M4 @command{configure} script, which few
26186 people have to do (mainly its maintainer).
26188 @node Why Not Imake
26189 @section Why Not Imake?
26190 @cindex Imake
26192 @display
26193 Why not use Imake instead of @command{configure} scripts?
26194 @end display
26196 Several people have written addressing this question, so
26197 adaptations of their explanations are included here.
26199 The following answer is based on one written by Richard Pixley:
26201 @quotation
26202 Autoconf generated scripts frequently work on machines that it has
26203 never been set up to handle before.  That is, it does a good job of
26204 inferring a configuration for a new system.  Imake cannot do this.
26206 Imake uses a common database of host specific data.  For X11, this makes
26207 sense because the distribution is made as a collection of tools, by one
26208 central authority who has control over the database.
26210 GNU tools are not released this way.  Each GNU tool has a
26211 maintainer; these maintainers are scattered across the world.  Using a
26212 common database would be a maintenance nightmare.  Autoconf may appear
26213 to be this kind of database, but in fact it is not.  Instead of listing
26214 host dependencies, it lists program requirements.
26216 If you view the GNU suite as a collection of native tools, then the
26217 problems are similar.  But the GNU development tools can be
26218 configured as cross tools in almost any host+target permutation.  All of
26219 these configurations can be installed concurrently.  They can even be
26220 configured to share host independent files across hosts.  Imake doesn't
26221 address these issues.
26223 Imake templates are a form of standardization.  The GNU coding
26224 standards address the same issues without necessarily imposing the same
26225 restrictions.
26226 @end quotation
26229 Here is some further explanation, written by Per Bothner:
26231 @quotation
26232 One of the advantages of Imake is that it is easy to generate large
26233 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
26234 However, @code{cpp} is not programmable: it has limited conditional
26235 facilities, and no looping.  And @code{cpp} cannot inspect its
26236 environment.
26238 All of these problems are solved by using @code{sh} instead of
26239 @code{cpp}.  The shell is fully programmable, has macro substitution,
26240 can execute (or source) other shell scripts, and can inspect its
26241 environment.
26242 @end quotation
26245 Paul Eggert elaborates more:
26247 @quotation
26248 With Autoconf, installers need not assume that Imake itself is already
26249 installed and working well.  This may not seem like much of an advantage
26250 to people who are accustomed to Imake.  But on many hosts Imake is not
26251 installed or the default installation is not working well, and requiring
26252 Imake to install a package hinders the acceptance of that package on
26253 those hosts.  For example, the Imake template and configuration files
26254 might not be installed properly on a host, or the Imake build procedure
26255 might wrongly assume that all source files are in one big directory
26256 tree, or the Imake configuration might assume one compiler whereas the
26257 package or the installer needs to use another, or there might be a
26258 version mismatch between the Imake expected by the package and the Imake
26259 supported by the host.  These problems are much rarer with Autoconf,
26260 where each package comes with its own independent configuration
26261 processor.
26263 Also, Imake often suffers from unexpected interactions between
26264 @command{make} and the installer's C preprocessor.  The fundamental problem
26265 here is that the C preprocessor was designed to preprocess C programs,
26266 not makefiles.  This is much less of a problem with Autoconf,
26267 which uses the general-purpose preprocessor M4, and where the
26268 package's author (rather than the installer) does the preprocessing in a
26269 standard way.
26270 @end quotation
26273 Finally, Mark Eichin notes:
26275 @quotation
26276 Imake isn't all that extensible, either.  In order to add new features to
26277 Imake, you need to provide your own project template, and duplicate most
26278 of the features of the existing one.  This means that for a sophisticated
26279 project, using the vendor-provided Imake templates fails to provide any
26280 leverage---since they don't cover anything that your own project needs
26281 (unless it is an X11 program).
26283 On the other side, though:
26285 The one advantage that Imake has over @command{configure}:
26286 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
26287 than @file{Makefile.in} files.  There is a fix to this, however---at least
26288 for the Kerberos V5 tree, we've modified things to call in common
26289 @file{post.in} and @file{pre.in} makefile fragments for the
26290 entire tree.  This means that a lot of common things don't have to be
26291 duplicated, even though they normally are in @command{configure} setups.
26292 @end quotation
26295 @node Defining Directories
26296 @section How Do I @code{#define} Installation Directories?
26298 @display
26299 My program needs library files, installed in @code{datadir} and
26300 similar.  If I use
26302 @example
26303 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
26304   [Define to the read-only architecture-independent
26305    data directory.])
26306 @end example
26308 @noindent
26309 I get
26311 @example
26312 #define DATADIR "$@{prefix@}/share"
26313 @end example
26314 @end display
26316 As already explained, this behavior is on purpose, mandated by the
26317 GNU Coding Standards, see @ref{Installation Directory
26318 Variables}.  There are several means to achieve a similar goal:
26320 @itemize @minus
26321 @item
26322 Do not use @code{AC_DEFINE} but use your makefile to pass the
26323 actual value of @code{datadir} via compilation flags.
26324 @xref{Installation Directory Variables}, for the details.
26326 @item
26327 This solution can be simplified when compiling a program: you may either
26328 extend the @code{CPPFLAGS}:
26330 @example
26331 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
26332 @end example
26334 @noindent
26335 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
26337 @example
26338 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
26339 @end example
26341 @noindent
26342 Alternatively, create a dedicated header file:
26344 @example
26345 DISTCLEANFILES = myprog-paths.h
26346 myprog-paths.h: Makefile
26347         echo '#define DATADIR "$(datadir)"' >$@@
26348 @end example
26350 @noindent
26351 The Gnulib module @samp{configmake} provides such a header with all the
26352 standard directory variables defined, @pxref{configmake,,, gnulib, GNU
26353 Gnulib}.
26355 @item
26356 Use @code{AC_DEFINE} but have @command{configure} compute the literal
26357 value of @code{datadir} and others.  Many people have wrapped macros to
26358 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
26359 the @uref{https://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
26360 Archive}.
26362 This solution does not conform to the GNU Coding Standards.
26364 @item
26365 Note that all the previous solutions hard wire the absolute name of
26366 these directories in the executables, which is not a good property.  You
26367 may try to compute the names relative to @code{prefix}, and try to
26368 find @code{prefix} at runtime, this way your package is relocatable.
26369 @end itemize
26372 @node Autom4te Cache
26373 @section What is @file{autom4te.cache}?
26375 @display
26376 What is this directory @file{autom4te.cache}?  Can I safely remove it?
26377 @end display
26379 In the GNU Build System, @file{configure.ac} plays a central
26380 role and is read by many tools: @command{autoconf} to create
26381 @file{configure}, @command{autoheader} to create @file{config.h.in},
26382 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
26383 check the completeness of @file{configure.ac}, @command{autoreconf} to
26384 check the GNU Build System components that are used.  To
26385 ``read @file{configure.ac}'' actually means to compile it with M4,
26386 which can be a long process for complex @file{configure.ac}.
26388 This is why all these tools, instead of running directly M4, invoke
26389 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
26390 a specific demand, stores additional information in
26391 @file{autom4te.cache} for future runs.  For instance, if you run
26392 @command{autoconf}, behind the scenes, @command{autom4te} also
26393 stores information for the other tools, so that when you invoke
26394 @command{autoheader} or @command{automake} etc., reprocessing
26395 @file{configure.ac} is not needed.  The speed up is frequently 30%,
26396 and is increasing with the size of @file{configure.ac}.
26398 But it is and remains being simply a cache: you can safely remove it.
26400 @sp 1
26402 @display
26403 Can I permanently get rid of it?
26404 @end display
26406 The creation of this cache can be disabled from
26407 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
26408 details.  You should be aware that disabling the cache slows down the
26409 Autoconf test suite by 40%.  The more GNU Build System
26410 components are used, the more the cache is useful; for instance
26411 running @samp{autoreconf -f} on the Core Utilities is twice slower without
26412 the cache @emph{although @option{--force} implies that the cache is
26413 not fully exploited}, and eight times slower than without
26414 @option{--force}.
26417 @node Present But Cannot Be Compiled
26418 @section Header Present But Cannot Be Compiled
26420 The most important guideline to bear in mind when checking for
26421 features is to mimic as much as possible the intended use.
26422 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
26423 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
26424 the preprocessor, instead of the compiler, to check for headers.  As a
26425 result, incompatibilities between headers went unnoticed during
26426 configuration, and maintainers finally had to deal with this issue
26427 elsewhere.
26429 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
26430 checks are performed, and @command{configure} complains loudly if the
26431 compiler and the preprocessor do not agree.  However, only the compiler
26432 result is considered.  As of Autoconf 2.70, only the compiler check is
26433 performed.
26435 Consider the following example:
26437 @smallexample
26438 $ @kbd{cat number.h}
26439 typedef int number;
26440 $ @kbd{cat pi.h}
26441 const number pi = 3;
26442 $ @kbd{cat configure.ac}
26443 AC_INIT([Example], [1.0], [bug-example@@example.org])
26444 AC_CHECK_HEADERS([pi.h])
26445 $ @kbd{autoconf -Wall}
26446 $ @kbd{./configure CPPFLAGS='-I.'}
26447 checking for gcc... gcc
26448 checking whether the C compiler works... yes
26449 checking for C compiler default output file name... a.out
26450 checking for suffix of executables...
26451 checking whether we are cross compiling... no
26452 checking for suffix of object files... o
26453 checking whether the compiler supports GNU C... yes
26454 checking whether gcc accepts -g... yes
26455 checking for gcc option to enable C11 features... -std=gnu11
26456 checking for sys/types.h... yes
26457 checking for sys/stat.h... yes
26458 checking for strings.h... yes
26459 checking for inttypes.h... yes
26460 checking for stdint.h... yes
26461 checking for unistd.h... yes
26462 checking for pi.h... no
26463 @end smallexample
26465 @noindent
26466 The proper way to handle this case is using the fourth argument
26467 (@pxref{Generic Headers}):
26469 @example
26470 $ @kbd{cat configure.ac}
26471 AC_INIT([Example], [1.0], [bug-example@@example.org])
26472 AC_CHECK_HEADERS([number.h pi.h], [], [],
26473 [[#ifdef HAVE_NUMBER_H
26474 # include <number.h>
26475 #endif
26477 $ @kbd{autoconf -Wall}
26478 $ @kbd{./configure CPPFLAGS='-I.'}
26479 checking for gcc... gcc
26480 checking whether the C compiler works... yes
26481 checking for C compiler default output file name... a.out
26482 checking for suffix of executables...
26483 checking whether we are cross compiling... no
26484 checking for suffix of object files... o
26485 checking whether the compiler supports GNU C... yes
26486 checking whether gcc accepts -g... yes
26487 checking for gcc option to enable C11 features... -std=gnu11
26488 checking for number.h... yes
26489 checking for pi.h... yes
26490 @end example
26492 See @ref{Particular Headers}, for a list of headers with their
26493 prerequisites.
26495 @node Expanded Before Required
26496 @section Expanded Before Required
26498 @cindex expanded before required
26499 Older versions of Autoconf silently built files with incorrect ordering
26500 between dependent macros if an outer macro first expanded, then later
26501 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
26502 situation no longer generates out-of-order code, but results in
26503 duplicate output and a syntax warning:
26505 @example
26506 $ @kbd{cat configure.ac}
26507 @result{}AC_DEFUN([TESTA], [[echo in A
26508 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
26509 @result{}SEEN_A=:]])
26510 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
26511 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
26512 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
26513 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
26514 @result{}TESTA
26515 @result{}TESTC])
26516 @result{}AC_INIT
26517 @result{}OUTER
26518 @result{}AC_OUTPUT
26519 $ @kbd{autoconf}
26520 @result{}configure.ac:11: warning: AC_REQUIRE:
26521 @result{} `TESTA' was expanded before it was required
26522 @result{}configure.ac:4: TESTB is expanded from...
26523 @result{}configure.ac:6: TESTC is expanded from...
26524 @result{}configure.ac:7: OUTER is expanded from...
26525 @result{}configure.ac:11: the top level
26526 @end example
26528 @noindent
26529 To avoid this warning, decide what purpose the macro in question serves.
26530 If it only needs to be expanded once (for example, if it provides
26531 initialization text used by later macros), then the simplest fix is to
26532 change the macro to be declared with @code{AC_DEFUN_ONCE}
26533 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
26534 newer.  A more portable fix is to change all
26535 instances of direct calls to instead go through @code{AC_REQUIRE}
26536 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
26537 by arguments or by the current definition of other macros in the m4
26538 environment, then the macro should always be directly expanded instead
26539 of required.
26541 For another case study, consider this example trimmed down from an
26542 actual package.  Originally, the package contained shell code and
26543 multiple macro invocations at the top level of @file{configure.ac}:
26545 @example
26546 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26547 foobar=
26548 AC_PROG_CC
26550 @end example
26552 @noindent
26553 but that was getting complex, so the author wanted to offload some of
26554 the text into a new macro in another file included via
26555 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
26556 macro:
26558 @example
26559 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26560 AC_DEFUN([BAR], [
26561 foobar=
26562 AC_PROG_CC
26566 @end example
26568 @noindent
26569 With older versions of Autoconf, the setting of @samp{foobar=} occurs
26570 before the single compiler check, as the author intended.  But with
26571 Autoconf 2.64, this issues the ``expanded before it was required''
26572 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
26573 check, one before @samp{foobar=}, and one after.  To understand why this
26574 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
26575 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
26576 the documented semantics of @code{AC_REQUIRE}, this means that
26577 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
26578 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceding the
26579 use of @samp{foobar=}.  The older versions of Autoconf were broken with
26580 regards to the rules of @code{AC_REQUIRE}, which explains why the code
26581 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
26582 autoconf.  In other words, the author was unknowingly relying on a bug
26583 exploit to get the desired results, and that exploit broke once the bug
26584 was fixed.
26586 So, what recourse does the author have, to restore their intended
26587 semantics of setting @samp{foobar=} prior to a single compiler check,
26588 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
26589 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
26590 there is always the possibility of using the lower-level
26591 @code{m4_define}:
26593 @example
26594 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26595 m4_define([BAR], [
26596 foobar=
26597 AC_PROG_CC
26601 @end example
26603 @noindent
26604 This works great if everything is in the same file.  However, it does
26605 not help in the case where the author wants to have @command{aclocal}
26606 find the definition of @code{BAR} from its own file, since
26607 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
26608 better fix is to recognize that if @code{BAR} also uses
26609 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
26610 to a subsequent require.  Then, by creating yet another helper macro,
26611 the author can once again guarantee a single invocation of
26612 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
26613 author can also use @code{AC_BEFORE} to make sure no other macro
26614 appearing before @code{BAR} has triggered an unwanted expansion of
26615 @code{AC_PROG_CC}.
26617 @example
26618 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26619 AC_DEFUN([BEFORE_CC], [
26620 foobar=
26622 AC_DEFUN([BAR], [
26623 AC_BEFORE([$0], [AC_PROG_CC])dnl
26624 AC_REQUIRE([BEFORE_CC])dnl
26625 AC_REQUIRE([AC_PROG_CC])dnl
26629 @end example
26632 @node Debugging
26633 @section Debugging @command{configure} scripts
26635 While in general, @command{configure} scripts generated by Autoconf
26636 strive to be fairly portable to various systems, compilers, shells, and
26637 other tools, it may still be necessary to debug a failing test, broken
26638 script or makefile, or fix or override an incomplete, faulty, or erroneous
26639 test, especially during macro development.  Failures can occur at all levels,
26640 in M4 syntax or semantics, shell script issues, or due to bugs in the
26641 test or the tools invoked by @command{configure}.  Together with the
26642 rather arcane error message that @command{m4} and @command{make} may
26643 produce when their input contains syntax errors, this can make debugging
26644 rather painful.
26646 Nevertheless, here is a list of hints and strategies that may help:
26648 @itemize
26649 @item
26650 When @command{autoconf} fails, common causes for error include:
26652 @itemize
26653 @item
26654 mismatched or unbalanced parentheses or braces (@pxref{Balancing
26655 Parentheses}),
26657 @item under- or over-quoted macro arguments (@pxref{Autoconf
26658 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
26659 Macros}),
26661 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
26662 Language}).
26663 @end itemize
26665 Typically, it helps to go back to the last working version of the input
26666 and compare the differences for each of these errors.  Another
26667 possibility is to sprinkle pairs of @code{m4_traceon} and
26668 @code{m4_traceoff} judiciously in the code, either without a parameter
26669 or listing some macro names and watch @command{m4} expand its input
26670 verbosely (@pxref{Debugging via autom4te}).
26672 @item
26673 Sometimes @command{autoconf} succeeds but the generated
26674 @command{configure} script has invalid shell syntax.  You can detect this
26675 case by running @samp{bash -n configure} or @samp{sh -n configure}.
26676 If this command fails, the same tips apply, as if @command{autoconf} had
26677 failed.
26679 @item
26680 Debugging @command{configure} script execution may be done by sprinkling
26681 pairs of @code{set -x} and @code{set +x} into the shell script before
26682 and after the region that contains a bug.  Running the whole script with
26683 @samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
26684 @var{shell} may work, but produces lots of output.  Here, it can help to
26685 search for markers like @samp{checking for} a particular test in the
26686 @var{log-file}.
26688 @item
26689 Alternatively, you might use a shell with debugging capabilities like
26690 @uref{http://bashdb.sourceforge.net/, bashdb}.
26692 @item
26693 When @command{configure} tests produce invalid results for your system,
26694 it may be necessary to override them:
26696 @itemize
26697 @item
26698 For programs, tools or libraries variables, preprocessor, compiler, or
26699 linker flags, it is often sufficient to override them at @command{make}
26700 run time with some care (@pxref{Macros and Submakes}).  Since this
26701 normally won't cause @command{configure} to be run again with these
26702 changed settings, it may fail if the changed variable would have caused
26703 different test results from @command{configure}, so this may work only
26704 for simple differences.
26706 @item
26707 Most tests which produce their result in a substituted variable allow to
26708 override the test by setting the variable on the @command{configure}
26709 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
26710 @pxref{Particular Systems}).
26712 @item
26713 Many tests store their result in a cache variable (@pxref{Caching
26714 Results}).  This lets you override them either on the
26715 @command{configure} command line as above, or through a primed cache or
26716 site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
26717 cache variable is documented with a test macro or may be inferred from
26718 @ref{Cache Variable Names}; the precise semantics of undocumented
26719 variables are often internal details, subject to change.
26720 @end itemize
26722 @item
26723 Alternatively, @command{configure} may produce invalid results because
26724 of uncaught programming errors, in your package or in an upstream
26725 library package.  For example, when @code{AC_CHECK_LIB} fails to find a
26726 library with a specified function, always check @file{config.log}.  This
26727 will reveal the exact error that produced the failing result: the
26728 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
26729 @end itemize
26731 Conversely, as macro author, you can make it easier for users of your
26732 macro:
26734 @itemize
26735 @item
26736 by minimizing dependencies between tests and between test results as far
26737 as possible,
26739 @item
26740 by using @command{make} variables to factorize and allow
26741 override of settings at @command{make} run time,
26743 @item
26744 by honoring the GNU Coding Standards and not overriding flags
26745 reserved for the user except temporarily during @command{configure}
26746 tests,
26748 @item
26749 by not requiring users of your macro to use the cache variables.
26750 Instead, expose the result of the test via @var{run-if-true} and
26751 @var{run-if-false} parameters.  If the result is not a boolean,
26752 then provide it through documented shell variables.
26753 @end itemize
26756 @c ===================================================== History of Autoconf.
26758 @node History
26759 @chapter History of Autoconf
26760 @cindex History of autoconf
26762 @emph{This chapter was written by the original author, David MacKenzie.}
26764 You may be wondering, Why was Autoconf originally written?  How did it
26765 get into its present form?  (Why does it look like gorilla spit?)  If
26766 you're not wondering, then this chapter contains no information useful
26767 to you, and you might as well skip it.  If you @emph{are} wondering,
26768 then let there be light@enddots{}
26770 @menu
26771 * Genesis::                     Prehistory and naming of @command{configure}
26772 * Exodus::                      The plagues of M4 and Perl
26773 * Leviticus::                   The priestly code of portability arrives
26774 * Numbers::                     Growth and contributors
26775 * Deuteronomy::                 Approaching the promises of easy configuration
26776 @end menu
26778 @node Genesis
26779 @section Genesis
26781 In June 1991 I was maintaining many of the GNU utilities for the
26782 Free Software Foundation.  As they were ported to more platforms and
26783 more programs were added, the number of @option{-D} options that users
26784 had to select in the makefile (around 20) became burdensome.
26785 Especially for me---I had to test each new release on a bunch of
26786 different systems.  So I wrote a little shell script to guess some of
26787 the correct settings for the fileutils package, and released it as part
26788 of fileutils 2.0.  That @command{configure} script worked well enough that
26789 the next month I adapted it (by hand) to create similar @command{configure}
26790 scripts for several other GNU utilities packages.  Brian Berliner
26791 also adapted one of my scripts for his CVS revision control system.
26793 Later that summer, I learned that Richard Stallman and Richard Pixley
26794 were developing similar scripts to use in the GNU compiler tools;
26795 so I adapted my @command{configure} scripts to support their evolving
26796 interface: using the file name @file{Makefile.in} as the templates;
26797 adding @samp{+srcdir}, the first option (of many); and creating
26798 @file{config.status} files.
26800 @node Exodus
26801 @section Exodus
26803 As I got feedback from users, I incorporated many improvements, using
26804 Emacs to search and replace, cut and paste, similar changes in each of
26805 the scripts.  As I adapted more GNU utilities packages to use
26806 @command{configure} scripts, updating them all by hand became impractical.
26807 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
26808 mail saying that the @command{configure} scripts were great, and asking if
26809 I had a tool for generating them that I could send him.  No, I thought,
26810 but I should!  So I started to work out how to generate them.  And the
26811 journey from the slavery of hand-written @command{configure} scripts to the
26812 abundance and ease of Autoconf began.
26814 Cygnus @command{configure}, which was being developed at around that time,
26815 is table driven; it is meant to deal mainly with a discrete number of
26816 system types with a small number of mainly unguessable features (such as
26817 details of the object file format).  The automatic configuration system
26818 that Brian Fox had developed for Bash takes a similar approach.  For
26819 general use, it seems to me a hopeless cause to try to maintain an
26820 up-to-date database of which features each variant of each operating
26821 system has.  It's easier and more reliable to check for most features on
26822 the fly---especially on hybrid systems that people have hacked on
26823 locally or that have patches from vendors installed.
26825 I considered using an architecture similar to that of Cygnus
26826 @command{configure}, where there is a single @command{configure} script that
26827 reads pieces of @file{configure.in} when run.  But I didn't want to have
26828 to distribute all of the feature tests with every package, so I settled
26829 on having a different @command{configure} made from each
26830 @file{configure.in} by a preprocessor.  That approach also offered more
26831 control and flexibility.
26833 I looked briefly into using the Metaconfig package, by Larry Wall,
26834 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
26835 reasons.  The @command{Configure} scripts it produces are interactive,
26836 which I find quite inconvenient; I didn't like the ways it checked for
26837 some features (such as library functions); I didn't know that it was
26838 still being maintained, and the @command{Configure} scripts I had
26839 seen didn't work on many modern systems (such as System V R4 and NeXT);
26840 it wasn't flexible in what it could do in response to a feature's
26841 presence or absence; I found it confusing to learn; and it was too big
26842 and complex for my needs (I didn't realize then how much Autoconf would
26843 eventually have to grow).
26845 I considered using Perl to generate my style of @command{configure}
26846 scripts, but decided that M4 was better suited to the job of simple
26847 textual substitutions: it gets in the way less, because output is
26848 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
26849 the GNU extensions to M4.)  Also, some of my friends at the
26850 University of Maryland had recently been putting M4 front ends on
26851 several programs, including @code{tvtwm}, and I was interested in trying
26852 out a new language.
26854 @node Leviticus
26855 @section Leviticus
26857 Since my @command{configure} scripts determine the system's capabilities
26858 automatically, with no interactive user intervention, I decided to call
26859 the program that generates them Autoconfig.  But with a version number
26860 tacked on, that name would be too long for old Unix file systems,
26861 so I shortened it to Autoconf.
26863 In the fall of 1991 I called together a group of fellow questers after
26864 the Holy Grail of portability (er, that is, alpha testers) to give me
26865 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
26866 and continued to add features and improve the techniques used in the
26867 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
26868 with the idea of making an Autoconf shell script to run M4
26869 and check for unresolved macro calls; Richard Pixley, who suggested
26870 running the compiler instead of searching the file system to find
26871 include files and symbols, for more accurate results; Karl Berry, who
26872 got Autoconf to configure @TeX{} and added the macro index to the
26873 documentation; and Ian Lance Taylor, who added support for creating a C
26874 header file as an alternative to putting @option{-D} options in a
26875 makefile, so he could use Autoconf for his UUCP package.
26876 The alpha testers cheerfully adjusted their files again and again as the
26877 names and calling conventions of the Autoconf macros changed from
26878 release to release.  They all contributed many specific checks, great
26879 ideas, and bug fixes.
26881 @node Numbers
26882 @section Numbers
26884 In July 1992, after months of alpha testing, I released Autoconf 1.0,
26885 and converted many GNU packages to use it.  I was surprised by how
26886 positive the reaction to it was.  More people started using it than I
26887 could keep track of, including people working on software that wasn't
26888 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
26889 Autoconf continued to improve rapidly, as many people using the
26890 @command{configure} scripts reported problems they encountered.
26892 Autoconf turned out to be a good torture test for M4 implementations.
26893 Unix M4 started to dump core because of the length of the
26894 macros that Autoconf defined, and several bugs showed up in GNU
26895 M4 as well.  Eventually, we realized that we needed to use some
26896 features that only GNU M4 has.  4.3BSD M4, in
26897 particular, has an impoverished set of builtin macros; the System V
26898 version is better, but still doesn't provide everything we need.
26900 More development occurred as people put Autoconf under more stresses
26901 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
26902 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
26903 invalid arguments.  Jim Blandy bravely coerced it into configuring
26904 GNU Emacs, laying the groundwork for several later improvements.
26905 Roland McGrath got it to configure the GNU C Library, wrote the
26906 @command{autoheader} script to automate the creation of C header file
26907 templates, and added a @option{--verbose} option to @command{configure}.
26908 Noah Friedman added the @option{--autoconf-dir} option and
26909 @code{AC_MACRODIR} environment variable.  (He also coined the term
26910 @dfn{autoconfiscate} to mean ``adapt a software package to use
26911 Autoconf''.)  Roland and Noah improved the quoting protection in
26912 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
26913 dealing with portability problems from February through June, 1993.
26915 @node Deuteronomy
26916 @section Deuteronomy
26918 A long wish list for major features had accumulated, and the effect of
26919 several years of patching by various people had left some residual
26920 cruft.  In April 1994, while working for Cygnus Support, I began a major
26921 revision of Autoconf.  I added most of the features of the Cygnus
26922 @command{configure} that Autoconf had lacked, largely by adapting the
26923 relevant parts of Cygnus @command{configure} with the help of david zuhn
26924 and Ken Raeburn.  These features include support for using
26925 @file{config.sub}, @file{config.guess}, @option{--host}, and
26926 @option{--target}; making links to files; and running @command{configure}
26927 scripts in subdirectories.  Adding these features enabled Ken to convert
26928 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
26929 Autoconf.
26931 I added more features in response to other peoples' requests.  Many
26932 people had asked for @command{configure} scripts to share the results of
26933 the checks between runs, because (particularly when configuring a large
26934 source tree, like Cygnus does) they were frustratingly slow.  Mike
26935 Haertel suggested adding site-specific initialization scripts.  People
26936 distributing software that had to unpack on MS-DOS asked for a way to
26937 override the @file{.in} extension on the file names, which produced file
26938 names like @file{config.h.in} containing two dots.  Jim Avera did an
26939 extensive examination of the problems with quoting in @code{AC_DEFINE}
26940 and @code{AC_SUBST}; his insights led to significant improvements.
26941 Richard Stallman asked that compiler output be sent to @file{config.log}
26942 instead of @file{/dev/null}, to help people debug the Emacs
26943 @command{configure} script.
26945 I made some other changes because of my dissatisfaction with the quality
26946 of the program.  I made the messages showing results of the checks less
26947 ambiguous, always printing a result.  I regularized the names of the
26948 macros and cleaned up coding style inconsistencies.  I added some
26949 auxiliary utilities that I had developed to help convert source code
26950 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
26951 the macros not interrupt each others' messages.  (That feature revealed
26952 some performance bottlenecks in GNU M4, which he hastily
26953 corrected!)  I reorganized the documentation around problems people want
26954 to solve.  And I began a test suite, because experience had shown that
26955 Autoconf has a pronounced tendency to regress when we change it.
26957 Again, several alpha testers gave invaluable feedback, especially
26958 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
26959 and Mark Eichin.
26961 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
26962 have free time again.  I think.  Yeah, right.)
26965 @c ========================================================== Appendices
26968 @node GNU Free Documentation License
26969 @appendix GNU Free Documentation License
26971 @include fdl.texi
26973 @node Indices
26974 @appendix Indices
26976 @menu
26977 * Environment Variable Index::  Index of environment variables used
26978 * Output Variable Index::       Index of variables set in output files
26979 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
26980 * Cache Variable Index::        Index of documented cache variables
26981 * Autoconf Macro Index::        Index of Autoconf macros
26982 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
26983 * Autotest Macro Index::        Index of Autotest macros
26984 * Program & Function Index::    Index of those with portability problems
26985 * Concept Index::               General index
26986 @end menu
26988 @node Environment Variable Index
26989 @appendixsec Environment Variable Index
26991 This is an alphabetical list of the environment variables that might
26992 influence Autoconf checks.
26994 @printindex ev
26996 @node Output Variable Index
26997 @appendixsec Output Variable Index
26999 This is an alphabetical list of the variables that Autoconf can
27000 substitute into files that it creates, typically one or more
27001 makefiles.  @xref{Setting Output Variables}, for more information
27002 on how this is done.
27004 @printindex ov
27006 @node Preprocessor Symbol Index
27007 @appendixsec Preprocessor Symbol Index
27009 This is an alphabetical list of the C preprocessor symbols that the
27010 Autoconf macros define.  To work with Autoconf, C source code needs to
27011 use these names in @code{#if} or @code{#ifdef} directives.
27013 @printindex cv
27015 @node Cache Variable Index
27016 @appendixsec Cache Variable Index
27018 This is an alphabetical list of documented cache variables used
27019 by macros defined in Autoconf.  Autoconf macros may use additional cache
27020 variables internally.
27021 @ifset shortindexflag
27022 To make the list easier to use, the variables are listed without their
27023 preceding @samp{ac_cv_}.
27024 @end ifset
27026 @printindex CA
27028 @node Autoconf Macro Index
27029 @appendixsec Autoconf Macro Index
27031 This is an alphabetical list of the Autoconf macros.
27032 @ifset shortindexflag
27033 To make the list easier to use, the macros are listed without their
27034 preceding @samp{AC_}.
27035 @end ifset
27037 @printindex AC
27039 @node M4 Macro Index
27040 @appendixsec M4 Macro Index
27042 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
27043 @ifset shortindexflag
27044 To make the list easier to use, the macros are listed without their
27045 preceding @samp{m4_} or @samp{AS_}.  The prefix is @samp{m4_} for
27046 all-lowercase macro names and @samp{AS_} for all-uppercase macro
27047 names.
27048 @end ifset
27050 @printindex MS
27052 @node Autotest Macro Index
27053 @appendixsec Autotest Macro Index
27055 This is an alphabetical list of the Autotest macros.
27056 @ifset shortindexflag
27057 To make the list easier to use, the macros are listed without their
27058 preceding @samp{AT_}.
27059 @end ifset
27061 @printindex AT
27063 @node Program & Function Index
27064 @appendixsec Program and Function Index
27066 This is an alphabetical list of the programs and functions whose
27067 portability is discussed in this document.
27069 @printindex pr
27071 @node Concept Index
27072 @appendixsec Concept Index
27074 This is an alphabetical list of the files, tools, and concepts
27075 introduced in this document.
27077 @printindex cp
27079 @bye
27081 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
27082 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
27083 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
27084 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
27085 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
27086 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
27087 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
27088 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
27089 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
27090 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
27091 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
27092 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
27093 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir vr
27094 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
27095 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
27096 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
27097 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
27098 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
27099 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
27100 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
27101 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
27102 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
27103 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
27104 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
27105 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
27106 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
27107 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
27108 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
27109 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
27110 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
27111 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
27112 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
27113 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
27114 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
27115 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
27116 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix acxindex autom
27117 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
27118 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
27119 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
27120 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
27121 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
27122 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
27123 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
27124 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
27125 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
27126 @c  LocalWords:  STDBOOL BOOL stdbool cplusplus bool Bool stdarg tm te
27127 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
27128 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
27129 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
27130 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
27131 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
27132 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
27133 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
27134 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
27135 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
27136 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
27137 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
27138 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
27139 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
27140 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
27141 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
27142 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
27143 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
27144 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
27145 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
27146 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
27147 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
27148 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
27149 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp pR
27150 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM url fc
27151 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc ing FP
27152 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
27153 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped SUBST'ed
27154 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
27155 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
27156 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
27157 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
27158 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
27159 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
27160 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
27161 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
27162 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
27163 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
27164 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
27165 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
27166 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
27167 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
27168 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
27169 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
27170 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
27171 @c  LocalWords:  Dynix basename aname cname macroexpands xno xcheck iso
27172 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline vrindex SYS
27173 @c  LocalWords:  syncodeindex define'd caindex CAindex MacKenzie DIRS
27174 @c  LocalWords:  Runtime runtime Submakes submakes MAKEFLAGS whitespace
27175 @c  LocalWords:  Timestamps Unportability Canonicalizing stdalign dirN
27176 @c  LocalWords:  acinclude AMFLAGS LIBS OBJCXXFLAGS GOFLAGS runstatedir
27177 @c  LocalWords:  metacharacter EXPENSIVEP errno setjmp wctype sys mawk
27178 @c  LocalWords:  nawk ggrep egrep gegrep fgrep gfgrep LEX lex yytext nm
27179 @c  LocalWords:  yywrap xflex lexyy YFLAGS yacc divnum libs fuindex ffs
27180 @c  LocalWords:  environ sigaction extern ftello nonnull STRTOLD LLONG
27181 @c  LocalWords:  strtold vfprintf ULLONG strcasecmp strncasecmp MSVC th
27182 @c  LocalWords:  NDEBUG Xenix INO libc ISDIR ISREG Tektronix Amdahl ino
27183 @c  LocalWords:  typedef pxref fileblocks submembers INTMAX intmax UINT
27184 @c  LocalWords:  INTPTR intptr SSIZE ssize uint UINTPTR uintptr OPENMP
27185 @c  LocalWords:  openmp OpenMP omp Alignas Alignof Noreturn UTF vals gl
27186 @c  LocalWords:  offsetof VARARRAYS VLA CCC stdcxx nullptr
27187 @c  LocalWords:  constexpr decltype unicode fstreams iostreams iomanip
27188 @c  LocalWords:  stringstreams GXX OBJCPP OBJCXX objcxx GOBJCXX erlc tx
27189 @c  LocalWords:  OBJCXXCPP FIXEDFORM GFC argc argv shellvar fpp MODEXT
27190 @c  LocalWords:  freeform fixedform MODINC MODOUT gccgo GOC xmkmf fseek
27191 @c  LocalWords:  interpval ftell Interix macOS PTHREAD NonStop XOPEN xc
27192 @c  LocalWords:  IEC ATTRIBS BFP DFP O'Donell Sebor ERTS Erlang's erts
27193 @c  LocalWords:  erlang Wundef scalable USG NOTMAKE DOUCH
27194 @c  LocalWords:  IVE changesyntax ifnotinfo oline num cfg debugfile cdr
27195 @c  LocalWords:  debugmode traceoff traceon patsubst dumpdefs ifelse aa
27196 @c  LocalWords:  mkstemp undivert lifo errprintn BINSH sanitization bcd
27197 @c  LocalWords:  cleardivert bmatch bpatsubsts subst cond nblank ifval
27198 @c  LocalWords:  ifblank ifnblank ifvaln fputc fgetc argn mapall dvarv
27199 @c  LocalWords:  shiftn abcd elt noquote mkargs joinall SHA prereq dup
27200 @c  LocalWords:  listc setb seta ARITH HNUM xcurly xoccupied
27201 @c  LocalWords:  TESTA TESTB TESTC hoc xpg xxyzzyz dtksh nosuch fifos
27202 @c  LocalWords:  fifo Stardent sig WIF WIFSIGNALED SIGQUIT tty perl ret
27203 @c  LocalWords:  SIGINT NUL SFN PRN aeiou MSYS SIGTERM xhi arith UWIN
27204 @c  LocalWords:  CLICOLOR FPATH POSIXLY Shellshock CVE OSF doit ec ci
27205 @c  LocalWords:  notreached cim nc ACL faccessat Alexandre getline sqrt
27206 @c  LocalWords:  CONVFMT FS OFMT CDS chgrp futimens utimensat oo esc od
27207 @c  LocalWords:  ownerships mape readdir mkfifo mknod testsuites XSI rf
27208 @c  LocalWords:  bcdox hexdump filelist rmdir flushleft busybox nl HAZy
27209 @c  LocalWords:  ABCDEFGHIJKLMNOPQRSTUVWXYZ Fantazy FAntAZy adc unix xb
27210 @c  LocalWords:  SUBMAKEFLAGS ehBc ehB hBc hvB dmake hostname nlinit xf
27211 @c  LocalWords:  DCOMMENT bart pathnames ifhtml randx
27212 @c  LocalWords:  sumc hic ic fwrapv ftrapv SIGFPE memset fmudflap ctime
27213 @c  LocalWords:  asctime lvalues lvalue Multithreaded decstation gdb na
27214 @c  LocalWords:  enableval lesskey FHS superset waitpid libfoo cposix
27215 @c  LocalWords:  mem RESTARTABLE bzero DejaGNU EUNIT subfile optarg ive
27216 @c  LocalWords:  nolog expout experr erlflags EUnit testme eunit myprog
27217 @c  LocalWords:  configmake vx bashdb tvtwm questers UUCP McGrath
27218 @c  LocalWords:  ispell
27219 @c Local Variables:
27220 @c fill-column: 72
27221 @c ispell-local-dictionary: "american"
27222 @c indent-tabs-mode: nil
27223 @c whitespace-check-buffer-indent: nil
27224 @c End: