doc: Patterns in m4_pattern_forbid cause error, not warning
[autoconf.git] / doc / autoconf.texi
blob01a8313629990e0c07f7e9c2c1777dd18b0de073
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 @setchapternewpage odd
9 @finalout
11 @c @ovar(ARG)
12 @c ----------
13 @c The ARG is an optional argument.  To be used for macro arguments in
14 @c their documentation (@defmac).
15 @macro ovar{varname}
16 @r{[}@var{\varname\}@r{]}
17 @end macro
19 @c @dvar(ARG, DEFAULT)
20 @c -------------------
21 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
22 @c for macro arguments in their documentation (@defmac).
23 @macro dvar{varname, default}
24 @r{[}@var{\varname\} = @samp{\default\}@r{]}
25 @end macro
27 @c @dvarv(ARG, DEFAULT-VAR)
28 @c ------------------------
29 @c Same as @dvar{ARG, DEFAULT-VAR}, but with @var instead of @samp
30 @c around DEFAULT-VAR.
31 @macro dvarv{varname, default}
32 @r{[}@var{\varname\} = @var{\default\}@r{]}@c
33 @end macro
35 @c Handling the indexes with Texinfo yields several different problems.
37 @c Because we want to drop out the AC_ part of the macro names in the
38 @c printed manual, but not in the other outputs, we need a layer above
39 @c the usual @acindex{} etc.  That's why we first define indexes such as
40 @c acx meant to become the macro @acindex.  First of all, using 'ac_'
41 @c does not work with makeinfo, and using 'ac1' doesn't work with TeX.
42 @c So use something more regular 'acx'.  Then you finish with a printed
43 @c index saying 'index is not existent'.  Of course: you ought to use
44 @c two letters :(  So you use capitals.
46 @c Second, when defining a macro in the TeX world, following spaces are
47 @c eaten.  But then, since we embed @acxindex commands that use the end
48 @c of line as an end marker, the whole things wrecks itself.  So make
49 @c sure you do *force* an additional end of line, add a '@c'.
51 @c Finally, you might want to get rid of TeX expansion, using --expand
52 @c with texi2dvi.  But then you wake up an old problem: we use macros
53 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
55 @c Define an environment variable index, for variables users may set
56 @c in their environment or on the configure command line.
57 @defcodeindex ev
58 @c Define an output variable index, for commonly AC_SUBST'ed variables.
59 @defcodeindex ov
60 @c Define a cache variable index, for variables matching *_cv_*.
61 @defcodeindex CA
62 @c Other shell variables not fitting the above categories should be
63 @c listed in the predefined vrindex, which we merge in the concept index.
64 @syncodeindex vr cp
65 @c Define a CPP preprocessor macro index, for #define'd strings.
66 @defcodeindex cv
67 @c Define an Autoconf macro index that @defmac doesn't write to.
68 @defcodeindex AC
69 @c Define an Autotest macro index that @defmac doesn't write to.
70 @defcodeindex AT
71 @c Define an M4sugar macro index that @defmac doesn't write to.
72 @defcodeindex MS
73 @c Define an index for *foreign* programs: 'mv' etc.  Used for the
74 @c portability sections and so on.
75 @defindex pr
77 @c shortindexflag
78 @c --------------
79 @c Shall we factor AC_ out of the Autoconf macro index etc.?
80 @iftex
81 @set shortindexflag
82 @end iftex
84 @c @acindex{MACRO}
85 @c ---------------
86 @c Registering an AC_\MACRO\.
87 @ifset shortindexflag
88 @macro acindex{macro}
89 @ACindex \macro\
91 @end macro
92 @end ifset
93 @ifclear shortindexflag
94 @macro acindex{macro}
95 @ACindex AC_\macro\
96 @end macro
97 @end ifclear
99 @c @ahindex{MACRO}
100 @c ---------------
101 @c Registering an AH_\MACRO\.
102 @macro ahindex{macro}
103 @ACindex AH_\macro\
105 @end macro
107 @c @asindex{MACRO}
108 @c ---------------
109 @c Registering an AS_\MACRO\.
110 @ifset shortindexflag
111 @macro asindex{macro}
112 @MSindex \macro\
114 @end macro
115 @end ifset
116 @ifclear shortindexflag
117 @macro asindex{macro}
118 @MSindex AS_\macro\
119 @end macro
120 @end ifclear
122 @c @atindex{MACRO}
123 @c ---------------
124 @c Registering an AT_\MACRO\.
125 @ifset shortindexflag
126 @macro atindex{macro}
127 @ATindex \macro\
129 @end macro
130 @end ifset
131 @ifclear shortindexflag
132 @macro atindex{macro}
133 @ATindex AT_\macro\
134 @end macro
135 @end ifclear
137 @c @auindex{MACRO}
138 @c ---------------
139 @c Registering an AU_\MACRO\.
140 @macro auindex{macro}
141 @ACindex AU_\macro\
143 @end macro
145 @c @hdrindex{MACRO}
146 @c ----------------
147 @c Indexing a header.
148 @macro hdrindex{macro}
149 @prindex @file{\macro\}
151 @end macro
153 @c @msindex{MACRO}
154 @c ---------------
155 @c Registering an m4_\MACRO\.
156 @ifset shortindexflag
157 @macro msindex{macro}
158 @MSindex \macro\
160 @end macro
161 @end ifset
162 @ifclear shortindexflag
163 @macro msindex{macro}
164 @MSindex m4_\macro\
165 @end macro
166 @end ifclear
169 @c @caindex{VARIABLE}
170 @c ------------------
171 @c Registering an ac_cv_\VARIABLE\ cache variable.
172 @ifset shortindexflag
173 @macro caindex{macro}
174 @CAindex \macro\
175 @end macro
176 @end ifset
177 @ifclear shortindexflag
178 @macro caindex{macro}
179 @CAindex ac_cv_\macro\
180 @end macro
181 @end ifclear
183 @c Define an index for functions: `alloca' etc.  Used for the
184 @c portability sections and so on.  We can't use `fn' (aka `fnindex),
185 @c since `@defmac' goes into it => we'd get all the macros too.
187 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
189 @c   ! No room for a new @write .
190 @c   l.112 @defcodeindex fu
192 @c   so don't define yet another one :(  Just put some tags before each
193 @c   @prindex which is actually a @funindex.
195 @c   @defcodeindex fu
198 @c   @c Put the programs and functions into their own index.
199 @c   @syncodeindex fu pr
201 @comment %**end of header
202 @comment ========================================================
204 @copying
206 This manual (@value{UPDATED}) is for GNU Autoconf
207 (version @value{VERSION}),
208 a package for creating scripts to configure source code packages using
209 templates and an M4 macro package.
211 Copyright @copyright{} 1992--1996, 1998--2016 Free Software Foundation,
212 Inc.
214 @quotation
215 Permission is granted to copy, distribute and/or modify this document
216 under the terms of the GNU Free Documentation License,
217 Version 1.3 or any later version published by the Free Software
218 Foundation; with no Invariant Sections, no Front-Cover texts, and
219 no Back-Cover Texts.  A copy of the license is included in the section
220 entitled ``GNU Free Documentation License.''
221 @end quotation
222 @end copying
226 @dircategory Software development
227 @direntry
228 * Autoconf: (autoconf).         Create source code configuration scripts.
229 @end direntry
231 @dircategory Individual utilities
232 @direntry
233 * autoscan: (autoconf)autoscan Invocation.
234                                 Semi-automatic @file{configure.ac} writing
235 * ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
236 * autoconf-invocation: (autoconf)autoconf Invocation.
237                                 How to create configuration scripts
238 * autoreconf: (autoconf)autoreconf Invocation.
239                                 Remaking multiple @command{configure} scripts
240 * autoheader: (autoconf)autoheader Invocation.
241                                 How to create configuration templates
242 * autom4te: (autoconf)autom4te Invocation.
243                                 The Autoconf executables backbone
244 * configure: (autoconf)configure Invocation.    Configuring a package.
245 * autoupdate: (autoconf)autoupdate Invocation.
246                                 Automatic update of @file{configure.ac}
247 * config.status: (autoconf)config.status Invocation. Recreating configurations.
248 * testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
249 @end direntry
251 @titlepage
252 @title Autoconf
253 @subtitle Creating Automatic Configuration Scripts
254 @subtitle for version @value{VERSION}, @value{UPDATED}
255 @author David MacKenzie
256 @author Ben Elliston
257 @author Akim Demaille
258 @page
259 @vskip 0pt plus 1filll
260 @insertcopying
261 @end titlepage
263 @contents
266 @ifnottex
267 @node Top
268 @top Autoconf
269 @insertcopying
270 @end ifnottex
272 @c The master menu, created with texinfo-master-menu, goes here.
274 @menu
275 * Introduction::                Autoconf's purpose, strengths, and weaknesses
276 * The GNU Build System::        A set of tools for portable software packages
277 * Making configure Scripts::    How to organize and produce Autoconf scripts
278 * Setup::                       Initialization and output
279 * Existing Tests::              Macros that check for particular features
280 * Writing Tests::               How to write new feature checks
281 * Results::                     What to do with results from feature checks
282 * Programming in M4::           Layers on top of which Autoconf is written
283 * Programming in M4sh::         Shell portability layer
284 * Writing Autoconf Macros::     Adding new macros to Autoconf
285 * Portable Shell::              Shell script portability pitfalls
286 * Portable Make::               Makefile portability pitfalls
287 * Portable C and C++::          C and C++ portability pitfalls
288 * Manual Configuration::        Selecting features that can't be guessed
289 * Site Configuration::          Local defaults for @command{configure}
290 * Running configure Scripts::   How to use the Autoconf output
291 * config.status Invocation::    Recreating a configuration
292 * Obsolete Constructs::         Kept for backward compatibility
293 * Using Autotest::              Creating portable test suites
294 * FAQ::                         Frequent Autoconf Questions, with answers
295 * History::                     History of Autoconf
296 * GNU Free Documentation License::  License for copying this manual
297 * Indices::                     Indices of symbols, concepts, etc.
299 @detailmenu
300  --- The Detailed Node Listing ---
302 The GNU Build System
304 * Automake::                    Escaping makefile hell
305 * Gnulib::                      The GNU portability library
306 * Libtool::                     Building libraries portably
307 * Pointers::                    More info on the GNU build system
309 Making @command{configure} Scripts
311 * Writing Autoconf Input::      What to put in an Autoconf input file
312 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
313 * ifnames Invocation::          Listing the conditionals in source code
314 * autoconf Invocation::         How to create configuration scripts
315 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
317 Writing @file{configure.ac}
319 * Shell Script Compiler::       Autoconf as solution of a problem
320 * Autoconf Language::           Programming in Autoconf
321 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
323 Initialization and Output Files
325 * Initializing configure::      Option processing etc.
326 * Versioning::                  Dealing with Autoconf versions
327 * Notices::                     Copyright, version numbers in @command{configure}
328 * Input::                       Where Autoconf should find files
329 * Output::                      Outputting results from the configuration
330 * Configuration Actions::       Preparing the output based on results
331 * Configuration Files::         Creating output files
332 * Makefile Substitutions::      Using output variables in makefiles
333 * Configuration Headers::       Creating a configuration header file
334 * Configuration Commands::      Running arbitrary instantiation commands
335 * Configuration Links::         Links depending on the configuration
336 * Subdirectories::              Configuring independent packages together
337 * Default Prefix::              Changing the default installation prefix
339 Substitutions in Makefiles
341 * Preset Output Variables::     Output variables that are always set
342 * Installation Directory Variables::  Other preset output variables
343 * Changed Directory Variables::  Warnings about @file{datarootdir}
344 * Build Directories::           Supporting multiple concurrent compiles
345 * Automatic Remaking::          Makefile rules for configuring
347 Configuration Header Files
349 * Header Templates::            Input for the configuration headers
350 * autoheader Invocation::       How to create configuration templates
351 * Autoheader Macros::           How to specify CPP templates
353 Existing Tests
355 * Common Behavior::             Macros' standard schemes
356 * Alternative Programs::        Selecting between alternative programs
357 * Files::                       Checking for the existence of files
358 * Libraries::                   Library archives that might be missing
359 * Library Functions::           C library functions that might be missing
360 * Header Files::                Header files that might be missing
361 * Declarations::                Declarations that may be missing
362 * Structures::                  Structures or members that might be missing
363 * Types::                       Types that might be missing
364 * Compilers and Preprocessors::  Checking for compiling programs
365 * System Services::             Operating system services
366 * C and Posix Variants::        Kludges for C and Posix variants
367 * Erlang Libraries::            Checking for the existence of Erlang libraries
369 Common Behavior
371 * Standard Symbols::            Symbols defined by the macros
372 * Default Includes::            Includes used by the generic macros
374 Alternative Programs
376 * Particular Programs::         Special handling to find certain programs
377 * Generic Programs::            How to find other programs
379 Library Functions
381 * Function Portability::        Pitfalls with usual functions
382 * Particular Functions::        Special handling to find certain functions
383 * Generic Functions::           How to find other functions
385 Header Files
387 * Header Portability::          Collected knowledge on common headers
388 * Particular Headers::          Special handling to find certain headers
389 * Generic Headers::             How to find other headers
391 Declarations
393 * Particular Declarations::     Macros to check for certain declarations
394 * Generic Declarations::        How to find other declarations
396 Structures
398 * Particular Structures::       Macros to check for certain structure members
399 * Generic Structures::          How to find other structure members
401 Types
403 * Particular Types::            Special handling to find certain types
404 * Generic Types::               How to find other types
406 Compilers and Preprocessors
408 * Specific Compiler Characteristics::  Some portability issues
409 * Generic Compiler Characteristics::  Language independent tests and features
410 * C Compiler::                  Checking its characteristics
411 * C++ Compiler::                Likewise
412 * Objective C Compiler::        Likewise
413 * Objective C++ Compiler::      Likewise
414 * Erlang Compiler and Interpreter::  Likewise
415 * Fortran Compiler::            Likewise
416 * Go Compiler::                 Likewise
418 Writing Tests
420 * Language Choice::             Selecting which language to use for testing
421 * Writing Test Programs::       Forging source files for compilers
422 * Running the Preprocessor::    Detecting preprocessor symbols
423 * Running the Compiler::        Detecting language or header features
424 * Running the Linker::          Detecting library features
425 * Runtime::                     Testing for runtime features
426 * Systemology::                 A zoology of operating systems
427 * Multiple Cases::              Tests for several possible values
429 Writing Test Programs
431 * Guidelines::                  General rules for writing test programs
432 * Test Functions::              Avoiding pitfalls in test programs
433 * Generating Sources::          Source program boilerplate
435 Results of Tests
437 * Defining Symbols::            Defining C preprocessor symbols
438 * Setting Output Variables::    Replacing variables in output files
439 * Special Chars in Variables::  Characters to beware of in variables
440 * Caching Results::             Speeding up subsequent @command{configure} runs
441 * Printing Messages::           Notifying @command{configure} users
443 Caching Results
445 * Cache Variable Names::        Shell variables used in caches
446 * Cache Files::                 Files @command{configure} uses for caching
447 * Cache Checkpointing::         Loading and saving the cache file
449 Programming in M4
451 * M4 Quotation::                Protecting macros from unwanted expansion
452 * Using autom4te::              The Autoconf executables backbone
453 * Programming in M4sugar::      Convenient pure M4 macros
454 * Debugging via autom4te::      Figuring out what M4 was doing
456 M4 Quotation
458 * Active Characters::           Characters that change the behavior of M4
459 * One Macro Call::              Quotation and one macro call
460 * Quoting and Parameters::      M4 vs. shell parameters
461 * Quotation and Nested Macros::  Macros calling macros
462 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
463 * Quadrigraphs::                Another way to escape special characters
464 * Balancing Parentheses::       Dealing with unbalanced parentheses
465 * Quotation Rule Of Thumb::     One parenthesis, one quote
467 Using @command{autom4te}
469 * autom4te Invocation::         A GNU M4 wrapper
470 * Customizing autom4te::        Customizing the Autoconf package
472 Programming in M4sugar
474 * Redefined M4 Macros::         M4 builtins changed in M4sugar
475 * Diagnostic Macros::           Diagnostic messages from M4sugar
476 * Diversion support::           Diversions in M4sugar
477 * Conditional constructs::      Conditions in M4
478 * Looping constructs::          Iteration in M4
479 * Evaluation Macros::           More quotation and evaluation control
480 * Text processing Macros::      String manipulation in M4
481 * Number processing Macros::    Arithmetic computation in M4
482 * Set manipulation Macros::     Set manipulation in M4
483 * Forbidden Patterns::          Catching unexpanded macros
485 Programming in M4sh
487 * Common Shell Constructs::     Portability layer for common shell constructs
488 * Polymorphic Variables::       Support for indirect variable names
489 * Initialization Macros::       Macros to establish a sane shell environment
490 * File Descriptor Macros::      File descriptor macros for input and output
492 Writing Autoconf Macros
494 * Macro Definitions::           Basic format of an Autoconf macro
495 * Macro Names::                 What to call your new macros
496 * Reporting Messages::          Notifying @command{autoconf} users
497 * Dependencies Between Macros::  What to do when macros depend on other macros
498 * Obsoleting Macros::           Warning about old ways of doing things
499 * Coding Style::                Writing Autoconf macros @`a la Autoconf
501 Dependencies Between Macros
503 * Prerequisite Macros::         Ensuring required information
504 * Suggested Ordering::          Warning about possible ordering problems
505 * One-Shot Macros::             Ensuring a macro is called only once
507 Portable Shell Programming
509 * Shellology::                  A zoology of shells
510 * Invoking the Shell::          Invoking the shell as a command
511 * Here-Documents::              Quirks and tricks
512 * File Descriptors::            FDs and redirections
513 * Signal Handling::             Shells, signals, and headaches
514 * File System Conventions::     File names
515 * Shell Pattern Matching::      Pattern matching
516 * Shell Substitutions::         Variable and command expansions
517 * Assignments::                 Varying side effects of assignments
518 * Parentheses::                 Parentheses in shell scripts
519 * Slashes::                     Slashes in shell scripts
520 * Special Shell Variables::     Variables you should not change
521 * Shell Functions::             What to look out for if you use them
522 * Limitations of Builtins::     Portable use of not so portable /bin/sh
523 * Limitations of Usual Tools::  Portable use of portable tools
525 Portable Make Programming
527 * $< in Ordinary Make Rules::   $< in ordinary rules
528 * Failure in Make Rules::       Failing portably in rules
529 * Special Chars in Names::      Special Characters in Macro Names
530 * Backslash-Newline-Empty::     Empty lines after backslash-newline
531 * Backslash-Newline Comments::  Spanning comments across line boundaries
532 * Long Lines in Makefiles::     Line length limitations
533 * Macros and Submakes::         @code{make macro=value} and submakes
534 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
535 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
536 * Parallel Make::               Parallel @command{make} quirks
537 * Comments in Make Rules::      Other problems with Make comments
538 * Newlines in Make Rules::      Using literal newlines in rules
539 * Comments in Make Macros::     Other problems with Make comments in macros
540 * Trailing whitespace in Make Macros::  Macro substitution problems
541 * Command-line Macros and whitespace::  Whitespace trimming of values
542 * obj/ and Make::               Don't name a subdirectory @file{obj}
543 * make -k Status::              Exit status of @samp{make -k}
544 * VPATH and Make::              @code{VPATH} woes
545 * Single Suffix Rules::         Single suffix rules and separated dependencies
546 * Timestamps and Make::         Subsecond timestamp resolution
548 @code{VPATH} and Make
550 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
551 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
552 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
553 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
554 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
555 * Make Target Lookup::          More details about @code{VPATH} lookup
557 Portable C and C++ Programming
559 * Varieties of Unportability::  How to make your programs unportable
560 * Integer Overflow::            When integers get too large
561 * Preprocessor Arithmetic::     @code{#if} expression problems
562 * Null Pointers::               Properties of null pointers
563 * Buffer Overruns::             Subscript errors and the like
564 * Volatile Objects::            @code{volatile} and signals
565 * Floating Point Portability::  Portable floating-point arithmetic
566 * Exiting Portably::            Exiting and the exit status
568 Integer Overflow
570 * Integer Overflow Basics::     Why integer overflow is a problem
571 * Signed Overflow Examples::    Examples of code assuming wraparound
572 * Optimization and Wraparound::  Optimizations that break uses of wraparound
573 * Signed Overflow Advice::      Practical advice for signed overflow issues
574 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
576 Manual Configuration
578 * Specifying Target Triplets::  Specifying target triplets
579 * Canonicalizing::              Getting the canonical system type
580 * Using System Type::           What to do with the system type
582 Site Configuration
584 * Help Formatting::             Customizing @samp{configure --help}
585 * External Software::           Working with other optional software
586 * Package Options::             Selecting optional features
587 * Pretty Help Strings::         Formatting help string
588 * Option Checking::             Controlling checking of @command{configure} options
589 * Site Details::                Configuring site details
590 * Transforming Names::          Changing program names when installing
591 * Site Defaults::               Giving @command{configure} local defaults
593 Transforming Program Names When Installing
595 * Transformation Options::      @command{configure} options to transform names
596 * Transformation Examples::     Sample uses of transforming names
597 * Transformation Rules::        Makefile uses of transforming names
599 Running @command{configure} Scripts
601 * Basic Installation::          Instructions for typical cases
602 * Compilers and Options::       Selecting compilers and optimization
603 * Multiple Architectures::      Compiling for multiple architectures at once
604 * Installation Names::          Installing in different directories
605 * Optional Features::           Selecting optional features
606 * Particular Systems::          Particular systems
607 * System Type::                 Specifying the system type
608 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
609 * Defining Variables::          Specifying the compiler etc.
610 * configure Invocation::        Changing how @command{configure} runs
612 Obsolete Constructs
614 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
615 * acconfig Header::             Additional entries in @file{config.h.in}
616 * autoupdate Invocation::       Automatic update of @file{configure.ac}
617 * Obsolete Macros::             Backward compatibility macros
618 * Autoconf 1::                  Tips for upgrading your files
619 * Autoconf 2.13::               Some fresher tips
621 Upgrading From Version 1
623 * Changed File Names::          Files you might rename
624 * Changed Makefiles::           New things to put in @file{Makefile.in}
625 * Changed Macros::              Macro calls you might replace
626 * Changed Results::             Changes in how to check test results
627 * Changed Macro Writing::       Better ways to write your own macros
629 Upgrading From Version 2.13
631 * Changed Quotation::           Broken code which used to work
632 * New Macros::                  Interaction with foreign macros
633 * Hosts and Cross-Compilation::  Bugward compatibility kludges
634 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
635 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
637 Generating Test Suites with Autotest
639 * Using an Autotest Test Suite::  Autotest and the user
640 * Writing Testsuites::          Autotest macros
641 * testsuite Invocation::        Running @command{testsuite} scripts
642 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
644 Using an Autotest Test Suite
646 * testsuite Scripts::           The concepts of Autotest
647 * Autotest Logs::               Their contents
649 Frequent Autoconf Questions, with answers
651 * Distributing::                Distributing @command{configure} scripts
652 * Why GNU M4::                  Why not use the standard M4?
653 * Bootstrapping::               Autoconf and GNU M4 require each other?
654 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
655 * Defining Directories::        Passing @code{datadir} to program
656 * Autom4te Cache::              What is it?  Can I remove it?
657 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
658 * Expanded Before Required::    Expanded Before Required
659 * Debugging::                   Debugging @command{configure} scripts
661 History of Autoconf
663 * Genesis::                     Prehistory and naming of @command{configure}
664 * Exodus::                      The plagues of M4 and Perl
665 * Leviticus::                   The priestly code of portability arrives
666 * Numbers::                     Growth and contributors
667 * Deuteronomy::                 Approaching the promises of easy configuration
669 Indices
671 * Environment Variable Index::  Index of environment variables used
672 * Output Variable Index::       Index of variables set in output files
673 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
674 * Cache Variable Index::        Index of documented cache variables
675 * Autoconf Macro Index::        Index of Autoconf macros
676 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
677 * Autotest Macro Index::        Index of Autotest macros
678 * Program & Function Index::    Index of those with portability problems
679 * Concept Index::               General index
681 @end detailmenu
682 @end menu
684 @c ============================================================= Introduction.
686 @node Introduction
687 @chapter Introduction
688 @cindex Introduction
690 @flushright
691 A physicist, an engineer, and a computer scientist were discussing the
692 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
693 early in the Creation, God made Light; and you know, Maxwell's
694 equations, the dual nature of electromagnetic waves, the relativistic
695 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
696 before making Light, God split the Chaos into Land and Water; it takes
697 a hell of an engineer to handle that big amount of mud, and orderly
698 separation of solids from liquids@enddots{}'' The computer scientist
699 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
701 ---Anonymous
702 @end flushright
703 @c (via Franc,ois Pinard)
705 Autoconf is a tool for producing shell scripts that automatically
706 configure software source code packages to adapt to many kinds of
707 Posix-like systems.  The configuration scripts produced by Autoconf
708 are independent of Autoconf when they are run, so their users do not
709 need to have Autoconf.
711 The configuration scripts produced by Autoconf require no manual user
712 intervention when run; they do not normally even need an argument
713 specifying the system type.  Instead, they individually test for the
714 presence of each feature that the software package they are for might need.
715 (Before each check, they print a one-line message stating what they are
716 checking for, so the user doesn't get too bored while waiting for the
717 script to finish.)  As a result, they deal well with systems that are
718 hybrids or customized from the more common Posix variants.  There is
719 no need to maintain files that list the features supported by each
720 release of each variant of Posix.
722 For each software package that Autoconf is used with, it creates a
723 configuration script from a template file that lists the system features
724 that the package needs or can use.  After the shell code to recognize
725 and respond to a system feature has been written, Autoconf allows it to
726 be shared by many software packages that can use (or need) that feature.
727 If it later turns out that the shell code needs adjustment for some
728 reason, it needs to be changed in only one place; all of the
729 configuration scripts can be regenerated automatically to take advantage
730 of the updated code.
732 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
733 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
734 Those who do not understand Autoconf are condemned to reinvent it, poorly.
735 The primary goal of Autoconf is making the @emph{user's} life easier;
736 making the @emph{maintainer's} life easier is only a secondary goal.
737 Put another way, the primary goal is not to make the generation of
738 @file{configure} automatic for package maintainers (although patches
739 along that front are welcome, since package maintainers form the user
740 base of Autoconf); rather, the goal is to make @file{configure}
741 painless, portable, and predictable for the end user of each
742 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
743 successful at its goal---most complaints to the Autoconf list are
744 about difficulties in writing Autoconf input, and not in the behavior of
745 the resulting @file{configure}.  Even packages that don't use Autoconf
746 will generally provide a @file{configure} script, and the most common
747 complaint about these alternative home-grown scripts is that they fail
748 to meet one or more of the GNU Coding Standards (@pxref{Configuration, , ,
749 standards, The GNU Coding Standards}) that users
750 have come to expect from Autoconf-generated @file{configure} scripts.
752 The Metaconfig package is similar in purpose to Autoconf, but the
753 scripts it produces require manual user intervention, which is quite
754 inconvenient when configuring large source trees.  Unlike Metaconfig
755 scripts, Autoconf scripts can support cross-compiling, if some care is
756 taken in writing them.
758 Autoconf does not solve all problems related to making portable
759 software packages---for a more complete solution, it should be used in
760 concert with other GNU build tools like Automake and
761 Libtool.  These other tools take on jobs like the creation of a
762 portable, recursive makefile with all of the standard targets,
763 linking of shared libraries, and so on.  @xref{The GNU Build System},
764 for more information.
766 Autoconf imposes some restrictions on the names of macros used with
767 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
769 Autoconf requires GNU M4 version 1.4.6 or later in order to
770 generate the scripts.  It uses features that some versions of M4,
771 including GNU M4 1.3, do not have.  Autoconf works better
772 with GNU M4 version 1.4.14 or later, though this is not
773 required.
775 @xref{Autoconf 1}, for information about upgrading from version 1.
776 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
777 for answers to some common questions about Autoconf.
779 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
780 Autoconf web page} for up-to-date information, details on the mailing
781 lists, pointers to a list of known bugs, etc.
783 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
784 list}.  Past suggestions are
785 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
787 Mail bug reports to @email{bug-autoconf@@gnu.org, the
788 Autoconf Bugs mailing list}.  Past bug reports are
789 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
791 If possible, first check that your bug is
792 not already solved in current development versions, and that it has not
793 been reported yet.  Be sure to include all the needed information and a
794 short @file{configure.ac} that demonstrates the problem.
796 Autoconf's development tree is accessible via @command{git}; see the
797 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
798 Summary} for details, or view
799 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
800 repository}.  Anonymous CVS access is also available, see
801 @file{README} for more details.  Patches relative to the
802 current @command{git} version can be sent for review to the
803 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
804 discussion on prior patches
805 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
806 archived}; and all commits are posted in the read-only
807 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
808 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
809 archived}.
811 Because of its mission, the Autoconf package itself
812 includes only a set of often-used
813 macros that have already demonstrated their usefulness.  Nevertheless,
814 if you wish to share your macros, or find existing ones, see the
815 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
816 Archive}, which is kindly run by @email{simons@@cryp.to,
817 Peter Simons}.
820 @c ================================================= The GNU Build System
822 @node The GNU Build System
823 @chapter The GNU Build System
824 @cindex GNU build system
826 Autoconf solves an important problem---reliable discovery of
827 system-specific build and runtime information---but this is only one
828 piece of the puzzle for the development of portable software.  To this
829 end, the GNU project has developed a suite of integrated
830 utilities to finish the job Autoconf started: the GNU build
831 system, whose most important components are Autoconf, Automake, and
832 Libtool.  In this chapter, we introduce you to those tools, point you
833 to sources of more information, and try to convince you to use the
834 entire GNU build system for your software.
836 @menu
837 * Automake::                    Escaping makefile hell
838 * Gnulib::                      The GNU portability library
839 * Libtool::                     Building libraries portably
840 * Pointers::                    More info on the GNU build system
841 @end menu
843 @node Automake
844 @section Automake
846 The ubiquity of @command{make} means that a makefile is almost the
847 only viable way to distribute automatic build rules for software, but
848 one quickly runs into its numerous limitations.  Its lack of
849 support for automatic dependency tracking, recursive builds in
850 subdirectories, reliable timestamps (e.g., for network file systems), and
851 so on, mean that developers must painfully (and often incorrectly)
852 reinvent the wheel for each project.  Portability is non-trivial, thanks
853 to the quirks of @command{make} on many systems.  On top of all this is the
854 manual labor required to implement the many standard targets that users
855 have come to expect (@code{make install}, @code{make distclean},
856 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
857 you also have to insert repetitive code in your @file{Makefile.in} to
858 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
859 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
860 @cindex Automake
862 Automake allows you to specify your build needs in a @file{Makefile.am}
863 file with a vastly simpler and more powerful syntax than that of a plain
864 makefile, and then generates a portable @file{Makefile.in} for
865 use with Autoconf.  For example, the @file{Makefile.am} to build and
866 install a simple ``Hello world'' program might look like:
868 @example
869 bin_PROGRAMS = hello
870 hello_SOURCES = hello.c
871 @end example
873 @noindent
874 The resulting @file{Makefile.in} (~400 lines) automatically supports all
875 the standard targets, the substitutions provided by Autoconf, automatic
876 dependency tracking, @code{VPATH} building, and so on.  @command{make}
877 builds the @code{hello} program, and @code{make install} installs it
878 in @file{/usr/local/bin} (or whatever prefix was given to
879 @command{configure}, if not @file{/usr/local}).
881 The benefits of Automake increase for larger packages (especially ones
882 with subdirectories), but even for small programs the added convenience
883 and portability can be substantial.  And that's not all@enddots{}
885 @node Gnulib
886 @section Gnulib
888 GNU software has a well-deserved reputation for running on
889 many different types of systems.  While our primary goal is to write
890 software for the GNU system, many users and developers have
891 been introduced to us through the systems that they were already using.
893 @cindex Gnulib
894 Gnulib is a central location for common GNU code, intended to
895 be shared among free software packages.  Its components are typically
896 shared at the source level, rather than being a library that gets built,
897 installed, and linked against.  The idea is to copy files from Gnulib
898 into your own source tree.  There is no distribution tarball; developers
899 should just grab source modules from the repository.  The source files
900 are available online, under various licenses, mostly GNU
901 GPL or GNU LGPL.
903 Gnulib modules typically contain C source code along with Autoconf
904 macros used to configure the source code.  For example, the Gnulib
905 @code{stdalign} module implements a @file{stdalign.h} header that nearly
906 conforms to C11, even on old-fashioned hosts that lack @file{stdalign.h}.
907 This module contains a source file for the replacement header, along
908 with an Autoconf macro that arranges to use the replacement header on
909 old-fashioned systems.
911 @node Libtool
912 @section Libtool
914 Often, one wants to build not only programs, but libraries, so that
915 other programs can benefit from the fruits of your labor.  Ideally, one
916 would like to produce @emph{shared} (dynamically linked) libraries,
917 which can be used by multiple programs without duplication on disk or in
918 memory and can be updated independently of the linked programs.
919 Producing shared libraries portably, however, is the stuff of
920 nightmares---each system has its own incompatible tools, compiler flags,
921 and magic incantations.  Fortunately, GNU provides a solution:
922 @dfn{Libtool}.
923 @cindex Libtool
925 Libtool handles all the requirements of building shared libraries for
926 you, and at this time seems to be the @emph{only} way to do so with any
927 portability.  It also handles many other headaches, such as: the
928 interaction of Make rules with the variable suffixes of
929 shared libraries, linking reliably with shared libraries before they are
930 installed by the superuser, and supplying a consistent versioning system
931 (so that different versions of a library can be installed or upgraded
932 without breaking binary compatibility).  Although Libtool, like
933 Autoconf, can be used without Automake, it is most simply utilized in
934 conjunction with Automake---there, Libtool is used automatically
935 whenever shared libraries are needed, and you need not know its syntax.
937 @node Pointers
938 @section Pointers
940 Developers who are used to the simplicity of @command{make} for small
941 projects on a single system might be daunted at the prospect of
942 learning to use Automake and Autoconf.  As your software is
943 distributed to more and more users, however, you otherwise
944 quickly find yourself putting lots of effort into reinventing the
945 services that the GNU build tools provide, and making the
946 same mistakes that they once made and overcame.  (Besides, since
947 you're already learning Autoconf, Automake is a piece of cake.)
949 There are a number of places that you can go to for more information on
950 the GNU build tools.
952 @itemize @minus
954 @item Web
956 The project home pages for
957 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
958 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
959 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
960 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
962 @item Automake Manual
964 @xref{Top, , Automake, automake, GNU Automake}, for more
965 information on Automake.
967 @item Books
969 The book @cite{GNU Autoconf, Automake and
970 Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
971 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
972 New Riders), 2000, ISBN 1578701902.} describes the complete GNU
973 build environment.  You can also find
974 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
976 @end itemize
978 @c ================================================= Making configure Scripts.
980 @node Making configure Scripts
981 @chapter Making @command{configure} Scripts
982 @cindex @file{aclocal.m4}
983 @cindex @command{configure}
985 The configuration scripts that Autoconf produces are by convention
986 called @command{configure}.  When run, @command{configure} creates several
987 files, replacing configuration parameters in them with appropriate
988 values.  The files that @command{configure} creates are:
990 @itemize @minus
991 @item
992 one or more @file{Makefile} files, usually one in each subdirectory of the
993 package (@pxref{Makefile Substitutions});
995 @item
996 optionally, a C header file, the name of which is configurable,
997 containing @code{#define} directives (@pxref{Configuration Headers});
999 @item
1000 a shell script called @file{config.status} that, when run, recreates
1001 the files listed above (@pxref{config.status Invocation});
1003 @item
1004 an optional shell script normally called @file{config.cache}
1005 (created when using @samp{configure --config-cache}) that
1006 saves the results of running many of the tests (@pxref{Cache Files});
1008 @item
1009 a file called @file{config.log} containing any messages produced by
1010 compilers, to help debugging if @command{configure} makes a mistake.
1011 @end itemize
1013 @cindex @file{configure.ac}
1014 To create a @command{configure} script with Autoconf, you need
1015 to write an Autoconf input file @file{configure.ac} and run
1016 @command{autoconf} on it.  If you write your own feature tests to
1017 supplement those that come with Autoconf, you might also write files
1018 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
1019 file to contain @code{#define} directives, you might also run
1020 @command{autoheader}, and you can distribute the generated file
1021 @file{config.h.in} with the package.
1023 Here is a diagram showing how the files that can be used in
1024 configuration are produced.  Programs that are executed are suffixed by
1025 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
1026 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1027 macro files (by reading @file{autoconf.m4}).
1029 @noindent
1030 Files used in preparing a software package for distribution, when using
1031 just Autoconf:
1032 @example
1033 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1035 @group
1036 configure.ac --.
1037                |   .------> autoconf* -----> configure
1038 [aclocal.m4] --+---+
1039                |   `-----> [autoheader*] --> [config.h.in]
1040 [acsite.m4] ---'
1041 @end group
1043 Makefile.in
1044 @end example
1046 @noindent
1047 Additionally, if you use Automake, the following additional productions
1048 come into play:
1050 @example
1051 @group
1052 [acinclude.m4] --.
1053                  |
1054 [local macros] --+--> aclocal* --> aclocal.m4
1055                  |
1056 configure.ac ----'
1057 @end group
1059 @group
1060 configure.ac --.
1061                +--> automake* --> Makefile.in
1062 Makefile.am ---'
1063 @end group
1064 @end example
1066 @noindent
1067 Files used in configuring a software package:
1068 @example
1069 @group
1070                        .-------------> [config.cache]
1071 configure* ------------+-------------> config.log
1072                        |
1073 [config.h.in] -.       v            .-> [config.h] -.
1074                +--> config.status* -+               +--> make*
1075 Makefile.in ---'                    `-> Makefile ---'
1076 @end group
1077 @end example
1079 @menu
1080 * Writing Autoconf Input::      What to put in an Autoconf input file
1081 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1082 * ifnames Invocation::          Listing the conditionals in source code
1083 * autoconf Invocation::         How to create configuration scripts
1084 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1085 @end menu
1087 @node Writing Autoconf Input
1088 @section Writing @file{configure.ac}
1090 To produce a @command{configure} script for a software package, create a
1091 file called @file{configure.ac} that contains invocations of the
1092 Autoconf macros that test the system features your package needs or can
1093 use.  Autoconf macros already exist to check for many features; see
1094 @ref{Existing Tests}, for their descriptions.  For most other features,
1095 you can use Autoconf template macros to produce custom checks; see
1096 @ref{Writing Tests}, for information about them.  For especially tricky
1097 or specialized features, @file{configure.ac} might need to contain some
1098 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1099 Programming}.  The @command{autoscan} program can give you a good start
1100 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1101 information).
1103 @cindex @file{configure.in}
1104 Previous versions of Autoconf promoted the name @file{configure.in},
1105 which is somewhat ambiguous (the tool needed to process this file is not
1106 described by its extension), and introduces a slight confusion with
1107 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1108 processed by @command{configure}'').  Using @file{configure.ac} is now
1109 preferred, while the use of @file{configure.in} will cause warnings
1110 from @command{autoconf}.
1112 @menu
1113 * Shell Script Compiler::       Autoconf as solution of a problem
1114 * Autoconf Language::           Programming in Autoconf
1115 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1116 @end menu
1118 @node Shell Script Compiler
1119 @subsection A Shell Script Compiler
1121 Just as for any other computer language, in order to properly program
1122 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1123 the language tries to address and @emph{how} it does so.
1125 The problem Autoconf addresses is that the world is a mess.  After all,
1126 you are using Autoconf in order to have your package compile easily on
1127 all sorts of different systems, some of them being extremely hostile.
1128 Autoconf itself bears the price for these differences: @command{configure}
1129 must run on all those systems, and thus @command{configure} must limit itself
1130 to their lowest common denominator of features.
1132 Naturally, you might then think of shell scripts; who needs
1133 @command{autoconf}?  A set of properly written shell functions is enough to
1134 make it easy to write @command{configure} scripts by hand.  Sigh!
1135 Unfortunately, even in 2008, where shells without any function support are
1136 far and few between, there are pitfalls to avoid when making use of them.
1137 Also, finding a Bourne shell that accepts shell functions is not trivial,
1138 even though there is almost always one on interesting porting targets.
1140 So, what is really needed is some kind of compiler, @command{autoconf},
1141 that takes an Autoconf program, @file{configure.ac}, and transforms it
1142 into a portable shell script, @command{configure}.
1144 How does @command{autoconf} perform this task?
1146 There are two obvious possibilities: creating a brand new language or
1147 extending an existing one.  The former option is attractive: all
1148 sorts of optimizations could easily be implemented in the compiler and
1149 many rigorous checks could be performed on the Autoconf program
1150 (e.g., rejecting any non-portable construct).  Alternatively, you can
1151 extend an existing language, such as the @code{sh} (Bourne shell)
1152 language.
1154 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1155 therefore most convenient to implement @command{autoconf} as a macro
1156 expander: a program that repeatedly performs @dfn{macro expansions} on
1157 text input, replacing macro calls with macro bodies and producing a pure
1158 @code{sh} script in the end.  Instead of implementing a dedicated
1159 Autoconf macro expander, it is natural to use an existing
1160 general-purpose macro language, such as M4, and implement the extensions
1161 as a set of M4 macros.
1164 @node Autoconf Language
1165 @subsection The Autoconf Language
1166 @cindex quotation
1168 The Autoconf language differs from many other computer
1169 languages because it treats actual code the same as plain text.  Whereas
1170 in C, for instance, data and instructions have different syntactic
1171 status, in Autoconf their status is rigorously the same.  Therefore, we
1172 need a means to distinguish literal strings from text to be expanded:
1173 quotation.
1175 When calling macros that take arguments, there must not be any white
1176 space between the macro name and the open parenthesis.
1178 @example
1179 AC_INIT ([oops], [1.0]) # incorrect
1180 AC_INIT([hello], [1.0]) # good
1181 @end example
1183 Arguments should
1184 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1185 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1186 unless they are quoted.  You should always quote an argument that
1187 might contain a macro name, comma, parenthesis, or a leading blank or
1188 newline.  This rule applies recursively for every macro
1189 call, including macros called from other macros.  For more details on
1190 quoting rules, see @ref{Programming in M4}.
1192 For instance:
1194 @example
1195 AC_CHECK_HEADER([stdio.h],
1196                 [AC_DEFINE([HAVE_STDIO_H], [1],
1197                    [Define to 1 if you have <stdio.h>.])],
1198                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1199 @end example
1201 @noindent
1202 is quoted properly.  You may safely simplify its quotation to:
1204 @example
1205 AC_CHECK_HEADER([stdio.h],
1206                 [AC_DEFINE([HAVE_STDIO_H], 1,
1207                    [Define to 1 if you have <stdio.h>.])],
1208                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1209 @end example
1211 @noindent
1212 because @samp{1} cannot contain a macro call.  Here, the argument of
1213 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1214 interpreted as an argument separator.  Also, the second and third arguments
1215 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1216 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1217 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1218 if you unwisely defined a macro with a name like @samp{Define} or
1219 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1220 would keep the quotes, but many Autoconf users find such precautions
1221 annoying, and would rewrite the example as follows:
1223 @example
1224 AC_CHECK_HEADER(stdio.h,
1225                 [AC_DEFINE(HAVE_STDIO_H, 1,
1226                    [Define to 1 if you have <stdio.h>.])],
1227                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1228 @end example
1230 @noindent
1231 This is safe, so long as you adopt good naming conventions and do not
1232 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1233 @samp{h}.  Though it is also safe here to omit the quotes around
1234 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1235 message strings are more likely to inadvertently contain commas.
1237 The following example is wrong and dangerous, as it is underquoted:
1239 @example
1240 AC_CHECK_HEADER(stdio.h,
1241                 AC_DEFINE(HAVE_STDIO_H, 1,
1242                    Define to 1 if you have <stdio.h>.),
1243                 AC_MSG_ERROR([sorry, can't do anything for you]))
1244 @end example
1246 In other cases, you may want to use text that also resembles a macro
1247 call.  You must quote that text (whether just the potential problem, or
1248 the entire line) even when it is not passed as a macro argument; and you
1249 may also have to use @code{m4_pattern_allow} (@pxref{Forbidden
1250 Patterns}), to declare your intention that the resulting configure file
1251 will have a literal that resembles what would otherwise be reserved for
1252 a macro name.  For example:
1254 @example
1255 dnl Simulate a possible future autoconf macro
1256 m4_define([AC_DC], [oops])
1257 dnl Underquoted:
1258 echo "Hard rock was here!  --AC_DC"
1259 dnl Correctly quoted:
1260 m4_pattern_allow([AC_DC])
1261 echo "Hard rock was here!  --[AC_DC]"
1262 [echo "Hard rock was here!  --AC_DC"]
1263 @end example
1265 @noindent
1266 which results in this text in @file{configure}:
1268 @example
1269 echo "Hard rock was here!  --oops"
1270 echo "Hard rock was here!  --AC_DC"
1271 echo "Hard rock was here!  --AC_DC"
1272 @end example
1274 @noindent
1275 When you use the same text in a macro argument, you must therefore have
1276 an extra quotation level (since one is stripped away by the macro
1277 substitution).  In general, then, it is a good idea to @emph{use double
1278 quoting for all literal string arguments}, either around just the
1279 problematic portions, or over the entire argument:
1281 @example
1282 m4_pattern_allow([AC_DC])
1283 AC_MSG_WARN([[AC_DC] stinks  --Iron Maiden])
1284 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1285 @end example
1287 It is also possible to avoid the problematic patterns in the first
1288 place, by the use of additional escaping (either a quadrigraph, or
1289 creative shell constructs), in which case it is no longer necessary to
1290 use @code{m4_pattern_allow}:
1292 @example
1293 echo "Hard rock was here!  --AC""_DC"
1294 AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1295 @end example
1297 You are now able to understand one of the constructs of Autoconf that
1298 has been continually misunderstood@enddots{}  The rule of thumb is that
1299 @emph{whenever you expect macro expansion, expect quote expansion};
1300 i.e., expect one level of quotes to be lost.  For instance:
1302 @example
1303 AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [],
1304  [AC_MSG_ERROR([you lose])])
1305 @end example
1307 @noindent
1308 is incorrect: here, the first argument of @code{AC_LANG_SOURCE} is
1309 @samp{char b[10];} and is expanded once, which results in
1310 @samp{char b10;}; and the @code{AC_LANG_SOURCE} is also expanded prior
1311 to being passed to @code{AC_COMPILE_IFELSE}.  (There was an idiom common
1312 in Autoconf's past to
1313 address this issue via the M4 @code{changequote} primitive, but do not
1314 use it!)  Let's take a closer look: the author meant the first argument
1315 to be understood as a literal, and therefore it must be quoted twice;
1316 likewise, the intermediate @code{AC_LANG_SOURCE} macro should be quoted
1317 once so that it is only expanded after the rest of the body of
1318 @code{AC_COMPILE_IFELSE} is in place:
1320 @example
1321 AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [],
1322   [AC_MSG_ERROR([you lose])])
1323 @end example
1325 @noindent
1326 Voil@`a, you actually produce @samp{char b[10];} this time!
1328 On the other hand, descriptions (e.g., the last parameter of
1329 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1330 are subject to line breaking, for example---and should not be double quoted.
1331 Even if these descriptions are short and are not actually broken, double
1332 quoting them yields weird results.
1334 Some macros take optional arguments, which this documentation represents
1335 as @ovar{arg} (not to be confused with the quote characters).  You may
1336 just leave them empty, or use @samp{[]} to make the emptiness of the
1337 argument explicit, or you may simply omit the trailing commas.  The
1338 three lines below are equivalent:
1340 @example
1341 AC_CHECK_HEADERS([stdio.h], [], [], [])
1342 AC_CHECK_HEADERS([stdio.h],,,)
1343 AC_CHECK_HEADERS([stdio.h])
1344 @end example
1346 It is best to put each macro call on its own line in
1347 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1348 rely on the newline after the macro call to terminate the commands.
1349 This approach makes the generated @command{configure} script a little
1350 easier to read by not inserting lots of blank lines.  It is generally
1351 safe to set shell variables on the same line as a macro call, because
1352 the shell allows assignments without intervening newlines.
1354 You can include comments in @file{configure.ac} files by starting them
1355 with the @samp{#}.  For example, it is helpful to begin
1356 @file{configure.ac} files with a line like this:
1358 @example
1359 # Process this file with autoconf to produce a configure script.
1360 @end example
1362 @node Autoconf Input Layout
1363 @subsection Standard @file{configure.ac} Layout
1365 The order in which @file{configure.ac} calls the Autoconf macros is not
1366 important, with a few exceptions.  Every @file{configure.ac} must
1367 contain a call to @code{AC_INIT} before the checks, and a call to
1368 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1369 rely on other macros having been called first, because they check
1370 previously set values of some variables to decide what to do.  These
1371 macros are noted in the individual descriptions (@pxref{Existing
1372 Tests}), and they also warn you when @command{configure} is created if they
1373 are called out of order.
1375 To encourage consistency, here is a suggested order for calling the
1376 Autoconf macros.  Generally speaking, the things near the end of this
1377 list are those that could depend on things earlier in it.  For example,
1378 library functions could be affected by types and libraries.
1380 @display
1381 @group
1382 Autoconf requirements
1383 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1384 information on the package
1385 checks for programs
1386 checks for libraries
1387 checks for header files
1388 checks for types
1389 checks for structures
1390 checks for compiler characteristics
1391 checks for library functions
1392 checks for system services
1393 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1394 @code{AC_OUTPUT}
1395 @end group
1396 @end display
1399 @node autoscan Invocation
1400 @section Using @command{autoscan} to Create @file{configure.ac}
1401 @cindex @command{autoscan}
1403 The @command{autoscan} program can help you create and/or maintain a
1404 @file{configure.ac} file for a software package.  @command{autoscan}
1405 examines source files in the directory tree rooted at a directory given
1406 as a command line argument, or the current directory if none is given.
1407 It searches the source files for common portability problems and creates
1408 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1409 for that package, and checks a possibly existing @file{configure.ac} for
1410 completeness.
1412 When using @command{autoscan} to create a @file{configure.ac}, you
1413 should manually examine @file{configure.scan} before renaming it to
1414 @file{configure.ac}; it probably needs some adjustments.
1415 Occasionally, @command{autoscan} outputs a macro in the wrong order
1416 relative to another macro, so that @command{autoconf} produces a warning;
1417 you need to move such macros manually.  Also, if you want the package to
1418 use a configuration header file, you must add a call to
1419 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1420 also have to change or add some @code{#if} directives to your program in
1421 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1422 information about a program that can help with that job).
1424 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1425 consider adding its suggestions.  The file @file{autoscan.log}
1426 contains detailed information on why a macro is requested.
1428 @command{autoscan} uses several data files (installed along with Autoconf)
1429 to determine which macros to output when it finds particular symbols in
1430 a package's source files.  These data files all have the same format:
1431 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1432 output if that symbol is encountered.  Lines starting with @samp{#} are
1433 comments.
1435 @command{autoscan} accepts the following options:
1437 @table @option
1438 @item --help
1439 @itemx -h
1440 Print a summary of the command line options and exit.
1442 @item --version
1443 @itemx -V
1444 Print the version number of Autoconf and exit.
1446 @item --verbose
1447 @itemx -v
1448 Print the names of the files it examines and the potentially interesting
1449 symbols it finds in them.  This output can be voluminous.
1451 @item --debug
1452 @itemx -d
1453 Don't remove temporary files.
1455 @item --include=@var{dir}
1456 @itemx -I @var{dir}
1457 Append @var{dir} to the include path.  Multiple invocations accumulate.
1459 @item --prepend-include=@var{dir}
1460 @itemx -B @var{dir}
1461 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1462 @end table
1464 @node ifnames Invocation
1465 @section Using @command{ifnames} to List Conditionals
1466 @cindex @command{ifnames}
1468 @command{ifnames} can help you write @file{configure.ac} for a software
1469 package.  It prints the identifiers that the package already uses in C
1470 preprocessor conditionals.  If a package has already been set up to have
1471 some portability, @command{ifnames} can thus help you figure out what its
1472 @command{configure} needs to check for.  It may help fill in some gaps in a
1473 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1474 Invocation}).
1476 @command{ifnames} scans all of the C source files named on the command line
1477 (or the standard input, if none are given) and writes to the standard
1478 output a sorted list of all the identifiers that appear in those files
1479 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1480 directives.  It prints each identifier on a line, followed by a
1481 space-separated list of the files in which that identifier occurs.
1483 @noindent
1484 @command{ifnames} accepts the following options:
1486 @table @option
1487 @item --help
1488 @itemx -h
1489 Print a summary of the command line options and exit.
1491 @item --version
1492 @itemx -V
1493 Print the version number of Autoconf and exit.
1494 @end table
1496 @node autoconf Invocation
1497 @section Using @command{autoconf} to Create @command{configure}
1498 @cindex @command{autoconf}
1500 To create @command{configure} from @file{configure.ac}, run the
1501 @command{autoconf} program with no arguments.  @command{autoconf} processes
1502 @file{configure.ac} with the M4 macro processor, using the
1503 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1504 file instead of @file{configure.ac} and writes the configuration script
1505 to the standard output instead of to @command{configure}.  If you give
1506 @command{autoconf} the argument @option{-}, it reads from the standard
1507 input instead of @file{configure.ac} and writes the configuration script
1508 to the standard output.
1510 The Autoconf macros are defined in several files.  Some of the files are
1511 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1512 looks for the optional file @file{acsite.m4} in the directory that
1513 contains the distributed Autoconf macro files, and for the optional file
1514 @file{aclocal.m4} in the current directory.  Those files can contain
1515 your site's or the package's own Autoconf macro definitions
1516 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1517 defined in more than one of the files that @command{autoconf} reads, the
1518 last definition it reads overrides the earlier ones.
1520 @command{autoconf} accepts the following options:
1522 @table @option
1523 @item --help
1524 @itemx -h
1525 Print a summary of the command line options and exit.
1527 @item --version
1528 @itemx -V
1529 Print the version number of Autoconf and exit.
1531 @item --verbose
1532 @itemx -v
1533 Report processing steps.
1535 @item --debug
1536 @itemx -d
1537 Don't remove the temporary files.
1539 @item --force
1540 @itemx -f
1541 Remake @file{configure} even if newer than its input files.
1543 @item --include=@var{dir}
1544 @itemx -I @var{dir}
1545 Append @var{dir} to the include path.  Multiple invocations accumulate.
1547 @item --prepend-include=@var{dir}
1548 @itemx -B @var{dir}
1549 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1551 @item --output=@var{file}
1552 @itemx -o @var{file}
1553 Save output (script or trace) to @var{file}.  The file @option{-} stands
1554 for the standard output.
1556 @item --warnings=@var{category}
1557 @itemx -W @var{category}
1558 @evindex WARNINGS
1559 Report the warnings related to @var{category} (which can actually be a
1560 comma separated list).  @xref{Reporting Messages}, macro
1561 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1562 values include:
1564 @table @samp
1565 @item all
1566 report all the warnings
1568 @item none
1569 report none
1571 @item error
1572 treats warnings as errors
1574 @item no-@var{category}
1575 disable warnings falling into @var{category}
1576 @end table
1578 Warnings about @samp{syntax} are enabled by default, and the environment
1579 variable @env{WARNINGS}, a comma separated list of categories, is
1580 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1581 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1582 disable the defaults and @env{WARNINGS}, and then
1583 enable warnings about obsolete constructs, use @option{-W
1584 none,obsolete}.
1586 @cindex Back trace
1587 @cindex Macro invocation stack
1588 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1589 displays a back trace for errors, but not for warnings; if you want
1590 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1591 examples.
1593 @item --trace=@var{macro}[:@var{format}]
1594 @itemx -t @var{macro}[:@var{format}]
1595 Do not create the @command{configure} script, but list the calls to
1596 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1597 arguments can be used to list several macros.  Multiple @option{--trace}
1598 arguments for a single macro are not cumulative; instead, you should
1599 just make @var{format} as long as needed.
1601 The @var{format} is a regular string, with newlines if desired, and
1602 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1603 @ref{autom4te Invocation}, for details on the @var{format}.
1605 @item --initialization
1606 @itemx -i
1607 By default, @option{--trace} does not trace the initialization of the
1608 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1609 results in a noticeable speedup, but can be disabled by this option.
1610 @end table
1613 It is often necessary to check the content of a @file{configure.ac}
1614 file, but parsing it yourself is extremely fragile and error-prone.  It
1615 is suggested that you rely upon @option{--trace} to scan
1616 @file{configure.ac}.  For instance, to find the list of variables that
1617 are substituted, use:
1619 @example
1620 @group
1621 $ @kbd{autoconf -t AC_SUBST}
1622 configure.ac:2:AC_SUBST:ECHO_C
1623 configure.ac:2:AC_SUBST:ECHO_N
1624 configure.ac:2:AC_SUBST:ECHO_T
1625 @i{More traces deleted}
1626 @end group
1627 @end example
1629 @noindent
1630 The example below highlights the difference between @samp{$@@},
1631 @samp{$*}, and @samp{$%}.
1633 @example
1634 @group
1635 $ @kbd{cat configure.ac}
1636 AC_DEFINE(This, is, [an
1637 [example]])
1638 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1639 *: $*
1640 %: $%'
1641 @@: [This],[is],[an
1642 [example]]
1643 *: This,is,an
1644 [example]
1645 %: This:is:an [example]
1646 @end group
1647 @end example
1649 @noindent
1650 The @var{format} gives you a lot of freedom:
1652 @example
1653 @group
1654 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1655 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1656 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1657 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1658 @i{More traces deleted}
1659 @end group
1660 @end example
1662 @noindent
1663 A long @var{separator} can be used to improve the readability of complex
1664 structures, and to ease their parsing (for instance when no single
1665 character is suitable as a separator):
1667 @example
1668 @group
1669 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1670 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1671 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1672 AUTOMAKE|:::::|automake|:::::|$missing_dir
1673 @i{More traces deleted}
1674 @end group
1675 @end example
1677 @node autoreconf Invocation
1678 @section Using @command{autoreconf} to Update @command{configure} Scripts
1679 @cindex @command{autoreconf}
1681 Installing the various components of the GNU Build System can be
1682 tedious: running @command{autopoint} for Gettext, @command{automake} for
1683 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1684 because some tools such as @command{automake} have been updated on your
1685 system, or because some of the sources such as @file{configure.ac} have
1686 been updated, or finally, simply in order to install the GNU Build
1687 System in a fresh tree.
1689 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1690 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1691 @command{autopoint} (when appropriate) repeatedly to update the
1692 GNU Build System in the specified directories and their
1693 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1694 those files that are older than their sources.  The environment variables
1695 @env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE},
1696 @env{ACLOCAL}, @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE}
1697 may be used to override the invocation of the respective tools.
1699 If you install a new version of some tool, you can make
1700 @command{autoreconf} remake @emph{all} of the files by giving it the
1701 @option{--force} option.
1703 @xref{Automatic Remaking}, for Make rules to automatically
1704 rebuild @command{configure} scripts when their source files change.  That
1705 method handles the timestamps of configuration header templates
1706 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1707 @option{--localdir=@var{dir}}.
1709 @cindex Gettext
1710 @cindex @command{autopoint}
1711 Gettext supplies the @command{autopoint} command to add translation
1712 infrastructure to a source package.  If you use @command{autopoint},
1713 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1714 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1715 Invocation, , Invoking the @code{autopoint} Program, gettext,
1716 GNU @code{gettext} utilities}, for further details.
1718 @noindent
1719 @command{autoreconf} accepts the following options:
1721 @table @option
1722 @item --help
1723 @itemx -h
1724 Print a summary of the command line options and exit.
1726 @item --version
1727 @itemx -V
1728 Print the version number of Autoconf and exit.
1730 @item --verbose
1731 @itemx -v
1732 Print the name of each directory @command{autoreconf} examines and the
1733 commands it runs.  If given two or more times, pass @option{--verbose}
1734 to subordinate tools that support it.
1736 @item --debug
1737 @itemx -d
1738 Don't remove the temporary files.
1740 @item --force
1741 @itemx -f
1742 Remake even @file{configure} scripts and configuration headers that are
1743 newer than their input files (@file{configure.ac} and, if present,
1744 @file{aclocal.m4}).
1746 @item --install
1747 @itemx -i
1748 Install the missing auxiliary files in the package.  By default, files
1749 are copied; this can be changed with @option{--symlink}.
1751 If deemed appropriate, this option triggers calls to
1752 @samp{automake --add-missing},
1753 @samp{libtoolize}, @samp{autopoint}, etc.
1755 @item --no-recursive
1756 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1757 macro @code{AC_CONFIG_SUBDIRS}).
1759 @item --symlink
1760 @itemx -s
1761 When used with @option{--install}, install symbolic links to the missing
1762 auxiliary files instead of copying them.
1764 @item --make
1765 @itemx -m
1766 When the directories were configured, update the configuration by
1767 running @samp{./config.status --recheck && ./config.status}, and then
1768 run @samp{make}.
1770 @item --include=@var{dir}
1771 @itemx -I @var{dir}
1772 Append @var{dir} to the include path.  Multiple invocations accumulate.
1773 Passed on to @command{aclocal}, @command{autoconf} and
1774 @command{autoheader} internally.
1776 @item --prepend-include=@var{dir}
1777 @itemx -B @var{dir}
1778 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1779 Passed on to @command{autoconf} and @command{autoheader} internally.
1781 @item --warnings=@var{category}
1782 @itemx -W @var{category}
1783 @evindex WARNINGS
1784 Report the warnings related to @var{category} (which can actually be a
1785 comma separated list).
1787 @table @samp
1788 @item cross
1789 related to cross compilation issues.
1791 @item obsolete
1792 report the uses of obsolete constructs.
1794 @item portability
1795 portability issues
1797 @item syntax
1798 dubious syntactic constructs.
1800 @item all
1801 report all the warnings
1803 @item none
1804 report none
1806 @item error
1807 treats warnings as errors
1809 @item no-@var{category}
1810 disable warnings falling into @var{category}
1811 @end table
1813 Warnings about @samp{syntax} are enabled by default, and the environment
1814 variable @env{WARNINGS}, a comma separated list of categories, is
1815 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1816 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1817 disable the defaults and @env{WARNINGS}, and then
1818 enable warnings about obsolete constructs, use @option{-W
1819 none,obsolete}.
1820 @end table
1822 If you want @command{autoreconf} to pass flags that are not listed here
1823 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1824 Due to a limitation in the Autoconf implementation these flags currently
1825 must be set on a single line in @file{Makefile.am}, without any
1826 backslash-newlines.  Also, be aware that future Automake releases might
1827 start flagging @code{ACLOCAL_AMFLAGS} as obsolescent, or even remove
1828 support for it.
1830 @c ========================================= Initialization and Output Files.
1832 @node Setup
1833 @chapter Initialization and Output Files
1835 Autoconf-generated @command{configure} scripts need some information about
1836 how to initialize, such as how to find the package's source files and
1837 about the output files to produce.  The following sections describe the
1838 initialization and the creation of output files.
1840 @menu
1841 * Initializing configure::      Option processing etc.
1842 * Versioning::                  Dealing with Autoconf versions
1843 * Notices::                     Copyright, version numbers in @command{configure}
1844 * Input::                       Where Autoconf should find files
1845 * Output::                      Outputting results from the configuration
1846 * Configuration Actions::       Preparing the output based on results
1847 * Configuration Files::         Creating output files
1848 * Makefile Substitutions::      Using output variables in makefiles
1849 * Configuration Headers::       Creating a configuration header file
1850 * Configuration Commands::      Running arbitrary instantiation commands
1851 * Configuration Links::         Links depending on the configuration
1852 * Subdirectories::              Configuring independent packages together
1853 * Default Prefix::              Changing the default installation prefix
1854 @end menu
1856 @node Initializing configure
1857 @section Initializing @command{configure}
1859 Every @command{configure} script must call @code{AC_INIT} before doing
1860 anything else that produces output.  Calls to silent macros, such as
1861 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1862 are generally used via @file{aclocal.m4}, since that is implicitly
1863 included before the start of @file{configure.ac}.  The only other
1864 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1866 @anchor{AC_INIT}
1867 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1868   @ovar{tarname}, @ovar{url})
1869 @acindex{INIT}
1870 Process any command-line arguments and perform initialization
1871 and verification.
1873 Set the name of the @var{package} and its @var{version}.  These are
1874 typically used in @option{--version} support, including that of
1875 @command{configure}.  The optional argument @var{bug-report} should be
1876 the email to which users should send bug reports.  The package
1877 @var{tarname} differs from @var{package}: the latter designates the full
1878 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1879 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1880 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1881 other than alphanumerics and underscores are changed to @samp{-}.  If
1882 provided, @var{url} should be the home page for the package.
1884 The arguments of @code{AC_INIT} must be static, i.e., there should not
1885 be any shell computation, quotes, or newlines, but they can be computed
1886 by M4.  This is because the package information strings are expanded at
1887 M4 time into several contexts, and must give the same text at shell time
1888 whether used in single-quoted strings, double-quoted strings, quoted
1889 here-documents, or unquoted here-documents.  It is permissible to use
1890 @code{m4_esyscmd} or @code{m4_esyscmd_s} for computing a version string
1891 that changes with every commit to a version control system (in fact,
1892 Autoconf does just that, for all builds of the development tree made
1893 between releases).
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{http://@/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 Finding @command{configure} Input
2046 @anchor{AC_CONFIG_SRCDIR}
2047 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2048 @acindex{CONFIG_SRCDIR}
2049 @var{unique-file-in-source-dir} is some file that is in the package's
2050 source directory; @command{configure} checks for this file's existence to
2051 make sure that the directory that it is told contains the source code in
2052 fact does.  Occasionally people accidentally specify the wrong directory
2053 with @option{--srcdir}; this is a safety check.  @xref{configure
2054 Invocation}, for more information.
2055 @end defmac
2058 @c FIXME: Remove definitively once --install explained.
2060 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
2061 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
2062 @c to split the macros in several files.  In this case, Autoconf must be
2063 @c told which files to load, and in which order.
2065 @c @defmac AC_INCLUDE (@var{file}@dots{})
2066 @c @acindex{INCLUDE}
2067 @c @c FIXME: There is no longer shell globbing.
2068 @c Read the macro definitions that appear in the listed files.  A list of
2069 @c space-separated file names or shell globbing patterns is expected.  The
2070 @c files are read in the order they're listed.
2072 @c Because the order of definition of macros is important (only the last
2073 @c definition of a macro is used), beware that it is @code{AC_INIT} that
2074 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
2075 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
2076 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
2077 @c the latter case, non-macro lines from included files may end up in the
2078 @c @file{configure} script, whereas in the former case, they'd be discarded
2079 @c just like any text that appear before @code{AC_INIT}.
2080 @c @end defmac
2082 Packages that do manual configuration or use the @command{install} program
2083 might need to tell @command{configure} where to find some other shell
2084 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
2085 it looks are correct for most cases.
2087 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2088 @acindex{CONFIG_AUX_DIR}
2089 Use the auxiliary build tools (e.g., @file{install-sh},
2090 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
2091 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
2092 These are auxiliary files used in configuration.  @var{dir} can be
2093 either absolute or relative to @file{@var{srcdir}}.  The default is
2094 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
2095 @file{@var{srcdir}/../..}, whichever is the first that contains
2096 @file{install-sh}.  The other files are not checked for, so that using
2097 @code{AC_PROG_INSTALL} does not automatically require distributing the
2098 other auxiliary files.  It checks for @file{install.sh} also, but that
2099 name is obsolete because some @command{make} have a rule that creates
2100 @file{install} from it if there is no makefile.
2102 The auxiliary directory is commonly named @file{build-aux}.
2103 If you need portability to DOS variants, do not name the
2104 auxiliary directory @file{aux}.  @xref{File System Conventions}.
2105 @end defmac
2107 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2108 @acindex{REQUIRE_AUX_FILE}
2109 Declares that @var{file} is expected in the directory defined above.  In
2110 Autoconf proper, this macro does nothing: its sole purpose is to be
2111 traced by third-party tools to produce a list of expected auxiliary
2112 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
2113 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2114 (@pxref{Canonicalizing}) to register the auxiliary files they need.
2115 @end defmac
2117 Similarly, packages that use @command{aclocal} should declare where
2118 local macros can be found using @code{AC_CONFIG_MACRO_DIRS}.
2120 @defmac AC_CONFIG_MACRO_DIRS (@var{dir1} [@var{dir2} ... @var{dirN}])
2121 @defmacx AC_CONFIG_MACRO_DIR (@var{dir})
2122 @acindex{CONFIG_MACRO_DIRS}
2123 @acindex{CONFIG_MACRO_DIR}
2124 @acindex{CONFIG_MACRO_DIR_TRACE}
2125 Specify the given directories as the location of additional local Autoconf
2126 macros.  These macros are intended for use by commands like
2127 @command{autoreconf} or @command{aclocal} that trace macro calls; they should
2128 be called directly from @file{configure.ac} so that tools that install
2129 macros for @command{aclocal} can find the macros' declarations.  Tools
2130 that want to learn which directories have been selected should trace
2131 @code{AC_CONFIG_MACRO_DIR_TRACE}, which will be called once per directory.
2133 AC_CONFIG_MACRO_DIRS is the preferred form, and can be called multiple
2134 times and with multiple arguments; in such cases, directories in earlier
2135 calls are expected to be searched before directories in later calls, and
2136 directories appearing in the same call are expected to be searched in
2137 the order in which they appear in the call.  For historical reasons, the
2138 macro AC_CONFIG_MACRO_DIR can also be used once, if it appears first,
2139 for tools such as older @command{libtool} that weren't prepared to
2140 handle multiple directories.  For example, a usage like
2142 @smallexample
2143 AC_CONFIG_MACRO_DIR([dir1])
2144 AC_CONFIG_MACRO_DIRS([dir2])
2145 AC_CONFIG_MACRO_DIRS([dir3 dir4])
2146 @end smallexample
2148 will cause the trace of AC_CONFIG_MACRO_DIR_TRACE to appear four times,
2149 and should cause the directories to be searched in this order:
2150 @samp{dir1 dir2 dir3 dir4}.
2152 Note that if you use @command{aclocal} from an Automake release prior to
2153 1.13 to generate @file{aclocal.m4}, you must also set
2154 @code{ACLOCAL_AMFLAGS = -I @var{dir1} [-I @var{dir2} ... -I @var{dirN}]}
2155 in your top-level @file{Makefile.am}.  Due to a limitation in
2156 the Autoconf implementation of @command{autoreconf}, these include
2157 directives currently must be set on a single line in @file{Makefile.am},
2158 without any backslash-newlines.
2159 @end defmac
2162 @node Output
2163 @section Outputting Files
2164 @cindex Outputting files
2166 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2167 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2168 @file{config.status}, which in turn creates the makefiles and any
2169 other files resulting from configuration.  This is the only required
2170 macro besides @code{AC_INIT} (@pxref{Input}).
2172 @anchor{AC_OUTPUT}
2173 @defmac AC_OUTPUT
2174 @acindex{OUTPUT}
2175 @cindex Instantiation
2176 Generate @file{config.status} and launch it.  Call this macro once, at
2177 the end of @file{configure.ac}.
2179 @file{config.status} performs all the configuration actions: all the
2180 output files (see @ref{Configuration Files}, macro
2181 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2182 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2183 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2184 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2185 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2186 are honored.
2188 The location of your @code{AC_OUTPUT} invocation is the exact point
2189 where configuration actions are taken: any code afterwards is
2190 executed by @command{configure} once @command{config.status} was run.  If
2191 you want to bind actions to @command{config.status} itself
2192 (independently of whether @command{configure} is being run), see
2193 @ref{Configuration Commands, , Running Arbitrary Configuration
2194 Commands}.
2195 @end defmac
2197 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2198 @xref{Obsolete Macros}, for a description of the arguments that
2199 @code{AC_OUTPUT} used to support.
2202 If you run @command{make} in subdirectories, you should run it using the
2203 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2204 @code{MAKE} to the name of the @command{make} program plus any options it
2205 was given.  (But many do not include in it the values of any variables
2206 set on the command line, so those are not passed on automatically.)
2207 Some old versions of @command{make} do not set this variable.  The
2208 following macro allows you to use it even with those versions.
2210 @anchor{AC_PROG_MAKE_SET}
2211 @defmac AC_PROG_MAKE_SET
2212 @acindex{PROG_MAKE_SET}
2213 @ovindex SET_MAKE
2214 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2215 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2216 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2217 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2218 @code{SET_MAKE}.
2219 @end defmac
2221 If you use this macro, place a line like this in each @file{Makefile.in}
2222 that runs @command{MAKE} on other directories:
2224 @example
2225 @@SET_MAKE@@
2226 @end example
2230 @node Configuration Actions
2231 @section Performing Configuration Actions
2232 @cindex Configuration actions
2234 @file{configure} is designed so that it appears to do everything itself,
2235 but there is actually a hidden slave: @file{config.status}.
2236 @file{configure} is in charge of examining your system, but it is
2237 @file{config.status} that actually takes the proper actions based on the
2238 results of @file{configure}.  The most typical task of
2239 @file{config.status} is to @emph{instantiate} files.
2241 @acindex{CONFIG_@var{ITEMS}}
2242 This section describes the common behavior of the four standard
2243 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2244 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2245 have this prototype:
2247 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2248 @c awful.
2249 @example
2250 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2251 @end example
2253 @noindent
2254 where the arguments are:
2256 @table @var
2257 @item tag@dots{}
2258 A blank-or-newline-separated list of tags, which are typically the names of
2259 the files to instantiate.
2261 You are encouraged to use literals as @var{tags}.  In particular, you
2262 should avoid
2264 @example
2265 @dots{} && my_foos="$my_foos fooo"
2266 @dots{} && my_foos="$my_foos foooo"
2267 AC_CONFIG_@var{ITEMS}([$my_foos])
2268 @end example
2270 @noindent
2271 and use this instead:
2273 @example
2274 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2275 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2276 @end example
2278 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2279 special @var{tag} values: they may have the form @samp{@var{output}} or
2280 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2281 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2283 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2284 for example, asks for
2285 the creation of the file @file{Makefile} that contains the expansion of the
2286 output variables in the concatenation of @file{boiler/top.mk} and
2287 @file{boiler/bot.mk}.
2289 The special value @samp{-} might be used to denote the standard output
2290 when used in @var{output}, or the standard input when used in the
2291 @var{inputs}.  You most probably don't need to use this in
2292 @file{configure.ac}, but it is convenient when using the command line
2293 interface of @file{./config.status}, see @ref{config.status Invocation},
2294 for more details.
2296 The @var{inputs} may be absolute or relative file names.  In the latter
2297 case they are first looked for in the build tree, and then in the source
2298 tree.  Input files should be text files, and a line length below 2000
2299 bytes should be safe.
2301 @item commands
2302 Shell commands output literally into @file{config.status}, and
2303 associated with a tag that the user can use to tell @file{config.status}
2304 which commands to run.  The commands are run each time a @var{tag}
2305 request is given to @file{config.status}, typically each time the file
2306 @file{@var{tag}} is created.
2308 The variables set during the execution of @command{configure} are
2309 @emph{not} available here: you first need to set them via the
2310 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2312 @table @code
2313 @item srcdir
2314 @vrindex srcdir
2315 The name of the top source directory, assuming that the working
2316 directory is the top build directory.  This
2317 is what the @command{configure} option @option{--srcdir} sets.
2319 @item ac_top_srcdir
2320 @vrindex ac_top_srcdir
2321 The name of the top source directory, assuming that the working
2322 directory is the current build directory.
2324 @item ac_top_build_prefix
2325 @vrindex ac_top_build_prefix
2326 The name of the top build directory, assuming that the working
2327 directory is the current build directory.
2328 It can be empty, or else ends with a slash, so that you may concatenate
2331 @item ac_srcdir
2332 @vrindex ac_srcdir
2333 The name of the corresponding source directory, assuming that the
2334 working directory is the current build directory.
2336 @item tmp
2337 @vrindex tmp
2338 The name of a temporary directory within the build tree, which you
2339 can use if you need to create additional temporary files.  The
2340 directory is cleaned up when @command{config.status} is done or
2341 interrupted.  Please use package-specific file name prefixes to
2342 avoid clashing with files that @command{config.status} may use
2343 internally.
2344 @end table
2346 @noindent
2347 The @dfn{current} directory refers to the directory (or
2348 pseudo-directory) containing the input part of @var{tags}.  For
2349 instance, running
2351 @example
2352 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2353 @end example
2355 @noindent
2356  with @option{--srcdir=../package} produces the following values:
2358 @example
2359 # Argument of --srcdir
2360 srcdir='../package'
2361 # Reversing deep/dir
2362 ac_top_build_prefix='../../'
2363 # Concatenation of $ac_top_build_prefix and srcdir
2364 ac_top_srcdir='../../../package'
2365 # Concatenation of $ac_top_srcdir and deep/dir
2366 ac_srcdir='../../../package/deep/dir'
2367 @end example
2369 @noindent
2370 independently of @samp{in/in.in}.
2372 @item init-cmds
2373 Shell commands output @emph{unquoted} near the beginning of
2374 @file{config.status}, and executed each time @file{config.status} runs
2375 (regardless of the tag).  Because they are unquoted, for example,
2376 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2377 is typically used by @file{configure} to give @file{config.status} some
2378 variables it needs to run the @var{commands}.
2380 You should be extremely cautious in your variable names: all the
2381 @var{init-cmds} share the same name space and may overwrite each other
2382 in unpredictable ways.  Sorry@enddots{}
2383 @end table
2385 All these macros can be called multiple times, with different
2386 @var{tag} values, of course!
2389 @node Configuration Files
2390 @section Creating Configuration Files
2391 @cindex Creating configuration files
2392 @cindex Configuration file creation
2394 Be sure to read the previous section, @ref{Configuration Actions}.
2396 @anchor{AC_CONFIG_FILES}
2397 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2398 @acindex{CONFIG_FILES}
2399 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2400 file (by default @file{@var{file}.in}), substituting the output variable
2401 values.
2402 @c Before we used to have this feature, which was later rejected
2403 @c because it complicates the writing of makefiles:
2404 @c If the file would be unchanged, it is left untouched, to preserve
2405 @c timestamp.
2406 This macro is one of the instantiating macros; see @ref{Configuration
2407 Actions}.  @xref{Makefile Substitutions}, for more information on using
2408 output variables.  @xref{Setting Output Variables}, for more information
2409 on creating them.  This macro creates the directory that the file is in
2410 if it doesn't exist.  Usually, makefiles are created this way,
2411 but other files, such as @file{.gdbinit}, can be specified as well.
2413 Typical calls to @code{AC_CONFIG_FILES} look like this:
2415 @example
2416 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2417 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2418 @end example
2420 You can override an input file name by appending to @var{file} a
2421 colon-separated list of input files.  Examples:
2423 @example
2424 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2425                 [lib/Makefile:boiler/lib.mk])
2426 @end example
2428 @noindent
2429 Doing this allows you to keep your file names acceptable to
2430 DOS variants, or
2431 to prepend and/or append boilerplate to the file.
2432 @end defmac
2436 @node Makefile Substitutions
2437 @section Substitutions in Makefiles
2438 @cindex Substitutions in makefiles
2439 @cindex Makefile substitutions
2441 Each subdirectory in a distribution that contains something to be
2442 compiled or installed should come with a file @file{Makefile.in}, from
2443 which @command{configure} creates a file @file{Makefile} in that directory.
2444 To create @file{Makefile}, @command{configure} performs a simple variable
2445 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2446 @file{Makefile.in} with the value that @command{configure} has determined
2447 for that variable.  Variables that are substituted into output files in
2448 this way are called @dfn{output variables}.  They are ordinary shell
2449 variables that are set in @command{configure}.  To make @command{configure}
2450 substitute a particular variable into the output files, the macro
2451 @code{AC_SUBST} must be called with that variable name as an argument.
2452 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2453 left unchanged.  @xref{Setting Output Variables}, for more information
2454 on creating output variables with @code{AC_SUBST}.
2456 A software package that uses a @command{configure} script should be
2457 distributed with a file @file{Makefile.in}, but no makefile; that
2458 way, the user has to properly configure the package for the local system
2459 before compiling it.
2461 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2462 GNU Coding Standards}, for more information on what to put in
2463 makefiles.
2465 @menu
2466 * Preset Output Variables::     Output variables that are always set
2467 * Installation Directory Variables::  Other preset output variables
2468 * Changed Directory Variables::  Warnings about @file{datarootdir}
2469 * Build Directories::           Supporting multiple concurrent compiles
2470 * Automatic Remaking::          Makefile rules for configuring
2471 @end menu
2473 @node Preset Output Variables
2474 @subsection Preset Output Variables
2475 @cindex Output variables
2477 Some output variables are preset by the Autoconf macros.  Some of the
2478 Autoconf macros set additional output variables, which are mentioned in
2479 the descriptions for those macros.  @xref{Output Variable Index}, for a
2480 complete list of output variables.  @xref{Installation Directory
2481 Variables}, for the list of the preset ones related to installation
2482 directories.  Below are listed the other preset ones, many of which are
2483 precious variables (@pxref{Setting Output Variables},
2484 @code{AC_ARG_VAR}).
2486 The preset variables which are available during @file{config.status}
2487 (@pxref{Configuration Actions}) may also be used during
2488 @command{configure} tests.  For example, it is permissible to reference
2489 @samp{$srcdir} when constructing a list of directories to pass via
2490 option @option{-I} during a compiler feature check.  When used in this
2491 manner, coupled with the fact that @command{configure} is always run
2492 from the top build directory, it is sufficient to use just
2493 @samp{$srcdir} instead of @samp{$top_srcdir}.
2495 @c Just say no to ASCII sorting!  We're humans, not computers.
2496 @c These variables are listed as they would be in a dictionary:
2497 @c actor
2498 @c Actress
2499 @c actress
2501 @defvar CFLAGS
2502 @evindex CFLAGS
2503 @ovindex CFLAGS
2504 Debugging and optimization options for the C compiler.  If it is not set
2505 in the environment when @command{configure} runs, the default value is set
2506 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2507 uses this variable when compiling or linking programs to test for C features.
2509 If a compiler option affects only the behavior of the preprocessor
2510 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2511 instead.  If it affects only the linker (e.g., @option{-L@var{directory}}),
2512 it should be put into @code{LDFLAGS} instead.  If it
2513 affects only the compiler proper, @code{CFLAGS} is the natural home for
2514 it.  If an option affects multiple phases of the compiler, though,
2515 matters get tricky.  One approach to put such options directly into
2516 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2517 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2519 However, remember that some @file{Makefile} variables are reserved by
2520 the GNU Coding Standards for the use of the ``user''---the person
2521 building the package.  For instance, @code{CFLAGS} is one such variable.
2523 Sometimes package developers are tempted to set user variables such as
2524 @code{CFLAGS} because it appears to make their job easier.  However, the
2525 package itself should never set a user variable, particularly not to
2526 include switches that are required for proper compilation of the
2527 package.  Since these variables are documented as being for the package
2528 builder, that person rightfully expects to be able to override any of
2529 these variables at build time.  If the package developer needs to add
2530 switches without interfering with the user, the proper way to do that is
2531 to introduce an additional variable.  Automake makes this easy by
2532 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2533 automake, GNU Automake}), but the concept is the same even if
2534 Automake is not used.
2535 @end defvar
2537 @defvar configure_input
2538 @ovindex configure_input
2539 A comment saying that the file was generated automatically by
2540 @command{configure} and giving the name of the input file.
2541 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2542 of every makefile it creates.  For other files, you should
2543 reference this variable in a comment at the top of each input file.  For
2544 example, an input shell script should begin like this:
2546 @example
2547 #!/bin/sh
2548 # @@configure_input@@
2549 @end example
2551 @noindent
2552 The presence of that line also reminds people editing the file that it
2553 needs to be processed by @command{configure} in order to be used.
2554 @end defvar
2556 @defvar CPPFLAGS
2557 @evindex CPPFLAGS
2558 @ovindex CPPFLAGS
2559 Preprocessor options for the C, C++, Objective C, and Objective C++
2560 preprocessors and compilers.  If
2561 it is not set in the environment when @command{configure} runs, the default
2562 value is empty.  @command{configure} uses this variable when preprocessing
2563 or compiling programs to test for C, C++, Objective C, and Objective C++
2564 features.
2566 This variable's contents should contain options like @option{-I},
2567 @option{-D}, and @option{-U} that affect only the behavior of the
2568 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2569 can do if an option affects other phases of the compiler as well.
2571 Currently, @command{configure} always links as part of a single
2572 invocation of the compiler that also preprocesses and compiles, so it
2573 uses this variable also when linking programs.  However, it is unwise to
2574 depend on this behavior because the GNU Coding Standards do
2575 not require it and many packages do not use @code{CPPFLAGS} when linking
2576 programs.
2578 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2579 might run into.
2580 @end defvar
2582 @defvar CXXFLAGS
2583 @evindex CXXFLAGS
2584 @ovindex CXXFLAGS
2585 Debugging and optimization options for the C++ compiler.  It acts like
2586 @code{CFLAGS}, but for C++ instead of C.
2587 @end defvar
2589 @defvar DEFS
2590 @ovindex DEFS
2591 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2592 is called, @command{configure} replaces @samp{@@DEFS@@} with
2593 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2594 variable is not defined while @command{configure} is performing its tests,
2595 only when creating the output files.  @xref{Setting Output Variables}, for
2596 how to check the results of previous tests.
2597 @end defvar
2599 @defvar ECHO_C
2600 @defvarx ECHO_N
2601 @defvarx ECHO_T
2602 @ovindex ECHO_C
2603 @ovindex ECHO_N
2604 @ovindex ECHO_T
2605 How does one suppress the trailing newline from @command{echo} for
2606 question-answer message pairs?  These variables provide a way:
2608 @example
2609 echo $ECHO_N "And the winner is... $ECHO_C"
2610 sleep 100000000000
2611 echo "$@{ECHO_T@}dead."
2612 @end example
2614 @noindent
2615 Some old and uncommon @command{echo} implementations offer no means to
2616 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2617 want to use it.
2618 @end defvar
2620 @defvar ERLCFLAGS
2621 @evindex ERLCFLAGS
2622 @ovindex ERLCFLAGS
2623 Debugging and optimization options for the Erlang compiler.  If it is not set
2624 in the environment when @command{configure} runs, the default value is empty.
2625 @command{configure} uses this variable when compiling
2626 programs to test for Erlang features.
2627 @end defvar
2629 @defvar FCFLAGS
2630 @evindex FCFLAGS
2631 @ovindex FCFLAGS
2632 Debugging and optimization options for the Fortran compiler.  If it
2633 is not set in the environment when @command{configure} runs, the default
2634 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2635 @command{configure} uses this variable when compiling or linking
2636 programs to test for Fortran features.
2637 @end defvar
2639 @defvar FFLAGS
2640 @evindex FFLAGS
2641 @ovindex FFLAGS
2642 Debugging and optimization options for the Fortran 77 compiler.  If it
2643 is not set in the environment when @command{configure} runs, the default
2644 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2645 @command{configure} uses this variable when compiling or linking
2646 programs to test for Fortran 77 features.
2647 @end defvar
2649 @defvar LDFLAGS
2650 @evindex LDFLAGS
2651 @ovindex LDFLAGS
2652 Options for the linker.  If it is not set
2653 in the environment when @command{configure} runs, the default value is empty.
2654 @command{configure} uses this variable when linking programs to test for
2655 C, C++, Objective C, Objective C++, Fortran, and Go features.
2657 This variable's contents should contain options like @option{-s} and
2658 @option{-L} that affect only the behavior of the linker.  Please see the
2659 explanation of @code{CFLAGS} for what you can do if an option also
2660 affects other phases of the compiler.
2662 Don't use this variable to pass library names
2663 (@option{-l}) to the linker; use @code{LIBS} instead.
2664 @end defvar
2666 @defvar LIBS
2667 @evindex LIBS
2668 @ovindex LIBS
2669 @option{-l} options to pass to the linker.  The default value is empty,
2670 but some Autoconf macros may prepend extra libraries to this variable if
2671 those libraries are found and provide necessary functions, see
2672 @ref{Libraries}.  @command{configure} uses this variable when linking
2673 programs to test for C, C++, Objective C, Objective C++, Fortran, and Go
2674 features.
2675 @end defvar
2677 @defvar OBJCFLAGS
2678 @evindex OBJCFLAGS
2679 @ovindex OBJCFLAGS
2680 Debugging and optimization options for the Objective C compiler.  It
2681 acts like @code{CFLAGS}, but for Objective C instead of C.
2682 @end defvar
2684 @defvar OBJCXXFLAGS
2685 @evindex OBJCXXFLAGS
2686 @ovindex OBJCXXFLAGS
2687 Debugging and optimization options for the Objective C++ compiler.  It
2688 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2689 @end defvar
2691 @defvar GOFLAGS
2692 @evindex GOFLAGS
2693 @ovindex GOFLAGS
2694 Debugging and optimization options for the Go compiler.  It acts like
2695 @code{CFLAGS}, but for Go instead of C.
2696 @end defvar
2698 @defvar builddir
2699 @ovindex builddir
2700 Rigorously equal to @samp{.}.  Added for symmetry only.
2701 @end defvar
2703 @defvar abs_builddir
2704 @ovindex abs_builddir
2705 Absolute name of @code{builddir}.
2706 @end defvar
2708 @defvar top_builddir
2709 @ovindex top_builddir
2710 The relative name of the top level of the current build tree.  In the
2711 top-level directory, this is the same as @code{builddir}.
2712 @end defvar
2714 @defvar top_build_prefix
2715 @ovindex top_build_prefix
2716 The relative name of the top level of the current build tree with final
2717 slash if nonempty.  This is the same as @code{top_builddir}, except that
2718 it contains zero or more runs of @code{../}, so it should not be
2719 appended with a slash for concatenation.  This helps for @command{make}
2720 implementations that otherwise do not treat @file{./file} and @file{file}
2721 as equal in the toplevel build directory.
2722 @end defvar
2724 @defvar abs_top_builddir
2725 @ovindex abs_top_builddir
2726 Absolute name of @code{top_builddir}.
2727 @end defvar
2729 @defvar srcdir
2730 @ovindex srcdir
2731 The name of the directory that contains the source code for
2732 that makefile.
2733 @end defvar
2735 @defvar abs_srcdir
2736 @ovindex abs_srcdir
2737 Absolute name of @code{srcdir}.
2738 @end defvar
2740 @defvar top_srcdir
2741 @ovindex top_srcdir
2742 The name of the top-level source code directory for the
2743 package.  In the top-level directory, this is the same as @code{srcdir}.
2744 @end defvar
2746 @defvar abs_top_srcdir
2747 @ovindex abs_top_srcdir
2748 Absolute name of @code{top_srcdir}.
2749 @end defvar
2751 @node Installation Directory Variables
2752 @subsection Installation Directory Variables
2753 @cindex Installation directories
2754 @cindex Directories, installation
2756 The following variables specify the directories for
2757 package installation, see @ref{Directory Variables, , Variables for
2758 Installation Directories, standards, The GNU Coding
2759 Standards}, for more information.  Each variable corresponds to an
2760 argument of @command{configure}; trailing slashes are stripped so that
2761 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2762 between directory names.  See the end of this section for
2763 details on when and how to use these variables.
2765 @defvar bindir
2766 @ovindex bindir
2767 The directory for installing executables that users run.
2768 @end defvar
2770 @defvar datadir
2771 @ovindex datadir
2772 The directory for installing idiosyncratic read-only
2773 architecture-independent data.
2774 @end defvar
2776 @defvar datarootdir
2777 @ovindex datarootdir
2778 The root of the directory tree for read-only architecture-independent
2779 data files.
2780 @end defvar
2782 @defvar docdir
2783 @ovindex docdir
2784 The directory for installing documentation files (other than Info and
2785 man).
2786 @end defvar
2788 @defvar dvidir
2789 @ovindex dvidir
2790 The directory for installing documentation files in DVI format.
2791 @end defvar
2793 @defvar exec_prefix
2794 @ovindex exec_prefix
2795 The installation prefix for architecture-dependent files.  By default
2796 it's the same as @code{prefix}.  You should avoid installing anything
2797 directly to @code{exec_prefix}.  However, the default value for
2798 directories containing architecture-dependent files should be relative
2799 to @code{exec_prefix}.
2800 @end defvar
2802 @defvar htmldir
2803 @ovindex htmldir
2804 The directory for installing HTML documentation.
2805 @end defvar
2807 @defvar includedir
2808 @ovindex includedir
2809 The directory for installing C header files.
2810 @end defvar
2812 @defvar infodir
2813 @ovindex infodir
2814 The directory for installing documentation in Info format.
2815 @end defvar
2817 @defvar libdir
2818 @ovindex libdir
2819 The directory for installing object code libraries.
2820 @end defvar
2822 @defvar libexecdir
2823 @ovindex libexecdir
2824 The directory for installing executables that other programs run.
2825 @end defvar
2827 @defvar localedir
2828 @ovindex localedir
2829 The directory for installing locale-dependent but
2830 architecture-independent data, such as message catalogs.  This directory
2831 usually has a subdirectory per locale.
2832 @end defvar
2834 @defvar localstatedir
2835 @ovindex localstatedir
2836 The directory for installing modifiable single-machine data.  Content in
2837 this directory typically survives a reboot.
2838 @end defvar
2840 @defvar runstatedir
2841 @ovindex runstatedir
2842 The directory for installing temporary modifiable single-machine data.
2843 Content in this directory survives as long as the process is running
2844 (such as pid files), as contrasted with @file{/tmp} that may be
2845 periodically cleaned.  Conversely, this directory is typically cleaned
2846 on a reboot.  By default, this is a subdirectory of
2847 @code{localstatedir}.
2848 @end defvar
2850 @defvar mandir
2851 @ovindex mandir
2852 The top-level directory for installing documentation in man format.
2853 @end defvar
2855 @defvar oldincludedir
2856 @ovindex oldincludedir
2857 The directory for installing C header files for non-GCC compilers.
2858 @end defvar
2860 @defvar pdfdir
2861 @ovindex pdfdir
2862 The directory for installing PDF documentation.
2863 @end defvar
2865 @defvar prefix
2866 @ovindex prefix
2867 The common installation prefix for all files.  If @code{exec_prefix}
2868 is defined to a different value, @code{prefix} is used only for
2869 architecture-independent files.
2870 @end defvar
2872 @defvar psdir
2873 @ovindex psdir
2874 The directory for installing PostScript documentation.
2875 @end defvar
2877 @defvar sbindir
2878 @ovindex sbindir
2879 The directory for installing executables that system
2880 administrators run.
2881 @end defvar
2883 @defvar sharedstatedir
2884 @ovindex sharedstatedir
2885 The directory for installing modifiable architecture-independent data.
2886 @end defvar
2888 @defvar sysconfdir
2889 @ovindex sysconfdir
2890 The directory for installing read-only single-machine data.
2891 @end defvar
2894 Most of these variables have values that rely on @code{prefix} or
2895 @code{exec_prefix}.  It is deliberate that the directory output
2896 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2897 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2898 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2900 This behavior is mandated by the GNU Coding Standards, so that when
2901 the user runs:
2903 @table @samp
2904 @item make
2905 she can still specify a different prefix from the one specified to
2906 @command{configure}, in which case, if needed, the package should hard
2907 code dependencies corresponding to the make-specified prefix.
2909 @item make install
2910 she can specify a different installation location, in which case the
2911 package @emph{must} still depend on the location which was compiled in
2912 (i.e., never recompile when @samp{make install} is run).  This is an
2913 extremely important feature, as many people may decide to install all
2914 the files of a package grouped together, and then install links from
2915 the final locations to there.
2916 @end table
2918 In order to support these features, it is essential that
2919 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2920 so that its value can be expanded based
2921 on the current value of @code{prefix}.
2923 A corollary is that you should not use these variables except in
2924 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2925 in @file{configure} and hard-coding it in makefiles using
2926 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2927 you should add
2928 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2929 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2931 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2932 @code{bindir} and friends in your shell scripts and other files; instead,
2933 let @command{make} manage their replacement.  For instance Autoconf
2934 ships templates of its shell scripts ending with @samp{.in}, and uses a
2935 makefile snippet similar to the following to build scripts like
2936 @command{autoheader} and @command{autom4te}:
2938 @example
2939 @group
2940 edit = sed \
2941         -e 's|@@bindir[@@]|$(bindir)|g' \
2942         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2943         -e 's|@@prefix[@@]|$(prefix)|g'
2944 @end group
2946 @group
2947 autoheader autom4te: Makefile
2948         rm -f $@@ $@@.tmp
2949         srcdir=''; \
2950           test -f ./$@@.in || srcdir=$(srcdir)/; \
2951           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2952 @c $$ restore font-lock
2953         chmod +x $@@.tmp
2954         chmod a-w $@@.tmp
2955         mv $@@.tmp $@@
2956 @end group
2958 @group
2959 autoheader: $(srcdir)/autoheader.in
2960 autom4te: $(srcdir)/autom4te.in
2961 @end group
2962 @end example
2964 Some details are noteworthy:
2966 @table @asis
2967 @item @samp{@@bindir[@@]}
2968 The brackets prevent @command{configure} from replacing
2969 @samp{@@bindir@@} in the Sed expression itself.
2970 Brackets are preferable to a backslash here, since
2971 Posix says @samp{\@@} is not portable.
2973 @item @samp{$(bindir)}
2974 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2975 instead.
2977 @item @samp{$(pkgdatadir)}
2978 The example takes advantage of the variable @samp{$(pkgdatadir)}
2979 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2981 @item @samp{/}
2982 Don't use @samp{/} in the Sed expressions that replace file names since
2983 most likely the
2984 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2985 Use a shell metacharacter instead, such as @samp{|}.
2987 @item special characters
2988 File names, file name components, and the value of @code{VPATH} should
2989 not contain shell metacharacters or white
2990 space.  @xref{Special Chars in Variables}.
2992 @item dependency on @file{Makefile}
2993 Since @code{edit} uses values that depend on the configuration specific
2994 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2995 the output depends on @file{Makefile}, not @file{configure.ac}.
2997 @item @samp{$@@}
2998 The main rule is generic, and uses @samp{$@@} extensively to
2999 avoid the need for multiple copies of the rule.
3001 @item Separated dependencies and single suffix rules
3002 You can't use them!  The above snippet cannot be (portably) rewritten
3005 @example
3006 autoconf autoheader: Makefile
3007 @group
3008 .in:
3009         rm -f $@@ $@@.tmp
3010         $(edit) $< >$@@.tmp
3011         chmod +x $@@.tmp
3012         mv $@@.tmp $@@
3013 @end group
3014 @end example
3016 @xref{Single Suffix Rules}, for details.
3018 @item @samp{$(srcdir)}
3019 Be sure to specify the name of the source directory,
3020 otherwise the package won't support separated builds.
3021 @end table
3023 For the more specific installation of Erlang libraries, the following variables
3024 are defined:
3026 @defvar ERLANG_INSTALL_LIB_DIR
3027 @ovindex ERLANG_INSTALL_LIB_DIR
3028 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
3029 The common parent directory of Erlang library installation directories.
3030 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
3031 macro in @file{configure.ac}.
3032 @end defvar
3034 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
3035 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
3036 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3037 The installation directory for Erlang library @var{library}.
3038 This variable is set by using the
3039 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3040 macro in @file{configure.ac}.
3041 @end defvar
3043 @xref{Erlang Libraries}, for details.
3046 @node Changed Directory Variables
3047 @subsection Changed Directory Variables
3048 @cindex @file{datarootdir}
3050 In Autoconf 2.60, the set of directory variables has changed, and the
3051 defaults of some variables have been adjusted
3052 (@pxref{Installation Directory Variables}) to changes in the
3053 GNU Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
3054 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
3055 upgrading from an earlier Autoconf version, you may need to adjust your files
3056 to ensure that the directory variables are substituted correctly
3057 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
3058 in place.  For example, in a @file{Makefile.in}, adding
3060 @example
3061 datarootdir = @@datarootdir@@
3062 @end example
3064 @noindent
3065 is usually sufficient.  If you use Automake to create @file{Makefile.in},
3066 it will add this for you.
3068 To help with the transition, Autoconf warns about files that seem to use
3069 @code{datarootdir} without defining it.  In some cases, it then expands
3070 the value of @code{$datarootdir} in substitutions of the directory
3071 variables.  The following example shows such a warning:
3073 @example
3074 $ @kbd{cat configure.ac}
3075 AC_INIT
3076 AC_CONFIG_FILES([Makefile])
3077 AC_OUTPUT
3078 $ @kbd{cat Makefile.in}
3079 prefix = @@prefix@@
3080 datadir = @@datadir@@
3081 $ @kbd{autoconf}
3082 $ @kbd{configure}
3083 configure: creating ./config.status
3084 config.status: creating Makefile
3085 config.status: WARNING:
3086                Makefile.in seems to ignore the --datarootdir setting
3087 $ @kbd{cat Makefile}
3088 prefix = /usr/local
3089 datadir = $@{prefix@}/share
3090 @end example
3092 Usually one can easily change the file to accommodate both older and newer
3093 Autoconf releases:
3095 @example
3096 $ @kbd{cat Makefile.in}
3097 prefix = @@prefix@@
3098 datarootdir = @@datarootdir@@
3099 datadir = @@datadir@@
3100 $ @kbd{configure}
3101 configure: creating ./config.status
3102 config.status: creating Makefile
3103 $ @kbd{cat Makefile}
3104 prefix = /usr/local
3105 datarootdir = $@{prefix@}/share
3106 datadir = $@{datarootdir@}
3107 @end example
3109 @acindex{DATAROOTDIR_CHECKED}
3110 In some cases, however, the checks may not be able to detect that a suitable
3111 initialization of @code{datarootdir} is in place, or they may fail to detect
3112 that such an initialization is necessary in the output file.  If, after
3113 auditing your package, there are still spurious @file{configure} warnings about
3114 @code{datarootdir}, you may add the line
3116 @example
3117 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3118 @end example
3120 @noindent
3121 to your @file{configure.ac} to disable the warnings.  This is an exception
3122 to the usual rule that you should not define a macro whose name begins with
3123 @code{AC_} (@pxref{Macro Names}).
3127 @node Build Directories
3128 @subsection Build Directories
3129 @cindex Build directories
3130 @cindex Directories, build
3132 You can support compiling a software package for several architectures
3133 simultaneously from the same copy of the source code.  The object files
3134 for each architecture are kept in their own directory.
3136 To support doing this, @command{make} uses the @code{VPATH} variable to
3137 find the files that are in the source directory.  GNU Make
3138 can do this.  Most other recent @command{make} programs can do this as
3139 well, though they may have difficulties and it is often simpler to
3140 recommend GNU @command{make} (@pxref{VPATH and Make}).  Older
3141 @command{make} programs do not support @code{VPATH}; when using them, the
3142 source code must be in the same directory as the object files.
3144 If you are using GNU Automake, the remaining details in this
3145 section are already covered for you, based on the contents of your
3146 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
3147 supporting @code{VPATH} requires the following in your
3148 @file{Makefile.in}:
3150 @example
3151 srcdir = @@srcdir@@
3152 VPATH = @@srcdir@@
3153 @end example
3155 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3156 listed in VPATH}.
3158 @command{configure} substitutes the correct value for @code{srcdir} when
3159 it produces @file{Makefile}.
3161 Do not use the @command{make} variable @code{$<}, which expands to the
3162 file name of the file in the source directory (found with @code{VPATH}),
3163 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3164 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3165 versions of @command{make} do not set @code{$<} in explicit rules; they
3166 expand it to an empty value.
3168 Instead, Make command lines should always refer to source
3169 files by prefixing them with @samp{$(srcdir)/}.  It's safer
3170 to quote the source directory name, in case it contains characters that
3171 are special to the shell.  Because @samp{$(srcdir)} is expanded by Make,
3172 single-quoting works and is safer than double-quoting.  For example:
3174 @example
3175 time.info: time.texinfo
3176         $(MAKEINFO) '$(srcdir)/time.texinfo'
3177 @end example
3179 @node Automatic Remaking
3180 @subsection Automatic Remaking
3181 @cindex Automatic remaking
3182 @cindex Remaking automatically
3184 You can put rules like the following in the top-level @file{Makefile.in}
3185 for a package to automatically update the configuration information when
3186 you change the configuration files.  This example includes all of the
3187 optional files, such as @file{aclocal.m4} and those related to
3188 configuration header files.  Omit from the @file{Makefile.in} rules for
3189 any of these files that your package does not use.
3191 The @samp{$(srcdir)/} prefix is included because of limitations in the
3192 @code{VPATH} mechanism.
3194 The @file{stamp-} files are necessary because the timestamps of
3195 @file{config.h.in} and @file{config.h} are not changed if remaking
3196 them does not change their contents.  This feature avoids unnecessary
3197 recompilation.  You should include the file @file{stamp-h.in} in your
3198 package's distribution, so that @command{make} considers
3199 @file{config.h.in} up to date.  Don't use @command{touch}
3200 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3201 @command{echo} (using
3202 @command{date} would cause needless differences, hence CVS
3203 conflicts, etc.).
3205 @example
3206 @group
3207 $(srcdir)/configure: configure.ac aclocal.m4
3208         cd '$(srcdir)' && autoconf
3210 # autoheader might not change config.h.in, so touch a stamp file.
3211 $(srcdir)/config.h.in: stamp-h.in ;
3212 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3213         cd '$(srcdir)' && autoheader
3214         echo timestamp > '$(srcdir)/stamp-h.in'
3216 config.h: stamp-h ;
3217 stamp-h: config.h.in config.status
3218         ./config.status
3220 Makefile: Makefile.in config.status
3221         ./config.status
3223 config.status: configure
3224         ./config.status --recheck
3225 @end group
3226 @end example
3228 @noindent
3229 (Be careful if you copy these lines directly into your makefile, as you
3230 need to convert the indented lines to start with the tab character.)
3232 In addition, you should use
3234 @example
3235 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3236 @end example
3238 @noindent
3239 so @file{config.status} ensures that @file{config.h} is considered up to
3240 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3242 @xref{config.status Invocation}, for more examples of handling
3243 configuration-related dependencies.
3245 @node Configuration Headers
3246 @section Configuration Header Files
3247 @cindex Configuration Header
3248 @cindex @file{config.h}
3250 When a package contains more than a few tests that define C preprocessor
3251 symbols, the command lines to pass @option{-D} options to the compiler
3252 can get quite long.  This causes two problems.  One is that the
3253 @command{make} output is hard to visually scan for errors.  More
3254 seriously, the command lines can exceed the length limits of some
3255 operating systems.  As an alternative to passing @option{-D} options to
3256 the compiler, @command{configure} scripts can create a C header file
3257 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3258 macro selects this kind of output.  Though it can be called anywhere
3259 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3260 it right after @code{AC_INIT}.
3262 The package should @samp{#include} the configuration header file before
3263 any other header files, to prevent inconsistencies in declarations (for
3264 example, if it redefines @code{const}).
3266 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3267 option (or @option{-I..}; whichever directory contains @file{config.h}).
3268 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3269 the directory of the currently read file, i.e., the source directory, not
3270 the build directory.
3272 With the appropriate @option{-I} option, you can use
3273 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3274 because in the rare case when the source directory contains another
3275 @file{config.h}, the build directory should be searched first.
3278 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3279 @acindex{CONFIG_HEADERS}
3280 @cvindex HAVE_CONFIG_H
3281 This macro is one of the instantiating macros; see @ref{Configuration
3282 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3283 blank-or-newline-separated list @var{header} containing C preprocessor
3284 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3285 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3286 The usual name for @var{header} is @file{config.h}.
3288 If @var{header} already exists and its contents are identical to what
3289 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3290 making some changes in the configuration without needlessly causing
3291 object files that depend on the header file to be recompiled.
3293 Usually the input file is named @file{@var{header}.in}; however, you can
3294 override the input file name by appending to @var{header} a
3295 colon-separated list of input files.  For example, you might need to make
3296 the input file name acceptable to DOS variants:
3298 @example
3299 AC_CONFIG_HEADERS([config.h:config.hin])
3300 @end example
3302 @end defmac
3304 @defmac AH_HEADER
3305 @ahindex{HEADER}
3306 This macro is defined as the name of the first declared config header
3307 and undefined if no config headers have been declared up to this point.
3308 A third-party macro may, for example, require use of a config header
3309 without invoking AC_CONFIG_HEADERS twice, like this:
3311 @example
3312 AC_CONFIG_COMMANDS_PRE(
3313         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3314 @end example
3316 @end defmac
3318 @xref{Configuration Actions}, for more details on @var{header}.
3320 @menu
3321 * Header Templates::            Input for the configuration headers
3322 * autoheader Invocation::       How to create configuration templates
3323 * Autoheader Macros::           How to specify CPP templates
3324 @end menu
3326 @node Header Templates
3327 @subsection Configuration Header Templates
3328 @cindex Configuration Header Template
3329 @cindex Header templates
3330 @cindex @file{config.h.in}
3332 Your distribution should contain a template file that looks as you want
3333 the final header file to look, including comments, with @code{#undef}
3334 statements which are used as hooks.  For example, suppose your
3335 @file{configure.ac} makes these calls:
3337 @example
3338 AC_CONFIG_HEADERS([conf.h])
3339 AC_CHECK_HEADERS([unistd.h])
3340 @end example
3342 @noindent
3343 Then you could have code like the following in @file{conf.h.in}.
3344 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3345 to 1, if and only if the system has @file{unistd.h}.
3347 @example
3348 @group
3349 /* Define as 1 if you have unistd.h.  */
3350 #undef HAVE_UNISTD_H
3351 @end group
3352 @end example
3354 The format of the template file is stricter than what the C preprocessor
3355 is required to accept.  A directive line should contain only whitespace,
3356 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3357 instead of @samp{#undef}, or of comments on the same line as
3358 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3359 once.  Other preprocessor lines, such as @samp{#ifdef} or
3360 @samp{#include}, are copied verbatim from the template into the
3361 generated header.
3363 Since it is a tedious task to keep a template header up to date, you may
3364 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3366 During the instantiation of the header, each @samp{#undef} line in the
3367 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3368 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3369 been executed during the @command{configure} run, the @samp{#undef} line is
3370 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3371 on many systems, it can be implicitly defined by the compiler, and
3372 undefining it in the header would then break compilation of subsequent
3373 headers.)
3375 Currently, @emph{all} remaining @samp{#undef} lines in the header
3376 template are commented out, whether or not there was a corresponding
3377 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3378 for future releases of Autoconf.
3380 Generally speaking, since you should not use @samp{#define}, and you
3381 cannot guarantee whether a @samp{#undef} directive in the header
3382 template will be converted to a @samp{#define} or commented out in the
3383 generated header file, the template file cannot be used for conditional
3384 definition effects.  Consequently, if you need to use the construct
3386 @example
3387 @group
3388 #ifdef THIS
3389 # define THAT
3390 #endif
3391 @end group
3392 @end example
3394 @noindent
3395 you must place it outside of the template.
3396 If you absolutely need to hook it to the config header itself, please put
3397 the directives to a separate file, and @samp{#include} that file from the
3398 config header template.  If you are using @command{autoheader}, you would
3399 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3402 @node autoheader Invocation
3403 @subsection Using @command{autoheader} to Create @file{config.h.in}
3404 @cindex @command{autoheader}
3406 The @command{autoheader} program can create a template file of C
3407 @samp{#define} statements for @command{configure} to use.
3408 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3409 @file{configure} sources to determine the name of the template.
3410 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3411 input file name, @command{autoheader} uses the first one.)
3413 It is recommended that only one input file is used.  If you want to append
3414 a boilerplate code, it is preferable to use
3415 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3416 File @file{conf_post.h} is not processed during the configuration then,
3417 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3418 prepend a boilerplate code.
3420 In order to do its job, @command{autoheader} needs you to document all
3421 of the symbols that you might use.  Typically this is done via an
3422 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3423 is a literal symbol and whose third argument describes the symbol
3424 (@pxref{Defining Symbols}).  Alternatively, you can use
3425 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3426 suitable input file for a subsequent configuration header file.
3427 Symbols defined by Autoconf's builtin tests are already documented properly;
3428 you need to document only those that you
3429 define yourself.
3431 You might wonder why @command{autoheader} is needed: after all, why
3432 would @command{configure} need to ``patch'' a @file{config.h.in} to
3433 produce a @file{config.h} instead of just creating @file{config.h} from
3434 scratch?  Well, when everything rocks, the answer is just that we are
3435 wasting our time maintaining @command{autoheader}: generating
3436 @file{config.h} directly is all that is needed.  When things go wrong,
3437 however, you'll be thankful for the existence of @command{autoheader}.
3439 The fact that the symbols are documented is important in order to
3440 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3441 well-defined list of symbols that should be defined (or not) is
3442 also important for people who are porting packages to environments where
3443 @command{configure} cannot be run: they just have to @emph{fill in the
3444 blanks}.
3446 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3448 If you give @command{autoheader} an argument, it uses that file instead
3449 of @file{configure.ac} and writes the header file to the standard output
3450 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3451 argument of @option{-}, it reads the standard input instead of
3452 @file{configure.ac} and writes the header file to the standard output.
3454 @command{autoheader} accepts the following options:
3456 @table @option
3457 @item --help
3458 @itemx -h
3459 Print a summary of the command line options and exit.
3461 @item --version
3462 @itemx -V
3463 Print the version number of Autoconf and exit.
3465 @item --verbose
3466 @itemx -v
3467 Report processing steps.
3469 @item --debug
3470 @itemx -d
3471 Don't remove the temporary files.
3473 @item --force
3474 @itemx -f
3475 Remake the template file even if newer than its input files.
3477 @item --include=@var{dir}
3478 @itemx -I @var{dir}
3479 Append @var{dir} to the include path.  Multiple invocations accumulate.
3481 @item --prepend-include=@var{dir}
3482 @itemx -B @var{dir}
3483 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3485 @item --warnings=@var{category}
3486 @itemx -W @var{category}
3487 @evindex WARNINGS
3488 Report the warnings related to @var{category} (which can actually be a
3489 comma separated list).  Current categories include:
3491 @table @samp
3492 @item obsolete
3493 report the uses of obsolete constructs
3495 @item all
3496 report all the warnings
3498 @item none
3499 report none
3501 @item error
3502 treats warnings as errors
3504 @item no-@var{category}
3505 disable warnings falling into @var{category}
3506 @end table
3508 @end table
3512 @node Autoheader Macros
3513 @subsection Autoheader Macros
3514 @cindex Autoheader macros
3516 @command{autoheader} scans @file{configure.ac} and figures out which C
3517 preprocessor symbols it might define.  It knows how to generate
3518 templates for symbols defined by @code{AC_CHECK_HEADERS},
3519 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3520 symbol, you must define a template for it.  If there are missing
3521 templates, @command{autoheader} fails with an error message.
3523 The template for a @var{symbol} is created
3524 by @command{autoheader} from
3525 the @var{description} argument to an @code{AC_DEFINE};
3526 see @ref{Defining Symbols}.
3528 For special needs, you can use the following macros.
3531 @defmac AH_TEMPLATE (@var{key}, @var{description})
3532 @ahindex{TEMPLATE}
3533 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3534 generates standard templates just like @code{AC_DEFINE} when a
3535 @var{description} is given.
3537 For example:
3539 @example
3540 AH_TEMPLATE([CRAY_STACKSEG_END],
3541             [Define to one of _getb67, GETB67, getb67
3542              for Cray-2 and Cray-YMP systems.  This
3543              function is required for alloca.c support
3544              on those systems.])
3545 @end example
3547 @noindent
3548 generates the following template, with the description properly
3549 justified.
3551 @example
3552 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3553    Cray-YMP systems.  This function is required for alloca.c
3554    support on those systems.  */
3555 #undef CRAY_STACKSEG_END
3556 @end example
3557 @end defmac
3560 @defmac AH_VERBATIM (@var{key}, @var{template})
3561 @ahindex{VERBATIM}
3562 Tell @command{autoheader} to include the @var{template} as-is in the header
3563 template file.  This @var{template} is associated with the @var{key},
3564 which is used to sort all the different templates and guarantee their
3565 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3566 @end defmac
3569 @defmac AH_TOP (@var{text})
3570 @ahindex{TOP}
3571 Include @var{text} at the top of the header template file.
3572 @end defmac
3575 @defmac AH_BOTTOM (@var{text})
3576 @ahindex{BOTTOM}
3577 Include @var{text} at the bottom of the header template file.
3578 @end defmac
3581 Please note that @var{text} gets included ``verbatim'' to the template file,
3582 not to the resulting config header, so it can easily get mangled when the
3583 template is processed.  There is rarely a need for something other than
3585 @example
3586 AH_BOTTOM([#include <custom.h>])
3587 @end example
3591 @node Configuration Commands
3592 @section Running Arbitrary Configuration Commands
3593 @cindex Configuration commands
3594 @cindex Commands for configuration
3596 You can execute arbitrary commands before, during, and after
3597 @file{config.status} is run.  The three following macros accumulate the
3598 commands to run when they are called multiple times.
3599 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3600 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3602 @anchor{AC_CONFIG_COMMANDS}
3603 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3604 @acindex{CONFIG_COMMANDS}
3605 Specify additional shell commands to run at the end of
3606 @file{config.status}, and shell commands to initialize any variables
3607 from @command{configure}.  Associate the commands with @var{tag}.
3608 Since typically the @var{cmds} create a file, @var{tag} should
3609 naturally be the name of that file.  If needed, the directory hosting
3610 @var{tag} is created.  This macro is one of the instantiating macros;
3611 see @ref{Configuration Actions}.
3613 Here is an unrealistic example:
3614 @example
3615 fubar=42
3616 AC_CONFIG_COMMANDS([fubar],
3617                    [echo this is extra $fubar, and so on.],
3618                    [fubar=$fubar])
3619 @end example
3621 Here is a better one:
3622 @example
3623 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3624 @end example
3625 @end defmac
3627 The following two macros look similar, but in fact they are not of the same
3628 breed: they are executed directly by @file{configure}, so you cannot use
3629 @file{config.status} to rerun them.
3631 @c Yet it is good to leave them here.  The user sees them together and
3632 @c decides which best fits their needs.
3634 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3635 @acindex{CONFIG_COMMANDS_PRE}
3636 Execute the @var{cmds} right before creating @file{config.status}.
3638 This macro presents the last opportunity to call @code{AC_SUBST},
3639 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3640 @end defmac
3642 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3643 @acindex{CONFIG_COMMANDS_POST}
3644 Execute the @var{cmds} right after creating @file{config.status}.
3645 @end defmac
3650 @node Configuration Links
3651 @section Creating Configuration Links
3652 @cindex Configuration links
3653 @cindex Links for configuration
3655 You may find it convenient to create links whose destinations depend upon
3656 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3657 creation of relative symbolic links can be delicate when the package is
3658 built in a directory different from the source directory.
3660 @anchor{AC_CONFIG_LINKS}
3661 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3662   @ovar{init-cmds})
3663 @acindex{CONFIG_LINKS}
3664 @cindex Links
3665 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3666 the corresponding link name @var{dest}.  Makes a symbolic link if
3667 possible, otherwise a hard link if possible, otherwise a copy.  The
3668 @var{dest} and @var{source} names should be relative to the top level
3669 source or build directory.  This macro is one of the instantiating
3670 macros; see @ref{Configuration Actions}.
3672 For example, this call:
3674 @example
3675 AC_CONFIG_LINKS([host.h:config/$machine.h
3676                 object.h:config/$obj_format.h])
3677 @end example
3679 @noindent
3680 creates in the current directory @file{host.h} as a link to
3681 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3682 link to @file{@var{srcdir}/config/$obj_format.h}.
3684 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3685 impossible for @samp{config.status} to guess the links to establish.
3687 One can then run:
3688 @example
3689 ./config.status host.h object.h
3690 @end example
3691 @noindent
3692 to create the links.
3693 @end defmac
3697 @node Subdirectories
3698 @section Configuring Other Packages in Subdirectories
3699 @cindex Configure subdirectories
3700 @cindex Subdirectory configure
3702 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3703 makefiles in subdirectories.  However, @command{configure} scripts
3704 that control more than one independent package can use
3705 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3706 packages in subdirectories.
3708 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3709 @acindex{CONFIG_SUBDIRS}
3710 @ovindex subdirs
3711 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3712 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3713 be a literal, i.e., please do not use:
3715 @example
3716 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3717 if test "x$package_foo_enabled" = xyes; then
3718   my_subdirs="$my_subdirs foo"
3720 AC_CONFIG_SUBDIRS([$my_subdirs])
3721 @end example
3723 @noindent
3724 because this prevents @samp{./configure --help=recursive} from
3725 displaying the options of the package @code{foo}.  Instead, you should
3726 write:
3728 @example
3729 if test "x$package_foo_enabled" = xyes; then
3730   AC_CONFIG_SUBDIRS([foo])
3732 @end example
3734 If a given @var{dir} is not found at @command{configure} run time, a
3735 warning is reported; if the subdirectory is optional, write:
3737 @example
3738 if test -d "$srcdir/foo"; then
3739   AC_CONFIG_SUBDIRS([foo])
3741 @end example
3743 @c NB: Yes, below we mean configure.in, not configure.ac.
3744 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3745 of @command{configure}.  This is for packages that might use a
3746 non-Autoconf script @command{Configure}, which can't be called through a
3747 wrapper @command{configure} since it would be the same file on
3748 case-insensitive file systems.  Likewise, if a @var{dir} contains
3749 @file{configure.in} but no @command{configure}, the Cygnus
3750 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3752 The subdirectory @command{configure} scripts are given the same command
3753 line options that were given to this @command{configure} script, with minor
3754 changes if needed, which include:
3756 @itemize @minus
3757 @item
3758 adjusting a relative name for the cache file;
3760 @item
3761 adjusting a relative name for the source directory;
3763 @item
3764 propagating the current value of @code{$prefix}, including if it was
3765 defaulted, and if the default values of the top level and of the subdirectory
3766 @file{configure} differ.
3767 @end itemize
3769 This macro also sets the output variable @code{subdirs} to the list of
3770 directories @samp{@var{dir} @dots{}}.  Make rules can use
3771 this variable to determine which subdirectories to recurse into.
3773 This macro may be called multiple times.
3774 @end defmac
3776 @node Default Prefix
3777 @section Default Prefix
3778 @cindex Install prefix
3779 @cindex Prefix for install
3781 By default, @command{configure} sets the prefix for files it installs to
3782 @file{/usr/local}.  The user of @command{configure} can select a different
3783 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3784 There are two ways to change the default: when creating
3785 @command{configure}, and when running it.
3787 Some software packages might want to install in a directory other than
3788 @file{/usr/local} by default.  To accomplish that, use the
3789 @code{AC_PREFIX_DEFAULT} macro.
3791 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3792 @acindex{PREFIX_DEFAULT}
3793 Set the default installation prefix to @var{prefix} instead of
3794 @file{/usr/local}.
3795 @end defmac
3797 It may be convenient for users to have @command{configure} guess the
3798 installation prefix from the location of a related program that they
3799 have already installed.  If you wish to do that, you can call
3800 @code{AC_PREFIX_PROGRAM}.
3802 @anchor{AC_PREFIX_PROGRAM}
3803 @defmac AC_PREFIX_PROGRAM (@var{program})
3804 @acindex{PREFIX_PROGRAM}
3805 If the user did not specify an installation prefix (using the
3806 @option{--prefix} option), guess a value for it by looking for
3807 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3808 is found, set the prefix to the parent of the directory containing
3809 @var{program}, else default the prefix as described above
3810 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3811 @var{program} is @code{gcc} and the @env{PATH} contains
3812 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3813 @end defmac
3817 @c ======================================================== Existing tests
3819 @node Existing Tests
3820 @chapter Existing Tests
3822 These macros test for particular system features that packages might
3823 need or want to use.  If you need to test for a kind of feature that
3824 none of these macros check for, you can probably do it by calling
3825 primitive test macros with appropriate arguments (@pxref{Writing
3826 Tests}).
3828 These tests print messages telling the user which feature they're
3829 checking for, and what they find.  They cache their results for future
3830 @command{configure} runs (@pxref{Caching Results}).
3832 Some of these macros set output variables.  @xref{Makefile
3833 Substitutions}, for how to get their values.  The phrase ``define
3834 @var{name}'' is used below as a shorthand to mean ``define the C
3835 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3836 Symbols}, for how to get those symbol definitions into your program.
3838 @menu
3839 * Common Behavior::             Macros' standard schemes
3840 * Alternative Programs::        Selecting between alternative programs
3841 * Files::                       Checking for the existence of files
3842 * Libraries::                   Library archives that might be missing
3843 * Library Functions::           C library functions that might be missing
3844 * Header Files::                Header files that might be missing
3845 * Declarations::                Declarations that may be missing
3846 * Structures::                  Structures or members that might be missing
3847 * Types::                       Types that might be missing
3848 * Compilers and Preprocessors::  Checking for compiling programs
3849 * System Services::             Operating system services
3850 * C and Posix Variants::        Kludges for C and Posix variants
3851 * Erlang Libraries::            Checking for the existence of Erlang libraries
3852 @end menu
3854 @node Common Behavior
3855 @section Common Behavior
3856 @cindex Common autoconf behavior
3858 Much effort has been expended to make Autoconf easy to learn.  The most
3859 obvious way to reach this goal is simply to enforce standard interfaces
3860 and behaviors, avoiding exceptions as much as possible.  Because of
3861 history and inertia, unfortunately, there are still too many exceptions
3862 in Autoconf; nevertheless, this section describes some of the common
3863 rules.
3865 @menu
3866 * Standard Symbols::            Symbols defined by the macros
3867 * Default Includes::            Includes used by the generic macros
3868 @end menu
3870 @node Standard Symbols
3871 @subsection Standard Symbols
3872 @cindex Standard symbols
3874 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3875 their test transform their @var{argument} values to a standard alphabet.
3876 First, @var{argument} is converted to upper case and any asterisks
3877 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3878 that are not alphanumeric are converted to underscores.
3880 For instance,
3882 @example
3883 AC_CHECK_TYPES([struct $Expensive*])
3884 @end example
3886 @noindent
3887 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3888 succeeds.
3891 @node Default Includes
3892 @subsection Default Includes
3893 @cindex Default includes
3894 @cindex Includes, default
3895 @hdrindex{assert.h}
3896 @hdrindex{ctype.h}
3897 @hdrindex{errno.h}
3898 @hdrindex{float.h}
3899 @hdrindex{iso646.h}
3900 @hdrindex{limits.h}
3901 @hdrindex{locale.h}
3902 @hdrindex{math.h}
3903 @hdrindex{setjmp.h}
3904 @hdrindex{signal.h}
3905 @hdrindex{stdarg.h}
3906 @hdrindex{stddef.h}
3907 @hdrindex{stdio.h}
3908 @hdrindex{stdlib.h}
3909 @hdrindex{string.h}
3910 @hdrindex{time.h}
3911 @hdrindex{wchar.h}
3912 @hdrindex{wctype.h}
3914 Test programs frequently need to include headers that may or may not be
3915 available on the system whose features are being tested.  Each test can
3916 use all the preprocessor macros that have been @code{AC_DEFINE}d by
3917 previous tests, so for example one may write
3919 @example
3920 @group
3921 #include <time.h>
3922 #ifdef HAVE_SYS_TIME_H
3923 # include <sys/time.h>
3924 #endif
3925 @end group
3926 @end example
3928 @noindent
3929 if @file{sys/time.h} has already been tested for.
3931 All hosted environments that are still of interest for portable code
3932 provide all of the headers specified in ISO C90 (as amended in 1995):
3933 @file{assert.h}, @file{ctype.h}, @file{errno.h}, @file{float.h},
3934 @file{iso646.h}, @file{limits.h}, @file{locale.h}, @file{math.h},
3935 @file{setjmp.h}, @file{signal.h}, @file{stdarg.h}, @file{stddef.h},
3936 @file{stdio.h}, @file{stdlib.h}, @file{string.h}, @file{time.h},
3937 @file{wchar.h}, and @file{wctype.h}.  Most programs can safely include
3938 these headers unconditionally.  All other headers, including all headers
3939 from later revisions of the C standard, need to be tested for
3940 (@pxref{Header Files}).
3942 If your program needs to be portable to a @emph{freestanding}
3943 environment, such as an embedded OS that doesn't provide all of the
3944 facilities of the C90 standard library, you may need to test for some of
3945 the above headers as well.  Note that many Autoconf macros internally
3946 assume that the complete set of C90 headers are available.
3948 Most generic macros use the following macro to provide a default set
3949 of includes:
3951 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3952 @acindex{INCLUDES_DEFAULT}
3953 Expand to @var{include-directives} if present and nonempty, otherwise to:
3955 @example
3956 @group
3957 #include <stddef.h>
3958 #include <stdio.h>
3959 #include <stdlib.h>
3960 #include <string.h>
3961 #ifdef HAVE_SYS_TYPES_H
3962 # include <sys/types.h>
3963 #endif
3964 #ifdef HAVE_SYS_STAT_H
3965 # include <sys/stat.h>
3966 #endif
3967 #ifdef HAVE_STRINGS_H
3968 # include <strings.h>
3969 #endif
3970 #ifdef HAVE_INTTYPES_H
3971 # include <inttypes.h>
3972 #endif
3973 #ifdef HAVE_STDINT_H
3974 # include <stdint.h>
3975 #endif
3976 #ifdef HAVE_UNISTD_H
3977 # include <unistd.h>
3978 #endif
3979 @end group
3980 @end example
3982 Using this macro without @var{include-directives} has the side effect of
3983 checking for @file{sys/types.h}, @file{sys/stat.h}, @file{strings.h},
3984 @file{inttypes.h}, @file{stdint.h}, and @file{unistd.h}, as if by
3985 @code{AC_CHECK_HEADERS}.  For backward compatibility's sake, it also
3986 unconditionally defines @code{HAVE_STRING_H}, @code{HAVE_STDLIB_H}, and
3987 @code{STDC_HEADERS}.  New code should not make use of these preprocessor
3988 macros.
3989 @end defmac
3991 @defmac AC_CHECK_INCLUDES_DEFAULT
3992 @acindex{CHECK_INCLUDES_DEFAULT}
3993 Check for all the headers that @code{AC_INCLUDES_DEFAULT} would check
3994 for as a side-effect, if this has not already happened.
3996 This macro mainly exists so that @code{autoupdate} can replace certain
3997 obsolete constructs with it. You should not need to use it yourself; in
3998 fact, it is likely to be safe to delete it from any script in which it
3999 appears.  (@code{autoupdate} does not know whether preprocessor macros
4000 such as @code{HAVE_STDINT_H} are used in the program, nor whether they
4001 would get defined as a side-effect of other checks.)
4002 @end defmac
4004 @node Alternative Programs
4005 @section Alternative Programs
4006 @cindex Programs, checking
4008 These macros check for the presence or behavior of particular programs.
4009 They are used to choose between several alternative programs and to
4010 decide what to do once one has been chosen.  If there is no macro
4011 specifically defined to check for a program you need, and you don't need
4012 to check for any special properties of it, then you can use one of the
4013 general program-check macros.
4015 @menu
4016 * Particular Programs::         Special handling to find certain programs
4017 * Generic Programs::            How to find other programs
4018 @end menu
4020 @node Particular Programs
4021 @subsection Particular Program Checks
4023 These macros check for particular programs---whether they exist, and
4024 in some cases whether they support certain features.
4026 @defmac AC_PROG_AWK
4027 @acindex{PROG_AWK}
4028 @ovindex AWK
4029 @caindex prog_AWK
4030 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
4031 order, and set output variable @code{AWK} to the first one that is found.
4032 It tries @code{gawk} first because that is reported to be the
4033 best implementation.  The result can be overridden by setting the
4034 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
4036 Using this macro is sufficient to avoid the pitfalls of traditional
4037 @command{awk} (@pxref{awk, , Limitations of Usual Tools}).
4038 @end defmac
4040 @defmac AC_PROG_GREP
4041 @acindex{PROG_GREP}
4042 @ovindex GREP
4043 @caindex prog_GREP
4044 Look for the best available @code{grep} or @code{ggrep} that accepts the
4045 longest input lines possible, and that supports multiple @option{-e} options.
4046 Set the output variable @code{GREP} to whatever is chosen.
4047 @xref{grep, , Limitations of Usual Tools}, for more information about
4048 portability problems with the @command{grep} command family.  The result
4049 can be overridden by setting the @code{GREP} variable and is cached in the
4050 @code{ac_cv_path_GREP} variable.
4051 @end defmac
4053 @defmac AC_PROG_EGREP
4054 @acindex{PROG_EGREP}
4055 @ovindex EGREP
4056 @caindex prog_EGREP
4057 Check whether @code{$GREP -E} works, or else look for the best available
4058 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
4059 Set the output variable @code{EGREP} to whatever is chosen.  The result
4060 can be overridden by setting the @code{EGREP} variable and is cached in the
4061 @code{ac_cv_path_EGREP} variable.
4062 @end defmac
4064 @defmac AC_PROG_FGREP
4065 @acindex{PROG_FGREP}
4066 @ovindex FGREP
4067 @caindex prog_FGREP
4068 Check whether @code{$GREP -F} works, or else look for the best available
4069 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
4070 Set the output variable @code{FGREP} to whatever is chosen.  The result
4071 can be overridden by setting the @code{FGREP} variable and is cached in the
4072 @code{ac_cv_path_FGREP} variable.
4073 @end defmac
4075 @defmac AC_PROG_INSTALL
4076 @acindex{PROG_INSTALL}
4077 @ovindex INSTALL
4078 @ovindex INSTALL_PROGRAM
4079 @ovindex INSTALL_DATA
4080 @ovindex INSTALL_SCRIPT
4081 @caindex path_install
4082 Set output variable @code{INSTALL} to the name of a BSD-compatible
4083 @command{install} program, if one is found in the current @env{PATH}.
4084 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
4085 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
4086 default directories) to determine @var{dir} (@pxref{Output}).  Also set
4087 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
4088 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
4090 @samp{@@INSTALL@@} is special, as its value may vary for different
4091 configuration files.
4093 This macro screens out various instances of @command{install} known not to
4094 work.  It prefers to find a C program rather than a shell script, for
4095 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
4096 but that name is obsolete because some @command{make} programs have a rule
4097 that creates @file{install} from it if there is no makefile.  Further, this
4098 macro requires @command{install} to be able to install multiple files into a
4099 target directory in a single invocation.
4101 Autoconf comes with a copy of @file{install-sh} that you can use.  If
4102 you use @code{AC_PROG_INSTALL}, you must include either
4103 @file{install-sh} or @file{install.sh} in your distribution; otherwise
4104 @command{configure} produces an error message saying it can't find
4105 them---even if the system you're on has a good @command{install} program.
4106 This check is a safety measure to prevent you from accidentally leaving
4107 that file out, which would prevent your package from installing on
4108 systems that don't have a BSD-compatible @command{install} program.
4110 If you need to use your own installation program because it has features
4111 not found in standard @command{install} programs, there is no reason to use
4112 @code{AC_PROG_INSTALL}; just put the file name of your program into your
4113 @file{Makefile.in} files.
4115 The result of the test can be overridden by setting the variable
4116 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4117 @end defmac
4119 @defmac AC_PROG_MKDIR_P
4120 @acindex{PROG_MKDIR_P}
4121 @ovindex MKDIR_P
4122 @caindex path_mkdir
4123 Set output variable @code{MKDIR_P} to a program that ensures that for
4124 each argument, a directory named by this argument exists, creating it
4125 and its parent directories if needed, and without race conditions when
4126 two instances of the program attempt to make the same directory at
4127 nearly the same time.
4129 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
4130 falls back on invoking @command{install-sh} with the @option{-d} option,
4131 so your package should
4132 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4133 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4134 is vulnerable to race conditions, so if you want to support parallel
4135 installs from
4136 different packages into the same directory you need to make sure you
4137 have an up-to-date @file{install-sh}.  In particular, be careful about
4138 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4140 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4141 in M4sh}), but it sets an output variable intended for use in other
4142 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4143 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
4144 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4145 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4146 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4147 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4148 Finally, @code{AS_MKDIR_P} does not check for race condition
4149 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4151 @samp{@@MKDIR_P@@} is special, as its value may vary for different
4152 configuration files.
4154 The result of the test can be overridden by setting the variable
4155 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4156 @end defmac
4158 @anchor{AC_PROG_LEX}
4159 @defmac AC_PROG_LEX
4160 @acindex{PROG_LEX}
4161 @ovindex LEX
4162 @ovindex LEXLIB
4163 @cvindex YYTEXT_POINTER
4164 @ovindex LEX_OUTPUT_ROOT
4165 @caindex prog_LEX
4166 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
4167 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
4168 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
4169 @option{-ll}, if found.  If neither variant is available, set @code{LEX}
4170 to @samp{:}; for packages that ship the generated @file{file.yy.c}
4171 alongside the source @file{file.l}, this default allows users without a
4172 lexer generator to still build the package even if the timestamp for
4173 @file{file.l} is inadvertently changed.
4175 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
4176 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
4177 the base of the file name that the lexer generates; usually
4178 @file{lex.yy}, but sometimes something else.  These results vary
4179 according to whether @code{lex} or @code{flex} is being used.
4181 You are encouraged to use Flex in your sources, since it is both more
4182 pleasant to use than plain Lex and the C source it produces is portable.
4183 In order to ensure portability, however, you must either provide a
4184 function @code{yywrap} or, if you don't use it (e.g., your scanner has
4185 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
4186 statement in the scanner's source.  Once this done, the scanner is
4187 portable (unless @emph{you} felt free to use nonportable constructs) and
4188 does not depend on any library.  In this case, and in this case only, it
4189 is suggested that you use this Autoconf snippet:
4191 @example
4192 AC_PROG_LEX
4193 if test "x$LEX" != xflex; then
4194   LEX="$SHELL $missing_dir/missing flex"
4195   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4196   AC_SUBST([LEXLIB], [''])
4198 @end example
4200 The shell script @command{missing} can be found in the Automake
4201 distribution.
4203 Remember that the user may have supplied an alternate location in
4204 @env{LEX}, so if Flex is required, it is better to check that the user
4205 provided something sufficient by parsing the output of @samp{$LEX
4206 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4208 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
4209 (indirectly) this macro twice, which causes an annoying but benign
4210 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
4211 of Automake will fix this issue; meanwhile, just ignore this message.
4213 As part of running the test, this macro may delete any file in the
4214 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
4216 The result of this test can be influenced by setting the variable
4217 @code{LEX} or the cache variable @code{ac_cv_prog_LEX}.
4218 @end defmac
4220 @anchor{AC_PROG_LN_S}
4221 @defmac AC_PROG_LN_S
4222 @acindex{PROG_LN_S}
4223 @ovindex LN_S
4224 If @samp{ln -s} works on the current file system (the operating system
4225 and file system support symbolic links), set the output variable
4226 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4227 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -pR}.
4229 If you make a link in a directory other than the current directory, its
4230 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4231 create links using @samp{$(LN_S)}, either find out which form is used
4232 and adjust the arguments, or always invoke @code{ln} in the directory
4233 where the link is to be created.
4235 In other words, it does not work to do:
4236 @example
4237 $(LN_S) foo /x/bar
4238 @end example
4240 Instead, do:
4242 @example
4243 (cd /x && $(LN_S) foo bar)
4244 @end example
4245 @end defmac
4247 @defmac AC_PROG_RANLIB
4248 @acindex{PROG_RANLIB}
4249 @ovindex RANLIB
4250 @c @caindex prog_RANLIB
4251 @c @caindex prog_ac_ct_RANLIB
4252 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4253 is found, and otherwise to @samp{:} (do nothing).
4254 @end defmac
4256 @defmac AC_PROG_SED
4257 @acindex{PROG_SED}
4258 @ovindex SED
4259 @caindex path_SED
4260 Set output variable @code{SED} to a Sed implementation that conforms to
4261 Posix and does not have arbitrary length limits.  Report an error if no
4262 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4263 information about portability problems with Sed.
4265 The result of this test can be overridden by setting the @code{SED} variable
4266 and is cached in the @code{ac_cv_path_SED} variable.
4267 @end defmac
4269 @defmac AC_PROG_YACC
4270 @acindex{PROG_YACC}
4271 @evindex YACC
4272 @evindex YFLAGS
4273 @ovindex YACC
4274 @caindex prog_YACC
4275 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4276 -o y.tab.c}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4277 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4278 The result of this test can be influenced by setting the variable
4279 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4280 @end defmac
4282 @node Generic Programs
4283 @subsection Generic Program and File Checks
4285 These macros are used to find programs not covered by the ``particular''
4286 test macros.  If you need to check the behavior of a program as well as
4287 find out whether it is present, you have to write your own test for it
4288 (@pxref{Writing Tests}).  By default, these macros use the environment
4289 variable @env{PATH}.  If you need to check for a program that might not
4290 be in the user's @env{PATH}, you can pass a modified path to use
4291 instead, like this:
4293 @example
4294 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4295              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4296 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4297 @end example
4299 You are strongly encouraged to declare the @var{variable} passed to
4300 @code{AC_CHECK_PROG} etc.@: as precious.  @xref{Setting Output Variables},
4301 @code{AC_ARG_VAR}, for more details.
4303 @anchor{AC_CHECK_PROG}
4304 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4305   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4306   @ovar{reject})
4307 @acindex{CHECK_PROG}
4308 @caindex prog_@var{variable}
4309 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4310 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4311 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4312 absolute file name) even if it is the first found in the search path; in
4313 that case, set @var{variable} using the absolute file name of the
4314 @var{prog-to-check-for} found that is not @var{reject}.  If
4315 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4316 @var{variable}.  The result of this test can be overridden by setting the
4317 @var{variable} variable or the cache variable
4318 @code{ac_cv_prog_@var{variable}}.
4319 @end defmac
4321 @anchor{AC_CHECK_PROGS}
4322 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4323   @ovar{value-if-not-found}, @dvar{path, $PATH})
4324 @acindex{CHECK_PROGS}
4325 @caindex prog_@var{variable}
4326 Check for each program in the blank-separated list
4327 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4328 @var{variable} to the name of that program.  Otherwise, continue
4329 checking the next program in the list.  If none of the programs in the
4330 list are found, set @var{variable} to @var{value-if-not-found}; if
4331 @var{value-if-not-found} is not specified, the value of @var{variable}
4332 is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4333 this test can be overridden by setting the @var{variable} variable or the
4334 cache variable @code{ac_cv_prog_@var{variable}}.
4335 @end defmac
4337 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4338   @ovar{value-if-not-found}, @dvar{path, $PATH})
4339 @acindex{CHECK_TARGET_TOOL}
4340 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4341 with a prefix of the target type as determined by
4342 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4343 If the tool cannot be found with a prefix, and if the build and target
4344 types are equal, then it is also searched for without a prefix.
4346 As noted in @ref{Specifying Target Triplets}, the
4347 target is rarely specified, because most of the time it is the same
4348 as the host: it is the type of system for which any compiler tool in
4349 the package produces code.  What this macro looks for is,
4350 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4351 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4352 uses to produce objects, archives or executables}.
4353 @end defmac
4355 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4356   @ovar{value-if-not-found}, @dvar{path, $PATH})
4357 @acindex{CHECK_TOOL}
4358 @c @caindex prog_@var{VARIABLE}
4359 @c @caindex prog_ac_ct_@var{VARIABLE}
4360 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4361 with a prefix of the host type as specified by @option{--host}, followed by a
4362 dash.  For example, if the user runs
4363 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4364 @example
4365 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4366 @end example
4367 @noindent
4368 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4369 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4370 @var{path}, or to @samp{:} if neither program exists.
4372 When cross-compiling, this macro will issue a warning if no program
4373 prefixed with the host type could be found.
4374 For more information, see @ref{Specifying Target Triplets}.
4375 @end defmac
4377 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4378   @ovar{value-if-not-found}, @dvar{path, $PATH})
4379 @acindex{CHECK_TARGET_TOOLS}
4380 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4381 @var{progs-to-check-for} are checked with a prefix of the target type as
4382 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4383 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4384 prefix, and if the build and target types are equal, then the first one
4385 without a prefix is used.  If a tool is found, set @var{variable} to
4386 the name of that program.  If none of the tools in the list are found,
4387 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4388 is not specified, the value of @var{variable} is not changed.  Calls
4389 @code{AC_SUBST} for @var{variable}.
4390 @end defmac
4392 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4393   @ovar{value-if-not-found}, @dvar{path, $PATH})
4394 @acindex{CHECK_TOOLS}
4395 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4396 @var{progs-to-check-for} are checked with a prefix of the host type as
4397 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4398 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4399 prefix, then the first one without a prefix is used.  If a tool is found,
4400 set @var{variable} to the name of that program.  If none of the tools in
4401 the list are found, set @var{variable} to @var{value-if-not-found}; if
4402 @var{value-if-not-found} is not specified, the value of @var{variable}
4403 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4405 When cross-compiling, this macro will issue a warning if no program
4406 prefixed with the host type could be found.
4407 For more information, see @ref{Specifying Target Triplets}.
4408 @end defmac
4410 @anchor{AC_PATH_PROG}
4411 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4412   @ovar{value-if-not-found}, @dvar{path, $PATH})
4413 @acindex{PATH_PROG}
4414 @caindex path_@var{variable}
4415 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4416 name of @var{prog-to-check-for} if found.  The result of this test
4417 can be overridden by setting the @var{variable} variable.  A positive
4418 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4419 variable.
4420 @end defmac
4422 @anchor{AC_PATH_PROGS}
4423 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4424   @ovar{value-if-not-found}, @dvar{path, $PATH})
4425 @acindex{PATH_PROGS}
4426 @caindex path_@var{variable}
4427 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4428 are found, set @var{variable} to the absolute name of the program
4429 found.  The result of this test can be overridden by setting the
4430 @var{variable} variable.  A positive result of this test is cached in
4431 the @code{ac_cv_path_@var{variable}} variable.
4432 @end defmac
4434 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4435   @var{progs-to-check-for}, @var{feature-test}, @
4436   @ovar{action-if-not-found}, @dvar{path, $PATH})
4437 @acindex{PATH_PROGS_FEATURE_CHECK}
4438 @caindex path_@var{variable}
4439 @vrindex ac_path_@var{variable}
4440 @vrindex ac_path_@var{variable}_found
4441 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4442 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4443 its value.  Otherwise, check for each program in the blank-separated
4444 list @var{progs-to-check-for} existing in @var{path}.  For each program
4445 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4446 set to the absolute name of the candidate program.  If no invocation of
4447 @var{feature-test} sets the shell variable
4448 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4449 executed.  @var{feature-test} will be run even when
4450 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4451 choose a better candidate found later in @var{path}; to accept the
4452 current setting and bypass all further checks, @var{feature-test} can
4453 execute @code{ac_path_@var{variable}_found=:}.
4455 Note that this macro has some subtle differences from
4456 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4457 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4458 particular, @var{variable} is not set to the final value of
4459 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4460 run.  Also, on failure, any action can be performed, whereas
4461 @code{AC_CHECK_PROGS} only performs
4462 @code{@var{variable}=@var{value-if-not-found}}.
4464 Here is an example, similar to what Autoconf uses in its own configure
4465 script.  It will search for an implementation of @command{m4} that
4466 supports the @code{indir} builtin, even if it goes by the name
4467 @command{gm4} or is not the first implementation on @env{PATH}.
4469 @example
4470 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4471   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4472     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4473       test "x$m4out" = x0 \
4474       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4475     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4476 AC_SUBST([M4], [$ac_cv_path_M4])
4477 @end example
4478 @end defmac
4480 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4481   @ovar{value-if-not-found}, @dvar{path, $PATH})
4482 @acindex{PATH_TARGET_TOOL}
4483 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4484 name of the program if it is found.
4485 @end defmac
4487 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4488   @ovar{value-if-not-found}, @dvar{path, $PATH})
4489 @acindex{PATH_TOOL}
4490 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4491 name of the program if it is found.
4493 When cross-compiling, this macro will issue a warning if no program
4494 prefixed with the host type could be found.
4495 For more information, see @ref{Specifying Target Triplets}.
4496 @end defmac
4499 @node Files
4500 @section Files
4501 @cindex File, checking
4503 You might also need to check for the existence of files.  Before using
4504 these macros, ask yourself whether a runtime test might not be a better
4505 solution.  Be aware that, like most Autoconf macros, they test a feature
4506 of the host machine, and therefore, they die when cross-compiling.
4508 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4509   @ovar{action-if-not-found})
4510 @acindex{CHECK_FILE}
4511 @caindex file_@var{file}
4512 Check whether file @var{file} exists on the native system.  If it is
4513 found, execute @var{action-if-found}, otherwise do
4514 @var{action-if-not-found}, if given.  Cache the result of this test
4515 in the @code{ac_cv_file_@var{file}} variable, with characters not
4516 suitable for a variable name mapped to underscores.
4517 @end defmac
4519 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4520   @ovar{action-if-not-found})
4521 @acindex{CHECK_FILES}
4522 @caindex file_@var{file}
4523 For each file listed in @var{files}, execute @code{AC_CHECK_FILE}
4524 and perform either @var{action-if-found} or @var{action-if-not-found}.
4525 Like @code{AC_CHECK_FILE}, this defines @samp{HAVE_@var{file}}
4526 (@pxref{Standard Symbols}) for each file found and caches the results of
4527 each test in the @code{ac_cv_file_@var{file}} variable, with characters
4528 not suitable for a variable name mapped to underscores.
4529 @end defmac
4532 @node Libraries
4533 @section Library Files
4534 @cindex Library, checking
4536 The following macros check for the presence of certain C, C++, Fortran,
4537 or Go library archive files.
4539 @anchor{AC_CHECK_LIB}
4540 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4541   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4542 @acindex{CHECK_LIB}
4543 @caindex lib_@var{library}_@var{function}
4544 Test whether the library @var{library} is available by trying to link
4545 a test program that calls function @var{function} with the library.
4546 @var{function} should be a function provided by the library.
4547 Use the base
4548 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4549 the @var{library} argument.
4551 @var{action-if-found} is a list of shell commands to run if the link
4552 with the library succeeds; @var{action-if-not-found} is a list of shell
4553 commands to run if the link fails.  If @var{action-if-found} is not
4554 specified, the default action prepends @option{-l@var{library}} to
4555 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4556 capitals).  This macro is intended to support building @code{LIBS} in
4557 a right-to-left (least-dependent to most-dependent) fashion such that
4558 library dependencies are satisfied as a natural side effect of
4559 consecutive tests.  Linkers are sensitive to library ordering
4560 so the order in which @code{LIBS} is generated is important to reliable
4561 detection of libraries.
4563 If linking with @var{library} results in unresolved symbols that would
4564 be resolved by linking with additional libraries, give those libraries
4565 as the @var{other-libraries} argument, separated by spaces:
4566 e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4567 that @var{library} is present, because linking the test program can
4568 fail with unresolved symbols.  The @var{other-libraries} argument
4569 should be limited to cases where it is desirable to test for one library
4570 in the presence of another that is not already in @code{LIBS}.
4572 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4573 in some common cases.  Many standard functions like @code{gethostbyname}
4574 appear in the standard C library on some hosts, and in special libraries
4575 like @code{nsl} on other hosts.  On some hosts the special libraries
4576 contain variant implementations that you may not want to use.  These
4577 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4578 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4580 The result of this test is cached in the
4581 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4582 @end defmac
4584 @anchor{AC_SEARCH_LIBS}
4585 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4586   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4587 @acindex{SEARCH_LIBS}
4588 @caindex search_@var{function}
4589 Search for a library defining @var{function} if it's not already
4590 available.  This equates to calling
4591 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4592 no libraries, then for each library listed in @var{search-libs}.
4594 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4595 to contain @var{function}, and run @var{action-if-found}.  If the
4596 function is not found, run @var{action-if-not-found}.
4598 If linking with @var{library} results in unresolved symbols that would
4599 be resolved by linking with additional libraries, give those libraries
4600 as the @var{other-libraries} argument, separated by spaces:
4601 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4602 that @var{function} is present, because linking the test program
4603 always fails with unresolved symbols.
4605 The result of this test is cached in the
4606 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4607 @var{function} is already available, as @samp{no} if no library
4608 containing @var{function} was found, otherwise as the
4609 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4610 @end defmac
4614 @node Library Functions
4615 @section Library Functions
4617 The following macros check for particular C library functions.
4618 If there is no macro specifically defined to check for a function you need,
4619 and you don't need to check for any special properties of
4620 it, then you can use one of the general function-check macros.
4622 @menu
4623 * Function Portability::        Pitfalls with usual functions
4624 * Particular Functions::        Special handling to find certain functions
4625 * Generic Functions::           How to find other functions
4626 @end menu
4628 @node Function Portability
4629 @subsection Portability of C Functions
4630 @cindex Portability of C functions
4631 @cindex C function portability
4633 Most usual functions can either be missing, or be buggy, or be limited
4634 on some architectures.  This section tries to make an inventory of these
4635 portability issues.  By definition, this list always requires
4636 additions.  A much more complete list is maintained by the Gnulib
4637 project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4638 Current Posix Functions, gnulib, GNU gnulib}, @ref{Legacy Function
4639 Substitutes, , Legacy Functions, gnulib, GNU gnulib}, and @ref{Glibc
4640 Function Substitutes, , Glibc Functions, gnulib, GNU gnulib}.  Please
4641 help us keep the gnulib list as complete as possible.
4643 @table @asis
4644 @item @code{exit}
4645 @c @fuindex exit
4646 @prindex @code{exit}
4647 On ancient hosts, @code{exit} returned @code{int}.
4648 This is because @code{exit} predates @code{void}, and there was a long
4649 tradition of it returning @code{int}.
4651 On current hosts, the problem more likely is that @code{exit} is not
4652 declared, due to C++ problems of some sort or another.  For this reason
4653 we suggest that test programs not invoke @code{exit}, but return from
4654 @code{main} instead.
4656 @item @code{free}
4657 @c @fuindex free
4658 @prindex @code{free}
4659 The C standard says a call @code{free (NULL)} does nothing, but
4660 some old systems don't support this (e.g., NextStep).
4662 @item @code{isinf}
4663 @itemx @code{isnan}
4664 @c @fuindex isinf
4665 @c @fuindex isnan
4666 @prindex @code{isinf}
4667 @prindex @code{isnan}
4668 In C99 and later, @code{isinf} and @code{isnan} are
4669 macros.  On some systems just macros are available
4670 (e.g., HP-UX and Solaris 10), on
4671 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4672 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4673 these functions are declared in nonstandard headers like
4674 @code{<sunmath.h>} and defined in non-default libraries like
4675 @option{-lm} or @option{-lsunmath}.
4677 In C99 and later, @code{isinf} and @code{isnan} macros work correctly with
4678 @code{long double} arguments, but pre-C99 systems that use functions
4679 typically assume @code{double} arguments.  On such a system,
4680 @code{isinf} incorrectly returns true for a finite @code{long double}
4681 argument that is outside the range of @code{double}.
4683 The best workaround for these issues is to use gnulib modules
4684 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4685 solution involves code like the following.
4687 @smallexample
4688 #include <math.h>
4690 #ifndef isnan
4691 # define isnan(x) \
4692     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4693      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4694      : isnan_f (x))
4695 static int isnan_f  (float       x) @{ return x != x; @}
4696 static int isnan_d  (double      x) @{ return x != x; @}
4697 static int isnan_ld (long double x) @{ return x != x; @}
4698 #endif
4700 #ifndef isinf
4701 # define isinf(x) \
4702     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4703      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4704      : isinf_f (x))
4705 static int isinf_f  (float       x)
4706 @{ return !isnan (x) && isnan (x - x); @}
4707 static int isinf_d  (double      x)
4708 @{ return !isnan (x) && isnan (x - x); @}
4709 static int isinf_ld (long double x)
4710 @{ return !isnan (x) && isnan (x - x); @}
4711 #endif
4712 @end smallexample
4714 Some optimizing compilers mishandle these definitions, but systems with that bug
4715 typically have many other floating point corner-case compliance problems
4716 anyway, so it's probably not worth worrying about.
4718 @item @code{malloc}
4719 @c @fuindex malloc
4720 @prindex @code{malloc}
4721 The C standard says a call @code{malloc (0)} is implementation
4722 dependent.  It can return either @code{NULL} or a new non-null pointer.
4723 The latter is more common (e.g., the GNU C Library) but is by
4724 no means universal.  @code{AC_FUNC_MALLOC}
4725 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4727 @item @code{putenv}
4728 @c @fuindex putenv
4729 @prindex @code{putenv}
4730 Posix prefers @code{setenv} to @code{putenv}; among other things,
4731 @code{putenv} is not required of all Posix implementations, but
4732 @code{setenv} is.
4734 Posix specifies that @code{putenv} puts the given string directly in
4735 @code{environ}, but some systems make a copy of it instead (e.g.,
4736 glibc 2.0, or BSD).  And when a copy is made, @code{unsetenv} might
4737 not free it, causing a memory leak (e.g., FreeBSD 4).
4739 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4740 environment, but this is not standard usage and it dumps core
4741 on some systems (e.g., AIX).
4743 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4744 environment, rather than inserting it with an empty value.
4746 @item @code{realloc}
4747 @c @fuindex realloc
4748 @prindex @code{realloc}
4749 The C standard says a call @code{realloc (NULL, size)} is equivalent
4750 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4751 NextStep).
4753 @item @code{signal} handler
4754 @c @fuindex signal
4755 @prindex @code{signal}
4756 @prindex @code{sigaction}
4757 Normally @code{signal} takes a handler function with a return type of
4758 @code{void}, but some old systems required @code{int} instead.  Any
4759 actual @code{int} value returned is not used; this is only a
4760 difference in the function prototype demanded.
4762 All systems we know of in current use return @code{void}.  The
4763 @code{int} was to support K&R C, where of course @code{void} is not
4764 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4765 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4766 all cases.
4768 In most cases, it is more robust to use @code{sigaction} when it is
4769 available, rather than @code{signal}.
4771 @item @code{snprintf}
4772 @c @fuindex snprintf
4773 @prindex @code{snprintf}
4774 @c @fuindex vsnprintf
4775 @prindex @code{vsnprintf}
4776 In C99 and later, if the output array isn't big enough
4777 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4778 truncate the output and return the number of bytes that ought to have
4779 been produced.  Some older systems return the truncated length (e.g.,
4780 GNU C Library 2.0.x or IRIX 6.5), some a negative value
4781 (e.g., earlier GNU C Library versions), and some the buffer
4782 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4783 older systems ignore the length and overrun the buffer (e.g., 64-bit
4784 Solaris 7).
4786 @item @code{sprintf}
4787 @c @fuindex sprintf
4788 @prindex @code{sprintf}
4789 @c @fuindex vsprintf
4790 @prindex @code{vsprintf}
4791 The C standard says @code{sprintf} and @code{vsprintf} return the
4792 number of bytes written.  On some ancient systems (SunOS 4 for
4793 instance) they return the buffer pointer instead, but these no
4794 longer need to be worried about.
4796 @item @code{sscanf}
4797 @c @fuindex sscanf
4798 @prindex @code{sscanf}
4799 On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4800 that its
4801 input string be writable (though it doesn't actually change it).  This
4802 can be a problem when using @command{gcc} since it normally puts
4803 constant strings in read-only memory (@pxref{Incompatibilities,
4804 Incompatibilities of GCC, , gcc, Using and
4805 Porting the GNU Compiler Collection}).  Apparently in some cases even
4806 having format strings read-only can be a problem.
4808 @item @code{strerror_r}
4809 @c @fuindex strerror_r
4810 @prindex @code{strerror_r}
4811 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4812 systems (e.g., GNU C Library version 2.2.4) provide a
4813 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4814 can detect which is in use (@pxref{Particular Functions}).
4816 @item @code{strnlen}
4817 @c @fuindex strnlen
4818 @prindex @code{strnlen}
4819 AIX 4.3 provides a broken version which produces the
4820 following results:
4822 @example
4823 strnlen ("foobar", 0) = 0
4824 strnlen ("foobar", 1) = 3
4825 strnlen ("foobar", 2) = 2
4826 strnlen ("foobar", 3) = 1
4827 strnlen ("foobar", 4) = 0
4828 strnlen ("foobar", 5) = 6
4829 strnlen ("foobar", 6) = 6
4830 strnlen ("foobar", 7) = 6
4831 strnlen ("foobar", 8) = 6
4832 strnlen ("foobar", 9) = 6
4833 @end example
4835 @item @code{sysconf}
4836 @c @fuindex sysconf
4837 @prindex @code{sysconf}
4838 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4839 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4840 @code{#ifdef}.
4842 @item @code{unlink}
4843 @c @fuindex unlink
4844 @prindex @code{unlink}
4845 The Posix spec says that @code{unlink} causes the given file to be
4846 removed only after there are no more open file handles for it.  Some
4847 non-Posix hosts have trouble with this requirement, though,
4848 and some DOS variants even corrupt the file system.
4850 @item @code{unsetenv}
4851 @c @fuindex unsetenv
4852 @prindex @code{unsetenv}
4853 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4854 can be removed with a call @code{putenv ("FOO=")}, as described under
4855 @code{putenv} above.
4857 @item @code{va_copy}
4858 @c @fuindex va_copy
4859 @prindex @code{va_copy}
4860 C99 and later provide @code{va_copy} for copying
4861 @code{va_list} variables.  It may be available in older environments
4862 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4863 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4864 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4865 portability.
4867 @item @code{va_list}
4868 @c @fuindex va_list
4869 @prindex @code{va_list}
4870 @code{va_list} is not necessarily just a pointer.  It can be a
4871 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4872 not portable.  Or it can be an array (e.g., @command{gcc} in some
4873 PowerPC configurations), which means as a function parameter it can be
4874 effectively call-by-reference and library routines might modify the
4875 value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
4876 2.1).
4878 @item Signed @code{>>}
4879 Normally the C @code{>>} right shift of a signed type replicates the
4880 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4881 taken since Standard C doesn't require that behavior.  On those
4882 few processors without a native arithmetic shift (for instance Cray
4883 vector systems) zero bits may be shifted in, the same as a shift of an
4884 unsigned type.
4886 @item Integer @code{/}
4887 C divides signed integers by truncating their quotient toward zero,
4888 yielding the same result as Fortran.  However, before C99 the standard
4889 allowed C implementations to take the floor or ceiling of the quotient
4890 in some cases.  Hardly any implementations took advantage of this
4891 freedom, though, and it's probably not worth worrying about this issue
4892 nowadays.
4893 @end table
4896 @node Particular Functions
4897 @subsection Particular Function Checks
4898 @cindex Function, checking
4900 These macros check for particular C functions---whether they exist, and
4901 in some cases how they respond when given certain arguments.
4903 @anchor{AC_FUNC_ALLOCA}
4904 @defmac AC_FUNC_ALLOCA
4905 @acindex{FUNC_ALLOCA}
4906 @cvindex C_ALLOCA
4907 @cvindex HAVE_ALLOCA_H
4908 @ovindex ALLOCA
4909 @c @fuindex alloca
4910 @prindex @code{alloca}
4911 @hdrindex{alloca.h}
4912 @c @caindex working_alloca_h
4913 Check for the @code{alloca} function.  Define @code{HAVE_ALLOCA_H} if
4914 @file{alloca.h} defines a working @code{alloca}.  If not, look for a
4915 builtin alternative.  If either method succeeds, define
4916 @code{HAVE_ALLOCA}.  Otherwise, set the output variable @code{ALLOCA} to
4917 @samp{$@{LIBOBJDIR@}alloca.o} and define
4918 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4919 garbage collect).  This variable is separate from @code{LIBOBJS} so
4920 multiple programs can share the value of @code{ALLOCA} without needing
4921 to create an actual library, in case only some of them use the code in
4922 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4923 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4925 Source files that use @code{alloca} should start with a piece of code
4926 like the following, to declare it properly.
4928 @example
4929 @group
4930 #include <stdlib.h>
4931 #include <stddef.h>
4932 #ifdef HAVE_ALLOCA_H
4933 # include <alloca.h>
4934 #elif !defined alloca
4935 # ifdef __GNUC__
4936 #  define alloca __builtin_alloca
4937 # elif defined _MSC_VER
4938 #  include <malloc.h>
4939 #  define alloca _alloca
4940 # elif !defined HAVE_ALLOCA
4941 #  ifdef  __cplusplus
4942 extern "C"
4943 #  endif
4944 void *alloca (size_t);
4945 # endif
4946 #endif
4947 @end group
4948 @end example
4949 @end defmac
4951 @defmac AC_FUNC_CHOWN
4952 @acindex{FUNC_CHOWN}
4953 @cvindex HAVE_CHOWN
4954 @c @fuindex chown
4955 @prindex @code{chown}
4956 @caindex func_chown_works
4957 If the @code{chown} function is available and works (in particular, it
4958 should accept @option{-1} for @code{uid} and @code{gid}), define
4959 @code{HAVE_CHOWN}.  The result of this macro is cached in the
4960 @code{ac_cv_func_chown_works} variable.
4961 @end defmac
4963 @anchor{AC_FUNC_CLOSEDIR_VOID}
4964 @defmac AC_FUNC_CLOSEDIR_VOID
4965 @acindex{FUNC_CLOSEDIR_VOID}
4966 @cvindex CLOSEDIR_VOID
4967 @c @fuindex closedir
4968 @prindex @code{closedir}
4969 @caindex func_closedir_void
4970 If the @code{closedir} function does not return a meaningful value,
4971 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4972 return value for an error indicator.
4974 Currently this test is implemented by running a test program.  When
4975 cross compiling the pessimistic assumption that @code{closedir} does not
4976 return a meaningful value is made.
4978 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
4979 variable.
4981 This macro is obsolescent, as @code{closedir} returns a meaningful value
4982 on current systems.  New programs need not use this macro.
4983 @end defmac
4985 @defmac AC_FUNC_ERROR_AT_LINE
4986 @acindex{FUNC_ERROR_AT_LINE}
4987 @c @fuindex error_at_line
4988 @prindex @code{error_at_line}
4989 @caindex lib_error_at_line
4990 If the @code{error_at_line} function is not found, require an
4991 @code{AC_LIBOBJ} replacement of @samp{error}.
4993 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
4994 variable.
4996 The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent.  New programs
4997 should use Gnulib's @code{error} module.  @xref{Gnulib}.
4998 @end defmac
5000 @defmac AC_FUNC_FNMATCH
5001 @acindex{FUNC_FNMATCH}
5002 @c @fuindex fnmatch
5003 @prindex @code{fnmatch}
5004 @caindex func_fnmatch_works
5005 If the @code{fnmatch} function conforms to Posix, define
5006 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
5007 the bugs in Solaris 2.4.
5009 Unlike the other specific
5010 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
5011 broken/missing @code{fnmatch}.  This is for historical reasons.
5012 See @code{AC_REPLACE_FNMATCH} below.
5014 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
5015 variable.
5017 This macro is obsolescent.  New programs should use Gnulib's
5018 @code{fnmatch-posix} module.  @xref{Gnulib}.
5019 @end defmac
5021 @defmac AC_FUNC_FNMATCH_GNU
5022 @acindex{FUNC_FNMATCH_GNU}
5023 @c @fuindex fnmatch
5024 @prindex @code{fnmatch}
5025 @caindex func_fnmatch_gnu
5026 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
5027 whether @code{fnmatch} supports GNU extensions.  Detect common
5028 implementation bugs, for example, the bugs in the GNU C
5029 Library 2.1.
5031 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
5032 variable.
5034 This macro is obsolescent.  New programs should use Gnulib's
5035 @code{fnmatch-gnu} module.  @xref{Gnulib}.
5036 @end defmac
5038 @anchor{AC_FUNC_FORK}
5039 @defmac AC_FUNC_FORK
5040 @acindex{FUNC_FORK}
5041 @cvindex HAVE_VFORK_H
5042 @cvindex HAVE_WORKING_FORK
5043 @cvindex HAVE_WORKING_VFORK
5044 @cvindex vfork
5045 @c @fuindex fork
5046 @prindex @code{fork}
5047 @c @fuindex vfork
5048 @prindex @code{vfork}
5049 @hdrindex{vfork.h}
5050 @c @caindex func_fork
5051 @c @caindex func_fork_works
5052 This macro checks for the @code{fork} and @code{vfork} functions.  If a
5053 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
5054 checks whether @code{fork} is just a stub by trying to run it.
5056 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
5057 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
5058 define @code{vfork} to be @code{fork} for backward compatibility with
5059 previous versions of @command{autoconf}.  This macro checks for several known
5060 errors in implementations of @code{vfork} and considers the system to not
5061 have a working @code{vfork} if it detects any of them.
5063 Since this macro defines @code{vfork} only for backward compatibility with
5064 previous versions of @command{autoconf} you're encouraged to define it
5065 yourself in new code:
5066 @example
5067 @group
5068 #ifndef HAVE_WORKING_VFORK
5069 # define vfork fork
5070 #endif
5071 @end group
5072 @end example
5074 The results of this macro are cached in the @code{ac_cv_func_fork_works}
5075 and @code{ac_cv_func_vfork_works} variables.  In order to override the
5076 test, you also need to set the @code{ac_cv_func_fork} and
5077 @code{ac_cv_func_vfork} variables.
5078 @end defmac
5080 @defmac AC_FUNC_FSEEKO
5081 @acindex{FUNC_FSEEKO}
5082 @cvindex _LARGEFILE_SOURCE
5083 @cvindex HAVE_FSEEKO
5084 @c @fuindex fseeko
5085 @prindex @code{fseeko}
5086 @c @fuindex ftello
5087 @prindex @code{ftello}
5088 @c @caindex sys_largefile_source
5089 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
5090 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
5091 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
5092 may occur when compiling with @code{AC_SYS_LARGEFILE} on
5093 largefile-sensitive systems where @code{off_t} does not default to a
5094 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
5095 @end defmac
5097 @defmac AC_FUNC_GETGROUPS
5098 @acindex{FUNC_GETGROUPS}
5099 @cvindex HAVE_GETGROUPS
5100 @ovindex GETGROUPS_LIBS
5101 @c @fuindex getgroups
5102 @prindex @code{getgroups}
5103 @caindex func_getgroups_works
5104 If the @code{getgroups} function is available and works (unlike on
5105 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
5106 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
5107 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
5108 @end defmac
5110 @anchor{AC_FUNC_GETLOADAVG}
5111 @defmac AC_FUNC_GETLOADAVG
5112 @acindex{FUNC_GETLOADAVG}
5113 @cvindex SVR4
5114 @cvindex DGUX
5115 @cvindex UMAX
5116 @cvindex UMAX4_3
5117 @cvindex HAVE_NLIST_H
5118 @cvindex NLIST_NAME_UNION
5119 @cvindex GETLOADAVG_PRIVILEGED
5120 @cvindex NEED_SETGID
5121 @cvindex C_GETLOADAVG
5122 @ovindex LIBOBJS
5123 @ovindex NEED_SETGID
5124 @ovindex KMEM_GROUP
5125 @ovindex GETLOADAVG_LIBS
5126 @c @fuindex getloadavg
5127 @prindex @code{getloadavg}
5128 Check how to get the system load averages.  To perform its tests
5129 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5130 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5131 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5133 If the system has the @code{getloadavg} function, define
5134 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5135 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
5136 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
5137 @samp{getloadavg} and possibly define several other C preprocessor
5138 macros and output variables:
5140 @enumerate
5141 @item
5142 Define @code{C_GETLOADAVG}.
5144 @item
5145 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5146 those systems.
5148 @item
5149 @hdrindex{nlist.h}
5150 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5152 @item
5153 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5154 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
5155 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5157 @item
5158 Programs may need to be installed set-group-ID (or set-user-ID) for
5159 @code{getloadavg} to work.  In this case, define
5160 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5161 to @samp{true} (and otherwise to @samp{false}), and set
5162 @code{KMEM_GROUP} to the name of the group that should own the installed
5163 program.
5164 @end enumerate
5166 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5167 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5168 @end defmac
5170 @anchor{AC_FUNC_GETMNTENT}
5171 @defmac AC_FUNC_GETMNTENT
5172 @acindex{FUNC_GETMNTENT}
5173 @cvindex HAVE_GETMNTENT
5174 @c @fuindex getmntent
5175 @prindex @code{getmntent}
5176 @caindex search_getmntent
5177 Check for @code{getmntent} in the standard C library, and then in the
5178 @file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5179 IRIX 4, PTX, and UnixWare, respectively.  Then, if
5180 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5181 @code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5182 @code{ac_cv_func_getmntent} to @code{no}.
5184 The result of this macro can be overridden by setting the cache variable
5185 @code{ac_cv_search_getmntent}.
5186 @end defmac
5188 @defmac AC_FUNC_GETPGRP
5189 @acindex{FUNC_GETPGRP}
5190 @cvindex GETPGRP_VOID
5191 @c @fuindex getpgid
5192 @c @fuindex getpgrp
5193 @prindex @code{getpgid}
5194 @prindex @code{getpgrp}
5195 @caindex func_getpgrp_void
5196 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5197 @code{getpgrp}; this is the Posix behavior.  On older BSD
5198 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5199 behaves like Posix's @code{getpgid}.
5201 @example
5202 #ifdef GETPGRP_VOID
5203   pid = getpgrp ();
5204 #else
5205   pid = getpgrp (0);
5206 #endif
5207 @end example
5209 This macro does not check whether
5210 @code{getpgrp} exists at all; if you need to work in that situation,
5211 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5213 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5214 variable.
5216 This macro is obsolescent, as current systems have a @code{getpgrp}
5217 whose signature conforms to Posix.  New programs need not use this macro.
5218 @end defmac
5220 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5221 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5222 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5223 @c @fuindex lstat
5224 @prindex @code{lstat}
5225 @caindex func_lstat_dereferences_slashed_symlink
5226 If @file{link} is a symbolic link, then @code{lstat} should treat
5227 @file{link/} the same as @file{link/.}.  However, many older
5228 @code{lstat} implementations incorrectly ignore trailing slashes.
5230 It is safe to assume that if @code{lstat} incorrectly ignores
5231 trailing slashes, then other symbolic-link-aware functions like
5232 @code{unlink} also incorrectly ignore trailing slashes.
5234 If @code{lstat} behaves properly, define
5235 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5236 @code{AC_LIBOBJ} replacement of @code{lstat}.
5238 The result of this macro is cached in the
5239 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5241 The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5242 New programs should use Gnulib's @code{lstat} module.  @xref{Gnulib}.
5243 @end defmac
5245 @defmac AC_FUNC_MALLOC
5246 @acindex{FUNC_MALLOC}
5247 @cvindex HAVE_MALLOC
5248 @cvindex malloc
5249 @c @fuindex malloc
5250 @prindex @code{malloc}
5251 @caindex func_malloc_0_nonnull
5252 If the @code{malloc} function is compatible with the GNU C
5253 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5254 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5255 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5256 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5257 native @code{malloc} is not used in the main project.
5259 Typically, the replacement file @file{malloc.c} should look like (note
5260 the @samp{#undef malloc}):
5262 @verbatim
5263 #include <config.h>
5264 #undef malloc
5266 #include <sys/types.h>
5268 void *malloc ();
5270 /* Allocate an N-byte block of memory from the heap.
5271    If N is zero, allocate a 1-byte block.  */
5273 void *
5274 rpl_malloc (size_t n)
5276   if (n == 0)
5277     n = 1;
5278   return malloc (n);
5280 @end verbatim
5282 The result of this macro is cached in the
5283 @code{ac_cv_func_malloc_0_nonnull} variable.
5284 @end defmac
5286 @defmac AC_FUNC_MBRTOWC
5287 @acindex{FUNC_MBRTOWC}
5288 @cvindex HAVE_MBRTOWC
5289 @c @fuindex mbrtowc
5290 @prindex @code{mbrtowc}
5291 @caindex func_mbrtowc
5292 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5293 type @code{mbstate_t} are properly declared.
5295 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5296 variable.
5297 @end defmac
5299 @defmac AC_FUNC_MEMCMP
5300 @acindex{FUNC_MEMCMP}
5301 @ovindex LIBOBJS
5302 @c @fuindex memcmp
5303 @prindex @code{memcmp}
5304 @caindex func_memcmp_working
5305 If the @code{memcmp} function is not available, or does not work on
5306 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5307 bytes or more and with at least one buffer not starting on a 4-byte
5308 boundary (such as the one on NeXT x86 OpenStep), require an
5309 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5311 The result of this macro is cached in the
5312 @code{ac_cv_func_memcmp_working} variable.
5314 This macro is obsolescent, as current systems have a working
5315 @code{memcmp}.  New programs need not use this macro.
5316 @end defmac
5318 @defmac AC_FUNC_MKTIME
5319 @acindex{FUNC_MKTIME}
5320 @ovindex LIBOBJS
5321 @c @fuindex mktime
5322 @prindex @code{mktime}
5323 @caindex func_working_mktime
5324 If the @code{mktime} function is not available, or does not work
5325 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5326 For the purposes of this test, @code{mktime} should conform to the
5327 Posix standard and should be the inverse of
5328 @code{localtime}.
5330 The result of this macro is cached in the
5331 @code{ac_cv_func_working_mktime} variable.
5333 The @code{AC_FUNC_MKTIME} macro is obsolescent.  New programs should
5334 use Gnulib's @code{mktime} module.  @xref{Gnulib}.
5335 @end defmac
5337 @anchor{AC_FUNC_MMAP}
5338 @defmac AC_FUNC_MMAP
5339 @acindex{FUNC_MMAP}
5340 @cvindex HAVE_MMAP
5341 @c @fuindex mmap
5342 @prindex @code{mmap}
5343 @caindex func_mmap_fixed_mapped
5344 If the @code{mmap} function exists and works correctly, define
5345 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5346 memory.
5348 The result of this macro is cached in the
5349 @code{ac_cv_func_mmap_fixed_mapped} variable.
5350 @end defmac
5352 @defmac AC_FUNC_OBSTACK
5353 @acindex{FUNC_OBSTACK}
5354 @cvindex HAVE_OBSTACK
5355 @cindex obstack
5356 @caindex func_obstack
5357 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5358 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5360 The result of this macro is cached in the @code{ac_cv_func_obstack}
5361 variable.
5362 @end defmac
5364 @defmac AC_FUNC_REALLOC
5365 @acindex{FUNC_REALLOC}
5366 @cvindex HAVE_REALLOC
5367 @cvindex realloc
5368 @c @fuindex realloc
5369 @prindex @code{realloc}
5370 @caindex func_realloc_0_nonnull
5371 If the @code{realloc} function is compatible with the GNU C
5372 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5373 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5374 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5375 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5376 the native @code{realloc} is not used in the main project.  See
5377 @code{AC_FUNC_MALLOC} for details.
5379 The result of this macro is cached in the
5380 @code{ac_cv_func_realloc_0_nonnull} variable.
5381 @end defmac
5383 @defmac AC_FUNC_SELECT_ARGTYPES
5384 @acindex{FUNC_SELECT_ARGTYPES}
5385 @cvindex SELECT_TYPE_ARG1
5386 @cvindex SELECT_TYPE_ARG234
5387 @cvindex SELECT_TYPE_ARG5
5388 @c @fuindex select
5389 @prindex @code{select}
5390 @c @caindex func_select_args
5391 Determines the correct type to be passed for each of the
5392 @code{select} function's arguments, and defines those types
5393 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5394 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5395 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5396 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5398 This macro is obsolescent, as current systems have a @code{select} whose
5399 signature conforms to Posix.  New programs need not use this macro.
5400 @end defmac
5402 @defmac AC_FUNC_SETPGRP
5403 @acindex{FUNC_SETPGRP}
5404 @cvindex SETPGRP_VOID
5405 @c @fuindex setpgrp
5406 @prindex @code{setpgrp}
5407 @caindex func_setpgrp_void
5408 If @code{setpgrp} takes no argument (the Posix version), define
5409 @code{SETPGRP_VOID}.  Otherwise, it is the BSD version, which takes
5410 two process IDs as arguments.  This macro does not check whether
5411 @code{setpgrp} exists at all; if you need to work in that situation,
5412 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5414 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5415 variable.
5417 This macro is obsolescent, as current systems have a @code{setpgrp}
5418 whose signature conforms to Posix.  New programs need not use this macro.
5419 @end defmac
5421 @defmac AC_FUNC_STAT
5422 @defmacx AC_FUNC_LSTAT
5423 @acindex{FUNC_STAT}
5424 @acindex{FUNC_LSTAT}
5425 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5426 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5427 @c @fuindex stat
5428 @prindex @code{stat}
5429 @c @fuindex lstat
5430 @prindex @code{lstat}
5431 @caindex func_stat_empty_string_bug
5432 @caindex func_lstat_empty_string_bug
5433 Determine whether @code{stat} or @code{lstat} have the bug that it
5434 succeeds when given the zero-length file name as argument.  The @code{stat}
5435 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5436 this.
5438 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5439 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5440 replacement of it.
5442 The results of these macros are cached in the
5443 @code{ac_cv_func_stat_empty_string_bug} and the
5444 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5446 These macros are obsolescent, as no current systems have the bug.
5447 New programs need not use these macros.
5448 @end defmac
5450 @anchor{AC_FUNC_STRCOLL}
5451 @defmac AC_FUNC_STRCOLL
5452 @acindex{FUNC_STRCOLL}
5453 @cvindex HAVE_STRCOLL
5454 @c @fuindex strcoll
5455 @prindex @code{strcoll}
5456 @caindex func_strcoll_works
5457 If the @code{strcoll} function exists and works correctly, define
5458 @code{HAVE_STRCOLL}.  This does a bit more than
5459 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5460 definitions of @code{strcoll} that should not be used.
5462 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5463 variable.
5464 @end defmac
5466 @defmac AC_FUNC_STRERROR_R
5467 @acindex{FUNC_STRERROR_R}
5468 @cvindex HAVE_STRERROR_R
5469 @cvindex HAVE_DECL_STRERROR_R
5470 @cvindex STRERROR_R_CHAR_P
5471 @c @fuindex strerror_r
5472 @caindex func_strerror_r_char_p
5473 @prindex @code{strerror_r}
5474 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5475 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5476 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5477 returns an @code{int} error number.  The Thread-Safe Functions option of
5478 Posix requires @code{strerror_r} to return @code{int}, but
5479 many systems (including, for example, version 2.2.4 of the GNU C
5480 Library) return a @code{char *} value that is not necessarily equal to
5481 the buffer argument.
5483 The result of this macro is cached in the
5484 @code{ac_cv_func_strerror_r_char_p} variable.
5485 @end defmac
5487 @anchor{AC_FUNC_STRFTIME}
5488 @defmac AC_FUNC_STRFTIME
5489 @acindex{FUNC_STRFTIME}
5490 @cvindex HAVE_STRFTIME
5491 @c @fuindex strftime
5492 @prindex @code{strftime}
5493 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5494 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5496 This macro is obsolescent, as no current systems require the @file{intl}
5497 library for @code{strftime}.  New programs need not use this macro.
5498 @end defmac
5500 @defmac AC_FUNC_STRTOD
5501 @acindex{FUNC_STRTOD}
5502 @ovindex POW_LIB
5503 @c @fuindex strtod
5504 @prindex @code{strtod}
5505 @caindex func_strtod
5506 @caindex func_pow
5507 If the @code{strtod} function does not exist or doesn't work correctly,
5508 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5509 because @file{strtod.c} is likely to need @samp{pow}, set the output
5510 variable @code{POW_LIB} to the extra library needed.
5512 This macro caches its result in the @code{ac_cv_func_strtod} variable
5513 and depends upon the result in the @code{ac_cv_func_pow} variable.
5515 The @code{AC_FUNC_STRTOD} macro is obsolescent.  New programs should
5516 use Gnulib's @code{strtod} module.  @xref{Gnulib}.
5517 @end defmac
5519 @defmac AC_FUNC_STRTOLD
5520 @acindex{FUNC_STRTOLD}
5521 @cvindex HAVE_STRTOLD
5522 @prindex @code{strtold}
5523 @caindex func_strtold
5524 If the @code{strtold} function exists and conforms to C99 or later, define
5525 @code{HAVE_STRTOLD}.
5527 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5528 @end defmac
5530 @defmac AC_FUNC_STRNLEN
5531 @acindex{FUNC_STRNLEN}
5532 @cvindex HAVE_STRNLEN
5533 @c @fuindex strnlen
5534 @prindex @code{strnlen}
5535 @caindex func_strnlen_working
5536 If the @code{strnlen} function is not available, or is buggy (like the one
5537 from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5539 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5540 variable.
5541 @end defmac
5543 @anchor{AC_FUNC_UTIME_NULL}
5544 @defmac AC_FUNC_UTIME_NULL
5545 @acindex{FUNC_UTIME_NULL}
5546 @cvindex HAVE_UTIME_NULL
5547 @c @fuindex utime
5548 @prindex @code{utime}
5549 @caindex func_utime_null
5550 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5551 the present, define @code{HAVE_UTIME_NULL}.
5553 This macro caches its result in the @code{ac_cv_func_utime_null}
5554 variable.
5556 This macro is obsolescent, as all current systems have a @code{utime}
5557 that behaves this way.  New programs need not use this macro.
5558 @end defmac
5560 @anchor{AC_FUNC_VPRINTF}
5561 @defmac AC_FUNC_VPRINTF
5562 @acindex{FUNC_VPRINTF}
5563 @cvindex HAVE_VPRINTF
5564 @cvindex HAVE_DOPRNT
5565 @c @fuindex vprintf
5566 @prindex @code{vprintf}
5567 @c @fuindex vsprintf
5568 @prindex @code{vsprintf}
5569 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5570 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5571 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5572 are also available.)
5574 This macro is obsolescent, as all current systems have @code{vprintf}.
5575 New programs need not use this macro.
5576 @end defmac
5578 @defmac AC_REPLACE_FNMATCH
5579 @acindex{REPLACE_FNMATCH}
5580 @c @fuindex fnmatch
5581 @prindex @code{fnmatch}
5582 @hdrindex{fnmatch.h}
5583 @caindex func_fnmatch_works
5584 If the @code{fnmatch} function does not conform to Posix (see
5585 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5587 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5588 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5589 copy of the source code of GNU @code{fnmatch}.  If necessary,
5590 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5591 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5592 included in place of the system @code{<fnmatch.h>}.
5594 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5595 variable.
5597 This macro is obsolescent, as it assumes the use of particular source
5598 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5599 which provides this macro along with the source files.  @xref{Gnulib}.
5600 @end defmac
5604 @node Generic Functions
5605 @subsection Generic Function Checks
5607 These macros are used to find functions not covered by the ``particular''
5608 test macros.  If the functions might be in libraries other than the
5609 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5610 If you need to check the behavior of a function as well as find out
5611 whether it is present, you have to write your own test for
5612 it (@pxref{Writing Tests}).
5614 @anchor{AC_CHECK_FUNC}
5615 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5616   @ovar{action-if-not-found})
5617 @acindex{CHECK_FUNC}
5618 @caindex func_@var{function}
5619 If C function @var{function} is available, run shell commands
5620 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5621 want to define a symbol if the function is available, consider using
5622 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5623 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5624 standardized than C++.  (@pxref{Language Choice}, for more information
5625 about selecting the language for checks.)
5627 This macro caches its result in the @code{ac_cv_func_@var{function}}
5628 variable.
5629 @end defmac
5631 @anchor{AC_CHECK_FUNCS}
5632 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5633   @ovar{action-if-not-found})
5634 @acindex{CHECK_FUNCS}
5635 @cvindex HAVE_@var{function}
5636 For each @var{function} enumerated in the blank-or-newline-separated argument
5637 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5638 If @var{action-if-found} is given, it is additional shell code to
5639 execute when one of the functions is found.  You can give it a value of
5640 @samp{break} to break out of the loop on the first match.  If
5641 @var{action-if-not-found} is given, it is executed when one of the
5642 functions is not found.
5644 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5645 @end defmac
5647 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5648 @acindex{CHECK_FUNCS_ONCE}
5649 @cvindex HAVE_@var{function}
5650 For each @var{function} enumerated in the blank-or-newline-separated argument
5651 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5652 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5653 checking code at most once, so that @command{configure} is smaller and
5654 faster; but the checks cannot be conditionalized and are always done once,
5655 early during the @command{configure} run.
5656 @end defmac
5658 @sp 1
5660 Autoconf follows a philosophy that was formed over the years by those
5661 who have struggled for portability: isolate the portability issues in
5662 specific files, and then program as if you were in a Posix
5663 environment.  Some functions may be missing or unfixable, and your
5664 package must be ready to replace them.
5666 Suitable replacements for many such problem functions are available from
5667 Gnulib (@pxref{Gnulib}).
5669 @defmac AC_LIBOBJ (@var{function})
5670 @acindex{LIBOBJ}
5671 @ovindex LIBOBJS
5672 Specify that @samp{@var{function}.c} must be included in the executables
5673 to replace a missing or broken implementation of @var{function}.
5675 @vrindex ac_objext
5676 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5677 variable @code{LIBOBJS} if it is not already in, and calls
5678 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5679 directly change @code{LIBOBJS}, since this is not traceable.
5680 @end defmac
5682 @defmac AC_LIBSOURCE (@var{file})
5683 @acindex{LIBSOURCE}
5684 Specify that @var{file} might be needed to compile the project.  If you
5685 need to know what files might be needed by a @file{configure.ac}, you
5686 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5688 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5689 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5690 that case, since shell variables cannot be traced statically, you must
5691 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5692 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5693 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5694 @code{"foo"} or @code{"bar"}, you should do:
5696 @example
5697 AC_LIBSOURCE([foo.c])
5698 AC_LIBSOURCE([bar.c])
5699 AC_LIBOBJ([$foo_or_bar])
5700 @end example
5702 @noindent
5703 There is usually a way to avoid this, however, and you are encouraged to
5704 simply call @code{AC_LIBOBJ} with literal arguments.
5706 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5707 slightly different semantics: the old macro took the function name,
5708 e.g., @code{foo}, as its argument rather than the file name.
5709 @end defmac
5711 @defmac AC_LIBSOURCES (@var{files})
5712 @acindex{LIBSOURCES}
5713 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5714 comma-separated M4 list.  Thus, the above example might be rewritten:
5716 @example
5717 AC_LIBSOURCES([foo.c, bar.c])
5718 AC_LIBOBJ([$foo_or_bar])
5719 @end example
5720 @end defmac
5722 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5723 @acindex{CONFIG_LIBOBJ_DIR}
5724 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5725 @var{directory}, a name relative to the top level of the
5726 source tree.  The replacement directory defaults to @file{.}, the top
5727 level directory, and the most typical value is @file{lib}, corresponding
5728 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5730 @command{configure} might need to know the replacement directory for the
5731 following reasons: (i) some checks use the replacement files, (ii) some
5732 macros bypass broken system headers by installing links to the
5733 replacement headers (iii) when used in conjunction with Automake,
5734 within each makefile, @var{directory} is used as a relative path
5735 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5736 @code{LTLIBOBJS}, etc.
5737 @end defmac
5739 @sp 1
5741 It is common to merely check for the existence of a function, and ask
5742 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5743 a convenient shorthand.
5745 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5746 @acindex{REPLACE_FUNCS}
5747 @cvindex HAVE_@var{function}
5748 @ovindex LIBOBJS
5749 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5750 @var{action-if-not-found}.  You can declare your replacement function by
5751 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5752 system has the function, it probably declares it in a header file you
5753 should be including, so you shouldn't redeclare it lest your declaration
5754 conflict.
5755 @end defmac
5757 @node Header Files
5758 @section Header Files
5759 @cindex Header, checking
5761 The following macros check for the presence of certain C header files.
5762 If there is no macro specifically defined to check for a header file you need,
5763 and you don't need to check for any special properties of
5764 it, then you can use one of the general header-file check macros.
5766 @menu
5767 * Header Portability::          Collected knowledge on common headers
5768 * Particular Headers::          Special handling to find certain headers
5769 * Generic Headers::             How to find other headers
5770 @end menu
5772 @node Header Portability
5773 @subsection Portability of Headers
5774 @cindex Portability of headers
5775 @cindex Header portability
5777 This section documents some collected knowledge about common headers,
5778 and the problems they cause.  By definition, this list always requires
5779 additions.  A much more complete list is maintained by the Gnulib
5780 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5781 Posix Headers, gnulib, GNU gnulib} and @ref{Glibc Header File
5782 Substitutes, , Glibc Headers, gnulib, GNU gnulib}.  Please help us keep
5783 the gnulib list as complete as possible.
5785 When we say that a header ``may require'' some set of other headers, we
5786 mean that it may be necessary for you to manually include those other
5787 headers first, or the contents of the header under test will fail to
5788 compile.  When checking for these headers, you must provide the
5789 potentially-required headers in the @var{includes} argument to
5790 @code{AC_CHECK_HEADER} or @code{AC_CHECK_HEADERS}, or the check will
5791 fail spuriously.  @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes})
5792 arranges to include a number of common requirements and should normally
5793 come first in your @var{includes}.  For example, @file{net/if.h} may
5794 require @file{sys/types.h}, @file{sys/socket.h}, or both, and
5795 @code{AC_INCLUDES_DEFAULT} handles @file{sys/types.h} but not
5796 @file{sys/socket.h}, so you should check for it like this:
5798 @example
5799 AC_CHECK_HEADERS([sys/socket.h])
5800 AC_CHECK_HEADERS([net/if.h], [], [],
5801 [AC_INCLUDES_DEFAULT[
5802 #ifdef HAVE_SYS_SOCKET_H
5803 # include <sys/socket.h>
5804 #endif
5806 @end example
5808 Note that the example mixes single quoting (for@code{AC_INCLUDES_DEFAULT},
5809 so that it gets expanded) and double quoting (to ensure that each
5810 preprocessor @code{#} gets treated as a literal string rather than a
5811 comment).
5813 @table @asis
5815 @item @file{limits.h}
5816 In C99 and later, @file{limits.h} defines @code{LLONG_MIN},
5817 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5818 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5819 define them.
5821 @item @file{memory.h}
5822 @hdrindex{memory.h}
5823 This header file is obsolete; use @file{string.h} instead.
5825 @item @file{strings.h}
5826 @hdrindex{strings.h}
5827 On some systems, this is the only header that declares
5828 @code{strcasecmp}, @code{strncasecmp}, and @code{ffs}.
5830 This header may or may not include @file{string.h} for you.  However, on
5831 all recent systems it is safe to include both @file{string.h} and
5832 @file{strings.h}, in either order, in the same source file.
5834 @item @file{inttypes.h} vs.@: @file{stdint.h}
5835 @hdrindex{inttypes.h}
5836 @hdrindex{stdint.h}
5837 C99 specifies that @file{inttypes.h} includes @file{stdint.h}, so there's
5838 no need to include @file{stdint.h} separately in a standard environment.
5839 However, some implementations have @file{inttypes.h} but not @file{stdint.h}
5840 (e.g., Solaris 7), and some have @file{stdint.h} but not @file{inttypes.h}
5841 (e.g. MSVC 2012).  Therefore, it is necessary to check for each and include
5842 each only if available.
5844 @item @file{linux/irda.h}
5845 @hdrindex{linux/irda.h}
5846 This header may require @file{linux/types.h} and/or @file{sys/socket.h}.
5848 @item @file{linux/random.h}
5849 @hdrindex{linux/random.h}
5850 This header may require @file{linux/types.h}.
5852 @item @file{net/if.h}
5853 @hdrindex{net/if.h}
5854 This header may require @file{sys/types.h} and/or @file{sys/socket.h}.
5856 @item @file{netinet/if_ether.h}
5857 @hdrindex{netinet/if_ether.h}
5858 This header may require some combination of @file{sys/types.h},
5859 @file{sys/socket.h}, @file{netinet/in.h}, and @file{net/if.h}.
5861 @item @file{sys/mount.h}
5862 @hdrindex{sys/mount.h}
5863 This header may require @file{sys/params.h}.
5865 @item @file{sys/ptem.h}
5866 @hdrindex{sys/ptem.h}
5867 This header may require @file{sys/stream.h}.
5869 @item @file{sys/socket.h}
5870 @hdrindex{sys/socket.h}
5871 This header may require @file{sys/types.h}.
5873 @item @file{sys/ucred.h}
5874 @hdrindex{sys/ucred.h}
5875 This header may require @file{sys/types.h}.
5877 @item @file{X11/extensions/scrnsaver.h}
5878 @hdrindex{X11/extensions/scrnsaver.h}
5879 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5880 so required that you might not even consider looking for it.
5882 @end table
5885 @node Particular Headers
5886 @subsection Particular Header Checks
5888 These macros check for particular system header files---whether they
5889 exist, and in some cases whether they declare certain symbols.
5891 @defmac AC_CHECK_HEADER_STDBOOL
5892 @acindex{CHECK_HEADER_STDBOOL}
5893 @cvindex HAVE__BOOL
5894 @hdrindex{stdbool.h}
5895 @caindex header_stdbool_h
5896 Check whether @file{stdbool.h} exists and conforms to C99 or later,
5897 and cache the result in the @code{ac_cv_header_stdbool_h} variable.
5898 If the type @code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
5900 This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
5901 packages that supply a substitute @file{stdbool.h} on platforms lacking
5902 a conforming one.  The @code{AC_HEADER_STDBOOL} macro is better for code
5903 that explicitly checks for @file{stdbool.h}.
5904 @end defmac
5906 @defmac AC_HEADER_ASSERT
5907 @acindex{HEADER_ASSERT}
5908 @cvindex NDEBUG
5909 @hdrindex{assert.h}
5910 Check whether to enable assertions in the style of @file{assert.h}.
5911 Assertions are enabled by default, but the user can override this by
5912 invoking @command{configure} with the @option{--disable-assert} option.
5913 @end defmac
5915 @anchor{AC_HEADER_DIRENT}
5916 @defmac AC_HEADER_DIRENT
5917 @acindex{HEADER_DIRENT}
5918 @cvindex HAVE_DIRENT_H
5919 @cvindex HAVE_NDIR_H
5920 @cvindex HAVE_SYS_DIR_H
5921 @cvindex HAVE_SYS_NDIR_H
5922 @hdrindex{dirent.h}
5923 @hdrindex{sys/ndir.h}
5924 @hdrindex{sys/dir.h}
5925 @hdrindex{ndir.h}
5926 Check for the following header files.  For the first one that is
5927 found and defines @samp{DIR}, define the listed C preprocessor macro:
5929 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5930 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5931 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5932 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5933 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5934 @end multitable
5936 The directory-library declarations in your source code should look
5937 something like the following:
5939 @example
5940 @group
5941 #include <sys/types.h>
5942 #ifdef HAVE_DIRENT_H
5943 # include <dirent.h>
5944 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5945 #else
5946 # define dirent direct
5947 # define NAMLEN(dirent) ((dirent)->d_namlen)
5948 # ifdef HAVE_SYS_NDIR_H
5949 #  include <sys/ndir.h>
5950 # endif
5951 # ifdef HAVE_SYS_DIR_H
5952 #  include <sys/dir.h>
5953 # endif
5954 # ifdef HAVE_NDIR_H
5955 #  include <ndir.h>
5956 # endif
5957 #endif
5958 @end group
5959 @end example
5961 Using the above declarations, the program would declare variables to be
5962 of type @code{struct dirent}, not @code{struct direct}, and would access
5963 the length of a directory entry name by passing a pointer to a
5964 @code{struct dirent} to the @code{NAMLEN} macro.
5966 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5968 This macro is obsolescent, as all current systems with directory
5969 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5971 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5972 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5973 @end defmac
5975 @anchor{AC_HEADER_MAJOR}
5976 @defmac AC_HEADER_MAJOR
5977 @acindex{HEADER_MAJOR}
5978 @cvindex MAJOR_IN_MKDEV
5979 @cvindex MAJOR_IN_SYSMACROS
5980 @hdrindex{sys/mkdev.h}
5981 @hdrindex{sys/sysmacros.h}
5982 Detect the headers required to use @code{makedev}, @code{major}, and
5983 @code{minor}.  These functions may be defined by @file{sys/mkdev.h},
5984 @code{sys/sysmacros.h}, or @file{sys/types.h}.
5986 @code{AC_HEADER_MAJOR} defines @code{MAJOR_IN_MKDEV} if they are in
5987 @file{sys/mkdev.h}, or @code{MAJOR_IN_SYSMACROS} if they are in
5988 @file{sys/sysmacros.h}.  If neither macro is defined, they are either in
5989 @file{sys/types.h} or unavailable.
5991 To properly use these functions, your code should contain something
5992 like:
5994 @verbatim
5995 #include <sys/types.h>
5996 #ifdef MAJOR_IN_MKDEV
5997 # include <sys/mkdev.h>
5998 #elif defined MAJOR_IN_SYSMACROS
5999 # include <sys/sysmacros.h>
6000 #endif
6001 @end verbatim
6003 Note: Configure scripts built with Autoconf 2.69 or earlier will not
6004 detect a problem if @file{sys/types.h} contains definitions of
6005 @code{major}, @code{minor}, and/or @code{makedev} that trigger compiler
6006 warnings upon use.  This is known to occur with GNU libc 2.25, where
6007 those definitions are being deprecated to reduce namespace pollution.
6008 If it is not practical to use Autoconf 2.70 to regenerate the configure
6009 script of affected software, you can work around the problem by setting
6010 @samp{ac_cv_header_sys_types_h_makedev=no}, as an argument to
6011 @command{configure} or as part of a @file{config.site} site default file
6012 (@pxref{Site Defaults}).
6013 @end defmac
6015 @defmac AC_HEADER_RESOLV
6016 @acindex{HEADER_RESOLV}
6017 @cvindex HAVE_RESOLV_H
6018 @hdrindex{resolv.h}
6019 Checks for header @file{resolv.h}, checking for prerequisites first.
6020 To properly use @file{resolv.h}, your code should contain something like
6021 the following:
6023 @verbatim
6024 #ifdef HAVE_SYS_TYPES_H
6025 #  include <sys/types.h>
6026 #endif
6027 #ifdef HAVE_NETINET_IN_H
6028 #  include <netinet/in.h>   /* inet_ functions / structs */
6029 #endif
6030 #ifdef HAVE_ARPA_NAMESER_H
6031 #  include <arpa/nameser.h> /* DNS HEADER struct */
6032 #endif
6033 #ifdef HAVE_NETDB_H
6034 #  include <netdb.h>
6035 #endif
6036 #include <resolv.h>
6037 @end verbatim
6038 @end defmac
6040 @anchor{AC_HEADER_STAT}
6041 @defmac AC_HEADER_STAT
6042 @acindex{HEADER_STAT}
6043 @cvindex STAT_MACROS_BROKEN
6044 @hdrindex{sys/stat.h}
6045 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
6046 @file{sys/stat.h} do not work properly (returning false positives),
6047 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
6048 Amdahl UTS and Motorola System V/88.
6050 This macro is obsolescent, as no current systems have the bug.
6051 New programs need not use this macro.
6052 @end defmac
6054 @defmac AC_HEADER_STDBOOL
6055 @acindex{HEADER_STDBOOL}
6056 @cvindex HAVE_STDBOOL_H
6057 @cvindex HAVE__BOOL
6058 @hdrindex{stdbool.h}
6059 @caindex header_stdbool_h
6060 If @file{stdbool.h} exists and conforms to C99 or later, define
6061 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
6062 @code{HAVE__BOOL} to 1.  To fulfill the standard's requirements, your
6063 program could contain the following code:
6065 @example
6066 @group
6067 #ifdef HAVE_STDBOOL_H
6068 # include <stdbool.h>
6069 #else
6070 # ifndef HAVE__BOOL
6071 #  ifdef __cplusplus
6072 typedef bool _Bool;
6073 #  else
6074 #   define _Bool signed char
6075 #  endif
6076 # endif
6077 # define bool _Bool
6078 # define false 0
6079 # define true 1
6080 # define __bool_true_false_are_defined 1
6081 #endif
6082 @end group
6083 @end example
6085 Alternatively you can use the @samp{stdbool} package of Gnulib
6086 (@pxref{Gnulib}).  It simplifies your code so that it can say just
6087 @code{#include <stdbool.h>}, and it adds support for less-common
6088 platforms.
6090 This macro caches its result in the @code{ac_cv_header_stdbool_h}
6091 variable.
6093 This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
6094 defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
6095 does not.
6096 @end defmac
6098 @anchor{AC_HEADER_STDC}
6099 @defmac AC_HEADER_STDC
6100 @acindex{HEADER_STDC}
6101 @cvindex STDC_HEADERS
6102 @caindex header_stdc
6104 This macro is obsolescent.  Its sole effect is to make sure that all the
6105 headers that are included by @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6106 Includes}), but not part of ISO C90, have been checked for.
6108 All hosted environments that are still of interest for portable code
6109 provide all of the headers specified in ISO C90 (as amended in 1995).
6110 @end defmac
6112 @defmac AC_HEADER_SYS_WAIT
6113 @acindex{HEADER_SYS_WAIT}
6114 @cvindex HAVE_SYS_WAIT_H
6115 @hdrindex{sys/wait.h}
6116 @caindex header_sys_wait_h
6117 If @file{sys/wait.h} exists and is compatible with Posix, define
6118 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
6119 does not exist, or if it uses the old BSD @code{union wait} instead
6120 of @code{int} to store a status value.  If @file{sys/wait.h} is not
6121 Posix compatible, then instead of including it, define the
6122 Posix macros with their usual interpretations.  Here is an
6123 example:
6125 @example
6126 @group
6127 #include <sys/types.h>
6128 #ifdef HAVE_SYS_WAIT_H
6129 # include <sys/wait.h>
6130 #endif
6131 #ifndef WEXITSTATUS
6132 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6133 #endif
6134 #ifndef WIFEXITED
6135 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6136 #endif
6137 @end group
6138 @end example
6140 @noindent
6141 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6142 variable.
6144 This macro is obsolescent, as current systems are compatible with Posix.
6145 New programs need not use this macro.
6146 @end defmac
6148 @cvindex _POSIX_VERSION
6149 @hdrindex{unistd.h}
6150 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6151 Posix systems.  If there is no @file{unistd.h}, it is definitely
6152 not a Posix system.  However, some non-Posix systems do
6153 have @file{unistd.h}.
6155 The way to check whether the system supports Posix is:
6157 @example
6158 @group
6159 #ifdef HAVE_UNISTD_H
6160 # include <sys/types.h>
6161 # include <unistd.h>
6162 #endif
6164 #ifdef _POSIX_VERSION
6165 /* Code for Posix systems.  */
6166 #endif
6167 @end group
6168 @end example
6170 @defmac AC_HEADER_TIOCGWINSZ
6171 @acindex{HEADER_TIOCGWINSZ}
6172 @cvindex GWINSZ_IN_SYS_IOCTL
6173 @hdrindex{sys/ioctl.h}
6174 @hdrindex{termios.h}
6175 @c FIXME: I need clarifications from Jim.
6176 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6177 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6178 found in @file{<termios.h>}.
6180 Use:
6182 @example
6183 @group
6184 #ifdef HAVE_TERMIOS_H
6185 # include <termios.h>
6186 #endif
6188 #ifdef GWINSZ_IN_SYS_IOCTL
6189 # include <sys/ioctl.h>
6190 #endif
6191 @end group
6192 @end example
6193 @end defmac
6195 @node Generic Headers
6196 @subsection Generic Header Checks
6198 These macros are used to find system header files not covered by the
6199 ``particular'' test macros.  If you need to check the contents of a header
6200 as well as find out whether it is present, you have to write your own
6201 test for it (@pxref{Writing Tests}).
6203 @anchor{AC_CHECK_HEADER}
6204 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6205   @ovar{action-if-not-found}, @ovar{includes})
6206 @acindex{CHECK_HEADER}
6207 @caindex header_@var{header-file}
6208 If the system header file @var{header-file} is compilable, execute shell
6209 commands @var{action-if-found}, otherwise execute
6210 @var{action-if-not-found}.  If you just want to define a symbol if the
6211 header file is available, consider using @code{AC_CHECK_HEADERS}
6212 instead.
6214 @var{includes} should be the appropriate @dfn{prerequisite} code, i.e.@:
6215 whatever might be required to appear above
6216 @samp{#include <@var{header-file}>} for it to compile without error.
6217 This can be anything, but will normally be additional @samp{#include}
6218 directives. If @var{includes} is omitted or empty, @file{configure} will
6219 use the contents of the macro @code{AC_INCLUDES_DEFAULT}.
6220 @xref{Default Includes}.
6222 This macro used to check only for the @emph{presence} of a header, not
6223 whether its contents were acceptable to the compiler.  Some older
6224 @command{configure} scripts rely on this behavior, so it is still
6225 available by specifying @samp{-} as @var{includes}.  This mechanism is
6226 deprecated as of Autoconf 2.70; situations where a preprocessor-only
6227 check is required should use @code{AC_PREPROC_IFELSE}.
6228 @xref{Running the Preprocessor}.
6230 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6231 variable, with characters not suitable for a variable name mapped to
6232 underscores.
6233 @end defmac
6235 @anchor{AC_CHECK_HEADERS}
6236 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6237   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6238   @ovar{includes})
6239 @acindex{CHECK_HEADERS}
6240 @cvindex HAVE_@var{header}
6241 @caindex header_@var{header-file}
6242 For each given system header file @var{header-file} in the
6243 blank-separated argument list that exists, define
6244 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6245 is given, it is additional shell code to execute when one of the header
6246 files is found.  You can give it a value of @samp{break} to break out of
6247 the loop on the first match.  If @var{action-if-not-found} is given, it
6248 is executed when one of the header files is not found.
6250 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6251 choose the set of preprocessor directives supplied before the header
6252 under test.
6254 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6255 variable, with characters not suitable for a variable name mapped to
6256 underscores.
6257 @end defmac
6259 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6260 @acindex{CHECK_HEADERS_ONCE}
6261 @cvindex HAVE_@var{header}
6262 For each given system header file @var{header-file} in the
6263 blank-separated argument list that exists, define
6264 @code{HAVE_@var{header-file}} (in all capitals).
6266 If you do not need the full power of @code{AC_CHECK_HEADERS}, this
6267 variant generates smaller, faster @command{configure} files.  All
6268 headers passed to @code{AC_CHECK_HEADERS_ONCE} are checked for in one
6269 pass, early during the @command{configure} run.  The checks cannot be
6270 conditionalized, you cannot specify an @var{action-if-found} or
6271 @var{action-if-not-found}, and @code{AC_INCLUDES_DEFAULT} is always used
6272 for the prerequisites.
6273 @end defmac
6275 In previous versions of Autoconf, these macros merely checked whether
6276 the header was accepted by the preprocessor.  This was changed because
6277 the old test was inappropriate for typical uses.  Headers are typically
6278 used to compile, not merely to preprocess, and the old behavior
6279 sometimes accepted headers that clashed at compile-time
6280 (@pxref{Present But Cannot Be Compiled}).  If for some reason it is
6281 inappropriate to check whether a header is compilable, you should use
6282 @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}) instead of
6283 these macros.
6285 Requiring each header to compile improves the robustness of the test,
6286 but it also requires you to make sure that the @var{includes} are
6287 correct.  Most system headers nowadays make sure to @code{#include}
6288 whatever they require, or else have their dependencies satisfied by
6289 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), but
6290 @pxref{Header Portability}, for known exceptions.  In general, if you
6291 are looking for @file{bar.h}, which requires that @file{foo.h} be
6292 included first if it exists, you should do something like this:
6294 @example
6295 AC_CHECK_HEADERS([foo.h])
6296 AC_CHECK_HEADERS([bar.h], [], [],
6297 [#ifdef HAVE_FOO_H
6298 # include <foo.h>
6299 #endif
6301 @end example
6303 @node Declarations
6304 @section Declarations
6305 @cindex Declaration, checking
6307 The following macros check for the declaration of variables and
6308 functions.  If there is no macro specifically defined to check for a
6309 symbol you need, then you can use the general macros (@pxref{Generic
6310 Declarations}) or, for more complex tests, you may use
6311 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6313 @menu
6314 * Particular Declarations::     Macros to check for certain declarations
6315 * Generic Declarations::        How to find other declarations
6316 @end menu
6318 @node Particular Declarations
6319 @subsection Particular Declaration Checks
6321 There are no specific macros for declarations.
6323 @node Generic Declarations
6324 @subsection Generic Declaration Checks
6326 These macros are used to find declarations not covered by the ``particular''
6327 test macros.
6329 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6330   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6331 @acindex{CHECK_DECL}
6332 @caindex have_decl_@var{symbol}
6333 If @var{symbol} (a function, variable, or constant) is not declared in
6334 @var{includes} and a declaration is needed, run the shell commands
6335 @var{action-if-not-found}, otherwise @var{action-if-found}.
6336 @var{includes} is a series of include directives, defaulting to
6337 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6338 prior to the declaration under test.
6340 This macro actually tests whether @var{symbol} is defined as a macro or
6341 can be used as an r-value, not whether it is really declared, because it
6342 is much safer to avoid introducing extra declarations when they are not
6343 needed.  In order to facilitate use of C++ and overloaded function
6344 declarations, it is possible to specify function argument types in
6345 parentheses for types which can be zero-initialized:
6347 @example
6348 AC_CHECK_DECL([basename(char *)])
6349 @end example
6351 Some compilers don't indicate every missing declaration by the error
6352 status.  This macro checks the standard error from such compilers and
6353 considers a declaration missing if any warnings have been reported.  For
6354 most compilers, though, warnings do not affect this macro's outcome
6355 unless @code{AC_LANG_WERROR} is also specified.
6357 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6358 variable, with characters not suitable for a variable name mapped to
6359 underscores.
6360 @end defmac
6362 @anchor{AC_CHECK_DECLS}
6363 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6364   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6365 @acindex{CHECK_DECLS}
6366 @cvindex HAVE_DECL_@var{symbol}
6367 @caindex have_decl_@var{symbol}
6368 For each of the @var{symbols} (@emph{comma}-separated list with optional
6369 function argument types for C++ overloads), define
6370 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6371 @var{symbol} is declared, otherwise to @samp{0}.  If
6372 @var{action-if-not-found} is given, it is additional shell code to
6373 execute when one of the function declarations is needed, otherwise
6374 @var{action-if-found} is executed.
6376 @var{includes} is a series of include directives, defaulting to
6377 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6378 prior to the declarations under test.
6380 This macro uses an M4 list as first argument:
6381 @example
6382 AC_CHECK_DECLS([strdup])
6383 AC_CHECK_DECLS([strlen])
6384 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6385 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6386 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6387 @end example
6389 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6390 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6391 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6392 @emph{sure} that the check was performed, use
6393 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6395 @example
6396 #if !HAVE_DECL_SYMBOL
6397 extern char *symbol;
6398 #endif
6399 @end example
6401 @noindent
6402 If the test may have not been performed, however, because it is safer
6403 @emph{not} to declare a symbol than to use a declaration that conflicts
6404 with the system's one, you should use:
6406 @example
6407 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6408 void *malloc (size_t *s);
6409 #endif
6410 @end example
6412 @noindent
6413 You fall into the second category only in extreme situations: either
6414 your files may be used without being configured, or they are used during
6415 the configuration.  In most cases the traditional approach is enough.
6417 Some compilers don't indicate every missing declaration by the error
6418 status.  This macro checks the standard error from such compilers and
6419 considers a declaration missing if any warnings have been reported.  For
6420 most compilers, though, warnings do not affect this macro's outcome
6421 unless @code{AC_LANG_WERROR} is also specified.
6423 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6424 variables, with characters not suitable for a variable name mapped to
6425 underscores.
6426 @end defmac
6428 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6429 @acindex{CHECK_DECLS_ONCE}
6430 @cvindex HAVE_DECL_@var{symbol}
6431 For each of the @var{symbols} (@emph{comma}-separated list), define
6432 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6433 @var{symbol} is declared in the default include files, otherwise to
6434 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6435 generates the checking code at most once, so that @command{configure} is
6436 smaller and faster; but the checks cannot be conditionalized and are
6437 always done once, early during the @command{configure} run.
6438 @end defmac
6441 @node Structures
6442 @section Structures
6443 @cindex Structure, checking
6445 The following macros check for the presence of certain members in C
6446 structures.  If there is no macro specifically defined to check for a
6447 member you need, then you can use the general structure-member macros
6448 (@pxref{Generic Structures}) or, for more complex tests, you may use
6449 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6451 @menu
6452 * Particular Structures::       Macros to check for certain structure members
6453 * Generic Structures::          How to find other structure members
6454 @end menu
6456 @node Particular Structures
6457 @subsection Particular Structure Checks
6459 The following macros check for certain structures or structure members.
6461 @defmac AC_STRUCT_DIRENT_D_INO
6462 @acindex{STRUCT_DIRENT_D_INO}
6463 @cvindex HAVE_STRUCT_DIRENT_D_INO
6464 @c @caindex header_dirent_dirent_h
6465 @c @caindex member_struct_dirent_d_ino
6466 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6467 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6468 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6470 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6471 @code{d_ino}, not whether its contents are always reliable.
6472 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6473 though current systems hide this detail from the user and never return
6474 zero @code{d_ino} values.
6475 Many current systems report an incorrect @code{d_ino} for a directory
6476 entry that is a mount point.
6477 @end defmac
6479 @defmac AC_STRUCT_DIRENT_D_TYPE
6480 @acindex{STRUCT_DIRENT_D_TYPE}
6481 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6482 @c @caindex header_dirent_dirent_h
6483 @c @caindex member_struct_dirent_d_type
6484 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6485 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6486 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6487 @end defmac
6489 @anchor{AC_STRUCT_ST_BLOCKS}
6490 @defmac AC_STRUCT_ST_BLOCKS
6491 @acindex{STRUCT_ST_BLOCKS}
6492 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6493 @cvindex HAVE_ST_BLOCKS
6494 @ovindex LIBOBJS
6495 @caindex member_struct_stat_st_blocks
6496 If @code{struct stat} contains an @code{st_blocks} member, define
6497 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6498 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6499 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6500 future.
6502 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6503 variable.
6504 @end defmac
6506 @defmac AC_STRUCT_TM
6507 @acindex{STRUCT_TM}
6508 @cvindex TM_IN_SYS_TIME
6509 @hdrindex{time.h}
6510 @hdrindex{sys/time.h}
6511 If @file{time.h} does not define @code{struct tm}, define
6512 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6513 had better define @code{struct tm}.
6515 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6516 current systems.  New programs need not use this macro.
6517 @end defmac
6519 @anchor{AC_STRUCT_TIMEZONE}
6520 @defmac AC_STRUCT_TIMEZONE
6521 @acindex{STRUCT_TIMEZONE}
6522 @cvindex HAVE_DECL_TZNAME
6523 @cvindex HAVE_STRUCT_TM_TM_ZONE
6524 @cvindex HAVE_TM_ZONE
6525 @cvindex HAVE_TZNAME
6526 @c @caindex member_struct_tm_tm_zone
6527 @c @caindex struct_tm
6528 Figure out how to get the current timezone.  If @code{struct tm} has a
6529 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6530 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6531 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6532 define @code{HAVE_DECL_TZNAME}.
6533 @end defmac
6535 @node Generic Structures
6536 @subsection Generic Structure Checks
6538 These macros are used to find structure members not covered by the
6539 ``particular'' test macros.
6541 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6542   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6543   @dvar{includes, AC_INCLUDES_DEFAULT})
6544 @acindex{CHECK_MEMBER}
6545 @caindex member_@var{aggregate}_@var{member}
6546 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6547 If no @var{includes} are specified, the default includes are used
6548 (@pxref{Default Includes}).
6550 @example
6551 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6552                 [AC_MSG_ERROR([we need 'passwd.pw_gecos'])],
6553                 [[#include <pwd.h>]])
6554 @end example
6556 You can use this macro for submembers:
6558 @example
6559 AC_CHECK_MEMBER(struct top.middle.bot)
6560 @end example
6562 This macro caches its result in the
6563 @code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6564 characters not suitable for a variable name mapped to underscores.
6565 @end defmac
6567 @anchor{AC_CHECK_MEMBERS}
6568 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6569   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6570 @acindex{CHECK_MEMBERS}
6571 @cvindex HAVE_@var{aggregate}_@var{member}
6572 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6573 @var{members} using the previous macro.  When @var{member} belongs to
6574 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6575 capitals, with spaces and dots replaced by underscores).  If
6576 @var{action-if-found} is given, it is executed for each of the found
6577 members.  If @var{action-if-not-found} is given, it is executed for each
6578 of the members that could not be found.
6580 @var{includes} is a series of include directives, defaulting to
6581 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6582 prior to the members under test.
6584 This macro uses M4 lists:
6585 @example
6586 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6587 @end example
6588 @end defmac
6591 @node Types
6592 @section Types
6593 @cindex Types
6594 @cindex C types
6596 The following macros check for C types, either builtin or typedefs.  If
6597 there is no macro specifically defined to check for a type you need, and
6598 you don't need to check for any special properties of it, then you can
6599 use a general type-check macro.
6601 @menu
6602 * Particular Types::            Special handling to find certain types
6603 * Generic Types::               How to find other types
6604 @end menu
6606 @node Particular Types
6607 @subsection Particular Type Checks
6609 @hdrindex{sys/types.h}
6610 @hdrindex{stdlib.h}
6611 @hdrindex{stdint.h}
6612 @hdrindex{inttypes.h}
6613 These macros check for particular C types in @file{sys/types.h},
6614 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6615 exist.
6617 The Gnulib @code{stdint} module is an alternate way to define many of
6618 these symbols; it is useful if you prefer your code to assume a
6619 C99-or-better environment.  @xref{Gnulib}.
6621 @anchor{AC_TYPE_GETGROUPS}
6622 @defmac AC_TYPE_GETGROUPS
6623 @acindex{TYPE_GETGROUPS}
6624 @cvindex GETGROUPS_T
6625 @caindex type_getgroups
6626 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6627 is the base type of the array argument to @code{getgroups}.
6629 This macro caches the base type in the @code{ac_cv_type_getgroups}
6630 variable.
6631 @end defmac
6633 @defmac AC_TYPE_INT8_T
6634 @acindex{TYPE_INT8_T}
6635 @cvindex HAVE_INT8_T
6636 @cvindex int8_t
6637 @caindex c_int8_t
6638 If @file{stdint.h} or @file{inttypes.h} does not define the type
6639 @code{int8_t}, define @code{int8_t} to a signed
6640 integer type that is exactly 8 bits wide and that uses two's complement
6641 representation, if such a type exists.
6642 If you are worried about porting to hosts that lack such a type, you can
6643 use the results of this macro in C89-or-later code as follows:
6645 @example
6646 #if HAVE_STDINT_H
6647 # include <stdint.h>
6648 #endif
6649 #if defined INT8_MAX || defined int8_t
6650  @emph{code using int8_t}
6651 #else
6652  @emph{complicated alternative using >8-bit 'signed char'}
6653 #endif
6654 @end example
6656 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6657 @end defmac
6659 @defmac AC_TYPE_INT16_T
6660 @acindex{TYPE_INT16_T}
6661 @cvindex HAVE_INT16_T
6662 @cvindex int16_t
6663 @caindex c_int16_t
6664 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6665 @end defmac
6667 @defmac AC_TYPE_INT32_T
6668 @acindex{TYPE_INT32_T}
6669 @cvindex HAVE_INT32_T
6670 @cvindex int32_t
6671 @caindex c_int32_t
6672 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6673 @end defmac
6675 @defmac AC_TYPE_INT64_T
6676 @acindex{TYPE_INT64_T}
6677 @cvindex HAVE_INT64_T
6678 @cvindex int64_t
6679 @caindex c_int64_t
6680 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6681 @end defmac
6683 @defmac AC_TYPE_INTMAX_T
6684 @acindex{TYPE_INTMAX_T}
6685 @cvindex HAVE_INTMAX_T
6686 @cvindex intmax_t
6687 @c @caindex type_intmax_t
6688 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6689 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6690 widest signed integer type.
6691 @end defmac
6693 @defmac AC_TYPE_INTPTR_T
6694 @acindex{TYPE_INTPTR_T}
6695 @cvindex HAVE_INTPTR_T
6696 @cvindex intptr_t
6697 @c @caindex type_intptr_t
6698 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6699 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6700 signed integer type wide enough to hold a pointer, if such a type
6701 exists.
6702 @end defmac
6704 @defmac AC_TYPE_LONG_DOUBLE
6705 @acindex{TYPE_LONG_DOUBLE}
6706 @cvindex HAVE_LONG_DOUBLE
6707 @caindex type_long_double
6708 If the C compiler supports a working @code{long double} type, define
6709 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6710 same range and precision as @code{double}.
6712 This macro caches its result in the @code{ac_cv_type_long_double}
6713 variable.
6715 This macro is obsolescent, as current C compilers support @code{long
6716 double}.  New programs need not use this macro.
6717 @end defmac
6719 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6720 @acindex{TYPE_LONG_DOUBLE_WIDER}
6721 @cvindex HAVE_LONG_DOUBLE_WIDER
6722 @caindex type_long_double_wider
6723 If the C compiler supports a working @code{long double} type with more
6724 range or precision than the @code{double} type, define
6725 @code{HAVE_LONG_DOUBLE_WIDER}.
6727 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6728 variable.
6729 @end defmac
6731 @defmac AC_TYPE_LONG_LONG_INT
6732 @acindex{TYPE_LONG_LONG_INT}
6733 @cvindex HAVE_LONG_LONG_INT
6734 @caindex type_long_long_int
6735 If the C compiler supports a working @code{long long int} type, define
6736 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6737 @code{long long int} values in preprocessor @code{#if} expressions,
6738 because too many compilers mishandle such expressions.
6739 @xref{Preprocessor Arithmetic}.
6741 This macro caches its result in the @code{ac_cv_type_long_long_int}
6742 variable.
6743 @end defmac
6745 @defmac AC_TYPE_MBSTATE_T
6746 @acindex{TYPE_MBSTATE_T}
6747 @cvindex mbstate_t
6748 @hdrindex{wchar.h}
6749 @caindex type_mbstate_t
6750 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6751 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6752 @code{<wchar.h>} does not declare it.
6754 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6755 variable.
6756 @end defmac
6758 @anchor{AC_TYPE_MODE_T}
6759 @defmac AC_TYPE_MODE_T
6760 @acindex{TYPE_MODE_T}
6761 @cvindex mode_t
6762 @caindex type_mode_t
6763 Define @code{mode_t} to a suitable type, if standard headers do not
6764 define it.
6766 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6767 @end defmac
6769 @anchor{AC_TYPE_OFF_T}
6770 @defmac AC_TYPE_OFF_T
6771 @acindex{TYPE_OFF_T}
6772 @cvindex off_t
6773 @caindex type_off_t
6774 Define @code{off_t} to a suitable type, if standard headers do not
6775 define it.
6777 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6778 @end defmac
6780 @anchor{AC_TYPE_PID_T}
6781 @defmac AC_TYPE_PID_T
6782 @acindex{TYPE_PID_T}
6783 @cvindex pid_t
6784 @caindex type_pid_t
6785 Define @code{pid_t} to a suitable type, if standard headers do not
6786 define it.
6788 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6789 @end defmac
6791 @anchor{AC_TYPE_SIZE_T}
6792 @defmac AC_TYPE_SIZE_T
6793 @acindex{TYPE_SIZE_T}
6794 @cvindex size_t
6795 @caindex type_size_t
6796 Define @code{size_t} to a suitable type, if standard headers do not
6797 define it.
6799 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6800 @end defmac
6802 @defmac AC_TYPE_SSIZE_T
6803 @acindex{TYPE_SSIZE_T}
6804 @cvindex ssize_t
6805 @caindex type_ssize_t
6806 Define @code{ssize_t} to a suitable type, if standard headers do not
6807 define it.
6809 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6810 @end defmac
6812 @anchor{AC_TYPE_UID_T}
6813 @defmac AC_TYPE_UID_T
6814 @acindex{TYPE_UID_T}
6815 @cvindex uid_t
6816 @cvindex gid_t
6817 @caindex type_uid_t
6818 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6819 headers do not define them.
6821 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6822 @end defmac
6824 @defmac AC_TYPE_UINT8_T
6825 @acindex{TYPE_UINT8_T}
6826 @cvindex HAVE_UINT8_T
6827 @cvindex uint8_t
6828 @caindex c_uint8_t
6829 If @file{stdint.h} or @file{inttypes.h} does not define the type
6830 @code{uint8_t}, define @code{uint8_t} to an
6831 unsigned integer type that is exactly 8 bits wide, if such a type
6832 exists.
6833 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6834 @end defmac
6836 @defmac AC_TYPE_UINT16_T
6837 @acindex{TYPE_UINT16_T}
6838 @cvindex HAVE_UINT16_T
6839 @cvindex uint16_t
6840 @caindex c_uint16_t
6841 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6842 @end defmac
6844 @defmac AC_TYPE_UINT32_T
6845 @acindex{TYPE_UINT32_T}
6846 @cvindex HAVE_UINT32_T
6847 @cvindex uint32_t
6848 @caindex c_uint32_t
6849 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6850 @end defmac
6852 @defmac AC_TYPE_UINT64_T
6853 @acindex{TYPE_UINT64_T}
6854 @cvindex HAVE_UINT64_T
6855 @cvindex uint64_t
6856 @caindex c_uint64_t
6857 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6858 @end defmac
6860 @defmac AC_TYPE_UINTMAX_T
6861 @acindex{TYPE_UINTMAX_T}
6862 @cvindex HAVE_UINTMAX_T
6863 @cvindex uintmax_t
6864 @c @caindex type_uintmax_t
6865 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6866 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6867 widest unsigned integer type.
6868 @end defmac
6870 @defmac AC_TYPE_UINTPTR_T
6871 @acindex{TYPE_UINTPTR_T}
6872 @cvindex HAVE_UINTPTR_T
6873 @cvindex uintptr_t
6874 @c @caindex type_uintptr_t
6875 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6876 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6877 unsigned integer type wide enough to hold a pointer, if such a type
6878 exists.
6879 @end defmac
6881 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6882 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6883 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6884 @caindex type_unsigned_long_long_int
6885 If the C compiler supports a working @code{unsigned long long int} type,
6886 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6887 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6888 because too many compilers mishandle such expressions.
6889 @xref{Preprocessor Arithmetic}.
6891 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
6892 variable.
6893 @end defmac
6895 @node Generic Types
6896 @subsection Generic Type Checks
6898 These macros are used to check for types not covered by the ``particular''
6899 test macros.
6901 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6902   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6903 @acindex{CHECK_TYPE}
6904 @caindex type_@var{type}
6905 Check whether @var{type} is defined.  It may be a compiler builtin type
6906 or defined by the @var{includes}.  @var{includes} is a series of include
6907 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6908 Includes}), which are used prior to the type under test.
6910 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6911 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6912 same test is applied when compiling for C++, which means that in C++
6913 @var{type} should be a type-id and should not be an anonymous
6914 @samp{struct} or @samp{union}.
6916 This macro caches its result in the @code{ac_cv_type_@var{type}}
6917 variable, with @samp{*} mapped to @samp{p} and other characters not
6918 suitable for a variable name mapped to underscores.
6919 @end defmac
6922 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6923   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6924 @acindex{CHECK_TYPES}
6925 @cvindex HAVE_@var{type}
6926 For each @var{type} of the @var{types} that is defined, define
6927 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6928 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6929 specified, the default includes are used (@pxref{Default Includes}).  If
6930 @var{action-if-found} is given, it is additional shell code to execute
6931 when one of the types is found.  If @var{action-if-not-found} is given,
6932 it is executed when one of the types is not found.
6934 This macro uses M4 lists:
6935 @example
6936 AC_CHECK_TYPES([ptrdiff_t])
6937 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6938 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6939 @end example
6941 @end defmac
6943 Autoconf, up to 2.13, used to provide to another version of
6944 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6945 compatibility, a simple heuristic, quite safe but not totally, is
6946 implemented.  In case of doubt, read the documentation of the former
6947 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6950 @node Compilers and Preprocessors
6951 @section Compilers and Preprocessors
6952 @cindex Compilers
6953 @cindex Preprocessors
6955 @ovindex EXEEXT
6956 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6957 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6958 the output of the compiler, typically to the empty string if
6959 Posix and @samp{.exe} if a DOS variant.
6961 @ovindex OBJEXT
6962 They also define the output variable @code{OBJEXT} based on the
6963 output of the compiler, after @file{.c} files have been excluded, typically
6964 to @samp{o} if Posix, @samp{obj} if a DOS variant.
6966 If the compiler being used does not produce executables, the tests fail.  If
6967 the executables can't be run, and cross-compilation is not enabled, they
6968 fail too.  @xref{Manual Configuration}, for more on support for cross
6969 compiling.
6971 @menu
6972 * Specific Compiler Characteristics::  Some portability issues
6973 * Generic Compiler Characteristics::  Language independent tests and features
6974 * C Compiler::                  Checking its characteristics
6975 * C++ Compiler::                Likewise
6976 * Objective C Compiler::        Likewise
6977 * Objective C++ Compiler::      Likewise
6978 * Erlang Compiler and Interpreter::  Likewise
6979 * Fortran Compiler::            Likewise
6980 * Go Compiler::                 Likewise
6981 @end menu
6983 @node Specific Compiler Characteristics
6984 @subsection Specific Compiler Characteristics
6986 Some compilers exhibit different behaviors.
6988 @table @asis
6989 @item Static/Dynamic Expressions
6990 Autoconf relies on a trick to extract one bit of information from the C
6991 compiler: using negative array sizes.  For instance the following
6992 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6993 bytes wide:
6995 @example
6996 static int test_array[sizeof (int) == 4 ? 1 : -1];
6997 @end example
6999 @noindent
7000 To our knowledge, there is a single compiler that does not support this
7001 trick: the HP C compilers (the real ones, not only the
7002 ``bundled'') on HP-UX 11.00.
7003 They incorrectly reject the above program with the diagnostic
7004 ``Variable-length arrays cannot have static storage.''
7005 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
7006 not from the @code{? 1 : -1}, and
7007 Autoconf works around this problem by casting @code{sizeof (int)} to
7008 @code{long int} before comparing it.
7009 @end table
7011 @node Generic Compiler Characteristics
7012 @subsection Generic Compiler Characteristics
7014 @anchor{AC_CHECK_SIZEOF}
7015 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7016   @dvar{includes, AC_INCLUDES_DEFAULT})
7017 @acindex{CHECK_SIZEOF}
7018 @cvindex SIZEOF_@var{type-or-expr}
7019 @caindex sizeof_@var{type-or-expr}
7020 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7021 the size in bytes of @var{type-or-expr}, which may be either a type or
7022 an expression returning a value that has a size.  If the expression
7023 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7024 @var{includes} is a series of include directives, defaulting to
7025 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7026 prior to the expression under test.
7028 This macro now works even when cross-compiling.  The @var{unused}
7029 argument was used when cross-compiling.
7031 For example, the call
7033 @example
7034 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7035 AC_CHECK_SIZEOF([int *])
7036 @end example
7038 @noindent
7039 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
7041 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7042 variable, with @samp{*} mapped to @samp{p} and other characters not
7043 suitable for a variable name mapped to underscores.
7044 @end defmac
7046 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7047 @acindex{CHECK_ALIGNOF}
7048 @cvindex ALIGNOF_@var{type}
7049 @caindex alignof_@var{type-or-expr}
7050 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7051 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
7052 a structure member declaration.  If @samp{type} is unknown, the result
7053 is 0.  If no @var{includes} are specified, the default includes are used
7054 (@pxref{Default Includes}).
7056 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7057 variable, with @samp{*} mapped to @samp{p} and other characters not
7058 suitable for a variable name mapped to underscores.
7059 @end defmac
7061 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7062   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7063 @acindex{COMPUTE_INT}
7064 Store into the shell variable @var{var} the value of the integer
7065 @var{expression}.  The
7066 value should fit in an initializer in a C variable of type @code{signed
7067 long}.  To support cross compilation (in which case, the macro only works on
7068 hosts that use twos-complement arithmetic), it should be possible to evaluate
7069 the expression at compile-time.  If no @var{includes} are specified, the
7070 default includes are used (@pxref{Default Includes}).
7072 Execute @var{action-if-fails} if the value cannot be determined correctly.
7073 @end defmac
7075 @defmac AC_LANG_WERROR
7076 @acindex{LANG_WERROR}
7077 Normally Autoconf ignores warnings generated by the compiler, linker, and
7078 preprocessor.  If this macro is used, warnings count as fatal
7079 errors for the current language.  This macro is useful when the
7080 results of configuration are used where warnings are unacceptable; for
7081 instance, if parts of a program are built with the GCC
7082 @option{-Werror}
7083 option.  If the whole program is built using @option{-Werror} it is
7084 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7085 etc.).
7086 @end defmac
7088 @defmac AC_OPENMP
7089 @acindex{OPENMP}
7090 @cvindex _OPENMP
7091 @ovindex OPENMP_CFLAGS
7092 @ovindex OPENMP_CXXFLAGS
7093 @ovindex OPENMP_FFLAGS
7094 @ovindex OPENMP_FCFLAGS
7095 @caindex prog_c_openmp
7096 @caindex prog_cxx_openmp
7097 @caindex prog_f77_openmp
7098 @caindex prog_fc_openmp
7099 @uref{http://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7100 and Fortran that simplify optimization of shared memory parallelism,
7101 which is a common problem on multicore CPUs.
7103 If the current language is C, the macro @code{AC_OPENMP} sets the
7104 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7105 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
7106 compiler already supports OpenMP, if it has no way to activate OpenMP
7107 support, or if the user rejects OpenMP support by invoking
7108 @samp{configure} with the @samp{--disable-openmp} option.
7110 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7111 preprocessing program source, and when linking programs.  Therefore you
7112 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7113 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
7114 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
7115 OpenMP support is revealed at compile time by the preprocessor macro
7116 @code{_OPENMP}.
7118 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7119 shared library to the program's dependencies, so its use is recommended
7120 only on programs that actually require OpenMP.
7122 If the current language is C++, @code{AC_OPENMP} sets the variable
7123 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7124 hold as for C.
7126 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7127 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7128 respectively.  Similar remarks as for C hold, except that
7129 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7130 signals OpenMP support.
7132 For portability, it is best to avoid spaces between @samp{#} and
7133 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7134 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7135 latter.
7137 This macro caches its result in the @code{ac_cv_prog_c_openmp},
7138 @code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7139 @code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7140 @end defmac
7142 @node C Compiler
7143 @subsection C Compiler Characteristics
7145 The following macros provide ways to find and exercise a C Compiler.
7146 There are a few constructs that ought to be avoided, but do not deserve
7147 being checked for, since they can easily be worked around.
7149 @table @asis
7150 @item Don't use lines containing solitary backslashes
7151 They tickle a bug in the HP-UX C compiler (checked on
7152 HP-UX 10.20,
7153 11.00, and 11i).  When given the following source:
7155 @example
7156 #ifdef __STDC__
7158 * A comment with backslash-newlines in it.  %@{ %@} *\
7161 char str[] = "\\
7162 " A string with backslash-newlines in it %@{ %@} \\
7164 char apostrophe = '\\
7168 #endif
7169 @end example
7171 @noindent
7172 the compiler incorrectly fails with the diagnostics ``Non-terminating
7173 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7174 Removing the lines with solitary backslashes solves the problem.
7176 @item Don't compile several files at once if output matters to you
7177 Some compilers, such as HP's, report names of files being
7178 compiled when given more than one file operand.  For instance:
7180 @example
7181 $ @kbd{cc a.c b.c}
7182 a.c:
7183 b.c:
7184 @end example
7186 @noindent
7187 This can cause problems if you observe the output of the compiler to
7188 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7189 b.o} solves the issue.
7191 @item Don't rely on @code{#error} failing
7192 The IRIX C compiler does not fail when #error is preprocessed; it
7193 simply emits a diagnostic and continues, exiting successfully.  So,
7194 instead of an error directive like @code{#error "Unsupported word size"}
7195 it is more portable to use an invalid directive like @code{#Unsupported
7196 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7197 OK, since installers with inadequate compilers like IRIX can simply
7198 examine these compilers' diagnostic output.
7200 @item Don't rely on correct @code{#line} support
7201 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7202 diagnoses @code{#line} directives whose line
7203 numbers are greater than 32767.  Nothing in Posix
7204 makes this invalid.  That is why Autoconf stopped issuing
7205 @code{#line} directives.
7206 @end table
7208 @anchor{AC_PROG_CC}
7209 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7210 @acindex{PROG_CC}
7211 @evindex CC
7212 @evindex CFLAGS
7213 @ovindex CC
7214 @ovindex CFLAGS
7215 @caindex prog_cc_stdc
7216 Determine a C compiler to use.  If @code{CC} is not already set in the
7217 environment, check for @code{gcc} and @code{cc}, then for other C
7218 compilers.  Set output variable @code{CC} to the name of the compiler
7219 found.
7221 This macro may, however, be invoked with an optional first argument
7222 which, if specified, must be a blank-separated list of C compilers to
7223 search for.  This just gives the user an opportunity to specify an
7224 alternative search list for the C compiler.  For example, if you didn't
7225 like the default order, then you could invoke @code{AC_PROG_CC} like
7226 this:
7228 @example
7229 AC_PROG_CC([gcc cl cc])
7230 @end example
7232 If necessary, add an option to output variable @code{CC} to enable
7233 support for ISO Standard C features with extensions.  Prefer the newest
7234 C standard that is supported.  Currently the newest standard is ISO C11,
7235 with ISO C99 and ANSI C89 (ISO C90) being the older versions.
7236 After calling this macro you can check whether the C compiler has been
7237 set to accept Standard C; if not, the shell variable
7238 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7240 When attempting to add compiler options, prefer extended functionality
7241 to strict conformance: the goal is to enable whatever standard features
7242 that are available, not to check for full conformance to the standard or
7243 to prohibit incompatible extensions.  Test for C11 support by checking
7244 for @code{_Alignas}, @code{_Alignof}, @code{_Noreturn},
7245 @code{_Static_assert}, UTF-8 string literals, duplicate @code{typedef}s,
7246 and anonymous structures and unions.  Test for C99 support by checking
7247 for @code{_Bool}, @code{//} comments, flexible array members,
7248 @code{inline}, signed and unsigned @code{long long int}, mixed code and
7249 declarations, named initialization of structs, @code{restrict},
7250 @code{va_copy}, varargs macros, variable declarations in @code{for}
7251 loops, and variable length arrays.  Test for C89 support by checking for
7252 function prototypes.
7254 If using a compiler that supports GNU C, set shell variable @code{GCC} to
7255 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
7256 it to @option{-g -O2} for a GNU C compiler (@option{-O2} on systems
7257 where the compiler does not accept @option{-g}), or @option{-g} for
7258 other compilers.  If your package does not like this default, then it is
7259 acceptable to insert the line @samp{: $@{CFLAGS=""@}} after @code{AC_INIT}
7260 and before @code{AC_PROG_CC} to select an empty default instead.
7262 Many Autoconf macros use a compiler, and thus call
7263 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7264 determined before the body of the outermost @code{AC_DEFUN} macro.
7265 @code{AC_PROG_CC} is therefore defined via @code{AC_DEFUN_ONCE} to avoid
7266 needless reexpansion (@pxref{One-Shot Macros}).
7267 @end defmac
7269 @anchor{AC_PROG_CC_C_O}
7270 @defmac AC_PROG_CC_C_O
7271 @acindex{PROG_CC_C_O}
7272 @cvindex NO_MINUS_C_MINUS_O
7273 @caindex prog_cc_@var{compiler}_c_o
7274 If the C compiler does not accept the @option{-c} and @option{-o} options
7275 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7276 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7277 the first @code{cc} in the path.  The test fails if one fails.  This
7278 macro was created for GNU Make to choose the default C compilation
7279 rule.
7281 For the compiler @var{compiler}, this macro caches its result in the
7282 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7283 @end defmac
7286 @defmac AC_PROG_CPP
7287 @acindex{PROG_CPP}
7288 @evindex CPP
7289 @ovindex CPP
7290 Set output variable @code{CPP} to a command that runs the
7291 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
7292 It is only portable to run @code{CPP} on files with a @file{.c}
7293 extension.
7295 Some preprocessors don't indicate missing include files by the error
7296 status.  For such preprocessors an internal variable is set that causes
7297 other macros to check the standard error from the preprocessor and
7298 consider the test failed if any warnings have been reported.
7299 For most preprocessors, though, warnings do not cause include-file
7300 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7301 @end defmac
7303 @defmac AC_PROG_CPP_WERROR
7304 @acindex{PROG_CPP_WERROR}
7305 @ovindex CPP
7306 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7307 preprocessor as errors even if the preprocessor exit status indicates
7308 success.  This is useful for avoiding headers that generate mandatory
7309 warnings, such as deprecation notices.
7310 @end defmac
7313 The following macros check for C compiler or machine architecture
7314 features.  To check for characteristics not listed here, use
7315 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7316 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7318 @defmac AC_C_BACKSLASH_A
7319 @acindex{C_BACKSLASH_A}
7320 @cvindex HAVE_C_BACKSLASH_A
7321 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7322 @samp{\a}.
7324 This macro is obsolescent, as current C compilers understand @samp{\a}.
7325 New programs need not use this macro.
7326 @end defmac
7328 @anchor{AC_C_BIGENDIAN}
7329 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7330   @ovar{action-if-unknown}, @ovar{action-if-universal})
7331 @acindex{C_BIGENDIAN}
7332 @cvindex WORDS_BIGENDIAN
7333 @cindex Endianness
7334 If words are stored with the most significant byte first (like Motorola
7335 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7336 the least significant byte first (like Intel and VAX CPUs), execute
7337 @var{action-if-false}.
7339 This macro runs a test-case if endianness cannot be determined from the
7340 system header files.  When cross-compiling, the test-case is not run but
7341 grep'ed for some magic values.  @var{action-if-unknown} is executed if
7342 the latter case fails to determine the byte sex of the host system.
7344 In some cases a single run of a compiler can generate code for multiple
7345 architectures.  This can happen, for example, when generating Mac OS X
7346 universal binary files, which work on both PowerPC and Intel
7347 architectures.  In this case, the different variants might be for
7348 different architectures whose endiannesses differ.  If
7349 @command{configure} detects this, it executes @var{action-if-universal}
7350 instead of @var{action-if-unknown}.
7352 The default for @var{action-if-true} is to define
7353 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7354 nothing.  The default for @var{action-if-unknown} is to
7355 abort configure and tell the installer how to bypass this test.
7356 And finally, the default for @var{action-if-universal} is to ensure that
7357 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7358 detected and the current code is big-endian; this default works only if
7359 @command{autoheader} is used (@pxref{autoheader Invocation}).
7361 If you use this macro without specifying @var{action-if-universal}, you
7362 should also use @code{AC_CONFIG_HEADERS}; otherwise
7363 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7364 binary files.
7365 @end defmac
7367 @anchor{AC_C_CONST}
7368 @defmac AC_C_CONST
7369 @acindex{C_CONST}
7370 @cvindex const
7371 @caindex c_const
7372 If the C compiler does not fully support the @code{const} keyword,
7373 define @code{const} to be empty.  Some C compilers that do
7374 not define @code{__STDC__} do support @code{const}; some compilers that
7375 define @code{__STDC__} do not completely support @code{const}.  Programs
7376 can simply use @code{const} as if every C compiler supported it; for
7377 those that don't, the makefile or configuration header file
7378 defines it as empty.
7380 Occasionally installers use a C++ compiler to compile C code, typically
7381 because they lack a C compiler.  This causes problems with @code{const},
7382 because C and C++ treat @code{const} differently.  For example:
7384 @example
7385 const int foo;
7386 @end example
7388 @noindent
7389 is valid in C but not in C++.  These differences unfortunately cannot be
7390 papered over by defining @code{const} to be empty.
7392 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7393 as this generally yields better results in practice.  However, using a
7394 C++ compiler to compile C code is not recommended or supported, and
7395 installers who run into trouble in this area should get a C compiler
7396 like GCC to compile their C code.
7398 This macro caches its result in the @code{ac_cv_c_const} variable.
7400 This macro is obsolescent, as current C compilers support @code{const}.
7401 New programs need not use this macro.
7402 @end defmac
7404 @defmac AC_C__GENERIC
7405 @acindex{C__GENERIC}
7406 @cvindex _Generic
7407 If the C compiler supports C11-style generic selection using the
7408 @code{_Generic} keyword, define @code{HAVE_C__GENERIC}.
7409 @end defmac
7411 @defmac AC_C_RESTRICT
7412 @acindex{C_RESTRICT}
7413 @cvindex restrict
7414 @caindex c_restrict
7415 If the C compiler recognizes a variant spelling for the @code{restrict}
7416 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7417 then define @code{restrict} to that; this is more likely to do the right
7418 thing with compilers that support language variants where plain
7419 @code{restrict} is not a keyword.  Otherwise, if the C compiler
7420 recognizes the @code{restrict} keyword, don't do anything.
7421 Otherwise, define @code{restrict} to be empty.
7422 Thus, programs may simply use @code{restrict} as if every C compiler
7423 supported it; for those that do not, the makefile
7424 or configuration header defines it away.
7426 Although support in C++ for the @code{restrict} keyword is not
7427 required, several C++ compilers do accept the keyword.
7428 This macro works for them, too.
7430 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7431 if @code{restrict} is not supported, and a supported spelling otherwise.
7432 @end defmac
7434 @defmac AC_C_VOLATILE
7435 @acindex{C_VOLATILE}
7436 @cvindex volatile
7437 If the C compiler does not understand the keyword @code{volatile},
7438 define @code{volatile} to be empty.  Programs can simply use
7439 @code{volatile} as if every C compiler supported it; for those that do
7440 not, the makefile or configuration header defines it as
7441 empty.
7443 If the correctness of your program depends on the semantics of
7444 @code{volatile}, simply defining it to be empty does, in a sense, break
7445 your code.  However, given that the compiler does not support
7446 @code{volatile}, you are at its mercy anyway.  At least your
7447 program compiles, when it wouldn't before.
7448 @xref{Volatile Objects}, for more about @code{volatile}.
7450 In general, the @code{volatile} keyword is a standard C feature, so
7451 you might expect that @code{volatile} is available only when
7452 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7453 support volatile, but does not define @code{__STDC__}.
7455 This macro is obsolescent, as current C compilers support @code{volatile}.
7456 New programs need not use this macro.
7457 @end defmac
7459 @anchor{AC_C_INLINE}
7460 @defmac AC_C_INLINE
7461 @acindex{C_INLINE}
7462 @cvindex inline
7463 If the C compiler supports the keyword @code{inline}, do nothing.
7464 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7465 if it accepts one of those, otherwise define @code{inline} to be empty.
7466 @end defmac
7468 @anchor{AC_C_CHAR_UNSIGNED}
7469 @defmac AC_C_CHAR_UNSIGNED
7470 @acindex{C_CHAR_UNSIGNED}
7471 @cvindex __CHAR_UNSIGNED__
7472 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7473 unless the C compiler predefines it.
7475 These days, using this macro is not necessary.  The same information can
7476 be determined by this portable alternative, thus avoiding the use of
7477 preprocessor macros in the namespace reserved for the implementation.
7479 @example
7480 #include <limits.h>
7481 #if CHAR_MIN == 0
7482 # define CHAR_UNSIGNED 1
7483 #endif
7484 @end example
7485 @end defmac
7487 @defmac AC_C_STRINGIZE
7488 @acindex{C_STRINGIZE}
7489 @cvindex HAVE_STRINGIZE
7490 If the C preprocessor supports the stringizing operator, define
7491 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7492 found in macros such as this:
7494 @example
7495 #define x(y) #y
7496 @end example
7498 This macro is obsolescent, as current C compilers support the
7499 stringizing operator.  New programs need not use this macro.
7500 @end defmac
7502 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7503 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7504 @cvindex FLEXIBLE_ARRAY_MEMBER
7505 If the C compiler supports flexible array members, define
7506 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7507 That way, a declaration like this:
7509 @example
7510 struct s
7511   @{
7512     size_t n_vals;
7513     double val[FLEXIBLE_ARRAY_MEMBER];
7514   @};
7515 @end example
7517 @noindent
7518 will let applications use the ``struct hack'' even with compilers that
7519 do not support flexible array members.  To allocate and use such an
7520 object, you can use code like this:
7522 @example
7523 size_t i;
7524 size_t n = compute_value_count ();
7525 struct s *p =
7526    malloc (offsetof (struct s, val)
7527            + n * sizeof (double));
7528 p->n_vals = n;
7529 for (i = 0; i < n; i++)
7530   p->val[i] = compute_value (i);
7531 @end example
7532 @end defmac
7534 @defmac AC_C_VARARRAYS
7535 @acindex{C_VARARRAYS}
7536 @cvindex __STDC_NO_VLA__
7537 @cvindex HAVE_C_VARARRAYS
7538 If the C compiler does not support variable-length arrays, define the
7539 macro @code{__STDC_NO_VLA__} to be 1 if it is not already defined.  A
7540 variable-length array is an array of automatic storage duration whose
7541 length is determined at run time, when the array is declared.  For
7542 backward compatibility this macro also defines @code{HAVE_C_VARARRAYS}
7543 if the C compiler supports variable-length arrays, but this usage is
7544 obsolescent and new programs should use @code{__STDC_NO_VLA__}.
7545 @end defmac
7547 @defmac AC_C_TYPEOF
7548 @acindex{C_TYPEOF}
7549 @cvindex HAVE_TYPEOF
7550 @cvindex typeof
7551 If the C compiler supports GNU C's @code{typeof} syntax either
7552 directly or
7553 through a different spelling of the keyword (e.g., @code{__typeof__}),
7554 define @code{HAVE_TYPEOF}.  If the support is available only through a
7555 different spelling, define @code{typeof} to that spelling.
7556 @end defmac
7558 @defmac AC_C_PROTOTYPES
7559 @acindex{C_PROTOTYPES}
7560 @cvindex PROTOTYPES
7561 @cvindex __PROTOTYPES
7562 @cvindex PARAMS
7563 If function prototypes are understood by the compiler (as determined by
7564 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7565 Defining @code{__PROTOTYPES} is for the benefit of
7566 header files that cannot use macros that infringe on user name space.
7568 This macro is obsolescent, as current C compilers support prototypes.
7569 New programs need not use this macro.
7570 @end defmac
7572 @anchor{AC_PROG_GCC_TRADITIONAL}
7573 @defmac AC_PROG_GCC_TRADITIONAL
7574 @acindex{PROG_GCC_TRADITIONAL}
7575 @ovindex CC
7576 Add @option{-traditional} to output variable @code{CC} if using a
7577 GNU C compiler and @code{ioctl} does not work properly without
7578 @option{-traditional}.  That usually happens when the fixed header files
7579 have not been installed on an old system.
7581 This macro is obsolescent, since current versions of the GNU C
7582 compiler fix the header files automatically when installed.
7583 @end defmac
7586 @node C++ Compiler
7587 @subsection C++ Compiler Characteristics
7590 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7591 @acindex{PROG_CXX}
7592 @evindex CXX
7593 @evindex CXXFLAGS
7594 @ovindex CXX
7595 @ovindex CXXFLAGS
7596 Determine a C++ compiler to use.  Check whether the environment variable
7597 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7598 variable @code{CXX} to its value.
7600 Otherwise, if the macro is invoked without an argument, then search for
7601 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7602 then other names).  If none of those checks succeed, then as a last
7603 resort set @code{CXX} to @code{g++}.
7605 This macro may, however, be invoked with an optional first argument
7606 which, if specified, must be a blank-separated list of C++ compilers to
7607 search for.  This just gives the user an opportunity to specify an
7608 alternative search list for the C++ compiler.  For example, if you
7609 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7610 like this:
7612 @example
7613 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7614 @end example
7616 If necessary, add an option to output variable @code{CXX} to enable
7617 support for ISO Standard C++ features with extensions.  Prefer the
7618 newest C++ standard that is supported.  Currently the newest standard is
7619 ISO C++11, with ISO C++98 being the previous standard.  After calling
7620 this macro you can check whether the C++ compiler has been set to accept
7621 Standard C++; if not, the shell variable @code{ac_cv_prog_cxx_stdcxx} is
7622 set to @samp{no}.  If the C++ compiler will not accept C++11, the shell
7623 variable @code{ac_cv_prog_cxx_cxx11} is set to @samp{no}, and if it will
7624 not accept C++98, the shell variable @code{ac_cv_prog_cxx_cxx98} is set
7625 to @samp{no}.
7627 When attempting to add compiler options, prefer extended functionality
7628 to strict conformance: the goal is to enable whatever standard features
7629 that are available, not to check for full conformance to the standard or
7630 to prohibit incompatible extensions.  Test for C++11 support by checking
7631 for the language features @code{auto}, @code{constexpr},
7632 @code{decltype}, @code{default}ed and @code{delete}ed constructors,
7633 delegate constructors, @code{final}, initializer lists, lambda
7634 functions, @code{nullptr}, @code{override}, range-based for loops,
7635 template brackets without spaces and unicode literals, and library
7636 features @code{std::array}, @code{std::shared_ptr},
7637 @code{std::weak_ptr}, @code{std::regex} and @code{std::tuple}.  Test for
7638 C++98 support using basic features of the @code{std} namespace including
7639 @code{std::string}, containers (@code{std::list}, @code{std::map},
7640 @code{std::set}, @code{std::vector}), streams (fstreams, iostreams,
7641 stringstreams, iomanip), @code{std::pair}, exceptions (@code{try},
7642 @code{catch} and @code{std::runtime_error}) and algorithms.  Tests for
7643 more recent standards include all the tests for older standards.
7645 If using the GNU C++ compiler, set shell variable @code{GXX} to
7646 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7647 it to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on
7648 systems where G++ does not accept @option{-g}), or @option{-g} for other
7649 compilers.  If your package does not like this default, then it is
7650 acceptable to insert the line @samp{: $@{CXXFLAGS=""@}} after @code{AC_INIT}
7651 and before @code{AC_PROG_CXX} to select an empty default instead.
7652 @end defmac
7654 @defmac AC_PROG_CXXCPP
7655 @acindex{PROG_CXXCPP}
7656 @evindex CXXCPP
7657 @ovindex CXXCPP
7658 Set output variable @code{CXXCPP} to a command that runs the C++
7659 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7660 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7661 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7663 Some preprocessors don't indicate missing include files by the error
7664 status.  For such preprocessors an internal variable is set that causes
7665 other macros to check the standard error from the preprocessor and
7666 consider the test failed if any warnings have been reported.  However,
7667 it is not known whether such broken preprocessors exist for C++.
7668 @end defmac
7670 @defmac AC_PROG_CXX_C_O
7671 @acindex{PROG_CXX_C_O}
7672 @cvindex CXX_NO_MINUS_C_MINUS_O
7673 Test whether the C++ compiler accepts the options @option{-c} and
7674 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7675 if it does not.
7676 @end defmac
7679 @node Objective C Compiler
7680 @subsection Objective C Compiler Characteristics
7683 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7684 @acindex{PROG_OBJC}
7685 @evindex OBJC
7686 @evindex OBJCFLAGS
7687 @ovindex OBJC
7688 @ovindex OBJCFLAGS
7689 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7690 set in the environment, check for Objective C compilers.  Set output
7691 variable @code{OBJC} to the name of the compiler found.
7693 This macro may, however, be invoked with an optional first argument
7694 which, if specified, must be a blank-separated list of Objective C compilers to
7695 search for.  This just gives the user an opportunity to specify an
7696 alternative search list for the Objective C compiler.  For example, if you
7697 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7698 like this:
7700 @example
7701 AC_PROG_OBJC([gcc objcc objc])
7702 @end example
7704 If using a compiler that supports GNU Objective C, set shell variable
7705 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7706 already set, set it to @option{-g -O2} for a GNU Objective C
7707 compiler (@option{-O2} on systems where the compiler does not accept
7708 @option{-g}), or @option{-g} for other compilers.
7709 @end defmac
7711 @defmac AC_PROG_OBJCPP
7712 @acindex{PROG_OBJCPP}
7713 @evindex OBJCPP
7714 @ovindex OBJCPP
7715 Set output variable @code{OBJCPP} to a command that runs the Objective C
7716 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7717 @end defmac
7720 @node Objective C++ Compiler
7721 @subsection Objective C++ Compiler Characteristics
7724 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7725 @acindex{PROG_OBJCXX}
7726 @evindex OBJCXX
7727 @evindex OBJCXXFLAGS
7728 @ovindex OBJCXX
7729 @ovindex OBJCXXFLAGS
7730 Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
7731 set in the environment, check for Objective C++ compilers.  Set output
7732 variable @code{OBJCXX} to the name of the compiler found.
7734 This macro may, however, be invoked with an optional first argument
7735 which, if specified, must be a blank-separated list of Objective C++ compilers
7736 to search for.  This just gives the user an opportunity to specify an
7737 alternative search list for the Objective C++ compiler.  For example, if you
7738 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7739 like this:
7741 @example
7742 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7743 @end example
7745 If using a compiler that supports GNU Objective C++, set shell variable
7746 @code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
7747 already set, set it to @option{-g -O2} for a GNU Objective C++
7748 compiler (@option{-O2} on systems where the compiler does not accept
7749 @option{-g}), or @option{-g} for other compilers.
7750 @end defmac
7752 @defmac AC_PROG_OBJCXXCPP
7753 @acindex{PROG_OBJCXXCPP}
7754 @evindex OBJCXXCPP
7755 @ovindex OBJCXXCPP
7756 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7757 preprocessor.  If @samp{$OBJCXX -E} doesn't work, @file{/lib/cpp} is used.
7758 @end defmac
7761 @node Erlang Compiler and Interpreter
7762 @subsection Erlang Compiler and Interpreter Characteristics
7763 @cindex Erlang
7765 Autoconf defines the following macros for determining paths to the essential
7766 Erlang/OTP programs:
7768 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7769 @acindex{ERLANG_PATH_ERLC}
7770 @evindex ERLC
7771 @evindex ERLCFLAGS
7772 @ovindex ERLC
7773 @ovindex ERLCFLAGS
7774 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7775 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7776 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7777 is not set in the environment, set it to an empty value.
7779 The two optional arguments have the same meaning as the two last arguments of
7780 macro @code{AC_PATH_PROG} for looking for the @command{erlc} program.  For
7781 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7782 directory:
7784 @example
7785 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7786 @end example
7787 @end defmac
7789 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7790 @acindex{ERLANG_NEED_ERLC}
7791 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7792 error message and exits the @command{configure} script if the @command{erlc}
7793 program is not found.
7794 @end defmac
7796 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7797 @acindex{ERLANG_PATH_ERL}
7798 @evindex ERL
7799 @ovindex ERL
7800 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7801 set in the
7802 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7803 complete path of the interpreter command found.
7805 The two optional arguments have the same meaning as the two last arguments of
7806 macro @code{AC_PATH_PROG} for looking for the @command{erl} program.  For
7807 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7808 directory:
7810 @example
7811 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7812 @end example
7813 @end defmac
7815 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7816 @acindex{ERLANG_NEED_ERL}
7817 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7818 error message and exits the @command{configure} script if the @command{erl}
7819 program is not found.
7820 @end defmac
7823 @node Fortran Compiler
7824 @subsection Fortran Compiler Characteristics
7825 @cindex Fortran
7826 @cindex F77
7828 The Autoconf Fortran support is divided into two categories: legacy
7829 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7830 The former are intended for traditional Fortran 77 code, and have output
7831 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7832 are for newer programs that can (or must) compile under the newer
7833 Fortran standards, and have output variables like @code{FC},
7834 @code{FCFLAGS}, and @code{FCLIBS}.
7836 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7837 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7838 @code{FC} and @code{F77} macros behave almost identically, and so they
7839 are documented together in this section.
7842 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7843 @acindex{PROG_F77}
7844 @evindex F77
7845 @evindex FFLAGS
7846 @ovindex F77
7847 @ovindex FFLAGS
7848 @caindex f77_compiler_gnu
7849 @caindex prog_f77_g
7850 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7851 set in the environment, then check for @code{g77} and @code{f77}, and
7852 then some other names.  Set the output variable @code{F77} to the name
7853 of the compiler found.
7855 This macro may, however, be invoked with an optional first argument
7856 which, if specified, must be a blank-separated list of Fortran 77
7857 compilers to search for.  This just gives the user an opportunity to
7858 specify an alternative search list for the Fortran 77 compiler.  For
7859 example, if you didn't like the default order, then you could invoke
7860 @code{AC_PROG_F77} like this:
7862 @example
7863 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7864 @end example
7866 If using a compiler that supports GNU Fortran 77,
7867 set the shell variable @code{G77} to @samp{yes}.
7868 If the output variable @code{FFLAGS} was not already set in the
7869 environment, set it to @option{-g -02} for @code{g77} (or @option{-O2}
7870 where the GNU Fortran 77 compiler does not accept @option{-g}), or
7871 @option{-g} for other compilers.
7873 The result of the GNU test is cached in the
7874 @code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
7875 @code{ac_cv_prog_f77_g} variable.
7876 @end defmac
7878 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7879 @acindex{PROG_FC}
7880 @evindex FC
7881 @evindex FCFLAGS
7882 @ovindex FC
7883 @ovindex FCFLAGS
7884 @caindex fc_compiler_gnu
7885 @caindex prog_fc_g
7886 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7887 the environment, then @code{dialect} is a hint to indicate what Fortran
7888 dialect to search for; the default is to search for the newest available
7889 dialect.  Set the output variable @code{FC} to the name of the compiler
7890 found.
7892 By default, newer dialects are preferred over older dialects, but if
7893 @code{dialect} is specified then older dialects are preferred starting
7894 with the specified dialect.  @code{dialect} can currently be one of
7895 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7896 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7897 and no attempt is made to guarantee that a particular language standard
7898 is actually supported.  Thus, it is preferable that you avoid the
7899 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7900 the latest Fortran standard.
7902 This macro may, alternatively, be invoked with an optional first argument
7903 which, if specified, must be a blank-separated list of Fortran
7904 compilers to search for, just as in @code{AC_PROG_F77}.
7906 If using a compiler that supports GNU Fortran,
7907 set the shell variable @code{GFC} to @samp{yes}.
7908 If the output variable @code{FCFLAGS} was not already set in the
7909 environment, then set it to @option{-g -02} for a GNU Fortran compiler (or
7910 @option{-O2} where the compiler does not accept @option{-g}), or
7911 @option{-g} for other compilers.
7913 The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
7914 variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
7915 variable.
7916 @end defmac
7918 @defmac AC_PROG_F77_C_O
7919 @defmacx AC_PROG_FC_C_O
7920 @acindex{PROG_F77_C_O}
7921 @acindex{PROG_FC_C_O}
7922 @cvindex F77_NO_MINUS_C_MINUS_O
7923 @cvindex FC_NO_MINUS_C_MINUS_O
7924 @caindex prog_f77_c_o
7925 @caindex prog_fc_c_o
7926 Test whether the Fortran compiler accepts the options @option{-c} and
7927 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7928 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7930 The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
7931 @code{ac_cv_prog_fc_c_o} variable, respectively.
7932 @end defmac
7934 The following macros check for Fortran compiler characteristics.
7935 To check for characteristics not listed here, use
7936 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7937 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7938 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7939 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7942 @defmac AC_F77_LIBRARY_LDFLAGS
7943 @defmacx AC_FC_LIBRARY_LDFLAGS
7944 @acindex{F77_LIBRARY_LDFLAGS}
7945 @ovindex FLIBS
7946 @acindex{FC_LIBRARY_LDFLAGS}
7947 @ovindex FCLIBS
7948 @caindex prog_f77_v
7949 @caindex prog_fc_v
7950 @caindex f77_libs
7951 @caindex fc_libs
7952 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7953 @dfn{Fortran intrinsic and runtime libraries} that are required to
7954 successfully link a Fortran program or shared library.  The output
7955 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7956 should be included after @code{LIBS} when linking).
7958 This macro is intended to be used in those situations when it is
7959 necessary to mix, e.g., C++ and Fortran source code in a single
7960 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7961 automake, GNU Automake}).
7963 For example, if object files from a C++ and Fortran compiler must be
7964 linked together, then the C++ compiler/linker must be used for linking
7965 (since special C++-ish things need to happen at link time like calling
7966 global constructors, instantiating templates, enabling exception
7967 support, etc.).
7969 However, the Fortran intrinsic and runtime libraries must be linked in
7970 as well, but the C++ compiler/linker doesn't know by default how to add
7971 these Fortran 77 libraries.  Hence, this macro was created to determine
7972 these Fortran libraries.
7974 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7975 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7976 link C/C++ with Fortran; see below.  Further, it is highly recommended
7977 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
7978 because the complex defines that the function wrapper macros create
7979 may not work with C/C++ compiler drivers.
7981 These macros internally compute the flag needed to verbose linking
7982 output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
7983 variables, respectively.  The computed linker flags are cached in
7984 @code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
7985 @end defmac
7987 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @
7988   @dvar{action-if-not-found, AC_MSG_FAILURE})
7989 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @
7990   @dvar{action-if-not-found, AC_MSG_FAILURE})
7991 @acindex{F77_DUMMY_MAIN}
7992 @cvindex F77_DUMMY_MAIN
7993 @acindex{FC_DUMMY_MAIN}
7994 @cvindex FC_DUMMY_MAIN
7995 @caindex f77_dummy_main
7996 @caindex fc_dummy_main
7997 With many compilers, the Fortran libraries detected by
7998 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7999 their own @code{main} entry function that initializes things like
8000 Fortran I/O, and which then calls a user-provided entry function named
8001 (say) @code{MAIN__} to run the user's program.  The
8002 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8003 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
8004 this interaction.
8006 When using Fortran for purely numerical functions (no I/O, etc.)@: often
8007 one prefers to provide one's own @code{main} and skip the Fortran
8008 library initializations.  In this case, however, one may still need to
8009 provide a dummy @code{MAIN__} routine in order to prevent linking errors
8010 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8011 detects whether any such routine is @emph{required} for linking, and
8012 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8013 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8014 was found, and @code{none} when no such dummy main is needed.
8016 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8017 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8018 @emph{if} it is required.  @var{action-if-not-found} defaults to
8019 exiting with an error.
8021 In order to link with Fortran routines, the user's C/C++ program should
8022 then include the following code to define the dummy main if it is
8023 needed:
8025 @example
8026 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8027 #ifdef F77_DUMMY_MAIN
8028 #  ifdef __cplusplus
8029      extern "C"
8030 #  endif
8031    int F77_DUMMY_MAIN () @{ return 1; @}
8032 #endif
8033 @end example
8035 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8037 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8038 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8039 explicitly unless one wants to change the default actions.
8041 The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8042 @code{ac_cv_fc_dummy_main} variable, respectively.
8043 @end defmac
8045 @defmac AC_F77_MAIN
8046 @defmacx AC_FC_MAIN
8047 @acindex{F77_MAIN}
8048 @cvindex F77_MAIN
8049 @acindex{FC_MAIN}
8050 @cvindex FC_MAIN
8051 @caindex f77_main
8052 @caindex fc_main
8053 As discussed above, many Fortran libraries allow you to provide an entry
8054 point called (say) @code{MAIN__} instead of the usual @code{main}, which
8055 is then called by a @code{main} function in the Fortran libraries that
8056 initializes things like Fortran I/O@.  The
8057 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8058 @emph{possible} to utilize such an alternate main function, and defines
8059 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
8060 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8061 simply defined to @code{main}.)
8063 Thus, when calling Fortran routines from C that perform things like I/O,
8064 one should use this macro and declare the "main" function like so:
8066 @example
8067 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8068 #ifdef __cplusplus
8069   extern "C"
8070 #endif
8071 int F77_MAIN (int argc, char *argv[]);
8072 @end example
8074 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8076 The result of this macro is cached in the @code{ac_cv_f77_main} or
8077 @code{ac_cv_fc_main} variable, respectively.
8078 @end defmac
8080 @defmac AC_F77_WRAPPERS
8081 @defmacx AC_FC_WRAPPERS
8082 @acindex{F77_WRAPPERS}
8083 @cvindex F77_FUNC
8084 @cvindex F77_FUNC_
8085 @acindex{FC_WRAPPERS}
8086 @cvindex FC_FUNC
8087 @cvindex FC_FUNC_
8088 @caindex f77_mangling
8089 @caindex fc_mangling
8090 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8091 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8092 mangle the names of C/C++ identifiers, and identifiers with underscores,
8093 respectively, so that they match the name-mangling scheme used by the
8094 Fortran compiler.
8096 Fortran is case-insensitive, and in order to achieve this the Fortran
8097 compiler converts all identifiers into a canonical case and format.  To
8098 call a Fortran subroutine from C or to write a C function that is
8099 callable from Fortran, the C program must explicitly use identifiers in
8100 the format expected by the Fortran compiler.  In order to do this, one
8101 simply wraps all C identifiers in one of the macros provided by
8102 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
8103 you have the following Fortran 77 subroutine:
8105 @example
8106 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8107       subroutine foobar (x, y)
8108       double precision x, y
8109       y = 3.14159 * x
8110       return
8111       end
8112 @end example
8114 You would then declare its prototype in C or C++ as:
8116 @example
8117 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8118 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8119 #ifdef __cplusplus
8120 extern "C"  /* prevent C++ name mangling */
8121 #endif
8122 void FOOBAR_F77 (double *x, double *y);
8123 @end example
8125 Note that we pass both the lowercase and uppercase versions of the
8126 function name to @code{F77_FUNC} so that it can select the right one.
8127 Note also that all parameters to Fortran 77 routines are passed as
8128 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8129 Automake}).
8131 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8133 Although Autoconf tries to be intelligent about detecting the
8134 name-mangling scheme of the Fortran compiler, there may be Fortran
8135 compilers that it doesn't support yet.  In this case, the above code
8136 generates a compile-time error, but some other behavior
8137 (e.g., disabling Fortran-related features) can be induced by checking
8138 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8140 Now, to call that routine from a C program, we would do something like:
8142 @example
8143 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8145     double x = 2.7183, y;
8146     FOOBAR_F77 (&x, &y);
8148 @end example
8150 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8151 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8152 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
8153 because some Fortran compilers mangle names differently if they contain
8154 an underscore.
8156 The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8157 @code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8158 the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8159 @end defmac
8161 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8162 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8163 @acindex{F77_FUNC}
8164 @acindex{FC_FUNC}
8165 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8166 hold the mangled version @var{name} according to the rules of the
8167 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8168 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
8169 supplied, the shell variable is simply @var{name}.  The purpose of
8170 this macro is to give the caller a way to access the name-mangling
8171 information other than through the C preprocessor as above, for example,
8172 to call Fortran routines from some language other than C/C++.
8173 @end defmac
8175 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8176   @dvar{action-if-failure, AC_MSG_FAILURE})
8177 @defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8178   @dvar{action-if-failure, AC_MSG_FAILURE})
8179 @acindex{FC_SRCEXT}
8180 @acindex{FC_PP_SRCEXT}
8181 @caindex fc_srcext_@var{ext}
8182 @caindex fc_pp_srcext_@var{ext}
8183 By default, the @code{FC} macros perform their tests using a @file{.f}
8184 extension for source-code files.  Some compilers, however, only enable
8185 newer language features for appropriately named files, e.g., Fortran 90
8186 features only for @file{.f90} files, or preprocessing only with
8187 @file{.F} files or maybe other upper-case extensions.  On the other
8188 hand, some other compilers expect all source files to end in @file{.f}
8189 and require special flags to support other file name extensions.  The
8190 @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8191 issues.
8193 The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8194 accept files ending with the extension @file{.@var{ext}} (i.e.,
8195 @var{ext} does @emph{not} contain the dot).  If any special compiler
8196 flags are needed for this, it stores them in the output variable
8197 @code{FCFLAGS_@var{ext}}.  This extension and these flags are then used
8198 for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8199 @code{AC_FC_PP_SRCEXT} is called another time).
8201 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8202 @file{.f90} extension in future tests, and it would set the
8203 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8204 to compile such files.
8206 Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8207 compiler to preprocess and compile files with the extension
8208 @file{.@var{ext}}.  When both @command{fpp} and @command{cpp} style
8209 preprocessing are provided, the former is preferred, as the latter may
8210 treat continuation lines, @code{//} tokens, and white space differently
8211 from what some Fortran dialects expect.  Conversely, if you do not want
8212 files to be preprocessed, use only lower-case characters in the file
8213 name extension.  Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8214 are stored in the @code{FCFLAGS_@var{ext}} variable.
8216 The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8217 into @code{FCFLAGS}, for two reasons based on the limitations of some
8218 compilers.  First, only one @code{FCFLAGS_@var{ext}} can be used at a
8219 time, so files with different extensions must be compiled separately.
8220 Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8221 the source-code file name when compiling.  So, continuing the example
8222 above, you might compile a @file{foo.f90} file in your makefile with the
8223 command:
8225 @example
8226 foo.o: foo.f90
8227        $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8228 @end example
8230 If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8231 files with the @var{ext} extension, it calls @var{action-if-success}
8232 (defaults to nothing).  If it fails, and cannot find a way to make the
8233 @code{FC} compiler accept such files, it calls @var{action-if-failure}
8234 (defaults to exiting with an error message).
8236 The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8237 results in @code{ac_cv_fc_srcext_@var{ext}} and
8238 @code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8239 @end defmac
8241 @defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @
8242   @dvar{action-if-failure, AC_MSG_FAILURE})
8243 @acindex{FC_PP_DEFINE}
8244 @caindex fc_pp_define
8246 Find a flag to specify defines for preprocessed Fortran.  Not all
8247 Fortran compilers use @option{-D}.  Substitute @code{FC_DEFINE} with
8248 the result and call @var{action-if-success} (defaults to nothing) if
8249 successful, and @var{action-if-failure} (defaults to failing with an
8250 error message) if not.
8252 This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8253 preprocess a @file{conftest.F} file, but restores a previously used
8254 Fortran source file extension afterwards again.
8256 The result of this test is cached in the @code{ac_cv_fc_pp_define}
8257 variable.
8258 @end defmac
8260 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @
8261   @dvar{action-if-failure, AC_MSG_FAILURE})
8262 @acindex{FC_FREEFORM}
8263 @caindex fc_freeform
8265 Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8266 source code (as opposed to the older fixed-format style from Fortran
8267 77).  If necessary, it may add some additional flags to @code{FCFLAGS}.
8269 This macro is most important if you are using the default @file{.f}
8270 extension, since many compilers interpret this extension as indicating
8271 fixed-format source unless an additional flag is supplied.  If you
8272 specify a different extension with @code{AC_FC_SRCEXT}, such as
8273 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8274 modifying @code{FCFLAGS}.  For extensions which the compiler does not
8275 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8276 the compiler assume Fortran 77 by default, however.
8278 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8279 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8280 calls @var{action-if-failure} (defaults to exiting with an error
8281 message).
8283 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8284 the @code{ac_cv_fc_freeform} variable.
8285 @end defmac
8287 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @
8288   @dvar{action-if-failure, AC_MSG_FAILURE})
8289 @acindex{FC_FIXEDFORM}
8290 @caindex fc_fixedform
8292 Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8293 fixed-format source code (as opposed to free-format style).  If
8294 necessary, it may add some additional flags to @code{FCFLAGS}.
8296 This macro is needed for some compilers alias names like @command{xlf95}
8297 which assume free-form source code by default, and in case you want to
8298 use fixed-form source with an extension like @file{.f90} which many
8299 compilers interpret as free-form by default.  If you specify a different
8300 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8301 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8302 @code{FCFLAGS}.
8304 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8305 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8306 calls @var{action-if-failure} (defaults to exiting with an error
8307 message).
8309 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8310 the @code{ac_cv_fc_fixedform} variable.
8311 @end defmac
8313 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8314   @dvar{action-if-failure, AC_MSG_FAILURE})
8315 @acindex{FC_LINE_LENGTH}
8316 @caindex fc_line_length
8318 Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8319 code lines.  The @var{length} argument may be given as 80, 132, or
8320 unlimited, and defaults to 132.  Note that line lengths above 254
8321 columns are not portable, and some compilers do not accept more than 132
8322 columns at least for fixed format source.  If necessary, it may add some
8323 additional flags to @code{FCFLAGS}.
8325 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8326 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8327 calls @var{action-if-failure} (defaults to exiting with an error
8328 message).
8330 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8331 the @code{ac_cv_fc_line_length} variable.
8332 @end defmac
8334 @defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8335   @dvar{action-if-failure, AC_MSG_FAILURE})
8336 @acindex{FC_CHECK_BOUNDS}
8337 @caindex fc_check_bounds
8339 The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8340 in the Fortran compiler.  If successful, the @var{action-if-success}
8341 is called and any needed flags are added to @code{FCFLAGS}.  Otherwise,
8342 @var{action-if-failure} is called, which defaults to failing with an error
8343 message.  The macro currently requires Fortran 90 or a newer dialect.
8345 The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8346 variable.
8347 @end defmac
8349 @defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8350   @dvar{action-if-failure, AC_MSG_FAILURE})
8351 @defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8352   @dvar{action-if-failure, AC_MSG_FAILURE})
8353 @acindex{F77_IMPLICIT_NONE}
8354 @acindex{FC_IMPLICIT_NONE}
8355 @caindex f77_implicit_none
8356 @caindex fc_implicit_none
8358 Try to disallow implicit declarations in the Fortran compiler.  If
8359 successful, @var{action-if-success} is called and any needed flags
8360 are added to @code{FFLAGS} or @code{FCFLAGS}, respectively.  Otherwise,
8361 @var{action-if-failure} is called, which defaults to failing with an error
8362 message.
8364 The result of these macros are cached in the
8365 @code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8366 variables, respectively.
8367 @end defmac
8369 @defmac AC_FC_MODULE_EXTENSION
8370 @acindex{FC_MODULE_EXTENSION}
8371 @caindex fc_module_ext
8372 @ovindex FC_MODEXT
8374 Find the Fortran 90 module file name extension.  Most Fortran 90
8375 compilers store module information in files separate from the object
8376 files.  The module files are usually named after the name of the module
8377 rather than the source file name, with characters possibly turned to
8378 upper case, plus an extension, often @file{.mod}.
8380 Not all compilers use module files at all, or by default.  The Cray
8381 Fortran compiler requires @option{-e m} in order to store and search
8382 module information in @file{.mod} files rather than in object files.
8383 Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8384 indicate how module information is stored.
8386 The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8387 without the leading dot, and stores that in the @code{FC_MODEXT}
8388 variable.  If the compiler does not produce module files, or the
8389 extension cannot be determined, @code{FC_MODEXT} is empty.  Typically,
8390 the result of this macro may be used in cleanup @command{make} rules as
8391 follows:
8393 @example
8394 clean-modules:
8395         -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8396 @end example
8398 The extension, or @samp{unknown}, is cached in the
8399 @code{ac_cv_fc_module_ext} variable.
8400 @end defmac
8402 @defmac AC_FC_MODULE_FLAG (@ovar{action-if-success}, @
8403   @dvar{action-if-failure, AC_MSG_FAILURE})
8404 @acindex{FC_MODULE_FLAG}
8405 @caindex fc_module_flag
8406 @ovindex FC_MODINC
8407 @ovindex ac_empty
8409 Find the compiler flag to include Fortran 90 module information from
8410 another directory, and store that in the @code{FC_MODINC} variable.
8411 Call @var{action-if-success} (defaults to nothing) if successful, and
8412 set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8413 to exiting with an error message) if not.
8415 Most Fortran 90 compilers provide a way to specify module directories.
8416 Some have separate flags for the directory to write module files to,
8417 and directories to search them in, whereas others only allow writing to
8418 the current directory or to the first directory specified in the include
8419 path.  Further, with some compilers, the module search path and the
8420 preprocessor search path can only be modified with the same flag.  Thus,
8421 for portability, write module files to the current directory only and
8422 list that as first directory in the search path.
8424 There may be no whitespace between @code{FC_MODINC} and the following
8425 directory name, but @code{FC_MODINC} may contain trailing white space.
8426 For example, if you use Automake and would like to search @file{../lib}
8427 for module files, you can use the following:
8429 @example
8430 AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8431 @end example
8433 Inside @command{configure} tests, you can use:
8435 @example
8436 if test -n "$FC_MODINC"; then
8437   FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8439 @end example
8441 The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8442 The substituted value of @code{FC_MODINC} may refer to the
8443 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8444 the significant trailing whitespace in a @file{Makefile}.
8445 @end defmac
8447 @defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-success}, @
8448   @dvar{action-if-failure, AC_MSG_FAILURE})
8449 @acindex{FC_MODULE_OUTPUT_FLAG}
8450 @caindex fc_module_output_flag
8451 @ovindex FC_MODOUT
8453 Find the compiler flag to write Fortran 90 module information to
8454 another directory, and store that in the @code{FC_MODOUT} variable.
8455 Call @var{action-if-success} (defaults to nothing) if successful, and
8456 set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8457 to exiting with an error message) if not.
8459 Not all Fortran 90 compilers write module files, and of those that do,
8460 not all allow writing to a directory other than the current one, nor
8461 do all have separate flags for writing and reading; see the description
8462 of @code{AC_FC_MODULE_FLAG} above.  If you need to be able to write to
8463 another directory, for maximum portability use @code{FC_MODOUT} before
8464 any @code{FC_MODINC} and include both the current directory and the one
8465 you write to in the search path:
8467 @example
8468 AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8469 @end example
8471 The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8472 The substituted value of @code{FC_MODOUT} may refer to the
8473 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8474 the significant trailing whitespace in a @file{Makefile}.
8475 @end defmac
8478 @node Go Compiler
8479 @subsection Go Compiler Characteristics
8480 @cindex Go
8482 Autoconf provides basic support for the Go programming language when
8483 using the @code{gccgo} compiler (there is currently no support for the
8484 @code{6g} and @code{8g} compilers).
8486 @defmac AC_PROG_GO (@ovar{compiler-search-list})
8487 Find the Go compiler to use.  Check whether the environment variable
8488 @code{GOC} is set; if so, then set output variable @code{GOC} to its
8489 value.
8491 Otherwise, if the macro is invoked without an argument, then search for
8492 a Go compiler named @code{gccgo}.  If it is not found, then as a last
8493 resort set @code{GOC} to @code{gccgo}.
8495 This macro may be invoked with an optional first argument which, if
8496 specified, must be a blank-separated list of Go compilers to search for.
8498 If output variable @code{GOFLAGS} was not already set, set it to
8499 @option{-g -O2}.  If your package does not like this default,
8500 @code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8501 @end defmac
8504 @node System Services
8505 @section System Services
8507 The following macros check for operating system services or capabilities.
8509 @anchor{AC_PATH_X}
8510 @defmac AC_PATH_X
8511 @acindex{PATH_X}
8512 @evindex XMKMF
8513 @cindex X Window System
8514 Try to locate the X Window System include files and libraries.  If the
8515 user gave the command line options @option{--x-includes=@var{dir}} and
8516 @option{--x-libraries=@var{dir}}, use those directories.
8518 If either or both were not given, get the missing values by running
8519 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8520 environment variable) on a trivial @file{Imakefile} and examining the
8521 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8522 disables this method.
8524 If this method fails to find the X Window System, @command{configure}
8525 looks for the files in several directories where they often reside.
8526 If either method is successful, set the shell variables
8527 @code{x_includes} and @code{x_libraries} to their locations, unless they
8528 are in directories the compiler searches by default.
8530 If both methods fail, or the user gave the command line option
8531 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8532 otherwise set it to the empty string.
8533 @end defmac
8535 @anchor{AC_PATH_XTRA}
8536 @defmac AC_PATH_XTRA
8537 @acindex{PATH_XTRA}
8538 @ovindex X_CFLAGS
8539 @ovindex X_LIBS
8540 @ovindex X_EXTRA_LIBS
8541 @ovindex X_PRE_LIBS
8542 @cvindex X_DISPLAY_MISSING
8543 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8544 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8545 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8546 available.
8548 This macro also checks for special libraries that some systems need in
8549 order to compile X programs.  It adds any that the system needs to
8550 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8551 libraries that need to be linked with before @option{-lX11}, and adds
8552 any found to the output variable @code{X_PRE_LIBS}.
8554 @c This is an incomplete kludge.  Make a real way to do it.
8555 @c If you need to check for other X functions or libraries yourself, then
8556 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8557 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8558 @end defmac
8560 @anchor{AC_SYS_INTERPRETER}
8561 @defmac AC_SYS_INTERPRETER
8562 @acindex{SYS_INTERPRETER}
8563 Check whether the system supports starting scripts with a line of the
8564 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8565 After running this macro, shell code in @file{configure.ac} can check
8566 the shell variable @code{interpval}; it is set to @samp{yes}
8567 if the system supports @samp{#!}, @samp{no} if not.
8568 @end defmac
8570 @defmac AC_SYS_LARGEFILE
8571 @acindex{SYS_LARGEFILE}
8572 @cvindex _FILE_OFFSET_BITS
8573 @cvindex _LARGE_FILES
8574 @ovindex CC
8575 @cindex Large file support
8576 @cindex LFS
8577 Arrange for 64-bit file offsets, known as
8578 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
8579 large-file support}.  On some hosts, one must use special compiler
8580 options to build programs that can access large files.  Append any such
8581 options to the output variable @code{CC}.  Define
8582 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8584 Large-file support can be disabled by configuring with the
8585 @option{--disable-largefile} option.
8587 If you use this macro, check that your program works even when
8588 @code{off_t} is wider than @code{long int}, since this is common when
8589 large-file support is enabled.  For example, it is not correct to print
8590 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8591 (long int) X)}.
8593 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8594 replace their C counterparts @code{fseek} and @code{ftell} that do not
8595 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8596 prototypes available when using them and large-file support is
8597 enabled.
8598 @end defmac
8600 @anchor{AC_SYS_LONG_FILE_NAMES}
8601 @defmac AC_SYS_LONG_FILE_NAMES
8602 @acindex{SYS_LONG_FILE_NAMES}
8603 @cvindex HAVE_LONG_FILE_NAMES
8604 If the system supports file names longer than 14 characters, define
8605 @code{HAVE_LONG_FILE_NAMES}.
8606 @end defmac
8608 @defmac AC_SYS_POSIX_TERMIOS
8609 @acindex{SYS_POSIX_TERMIOS}
8610 @cindex Posix termios headers
8611 @cindex termios Posix headers
8612 @caindex sys_posix_termios
8613 Check to see if the Posix termios headers and functions are available on the
8614 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8615 @samp{yes}.  If not, set the variable to @samp{no}.
8616 @end defmac
8618 @node C and Posix Variants
8619 @section C and Posix Variants
8621 The following macro makes it possible to use C language and library
8622 extensions defined by the C standards committee, features of Posix that
8623 are extensions to C, and platform extensions not defined by Posix.
8625 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8626 @defmac AC_USE_SYSTEM_EXTENSIONS
8627 @acindex{USE_SYSTEM_EXTENSIONS}
8628 If possible, enable
8629 extensions to C or Posix on hosts that normally disable the extensions,
8630 typically due to standards-conformance namespace issues.  This should be
8631 called before any macros that run the C compiler.  The following
8632 preprocessor macros are defined where appropriate:
8634 @table @code
8635 @item _GNU_SOURCE
8636 @cvindex _GNU_SOURCE
8637 Enable extensions on GNU/Linux.
8638 @item _ALL_SOURCE
8639 @cvindex _ALL_SOURCE
8640 Enable extensions for AIX 3, and for Interix.
8641 @item _DARWIN_C_SOURCE
8642 @cvindex _DARWIN_C_SOURCE
8643 Enable extensions for macOS.
8644 @item _MINIX
8645 @cvindex _MINIX
8646 Identify Minix platform.  This particular preprocessor macro is
8647 obsolescent, and may be removed in a future release of Autoconf.
8648 @item _NETBSD_SOURCE
8649 @cvindex _NETBSD_SOURCE
8650 Enable NetBSD-related extensions for Minix.
8651 @item _POSIX_1_SOURCE
8652 @cvindex _POSIX_1_SOURCE
8653 Enable additional Posix functions for Minix.
8654 @item _POSIX_PTHREAD_SEMANTICS
8655 @cvindex _POSIX_PTHREAD_SEMANTICS
8656 Enable threading extensions on Solaris.
8657 @item _POSIX_SOURCE
8658 @cvindex _POSIX_SOURCE
8659 Enable Posix functions for Minix.
8660 @item _TANDEM_SOURCE
8661 @cvindex _TANDEM_SOURCE
8662 Enable extensions for the HP NonStop platform.
8663 @item _XOPEN_SOURCE
8664 @cvindex _XOPEN_SOURCE
8665 Enable X/Open extensions for HP-UX.
8666 @item __EXTENSIONS__
8667 @cvindex __EXTENSIONS__
8668 Enable general extensions on Solaris.
8669 @item __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8670 @cvindex __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8671 Enable extensions specified by ISO/IEC TS 18661-5:2014.
8672 @item __STDC_WANT_IEC_60559_BFP_EXT__
8673 @cvindex __STDC_WANT_IEC_60559_BFP_EXT__
8674 Enable extensions specified by ISO/IEC TS 18661-1:2014.
8675 @item __STDC_WANT_IEC_60559_DFP_EXT__
8676 @cvindex __STDC_WANT_IEC_60559_DFP_EXT__
8677 Enable extensions specified by ISO/IEC TS 18661-2:2015.
8678 @item __STDC_WANT_IEC_60559_FUNCS_EXT__
8679 @cvindex __STDC_WANT_IEC_60559_FUNCS_EXT__
8680 Enable extensions specified by ISO/IEC TS 18661-4:2015.
8681 @item __STDC_WANT_IEC_60559_TYPES_EXT__
8682 @cvindex __STDC_WANT_IEC_60559_TYPES_EXT__
8683 Enable extensions specified by ISO/IEC TS 18661-3:2015.
8684 @item __STDC_WANT_LIB_EXT2__
8685 @cvindex __STDC_WANT_LIB_EXT2__
8686 Enable extensions specified by ISO/IEC TR 24731-2:2010.
8687 @item __STDC_WANT_MATH_SPEC_FUNCS__
8688 @cvindex __STDC_WANT_MATH_SPEC_FUNCS__
8689 Enable extensions specified by ISO/IEC 24747:2009.
8690 @end table
8692 @cvindex __STDC_WANT_DEC_FP__
8693 The C preprocessor macro @code{__STDC_WANT_DEC_FP__} is not defined.
8694 ISO/IEC TR 24732:2009 was superseded by ISO/IEC TS 18661-2:2015.
8696 @cvindex __STDC_WANT_LIB_EXT1__
8697 The C preprocessor macro @code{__STDC_WANT_LIB_EXT1__} is not defined,
8698 as C11 Annex K is problematic.  See: O'Donell C, Sebor M.
8699 @uref{http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm, Field
8700 Experience With Annex K---Bounds Checking Interfaces}.
8702 The Autoconf macro @code{AC_USE_SYSTEM_EXTENSIONS} was introduced in
8703 Autoconf 2.60.
8704 @end defmac
8707 @node Erlang Libraries
8708 @section Erlang Libraries
8709 @cindex Erlang, Library, checking
8711 The following macros check for an installation of Erlang/OTP, and for the
8712 presence of certain Erlang libraries.  All those macros require the
8713 configuration of an Erlang interpreter and an Erlang compiler
8714 (@pxref{Erlang Compiler and Interpreter}).
8716 @defmac AC_ERLANG_SUBST_ERTS_VER
8717 @acindex{ERLANG_SUBST_ERTS_VER}
8718 @ovindex ERLANG_ERTS_VER
8719 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8720 Erlang runtime system (as returned by Erlang's
8721 @code{erlang:system_info(version)} function).  The result of this test
8722 is cached if caching is enabled when running @command{configure}.  The
8723 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8724 for features of specific ERTS versions, but to be used for substituting
8725 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8726 files), as shown below.
8727 @end defmac
8729 @defmac AC_ERLANG_SUBST_ROOT_DIR
8730 @acindex{ERLANG_SUBST_ROOT_DIR}
8731 @ovindex ERLANG_ROOT_DIR
8732 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8733 directory in which Erlang/OTP is installed (as returned by Erlang's
8734 @code{code:root_dir/0} function).  The result of this test is cached if
8735 caching is enabled when running @command{configure}.
8736 @end defmac
8738 @defmac AC_ERLANG_SUBST_LIB_DIR
8739 @acindex{ERLANG_SUBST_LIB_DIR}
8740 @ovindex ERLANG_LIB_DIR
8741 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8742 directory of Erlang/OTP (as returned by Erlang's
8743 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8744 Erlang/OTP library.  The result of this test is cached if caching is enabled
8745 when running @command{configure}.
8746 @end defmac
8748 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8749   @ovar{action-if-not-found})
8750 @acindex{ERLANG_CHECK_LIB}
8751 @ovindex ERLANG_LIB_DIR_@var{library}
8752 @ovindex ERLANG_LIB_VER_@var{library}
8753 Test whether the Erlang/OTP library @var{library} is installed by
8754 calling Erlang's @code{code:lib_dir/1} function.  The result of this
8755 test is cached if caching is enabled when running @command{configure}.
8756 @var{action-if-found} is a list of shell commands to run if the library
8757 is installed; @var{action-if-not-found} is a list of shell commands to
8758 run if it is not.  Additionally, if the library is installed, the output
8759 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8760 library installation directory, and the output variable
8761 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8762 part of the subdirectory name, if it is in the standard form
8763 (@code{@var{library}-@var{version}}).  If the directory name does not
8764 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8765 empty string.  If the library is not installed,
8766 @samp{ERLANG_LIB_DIR_@var{library}} and
8767 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
8768 example, to check if library @code{stdlib} is installed:
8770 @example
8771 AC_ERLANG_CHECK_LIB([stdlib],
8772   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8773    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8774   [AC_MSG_ERROR([stdlib was not found!])])
8775 @end example
8777 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8778 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8779 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8780 testing for features of specific versions of libraries or of the Erlang
8781 runtime system.  Those variables are intended to be substituted in
8782 Erlang release resource files (@code{.rel} files).  For instance, to
8783 generate a @file{example.rel} file for an application depending on the
8784 @code{stdlib} library, @file{configure.ac} could contain:
8786 @example
8787 AC_ERLANG_SUBST_ERTS_VER
8788 AC_ERLANG_CHECK_LIB([stdlib],
8789   [],
8790   [AC_MSG_ERROR([stdlib was not found!])])
8791 AC_CONFIG_FILES([example.rel])
8792 @end example
8794 @noindent
8795 The @file{example.rel.in} file used to generate @file{example.rel}
8796 should contain:
8798 @example
8799 @{release,
8800     @{"@@PACKAGE@@", "@@VERSION@@"@},
8801     @{erts, "@@ERLANG_ERTS_VER@@"@},
8802     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8803      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8804 @end example
8805 @end defmac
8807 In addition to the above macros, which test installed Erlang libraries, the
8808 following macros determine the paths to the directories into which newly built
8809 Erlang libraries are to be installed:
8811 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8812 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8813 @ovindex ERLANG_INSTALL_LIB_DIR
8815 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8816 which every built Erlang library should be installed in a separate
8817 subdirectory.
8818 If this variable is not set in the environment when @command{configure} runs,
8819 its default value is @code{$@{libdir@}/erlang/lib}.
8820 @end defmac
8822 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8823 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8824 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8826 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8827 directory into which the built Erlang library @var{library} version
8828 @var{version} should be installed.  If this variable is not set in the
8829 environment when @command{configure} runs, its default value is
8830 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
8831 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
8832 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
8833 @end defmac
8839 @c ========================================================= Writing Tests
8841 @node Writing Tests
8842 @chapter Writing Tests
8844 If the existing feature tests don't do something you need, you have to
8845 write new ones.  These macros are the building blocks.  They provide
8846 ways for other macros to check whether various kinds of features are
8847 available and report the results.
8849 This chapter contains some suggestions and some of the reasons why the
8850 existing tests are written the way they are.  You can also learn a lot
8851 about how to write Autoconf tests by looking at the existing ones.  If
8852 something goes wrong in one or more of the Autoconf tests, this
8853 information can help you understand the assumptions behind them, which
8854 might help you figure out how to best solve the problem.
8856 These macros check the output of the compiler system of the current
8857 language (@pxref{Language Choice}).  They do not cache the results of
8858 their tests for future use (@pxref{Caching Results}), because they don't
8859 know enough about the information they are checking for to generate a
8860 cache variable name.  They also do not print any messages, for the same
8861 reason.  The checks for particular kinds of features call these macros
8862 and do cache their results and print messages about what they're
8863 checking for.
8865 When you write a feature test that could be applicable to more than one
8866 software package, the best thing to do is encapsulate it in a new macro.
8867 @xref{Writing Autoconf Macros}, for how to do that.
8869 @menu
8870 * Language Choice::             Selecting which language to use for testing
8871 * Writing Test Programs::       Forging source files for compilers
8872 * Running the Preprocessor::    Detecting preprocessor symbols
8873 * Running the Compiler::        Detecting language or header features
8874 * Running the Linker::          Detecting library features
8875 * Runtime::                     Testing for runtime features
8876 * Systemology::                 A zoology of operating systems
8877 * Multiple Cases::              Tests for several possible values
8878 @end menu
8880 @node Language Choice
8881 @section Language Choice
8882 @cindex Language
8884 Autoconf-generated @command{configure} scripts check for the C compiler and
8885 its features by default.  Packages that use other programming languages
8886 (maybe more than one, e.g., C and C++) need to test features of the
8887 compilers for the respective languages.  The following macros determine
8888 which programming language is used in the subsequent tests in
8889 @file{configure.ac}.
8891 @anchor{AC_LANG}
8892 @defmac AC_LANG (@var{language})
8893 @acindex{LANG}
8894 Do compilation tests using the compiler, preprocessor, and file
8895 extensions for the specified @var{language}.
8897 Supported languages are:
8899 @table @samp
8900 @item C
8901 Do compilation tests using @code{CC} and @code{CPP} and use extension
8902 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
8903 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
8905 @item C++
8906 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8907 extension @file{.C} for test programs.  Use compilation flags:
8908 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8909 @code{CXXFLAGS} with @code{CXX}.
8911 @item Fortran 77
8912 Do compilation tests using @code{F77} and use extension @file{.f} for
8913 test programs.  Use compilation flags: @code{FFLAGS}.
8915 @item Fortran
8916 Do compilation tests using @code{FC} and use extension @file{.f} (or
8917 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
8918 compilation flags: @code{FCFLAGS}.
8920 @item Erlang
8921 @ovindex ERLC
8922 @ovindex ERL
8923 @ovindex ERLCFLAGS
8924 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8925 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
8927 @item Objective C
8928 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8929 extension @file{.m} for test programs.  Use compilation flags:
8930 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8931 @code{OBJCFLAGS} with @code{OBJC}.
8933 @item Objective C++
8934 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
8935 extension @file{.mm} for test programs.  Use compilation flags:
8936 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
8937 @code{OBJCXXFLAGS} with @code{OBJCXX}.
8939 @item Go
8940 Do compilation tests using @code{GOC} and use extension @file{.go} for
8941 test programs.  Use compilation flags @code{GOFLAGS}.
8942 @end table
8943 @end defmac
8945 @anchor{AC_LANG_PUSH}
8946 @defmac AC_LANG_PUSH (@var{language})
8947 @acindex{LANG_PUSH}
8948 Remember the current language (as set by @code{AC_LANG}) on a stack, and
8949 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
8950 in macros that need to temporarily switch to a particular language.
8951 @end defmac
8953 @defmac AC_LANG_POP (@ovar{language})
8954 @acindex{LANG_POP}
8955 Select the language that is saved on the top of the stack, as set by
8956 @code{AC_LANG_PUSH}, and remove it from the stack.
8958 If given, @var{language} specifies the language we just @emph{quit}.  It
8959 is a good idea to specify it when it's known (which should be the
8960 case@dots{}), since Autoconf detects inconsistencies.
8962 @example
8963 AC_LANG_PUSH([Fortran 77])
8964 # Perform some tests on Fortran 77.
8965 # @dots{}
8966 AC_LANG_POP([Fortran 77])
8967 @end example
8968 @end defmac
8970 @defmac AC_LANG_ASSERT (@var{language})
8971 @acindex{LANG_ASSERT}
8972 Check statically that the current language is @var{language}.
8973 You should use this in your language specific macros
8974 to avoid that they be called with an inappropriate language.
8976 This macro runs only at @command{autoconf} time, and incurs no cost at
8977 @command{configure} time.  Sadly enough and because Autoconf is a two
8978 layer language @footnote{Because M4 is not aware of Sh code,
8979 especially conditionals, some optimizations that look nice statically
8980 may produce incorrect results at runtime.}, the macros
8981 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8982 therefore as much as possible you ought to avoid using them to wrap
8983 your code, rather, require from the user to run the macro with a
8984 correct current language, and check it with @code{AC_LANG_ASSERT}.
8985 And anyway, that may help the user understand she is running a Fortran
8986 macro while expecting a result about her Fortran 77 compiler@enddots{}
8987 @end defmac
8990 @defmac AC_REQUIRE_CPP
8991 @acindex{REQUIRE_CPP}
8992 Ensure that whichever preprocessor would currently be used for tests has
8993 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
8994 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
8995 depending on which language is current.
8996 @end defmac
8999 @node Writing Test Programs
9000 @section Writing Test Programs
9002 Autoconf tests follow a common scheme: feed some program with some
9003 input, and most of the time, feed a compiler with some source file.
9004 This section is dedicated to these source samples.
9006 @menu
9007 * Guidelines::                  General rules for writing test programs
9008 * Test Functions::              Avoiding pitfalls in test programs
9009 * Generating Sources::          Source program boilerplate
9010 @end menu
9012 @node Guidelines
9013 @subsection Guidelines for Test Programs
9015 The most important rule to follow when writing testing samples is:
9017 @center @emph{Look for realism.}
9019 This motto means that testing samples must be written with the same
9020 strictness as real programs are written.  In particular, you should
9021 avoid ``shortcuts'' and simplifications.
9023 Don't just play with the preprocessor if you want to prepare a
9024 compilation.  For instance, using @command{cpp} to check whether a header is
9025 functional might let your @command{configure} accept a header which
9026 causes some @emph{compiler} error.  Do not hesitate to check a header with
9027 other headers included before, especially required headers.
9029 Make sure the symbols you use are properly defined, i.e., refrain from
9030 simply declaring a function yourself instead of including the proper
9031 header.
9033 Test programs should not write to standard output.  They
9034 should exit with status 0 if the test succeeds, and with status 1
9035 otherwise, so that success
9036 can be distinguished easily from a core dump or other failure;
9037 segmentation violations and other failures produce a nonzero exit
9038 status.  Unless you arrange for @code{exit} to be declared, test
9039 programs should @code{return}, not @code{exit}, from @code{main},
9040 because on many systems @code{exit} is not declared by default.
9042 Test programs can use @code{#if} or @code{#ifdef} to check the values of
9043 preprocessor macros defined by tests that have already run.  For
9044 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9045 @file{configure.ac} you can have a test program that includes
9046 @file{stdbool.h} conditionally:
9048 @example
9049 @group
9050 #ifdef HAVE_STDBOOL_H
9051 # include <stdbool.h>
9052 #endif
9053 @end group
9054 @end example
9056 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9057 work with any standard C compiler.  Some developers prefer @code{#if}
9058 because it is easier to read, while others prefer @code{#ifdef} because
9059 it avoids diagnostics with picky compilers like GCC with the
9060 @option{-Wundef} option.
9062 If a test program needs to use or create a data file, give it a name
9063 that starts with @file{conftest}, such as @file{conftest.data}.  The
9064 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
9065 after running test programs and if the script is interrupted.
9067 @node Test Functions
9068 @subsection Test Functions
9070 These days it's safe to assume support for function prototypes
9071 (introduced in C89).
9073 Functions that test programs declare should also be conditionalized for
9074 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
9075 include any header files containing clashing prototypes.
9077 @example
9078 #ifdef __cplusplus
9079 extern "C"
9080 #endif
9081 void *valloc (size_t);
9082 @end example
9084 If a test program calls a function with invalid parameters (just to see
9085 whether it exists), organize the program to ensure that it never invokes
9086 that function.  You can do this by calling it in another function that is
9087 never invoked.  You can't do it by putting it after a call to
9088 @code{exit}, because GCC version 2 knows that @code{exit}
9089 never returns
9090 and optimizes out any code that follows it in the same block.
9092 If you include any header files, be sure to call the functions
9093 relevant to them with the correct number of arguments, even if they are
9094 just 0, to avoid compilation errors due to prototypes.  GCC
9095 version 2
9096 has internal prototypes for several functions that it automatically
9097 inlines; for example, @code{memcpy}.  To avoid errors when checking for
9098 them, either pass them the correct number of arguments or redeclare them
9099 with a different return type (such as @code{char}).
9102 @node Generating Sources
9103 @subsection Generating Sources
9105 Autoconf provides a set of macros that can be used to generate test
9106 source files.  They are written to be language generic, i.e., they
9107 actually depend on the current language (@pxref{Language Choice}) to
9108 ``format'' the output properly.
9111 @defmac AC_LANG_CONFTEST (@var{source})
9112 @acindex{LANG_CONFTEST}
9113 Save the @var{source} text in the current test source file:
9114 @file{conftest.@var{extension}} where the @var{extension} depends on the
9115 current language.  As of Autoconf 2.63b, the source file also contains
9116 the results of all of the @code{AC_DEFINE} performed so far.
9118 Note that the @var{source} is evaluated exactly once, like regular
9119 Autoconf macro arguments, and therefore (i) you may pass a macro
9120 invocation, (ii) if not, be sure to double quote if needed.
9122 This macro issues a warning during @command{autoconf} processing if
9123 @var{source} does not include an expansion of the macro
9124 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9125 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9127 This macro is seldom called directly, but is used under the hood by more
9128 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9129 @end defmac
9131 @defmac AC_LANG_DEFINES_PROVIDED
9132 @acindex{LANG_DEFINES_PROVIDED}
9133 This macro is called as a witness that the file
9134 @file{conftest.@var{extension}} appropriate for the current language is
9135 complete, including all previously determined results from
9136 @code{AC_DEFINE}.  This macro is seldom called directly, but exists if
9137 you have a compelling reason to write a conftest file without using
9138 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9139 @code{AC_LANG_CONFTEST}.
9140 @end defmac
9142 @defmac AC_LANG_SOURCE (@var{source})
9143 @acindex{LANG_SOURCE}
9144 Expands into the @var{source}, with the definition of
9145 all the @code{AC_DEFINE} performed so far.  This macro includes an
9146 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9148 In many cases, you may find it more convenient to use the wrapper
9149 @code{AC_LANG_PROGRAM}.
9150 @end defmac
9152 For instance, executing (observe the double quotation!):
9154 @example
9155 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9156 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9157         [http://www.example.org/])
9158 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9159   [Greetings string.])
9160 AC_LANG([C])
9161 AC_LANG_CONFTEST(
9162    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9163 gcc -E -dD conftest.c
9164 @end example
9166 @noindent
9167 on a system with @command{gcc} installed, results in:
9169 @example
9170 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9171 @dots{}
9172 @asis{#} 1 "conftest.c"
9174 #define PACKAGE_NAME "Hello"
9175 #define PACKAGE_TARNAME "hello"
9176 #define PACKAGE_VERSION "1.0"
9177 #define PACKAGE_STRING "Hello 1.0"
9178 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9179 #define PACKAGE_URL "http://www.example.org/"
9180 #define HELLO_WORLD "Hello, World\n"
9182 const char hw[] = "Hello, World\n";
9183 @end example
9185 When the test language is Fortran, Erlang, or Go, the @code{AC_DEFINE}
9186 definitions are not automatically translated into constants in the
9187 source code by this macro.
9189 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
9190 @acindex{LANG_PROGRAM}
9191 Expands into a source file which consists of the @var{prologue}, and
9192 then @var{body} as body of the main function (e.g., @code{main} in
9193 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9194 available.
9195 @end defmac
9197 For instance:
9199 @example
9200 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9201 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9202         [http://www.example.org/])
9203 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9204   [Greetings string.])
9205 AC_LANG_CONFTEST(
9206 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9207                  [[fputs (hw, stdout);]])])
9208 gcc -E -dD conftest.c
9209 @end example
9211 @noindent
9212 on a system with @command{gcc} installed, results in:
9214 @example
9215 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9216 @dots{}
9217 @asis{#} 1 "conftest.c"
9219 #define PACKAGE_NAME "Hello"
9220 #define PACKAGE_TARNAME "hello"
9221 #define PACKAGE_VERSION "1.0"
9222 #define PACKAGE_STRING "Hello 1.0"
9223 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9224 #define PACKAGE_URL "http://www.example.org/"
9225 #define HELLO_WORLD "Hello, World\n"
9227 const char hw[] = "Hello, World\n";
9229 main (void)
9231 fputs (hw, stdout);
9232   ;
9233   return 0;
9235 @end example
9237 In Erlang tests, the created source file is that of an Erlang module called
9238 @code{conftest} (@file{conftest.erl}).  This module defines and exports
9239 at least
9240 one @code{start/0} function, which is called to perform the test.  The
9241 @var{prologue} is optional code that is inserted between the module header and
9242 the @code{start/0} function definition.  @var{body} is the body of the
9243 @code{start/0} function without the final period (@pxref{Runtime}, about
9244 constraints on this function's behavior).
9246 For instance:
9248 @example
9249 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9250 AC_LANG(Erlang)
9251 AC_LANG_CONFTEST(
9252 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9253                  [[io:format("~s~n", [?HELLO_WORLD])]])])
9254 cat conftest.erl
9255 @end example
9257 @noindent
9258 results in:
9260 @example
9261 -module(conftest).
9262 -export([start/0]).
9263 -define(HELLO_WORLD, "Hello, world!").
9264 start() ->
9265 io:format("~s~n", [?HELLO_WORLD])
9267 @end example
9269 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
9270 @acindex{LANG_CALL}
9271 Expands into a source file which consists of the @var{prologue}, and
9272 then a call to the @var{function} as body of the main function (e.g.,
9273 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
9274 of the latter are available.
9276 This function will probably be replaced in the future by a version
9277 which would enable specifying the arguments.  The use of this macro is
9278 not encouraged, as it violates strongly the typing system.
9280 This macro cannot be used for Erlang tests.
9281 @end defmac
9283 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9284 @acindex{LANG_FUNC_LINK_TRY}
9285 Expands into a source file which uses the @var{function} in the body of
9286 the main function (e.g., @code{main} in C).  Since it uses
9287 @code{AC_LANG_PROGRAM}, the features of the latter are available.
9289 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9290 It is considered to be severely broken, and in the future will be
9291 removed in favor of actual function calls (with properly typed
9292 arguments).
9294 This macro cannot be used for Erlang tests.
9295 @end defmac
9297 @node Running the Preprocessor
9298 @section Running the Preprocessor
9300 Sometimes one might need to run the preprocessor on some source file.
9301 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9302 your project, not merely run the preprocessor on it; therefore you
9303 certainly want to run the compiler, not the preprocessor.  Resist the
9304 temptation of following the easiest path.
9306 Nevertheless, if you need to run the preprocessor, then use
9307 @code{AC_PREPROC_IFELSE}.
9309 The macros described in this section cannot be used for tests in Erlang,
9310 Fortran, or Go, since those languages require no preprocessor.
9312 @anchor{AC_PREPROC_IFELSE}
9313 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9314   @ovar{action-if-false})
9315 @acindex{PREPROC_IFELSE}
9316 Run the preprocessor of the current language (@pxref{Language Choice})
9317 on the @var{input}, run the shell commands @var{action-if-true} on
9318 success, @var{action-if-false} otherwise.  The @var{input} can be made
9319 by @code{AC_LANG_PROGRAM} and friends.
9321 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9322 @option{-g}, @option{-O}, etc.@: are not valid options to many C
9323 preprocessors.
9325 It is customary to report unexpected failures with
9326 @code{AC_MSG_FAILURE}.  If needed, @var{action-if-true} can further access
9327 the preprocessed output in the file @file{conftest.i}.
9328 @end defmac
9330 For instance:
9332 @example
9333 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9334 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9335   [Greetings string.])
9336 AC_PREPROC_IFELSE(
9337    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9338                     [[fputs (hw, stdout);]])],
9339    [AC_MSG_RESULT([OK])],
9340    [AC_MSG_FAILURE([unexpected preprocessor failure])])
9341 @end example
9343 @noindent
9344 might result in:
9346 @example
9347 checking for gcc... gcc
9348 checking whether the C compiler works... yes
9349 checking for C compiler default output file name... a.out
9350 checking for suffix of executables...
9351 checking whether we are cross compiling... no
9352 checking for suffix of object files... o
9353 checking whether the compiler supports GNU C... yes
9354 checking whether gcc accepts -g... yes
9355 checking for gcc option to enable C11 features... -std=gnu11
9356 checking how to run the C preprocessor... gcc -std=gnu11 -E
9358 @end example
9360 @sp 1
9362 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9363 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9364 it impossible to use it to elaborate sources.  You are encouraged to
9365 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9366 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9367 to run the @emph{preprocessor} and not the compiler?
9369 @anchor{AC_EGREP_HEADER}
9370 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9371   @var{action-if-found}, @ovar{action-if-not-found})
9372 @acindex{EGREP_HEADER}
9373 If the output of running the preprocessor on the system header file
9374 @var{header-file} matches the extended regular expression
9375 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9376 execute @var{action-if-not-found}.
9377 @end defmac
9379 @anchor{AC_EGREP_CPP}
9380 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9381   @ovar{action-if-found}, @ovar{action-if-not-found})
9382 @acindex{EGREP_CPP}
9383 @var{program} is the text of a C or C++ program, on which shell
9384 variable, back quote, and backslash substitutions are performed.  If the
9385 output of running the preprocessor on @var{program} matches the
9386 extended regular expression @var{pattern}, execute shell commands
9387 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9388 @end defmac
9392 @node Running the Compiler
9393 @section Running the Compiler
9395 To check for a syntax feature of the current language's (@pxref{Language
9396 Choice}) compiler, such as whether it recognizes a certain keyword, or
9397 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9398 to compile a small program that uses that feature.
9400 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9401   @ovar{action-if-false})
9402 @acindex{COMPILE_IFELSE}
9403 Run the compiler and compilation flags of the current language
9404 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9405 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
9406 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9408 It is customary to report unexpected failures with
9409 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
9410 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9411 Linker}).  If needed, @var{action-if-true} can further access the
9412 just-compiled object file @file{conftest.$OBJEXT}.
9414 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9415 current language, which means that if the compiler has not yet been
9416 determined, the compiler determination will be made prior to the body of
9417 the outermost @code{AC_DEFUN} macro that triggered this macro to
9418 expand (@pxref{Expanded Before Required}).
9419 @end defmac
9421 @ovindex ERL
9422 For tests in Erlang, the @var{input} must be the source code of a module named
9423 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9424 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
9425 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9426 to ensure that the Erlang module has the right name.
9428 @node Running the Linker
9429 @section Running the Linker
9431 To check for a library, a function, or a global variable, Autoconf
9432 @command{configure} scripts try to compile and link a small program that
9433 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
9434 @code{ar} on the C library to try to figure out which functions are
9435 available.  Trying to link with the function is usually a more reliable
9436 approach because it avoids dealing with the variations in the options
9437 and output formats of @code{nm} and @code{ar} and in the location of the
9438 standard libraries.  It also allows configuring for cross-compilation or
9439 checking a function's runtime behavior if needed.  On the other hand,
9440 it can be slower than scanning the libraries once, but accuracy is more
9441 important than speed.
9443 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9444 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
9445 to check for libraries (@pxref{Libraries}), by adding the library being
9446 checked for to @code{LIBS} temporarily and trying to link a small
9447 program.
9449 @anchor{AC_LINK_IFELSE}
9450 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9451   @ovar{action-if-false})
9452 @acindex{LINK_IFELSE}
9453 Run the compiler (and compilation flags) and the linker of the current
9454 language (@pxref{Language Choice}) on the @var{input}, run the shell
9455 commands @var{action-if-true} on success, @var{action-if-false}
9456 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
9457 friends.  If needed, @var{action-if-true} can further access the
9458 just-linked program file @file{conftest$EXEEXT}.
9460 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9461 current compilation flags.
9463 It is customary to report unexpected failures with
9464 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
9465 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9466 @end defmac
9468 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9469 programs are interpreted and do not require linking.
9473 @node Runtime
9474 @section Checking Runtime Behavior
9476 Sometimes you need to find out how a system performs at runtime, such
9477 as whether a given function has a certain capability or bug.  If you
9478 can, make such checks when your program runs instead of when it is
9479 configured.  You can check for things like the machine's endianness when
9480 your program initializes itself.
9482 If you really need to test for a runtime behavior while configuring,
9483 you can write a test program to determine the result, and compile and
9484 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
9485 possible, because this prevents people from configuring your package for
9486 cross-compiling.
9488 @anchor{AC_RUN_IFELSE}
9489 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9490   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9491 @acindex{RUN_IFELSE}
9492 Run the compiler (and compilation flags) and the linker of the current
9493 language (@pxref{Language Choice}) on the @var{input}, then execute the
9494 resulting program.  If the program returns an exit
9495 status of 0 when executed, run shell commands @var{action-if-true}.
9496 Otherwise, run shell commands @var{action-if-false}.
9498 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9499 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9500 compilation flags of the current language (@pxref{Language Choice}).
9501 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9502 for further testing.
9504 In the @var{action-if-false} section, the failing exit status is
9505 available in the shell variable @samp{$?}.  This exit status might be
9506 that of a failed compilation, or it might be that of a failed program
9507 execution.
9509 If cross-compilation mode is enabled (this is the case if either the
9510 compiler being used does not produce executables that run on the system
9511 where @command{configure} is being run, or if the options @code{--build}
9512 and @code{--host} were both specified and their values are different),
9513 then the test program is
9514 not run.  If the optional shell commands @var{action-if-cross-compiling}
9515 are given, those commands are run instead; typically these commands
9516 provide pessimistic defaults that allow cross-compilation to work even
9517 if the guess was wrong.  If the fourth argument is empty or omitted, but
9518 cross-compilation is detected, then @command{configure} prints an error
9519 message and exits.  If you want your package to be useful in a
9520 cross-compilation scenario, you @emph{should} provide a non-empty
9521 @var{action-if-cross-compiling} clause, as well as wrap the
9522 @code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9523 (@pxref{Caching Results}) which allows the user to override the
9524 pessimistic default if needed.
9526 It is customary to report unexpected failures with
9527 @code{AC_MSG_FAILURE}.
9528 @end defmac
9530 @command{autoconf} prints a warning message when creating
9531 @command{configure} each time it encounters a call to
9532 @code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9533 given.  If you are not concerned about users configuring your package
9534 for cross-compilation, you may ignore the warning.  A few of the macros
9535 distributed with Autoconf produce this warning message; but if this is a
9536 problem for you, please report it as a bug, along with an appropriate
9537 pessimistic guess to use instead.
9539 To configure for cross-compiling you can also choose a value for those
9540 parameters based on the canonical system name (@pxref{Manual
9541 Configuration}).  Alternatively, set up a test results cache file with
9542 the correct values for the host system (@pxref{Caching Results}).
9544 @ovindex cross_compiling
9545 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9546 in other macros, including a few of the ones that come with Autoconf,
9547 you can test whether the shell variable @code{cross_compiling} is set to
9548 @samp{yes}, and then use an alternate method to get the results instead
9549 of calling the macros.
9551 It is also permissible to temporarily assign to @code{cross_compiling}
9552 in order to force tests to behave as though they are in a
9553 cross-compilation environment, particularly since this provides a way to
9554 test your @var{action-if-cross-compiling} even when you are not using a
9555 cross-compiler.
9557 @example
9558 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9559 # to use the slow link-only method
9560 save_cross_compiling=$cross_compiling
9561 cross_compiling=yes
9562 AC_COMPUTE_INT([@dots{}])
9563 cross_compiling=$save_cross_compiling
9564 @end example
9566 A C or C++ runtime test should be portable.
9567 @xref{Portable C and C++}.
9569 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9570 function: the given status code is used to determine the success of the test
9571 (status is @code{0}) or its failure (status is different than @code{0}), as
9572 explained above.  It must be noted that data output through the standard output
9573 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9574 Therefore, if a test must output configuration information, it is recommended
9575 to create and to output data into the temporary file named @file{conftest.out},
9576 using the functions of module @code{file}.  The @code{conftest.out} file is
9577 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9578 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9579 macro is:
9581 @example
9582 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9583 AC_ERLANG_NEED_ERL
9584 AC_LANG(Erlang)
9585 AC_RUN_IFELSE(
9586   [AC_LANG_PROGRAM([], [dnl
9587     file:write_file("conftest.out", code:lib_dir()),
9588     halt(0)])],
9589   [echo "code:lib_dir() returned: `cat conftest.out`"],
9590   [AC_MSG_FAILURE([test Erlang program execution failed])])
9591 @end example
9594 @node Systemology
9595 @section Systemology
9596 @cindex Systemology
9598 This section aims at presenting some systems and pointers to
9599 documentation.  It may help you addressing particular problems reported
9600 by users.
9602 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
9603 derived from the
9604 @uref{http://@/www.bell-labs.com/@/usr/@/dmr/@/www/@/hist.html, Unix
9605 operating system}.
9607 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9608 contains a table correlating the features of various Posix-conforming
9609 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
9610 simplified diagram of how many Unix systems were derived from each
9611 other.
9613 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9614 provides some variants of traditional implementations of Unix utilities.
9616 @table @asis
9617 @item Darwin
9618 @cindex Darwin
9619 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
9620 case-preserving, but case insensitive.  This can cause nasty problems,
9621 since for instance the installation attempt for a package having an
9622 @file{INSTALL} file can result in @samp{make install} report that
9623 nothing was to be done!
9625 That's all dependent on whether the file system is a UFS (case
9626 sensitive) or HFS+ (case preserving).  By default Apple wants you to
9627 install the OS on HFS+.  Unfortunately, there are some pieces of
9628 software which really need to be built on UFS@.  We may want to rebuild
9629 Darwin to have both UFS and HFS+ available (and put the /local/build
9630 tree on the UFS).
9632 @item QNX 4.25
9633 @cindex QNX 4.25
9634 @c FIXME: Please, if you feel like writing something more precise,
9635 @c it'd be great.  In particular, I can't understand the difference with
9636 @c QNX Neutrino.
9637 QNX is a realtime operating system running on Intel architecture
9638 meant to be scalable from the small embedded systems to the hundred
9639 processor super-computer.  It claims to be Posix certified.  More
9640 information is available on the
9641 @uref{http://@/www.qnx.com/, QNX home page}.
9643 @item Tru64
9644 @cindex Tru64
9645 @uref{http://@/h30097.www3.hp.com/@/docs/,
9646 Documentation of several versions of Tru64} is available in different
9647 formats.
9649 @item Unix version 7
9650 @cindex Unix version 7
9651 @cindex V7
9652 Officially this was called the ``Seventh Edition'' of ``the UNIX
9653 time-sharing system'' but we use the more-common name ``Unix version 7''.
9654 Documentation is available in the
9655 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
9656 Previous versions of Unix are called ``Unix version 6'', etc., but
9657 they were not as widely used.
9658 @end table
9661 @node Multiple Cases
9662 @section Multiple Cases
9664 Some operations are accomplished in several possible ways, depending on
9665 the OS variant.  Checking for them essentially requires a ``case
9666 statement''.  Autoconf does not directly provide one; however, it is
9667 easy to simulate by using a shell variable to keep track of whether a
9668 way to perform the operation has been found yet.
9670 Here is an example that uses the shell variable @code{fstype} to keep
9671 track of whether the remaining cases need to be checked.  Note that
9672 since the value of @code{fstype} is under our control, we don't have to
9673 use the longer @samp{test "x$fstype" = xno}.
9675 @example
9676 @group
9677 AC_MSG_CHECKING([how to get file system type])
9678 fstype=no
9679 # The order of these tests is important.
9680 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9681 #include <sys/fstyp.h>]])],
9682                   [AC_DEFINE([FSTYPE_STATVFS], [1],
9683                      [Define if statvfs exists.])
9684                    fstype=SVR4])
9685 if test $fstype = no; then
9686   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9687 #include <sys/fstyp.h>]])],
9688                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9689                      [Define if USG statfs.])
9690                    fstype=SVR3])
9692 if test $fstype = no; then
9693   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9694 #include <sys/vmount.h>]])]),
9695                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9696                      [Define if AIX statfs.])
9697                    fstype=AIX])
9699 # (more cases omitted here)
9700 AC_MSG_RESULT([$fstype])
9701 @end group
9702 @end example
9704 @c ====================================================== Results of Tests.
9706 @node Results
9707 @chapter Results of Tests
9709 Once @command{configure} has determined whether a feature exists, what can
9710 it do to record that information?  There are four sorts of things it can
9711 do: define a C preprocessor symbol, set a variable in the output files,
9712 save the result in a cache file for future @command{configure} runs, and
9713 print a message letting the user know the result of the test.
9715 @menu
9716 * Defining Symbols::            Defining C preprocessor symbols
9717 * Setting Output Variables::    Replacing variables in output files
9718 * Special Chars in Variables::  Characters to beware of in variables
9719 * Caching Results::             Speeding up subsequent @command{configure} runs
9720 * Printing Messages::           Notifying @command{configure} users
9721 @end menu
9723 @node Defining Symbols
9724 @section Defining C Preprocessor Symbols
9726 A common action to take in response to a feature test is to define a C
9727 preprocessor symbol indicating the results of the test.  That is done by
9728 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9730 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9731 into the output variable @code{DEFS}, which contains an option
9732 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
9733 Autoconf version 1, there is no variable @code{DEFS} defined while
9734 @command{configure} is running.  To check whether Autoconf macros have
9735 already defined a certain C preprocessor symbol, test the value of the
9736 appropriate cache variable, as in this example:
9738 @example
9739 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9740                           [Define if vprintf exists.])])
9741 if test "x$ac_cv_func_vprintf" != xyes; then
9742   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9743                             [Define if _doprnt exists.])])
9745 @end example
9747 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9748 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9749 correct values into @code{#define} statements in a template file.
9750 @xref{Configuration Headers}, for more information about this kind of
9751 output.
9753 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9754 @defmacx AC_DEFINE (@var{variable})
9755 @cvindex @var{variable}
9756 @acindex{DEFINE}
9757 Define @var{variable} to @var{value} (verbatim), by defining a C
9758 preprocessor macro for @var{variable}.  @var{variable} should be a C
9759 identifier, optionally suffixed by a parenthesized argument list to
9760 define a C preprocessor macro with arguments.  The macro argument list,
9761 if present, should be a comma-separated list of C identifiers, possibly
9762 terminated by an ellipsis @samp{...} if C99-or-later syntax is employed.
9763 @var{variable} should not contain comments, white space, trigraphs,
9764 backslash-newlines, universal character names, or non-ASCII
9765 characters.
9767 @var{value} may contain backslash-escaped newlines, which will be
9768 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9769 via @code{@@DEFS@@} (with no effect on the compilation, since the
9770 preprocessor sees only one line in the first place).  @var{value} should
9771 not contain raw newlines.  If you are not using
9772 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9773 characters, as @command{make} tends to eat them.  To use a shell
9774 variable, use @code{AC_DEFINE_UNQUOTED} instead.
9776 @var{description} is only useful if you are using
9777 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
9778 the generated @file{config.h.in} as the comment before the macro define.
9779 The following example defines the C preprocessor variable
9780 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
9782 @example
9783 AC_DEFINE([EQUATION], ["$a > $b"],
9784   [Equation string.])
9785 @end example
9787 If neither @var{value} nor @var{description} are given, then
9788 @var{value} defaults to 1 instead of to the empty string.  This is for
9789 backwards compatibility with older versions of Autoconf, but this usage
9790 is obsolescent and may be withdrawn in future versions of Autoconf.
9792 If the @var{variable} is a literal string, it is passed to
9793 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9795 If multiple @code{AC_DEFINE} statements are executed for the same
9796 @var{variable} name (not counting any parenthesized argument list),
9797 the last one wins.
9798 @end defmac
9800 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9801 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
9802 @acindex{DEFINE_UNQUOTED}
9803 @cvindex @var{variable}
9804 Like @code{AC_DEFINE}, but three shell expansions are
9805 performed---once---on @var{variable} and @var{value}: variable expansion
9806 (@samp{$}), command substitution (@samp{`}), and backslash escaping
9807 (@samp{\}), as if in an unquoted here-document.  Single and double quote
9808 characters in the value have no
9809 special meaning.  Use this macro instead of @code{AC_DEFINE} when
9810 @var{variable} or @var{value} is a shell variable.  Examples:
9812 @example
9813 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
9814   [Configuration machine file.])
9815 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
9816   [getgroups return type.])
9817 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
9818   [Translated header name.])
9819 @end example
9820 @end defmac
9822 Due to a syntactical bizarreness of the Bourne shell, do not use
9823 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
9824 calls from other macro calls or shell code; that can cause syntax errors
9825 in the resulting @command{configure} script.  Use either blanks or
9826 newlines.  That is, do this:
9828 @example
9829 AC_CHECK_HEADER([elf.h],
9830   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
9831 @end example
9833 @noindent
9834 or this:
9836 @example
9837 AC_CHECK_HEADER([elf.h],
9838   [AC_DEFINE([SVR4], [1], [System V Release 4])
9839    LIBS="-lelf $LIBS"])
9840 @end example
9842 @noindent
9843 instead of this:
9845 @example
9846 AC_CHECK_HEADER([elf.h],
9847   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
9848 @end example
9850 @node Setting Output Variables
9851 @section Setting Output Variables
9852 @cindex Output variables
9854 Another way to record the results of tests is to set @dfn{output
9855 variables}, which are shell variables whose values are substituted into
9856 files that @command{configure} outputs.  The two macros below create new
9857 output variables.  @xref{Preset Output Variables}, for a list of output
9858 variables that are always available.
9860 @defmac AC_SUBST (@var{variable}, @ovar{value})
9861 @acindex{SUBST}
9862 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
9863 substitute the variable @var{variable} into output files (typically one
9864 or more makefiles).  This means that @code{AC_OUTPUT}
9865 replaces instances of @samp{@@@var{variable}@@} in input files with the
9866 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
9867 is called.  The value can contain any non-@code{NUL} character, including
9868 newline.  If you are using Automake 1.11 or newer, for newlines in values
9869 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
9870 @command{automake} from adding a line @code{@var{variable} =
9871 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
9872 Automake, automake, Other things Automake recognizes}).
9874 Variable occurrences should not overlap: e.g., an input file should
9875 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
9876 are variable names.
9877 The substituted value is not rescanned for more output variables;
9878 occurrences of @samp{@@@var{variable}@@} in the value are inserted
9879 literally into the output file.  (The algorithm uses the special marker
9880 @code{|#_!!_#|} internally, so neither the substituted value nor the
9881 output file may contain @code{|#_!!_#|}.)
9883 If @var{value} is given, in addition assign it to @var{variable}.
9885 The string @var{variable} is passed to @code{m4_pattern_allow}
9886 (@pxref{Forbidden Patterns}).  @var{variable} is not further expanded,
9887 even if there is another macro by the same name.
9888 @end defmac
9890 @defmac AC_SUBST_FILE (@var{variable})
9891 @acindex{SUBST_FILE}
9892 Another way to create an output variable from a shell variable.  Make
9893 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
9894 named by shell variable @var{variable} into output files.  This means
9895 that @code{AC_OUTPUT} replaces instances of
9896 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
9897 with the contents of the file that the shell variable @var{variable}
9898 names when @code{AC_OUTPUT} is called.  Set the variable to
9899 @file{/dev/null} for cases that do not have a file to insert.
9900 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
9901 line by itself, optionally surrounded by spaces and tabs.  The
9902 substitution replaces the whole line, including the spaces, tabs, and
9903 the terminating newline.
9905 This macro is useful for inserting makefile fragments containing
9906 special dependencies or other @command{make} directives for particular host
9907 or target types into makefiles.  For example, @file{configure.ac}
9908 could contain:
9910 @example
9911 AC_SUBST_FILE([host_frag])
9912 host_frag=$srcdir/conf/sun4.mh
9913 @end example
9915 @noindent
9916 and then a @file{Makefile.in} could contain:
9918 @example
9919 @@host_frag@@
9920 @end example
9922 The string @var{variable} is passed to @code{m4_pattern_allow}
9923 (@pxref{Forbidden Patterns}).
9924 @end defmac
9926 @cindex Precious Variable
9927 @cindex Variable, Precious
9928 Running @command{configure} in varying environments can be extremely
9929 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
9930 ./configure}, then the cache, @file{config.h}, and many other output
9931 files depend upon @command{bizarre-cc} being the C compiler.  If
9932 for some reason the user runs @command{./configure} again, or if it is
9933 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
9934 and @pxref{config.status Invocation}), then the configuration can be
9935 inconsistent, composed of results depending upon two different
9936 compilers.
9938 Environment variables that affect this situation, such as @samp{CC}
9939 above, are called @dfn{precious variables}, and can be declared as such
9940 by @code{AC_ARG_VAR}.
9942 @defmac AC_ARG_VAR (@var{variable}, @var{description})
9943 @acindex{ARG_VAR}
9944 Declare @var{variable} is a precious variable, and include its
9945 @var{description} in the variable section of @samp{./configure --help}.
9947 Being precious means that
9948 @itemize @minus
9949 @item
9950 @var{variable} is substituted via @code{AC_SUBST}.
9952 @item
9953 The value of @var{variable} when @command{configure} was launched is
9954 saved in the cache, including if it was not specified on the command
9955 line but via the environment.  Indeed, while @command{configure} can
9956 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
9957 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
9958 which, unfortunately, is what most users do.
9960 We emphasize that it is the @emph{initial} value of @var{variable} which
9961 is saved, not that found during the execution of @command{configure}.
9962 Indeed, specifying @samp{./configure FOO=foo} and letting
9963 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
9964 different things.
9966 @item
9967 @var{variable} is checked for consistency between two
9968 @command{configure} runs.  For instance:
9970 @example
9971 $ @kbd{./configure --silent --config-cache}
9972 $ @kbd{CC=cc ./configure --silent --config-cache}
9973 configure: error: 'CC' was not set in the previous run
9974 configure: error: changes in the environment can compromise \
9975 the build
9976 configure: error: run 'make distclean' and/or \
9977 'rm config.cache' and start over
9978 @end example
9980 @noindent
9981 and similarly if the variable is unset, or if its content is changed.
9982 If the content has white space changes only, then the error is degraded
9983 to a warning only, but the old value is reused.
9985 @item
9986 @var{variable} is kept during automatic reconfiguration
9987 (@pxref{config.status Invocation}) as if it had been passed as a command
9988 line argument, including when no cache is used:
9990 @example
9991 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
9992 $ @kbd{./config.status --recheck}
9993 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
9994   CC=/usr/bin/cc  --no-create --no-recursion
9995 @end example
9996 @end itemize
9997 @end defmac
9999 @node Special Chars in Variables
10000 @section Special Characters in Output Variables
10001 @cindex Output variables, special characters in
10003 Many output variables are intended to be evaluated both by
10004 @command{make} and by the shell.  Some characters are expanded
10005 differently in these two contexts, so to avoid confusion these
10006 variables' values should not contain any of the following characters:
10008 @example
10009 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
10010 @end example
10012 Also, these variables' values should neither contain newlines, nor start
10013 with @samp{~}, nor contain white space or @samp{:} immediately followed
10014 by @samp{~}.  The values can contain nonempty sequences of white space
10015 characters like tabs and spaces, but each such sequence might
10016 arbitrarily be replaced by a single space during substitution.
10018 These restrictions apply both to the values that @command{configure}
10019 computes, and to the values set directly by the user.  For example, the
10020 following invocations of @command{configure} are problematic, since they
10021 attempt to use special characters within @code{CPPFLAGS} and white space
10022 within @code{$(srcdir)}:
10024 @example
10025 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
10027 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
10028 @end example
10030 @node Caching Results
10031 @section Caching Results
10032 @cindex Cache
10034 To avoid checking for the same features repeatedly in various
10035 @command{configure} scripts (or in repeated runs of one script),
10036 @command{configure} can optionally save the results of many checks in a
10037 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
10038 runs with caching enabled and finds a cache file, it reads the results
10039 of previous runs from the cache and avoids rerunning those checks.  As a
10040 result, @command{configure} can then run much faster than if it had to
10041 perform all of the checks every time.
10043 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10044 @acindex{CACHE_VAL}
10045 Ensure that the results of the check identified by @var{cache-id} are
10046 available.  If the results of the check were in the cache file that was
10047 read, and @command{configure} was not given the @option{--quiet} or
10048 @option{--silent} option, print a message saying that the result was
10049 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
10050 the shell commands are run to determine the value, the value is
10051 saved in the cache file just before @command{configure} creates its output
10052 files.  @xref{Cache Variable Names}, for how to choose the name of the
10053 @var{cache-id} variable.
10055 The @var{commands-to-set-it} @emph{must have no side effects} except for
10056 setting the variable @var{cache-id}, see below.
10057 @end defmac
10059 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10060   @var{commands-to-set-it})
10061 @acindex{CACHE_CHECK}
10062 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10063 messages.  This macro provides a convenient shorthand for the most
10064 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
10065 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10066 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10068 The @var{commands-to-set-it} @emph{must have no side effects} except for
10069 setting the variable @var{cache-id}, see below.
10070 @end defmac
10072 It is common to find buggy macros using @code{AC_CACHE_VAL} or
10073 @code{AC_CACHE_CHECK}, because people are tempted to call
10074 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
10075 @emph{follows} the call to @code{AC_CACHE_VAL} should call
10076 @code{AC_DEFINE}, by examining the value of the cache variable.  For
10077 instance, the following macro is broken:
10079 @example
10080 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10081 @group
10082 AC_DEFUN([AC_SHELL_TRUE],
10083 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10084                 [my_cv_shell_true_works=no
10085                  (true) 2>/dev/null && my_cv_shell_true_works=yes
10086                  if test "x$my_cv_shell_true_works" = xyes; then
10087                    AC_DEFINE([TRUE_WORKS], [1],
10088                              [Define if 'true(1)' works properly.])
10089                  fi])
10091 @end group
10092 @end example
10094 @noindent
10095 This fails if the cache is enabled: the second time this macro is run,
10096 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
10099 @example
10100 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10101 @group
10102 AC_DEFUN([AC_SHELL_TRUE],
10103 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10104                 [my_cv_shell_true_works=no
10105                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
10106  if test "x$my_cv_shell_true_works" = xyes; then
10107    AC_DEFINE([TRUE_WORKS], [1],
10108              [Define if 'true(1)' works properly.])
10109  fi
10111 @end group
10112 @end example
10114 Also, @var{commands-to-set-it} should not print any messages, for
10115 example with @code{AC_MSG_CHECKING}; do that before calling
10116 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10117 the results of the check are retrieved from the cache or determined by
10118 running the shell commands.
10120 @menu
10121 * Cache Variable Names::        Shell variables used in caches
10122 * Cache Files::                 Files @command{configure} uses for caching
10123 * Cache Checkpointing::         Loading and saving the cache file
10124 @end menu
10126 @node Cache Variable Names
10127 @subsection Cache Variable Names
10128 @cindex Cache variable
10130 The names of cache variables should have the following format:
10132 @example
10133 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10134 @end example
10136 @noindent
10137 for example, @samp{ac_cv_header_stat_broken} or
10138 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
10140 @table @asis
10141 @item @var{package-prefix}
10142 An abbreviation for your package or organization; the same prefix you
10143 begin local Autoconf macros with, except lowercase by convention.
10144 For cache values used by the distributed Autoconf macros, this value is
10145 @samp{ac}.
10147 @item @code{_cv_}
10148 Indicates that this shell variable is a cache value.  This string
10149 @emph{must} be present in the variable name, including the leading
10150 underscore.
10152 @item @var{value-type}
10153 A convention for classifying cache values, to produce a rational naming
10154 system.  The values used in Autoconf are listed in @ref{Macro Names}.
10156 @item @var{specific-value}
10157 Which member of the class of cache values this test applies to.
10158 For example, which function (@samp{alloca}), program (@samp{gcc}), or
10159 output variable (@samp{INSTALL}).
10161 @item @var{additional-options}
10162 Any particular behavior of the specific member that this test applies to.
10163 For example, @samp{broken} or @samp{set}.  This part of the name may
10164 be omitted if it does not apply.
10165 @end table
10167 The values assigned to cache variables may not contain newlines.
10168 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10169 names of files or functions; so this is not an important restriction.
10170 @ref{Cache Variable Index} for an index of cache variables with
10171 documented semantics.
10174 @node Cache Files
10175 @subsection Cache Files
10177 A cache file is a shell script that caches the results of configure
10178 tests run on one system so they can be shared between configure scripts
10179 and configure runs.  It is not useful on other systems.  If its contents
10180 are invalid for some reason, the user may delete or edit it, or override
10181 documented cache variables on the @command{configure} command line.
10183 By default, @command{configure} uses no cache file,
10184 to avoid problems caused by accidental
10185 use of stale cache files.
10187 To enable caching, @command{configure} accepts @option{--config-cache} (or
10188 @option{-C}) to cache results in the file @file{config.cache}.
10189 Alternatively, @option{--cache-file=@var{file}} specifies that
10190 @var{file} be the cache file.  The cache file is created if it does not
10191 exist already.  When @command{configure} calls @command{configure} scripts in
10192 subdirectories, it uses the @option{--cache-file} argument so that they
10193 share the same cache.  @xref{Subdirectories}, for information on
10194 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10196 @file{config.status} only pays attention to the cache file if it is
10197 given the @option{--recheck} option, which makes it rerun
10198 @command{configure}.
10200 It is wrong to try to distribute cache files for particular system types.
10201 There is too much room for error in doing that, and too much
10202 administrative overhead in maintaining them.  For any features that
10203 can't be guessed automatically, use the standard method of the canonical
10204 system type and linking files (@pxref{Manual Configuration}).
10206 The site initialization script can specify a site-wide cache file to
10207 use, instead of the usual per-program cache.  In this case, the cache
10208 file gradually accumulates information whenever someone runs a new
10209 @command{configure} script.  (Running @command{configure} merges the new cache
10210 results with the existing cache file.)  This may cause problems,
10211 however, if the system configuration (e.g., the installed libraries or
10212 compilers) changes and the stale cache file is not deleted.
10214 If @command{configure} is interrupted at the right time when it updates
10215 a cache file outside of the build directory where the @command{configure}
10216 script is run, it may leave behind a temporary file named after the
10217 cache file with digits following it.  You may safely delete such a file.
10220 @node Cache Checkpointing
10221 @subsection Cache Checkpointing
10223 If your configure script, or a macro called from @file{configure.ac}, happens
10224 to abort the configure process, it may be useful to checkpoint the cache
10225 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
10226 reduces the amount of time it takes to rerun the configure script with
10227 (hopefully) the error that caused the previous abort corrected.
10229 @c FIXME: Do we really want to document this guy?
10230 @defmac AC_CACHE_LOAD
10231 @acindex{CACHE_LOAD}
10232 Loads values from existing cache file, or creates a new cache file if a
10233 cache file is not found.  Called automatically from @code{AC_INIT}.
10234 @end defmac
10236 @defmac AC_CACHE_SAVE
10237 @acindex{CACHE_SAVE}
10238 Flushes all cached values to the cache file.  Called automatically from
10239 @code{AC_OUTPUT}, but it can be quite useful to call
10240 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10241 @end defmac
10243 For instance:
10245 @example
10246 @r{ @dots{} AC_INIT, etc. @dots{}}
10247 @group
10248 # Checks for programs.
10249 AC_PROG_CC
10250 AC_PROG_AWK
10251 @r{ @dots{} more program checks @dots{}}
10252 AC_CACHE_SAVE
10253 @end group
10255 @group
10256 # Checks for libraries.
10257 AC_CHECK_LIB([nsl], [gethostbyname])
10258 AC_CHECK_LIB([socket], [connect])
10259 @r{ @dots{} more lib checks @dots{}}
10260 AC_CACHE_SAVE
10261 @end group
10263 @group
10264 # Might abort@dots{}
10265 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10266 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10267 @end group
10268 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
10269 @end example
10271 @node Printing Messages
10272 @section Printing Messages
10273 @cindex Messages, from @command{configure}
10275 @command{configure} scripts need to give users running them several kinds
10276 of information.  The following macros print messages in ways appropriate
10277 for each kind.  The arguments to all of them get enclosed in shell
10278 double quotes, so the shell performs variable and back-quote
10279 substitution on them.
10281 These macros are all wrappers around the @command{echo} shell command.
10282 They direct output to the appropriate file descriptor (@pxref{File
10283 Descriptor Macros}).
10284 @command{configure} scripts should rarely need to run @command{echo} directly
10285 to print messages for the user.  Using these macros makes it easy to
10286 change how and when each kind of message is printed; such changes need
10287 only be made to the macro definitions and all the callers change
10288 automatically.
10290 To diagnose static issues, i.e., when @command{autoconf} is run, see
10291 @ref{Diagnostic Macros}.
10293 @defmac AC_MSG_CHECKING (@var{feature-description})
10294 @acindex{MSG_CHECKING}
10295 Notify the user that @command{configure} is checking for a particular
10296 feature.  This macro prints a message that starts with @samp{checking }
10297 and ends with @samp{...} and no newline.  It must be followed by a call
10298 to @code{AC_MSG_RESULT} to print the result of the check and the
10299 newline.  The @var{feature-description} should be something like
10300 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10301 _Alignof}.
10303 This macro prints nothing if @command{configure} is run with the
10304 @option{--quiet} or @option{--silent} option.
10305 @end defmac
10307 @anchor{AC_MSG_RESULT}
10308 @defmac AC_MSG_RESULT (@var{result-description})
10309 @acindex{MSG_RESULT}
10310 Notify the user of the results of a check.  @var{result-description} is
10311 almost always the value of the cache variable for the check, typically
10312 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
10313 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10314 the completion of the message printed by the call to
10315 @code{AC_MSG_CHECKING}.
10317 This macro prints nothing if @command{configure} is run with the
10318 @option{--quiet} or @option{--silent} option.
10319 @end defmac
10321 @anchor{AC_MSG_NOTICE}
10322 @defmac AC_MSG_NOTICE (@var{message})
10323 @acindex{MSG_NOTICE}
10324 Deliver the @var{message} to the user.  It is useful mainly to print a
10325 general description of the overall purpose of a group of feature checks,
10326 e.g.,
10328 @example
10329 AC_MSG_NOTICE([checking if stack overflow is detectable])
10330 @end example
10332 This macro prints nothing if @command{configure} is run with the
10333 @option{--quiet} or @option{--silent} option.
10334 @end defmac
10336 @anchor{AC_MSG_ERROR}
10337 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10338 @acindex{MSG_ERROR}
10339 Notify the user of an error that prevents @command{configure} from
10340 completing.  This macro prints an error message to the standard error
10341 output and exits @command{configure} with @var{exit-status} (@samp{$?}
10342 by default, except that @samp{0} is converted to @samp{1}).
10343 @var{error-description} should be something like @samp{invalid value
10344 $HOME for \$HOME}.
10346 The @var{error-description} should start with a lower-case letter, and
10347 ``cannot'' is preferred to ``can't''.
10348 @end defmac
10350 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10351 @acindex{MSG_FAILURE}
10352 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10353 prevents @command{configure} from completing @emph{and} that additional
10354 details are provided in @file{config.log}.  This is typically used when
10355 abnormal results are found during a compilation.
10356 @end defmac
10358 @anchor{AC_MSG_WARN}
10359 @defmac AC_MSG_WARN (@var{problem-description})
10360 @acindex{MSG_WARN}
10361 Notify the @command{configure} user of a possible problem.  This macro
10362 prints the message to the standard error output; @command{configure}
10363 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10364 provide a default (back-up) behavior for the situations they warn about.
10365 @var{problem-description} should be something like @samp{ln -s seems to
10366 make hard links}.
10367 @end defmac
10371 @c ====================================================== Programming in M4.
10373 @node Programming in M4
10374 @chapter Programming in M4
10375 @cindex M4
10377 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10378 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10379 provides macros dedicated to shell script generation.
10381 As of this version of Autoconf, these two layers still contain
10382 experimental macros, whose interface might change in the future.  As a
10383 matter of fact, @emph{anything that is not documented must not be used}.
10385 @menu
10386 * M4 Quotation::                Protecting macros from unwanted expansion
10387 * Using autom4te::              The Autoconf executables backbone
10388 * Programming in M4sugar::      Convenient pure M4 macros
10389 * Debugging via autom4te::      Figuring out what M4 was doing
10390 @end menu
10392 @node M4 Quotation
10393 @section M4 Quotation
10394 @cindex M4 quotation
10395 @cindex quotation
10397 The most common problem with existing macros is an improper quotation.
10398 This section, which users of Autoconf can skip, but which macro writers
10399 @emph{must} read, first justifies the quotation scheme that was chosen
10400 for Autoconf and then ends with a rule of thumb.  Understanding the
10401 former helps one to follow the latter.
10403 @menu
10404 * Active Characters::           Characters that change the behavior of M4
10405 * One Macro Call::              Quotation and one macro call
10406 * Quoting and Parameters::      M4 vs. shell parameters
10407 * Quotation and Nested Macros::  Macros calling macros
10408 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
10409 * Quadrigraphs::                Another way to escape special characters
10410 * Balancing Parentheses::       Dealing with unbalanced parentheses
10411 * Quotation Rule Of Thumb::     One parenthesis, one quote
10412 @end menu
10414 @node Active Characters
10415 @subsection Active Characters
10417 To fully understand where proper quotation is important, you first need
10418 to know what the special characters are in Autoconf: @samp{#} introduces
10419 a comment inside which no macro expansion is performed, @samp{,}
10420 separates arguments, @samp{[} and @samp{]} are the quotes
10421 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10422 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10423 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10424 @samp{$} inside a macro definition.
10426 In order to understand the delicate case of macro calls, we first have
10427 to present some obvious failures.  Below they are ``obvious-ified'',
10428 but when you find them in real life, they are usually in disguise.
10430 Comments, introduced by a hash and running up to the newline, are opaque
10431 tokens to the top level: active characters are turned off, and there is
10432 no macro expansion:
10434 @example
10435 # define([def], ine)
10436 @result{}# define([def], ine)
10437 @end example
10439 Each time there can be a macro expansion, there is a quotation
10440 expansion, i.e., one level of quotes is stripped:
10442 @example
10443 int tab[10];
10444 @result{}int tab10;
10445 [int tab[10];]
10446 @result{}int tab[10];
10447 @end example
10449 Without this in mind, the reader might try hopelessly to use her macro
10450 @code{array}:
10452 @example
10453 define([array], [int tab[10];])
10454 array
10455 @result{}int tab10;
10456 [array]
10457 @result{}array
10458 @end example
10460 @noindent
10461 How can you correctly output the intended results@footnote{Using
10462 @code{defn}.}?
10465 @node One Macro Call
10466 @subsection One Macro Call
10468 Let's proceed on the interaction between active characters and macros
10469 with this small macro, which just returns its first argument:
10471 @example
10472 define([car], [$1])
10473 @end example
10475 @noindent
10476 The two pairs of quotes above are not part of the arguments of
10477 @code{define}; rather, they are understood by the top level when it
10478 tries to find the arguments of @code{define}.  Therefore, assuming
10479 @code{car} is not already defined, it is equivalent to write:
10481 @example
10482 define(car, $1)
10483 @end example
10485 @noindent
10486 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10487 quotes, it is bad practice for Autoconf macros which must both be more
10488 robust and also advocate perfect style.
10490 At the top level, there are only two possibilities: either you
10491 quote or you don't:
10493 @example
10494 car(foo, bar, baz)
10495 @result{}foo
10496 [car(foo, bar, baz)]
10497 @result{}car(foo, bar, baz)
10498 @end example
10500 Let's pay attention to the special characters:
10502 @example
10503 car(#)
10504 @error{}EOF in argument list
10505 @end example
10507 The closing parenthesis is hidden in the comment; with a hypothetical
10508 quoting, the top level understood it this way:
10510 @example
10511 car([#)]
10512 @end example
10514 @noindent
10515 Proper quotation, of course, fixes the problem:
10517 @example
10518 car([#])
10519 @result{}#
10520 @end example
10522 Here are more examples:
10524 @example
10525 car(foo, bar)
10526 @result{}foo
10527 car([foo, bar])
10528 @result{}foo, bar
10529 car((foo, bar))
10530 @result{}(foo, bar)
10531 car([(foo], [bar)])
10532 @result{}(foo
10533 define([a], [b])
10534 @result{}
10535 car(a)
10536 @result{}b
10537 car([a])
10538 @result{}b
10539 car([[a]])
10540 @result{}a
10541 car([[[a]]])
10542 @result{}[a]
10543 @end example
10545 @node Quoting and Parameters
10546 @subsection Quoting and Parameters
10548 When M4 encounters @samp{$} within a macro definition, followed
10549 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10550 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10551 expansion.  This happens regardless of how many layers of quotes the
10552 parameter expansion is nested within, or even if it occurs in text that
10553 will be rescanned as a comment.
10555 @example
10556 define([none], [$1])
10557 @result{}
10558 define([one], [[$1]])
10559 @result{}
10560 define([two], [[[$1]]])
10561 @result{}
10562 define([comment], [# $1])
10563 @result{}
10564 define([active], [ACTIVE])
10565 @result{}
10566 none([active])
10567 @result{}ACTIVE
10568 one([active])
10569 @result{}active
10570 two([active])
10571 @result{}[active]
10572 comment([active])
10573 @result{}# active
10574 @end example
10576 On the other hand, since autoconf generates shell code, you often want
10577 to output shell variable expansion, rather than performing M4 parameter
10578 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10579 from the next character in the definition of your macro.  If the macro
10580 definition occurs in single-quoted text, then insert another level of
10581 quoting; if the usage is already inside a double-quoted string, then
10582 split it into concatenated strings.
10584 @example
10585 define([foo], [a single-quoted $[]1 definition])
10586 @result{}
10587 define([bar], [[a double-quoted $][1 definition]])
10588 @result{}
10590 @result{}a single-quoted $1 definition
10592 @result{}a double-quoted $1 definition
10593 @end example
10595 Posix states that M4 implementations are free to provide implementation
10596 extensions when @samp{$@{} is encountered in a macro definition.
10597 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10598 extensions that will be available in the future GNU M4 2.0,
10599 but guarantees that all other instances of @samp{$@{} will be output
10600 literally.  Therefore, this idiom can also be used to output shell code
10601 parameter references:
10603 @example
10604 define([first], [$@{1@}])first
10605 @result{}$@{1@}
10606 @end example
10608 Posix also states that @samp{$11} should expand to the first parameter
10609 concatenated with a literal @samp{1}, although some versions of
10610 GNU M4 expand the eleventh parameter instead.  For
10611 portability, you should only use single-digit M4 parameter expansion.
10613 With this in mind, we can explore the cases where macros invoke
10614 macros@enddots{}
10616 @node Quotation and Nested Macros
10617 @subsection Quotation and Nested Macros
10619 The examples below use the following macros:
10621 @example
10622 define([car], [$1])
10623 define([active], [ACT, IVE])
10624 define([array], [int tab[10]])
10625 @end example
10627 Each additional embedded macro call introduces other possible
10628 interesting quotations:
10630 @example
10631 car(active)
10632 @result{}ACT
10633 car([active])
10634 @result{}ACT, IVE
10635 car([[active]])
10636 @result{}active
10637 @end example
10639 In the first case, the top level looks for the arguments of @code{car},
10640 and finds @samp{active}.  Because M4 evaluates its arguments
10641 before applying the macro, @samp{active} is expanded, which results in:
10643 @example
10644 car(ACT, IVE)
10645 @result{}ACT
10646 @end example
10648 @noindent
10649 In the second case, the top level gives @samp{active} as first and only
10650 argument of @code{car}, which results in:
10652 @example
10653 active
10654 @result{}ACT, IVE
10655 @end example
10657 @noindent
10658 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10659 In the third case, @code{car} receives @samp{[active]}, which results in:
10661 @example
10662 [active]
10663 @result{}active
10664 @end example
10666 @noindent
10667 exactly as we already saw above.
10669 The example above, applied to a more realistic example, gives:
10671 @example
10672 car(int tab[10];)
10673 @result{}int tab10;
10674 car([int tab[10];])
10675 @result{}int tab10;
10676 car([[int tab[10];]])
10677 @result{}int tab[10];
10678 @end example
10680 @noindent
10681 Huh?  The first case is easily understood, but why is the second wrong,
10682 and the third right?  To understand that, you must know that after
10683 M4 expands a macro, the resulting text is immediately subjected
10684 to macro expansion and quote removal.  This means that the quote removal
10685 occurs twice---first before the argument is passed to the @code{car}
10686 macro, and second after the @code{car} macro expands to the first
10687 argument.
10689 As the author of the Autoconf macro @code{car}, you then consider it to
10690 be incorrect that your users have to double-quote the arguments of
10691 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
10692 quoted car:
10694 @example
10695 define([qar], [[$1]])
10696 @end example
10698 @noindent
10699 and check that @code{qar} is properly fixed:
10701 @example
10702 qar([int tab[10];])
10703 @result{}int tab[10];
10704 @end example
10706 @noindent
10707 Ahhh!  That's much better.
10709 But note what you've done: now that the result of @code{qar} is always
10710 a literal string, the only time a user can use nested macros is if she
10711 relies on an @emph{unquoted} macro call:
10713 @example
10714 qar(active)
10715 @result{}ACT
10716 qar([active])
10717 @result{}active
10718 @end example
10720 @noindent
10721 leaving no way for her to reproduce what she used to do with @code{car}:
10723 @example
10724 car([active])
10725 @result{}ACT, IVE
10726 @end example
10728 @noindent
10729 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10730 macros:
10732 @example
10733 define([my_includes], [#include <stdio.h>])
10734 car([my_includes])
10735 @result{}#include <stdio.h>
10736 qar(my_includes)
10737 @error{}EOF in argument list
10738 @end example
10740 This macro, @code{qar}, because it double quotes its arguments, forces
10741 its users to leave their macro calls unquoted, which is dangerous.
10742 Commas and other active symbols are interpreted by M4 before
10743 they are given to the macro, often not in the way the users expect.
10744 Also, because @code{qar} behaves differently from the other macros,
10745 it's an exception that should be avoided in Autoconf.
10747 @node Changequote is Evil
10748 @subsection @code{changequote} is Evil
10749 @cindex @code{changequote}
10751 The temptation is often high to bypass proper quotation, in particular
10752 when it's late at night.  Then, many experienced Autoconf hackers
10753 finally surrender to the dark side of the force and use the ultimate
10754 weapon: @code{changequote}.
10756 The M4 builtin @code{changequote} belongs to a set of primitives that
10757 allow one to adjust the syntax of the language to adjust it to one's
10758 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
10759 quotes, but in the context of shell programming (and actually of most
10760 programming languages), that's about the worst choice one can make:
10761 because of strings and back-quoted expressions in shell code (such as
10762 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
10763 programming languages (as in @samp{'0'}), there are many unbalanced
10764 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
10765 not impossible.  In order to make M4 useful in such a context, its
10766 designers have equipped it with @code{changequote}, which makes it
10767 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
10768 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
10769 because they are unlikely characters, but @emph{because they are
10770 characters unlikely to be unbalanced}.
10772 There are other magic primitives, such as @code{changecom} to specify
10773 what syntactic forms are comments (it is common to see
10774 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10775 @code{changeword} and @code{changesyntax} to change other syntactic
10776 details (such as the character to denote the @var{n}th argument, @samp{$} by
10777 default, the parentheses around arguments, etc.).
10779 These primitives are really meant to make M4 more useful for specific
10780 domains: they should be considered like command line options:
10781 @option{--quotes}, @option{--comments}, @option{--words}, and
10782 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
10783 it makes M4 libraries self contained (no need for additional options).
10785 There lies the problem@enddots{}
10787 @sp 1
10789 The problem is that it is then tempting to use them in the middle of an
10790 M4 script, as opposed to its initialization.  This, if not carefully
10791 thought out, can lead to disastrous effects: @emph{you are changing the
10792 language in the middle of the execution}.  Changing and restoring the
10793 syntax is often not enough: if you happened to invoke macros in between,
10794 these macros are lost, as the current syntax is probably not
10795 the one they were implemented with.
10797 @c FIXME: I've been looking for a short, real case example, but I
10798 @c lost them all :(
10801 @node Quadrigraphs
10802 @subsection Quadrigraphs
10803 @cindex quadrigraphs
10804 @cindex @samp{@@S|@@}
10805 @cindex @samp{@@&t@@}
10806 @c Info cannot handle ':' in index entries.
10807 @ifnotinfo
10808 @cindex @samp{@@<:@@}
10809 @cindex @samp{@@:>@@}
10810 @cindex @samp{@@%:@@}
10811 @cindex @samp{@@@{:@@}
10812 @cindex @samp{@@:@}@@}
10813 @end ifnotinfo
10815 When writing an Autoconf macro you may occasionally need to generate
10816 special characters that are difficult to express with the standard
10817 Autoconf quoting rules.  For example, you may need to output the regular
10818 expression @samp{[^[]}, which matches any character other than @samp{[}.
10819 This expression contains unbalanced brackets so it cannot be put easily
10820 into an M4 macro.
10822 Additionally, there are a few m4sugar macros (such as @code{m4_split}
10823 and @code{m4_expand}) which internally use special markers in addition
10824 to the regular quoting characters.  If the arguments to these macros
10825 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
10826 might behave incorrectly.
10828 You can work around these problems by using one of the following
10829 @dfn{quadrigraphs}:
10831 @table @samp
10832 @item @@<:@@
10833 @samp{[}
10834 @item @@:>@@
10835 @samp{]}
10836 @item @@S|@@
10837 @samp{$}
10838 @item @@%:@@
10839 @samp{#}
10840 @item @@@{:@@
10841 @samp{(}
10842 @item @@:@}@@
10843 @samp{)}
10844 @item @@&t@@
10845 Expands to nothing.
10846 @end table
10848 Quadrigraphs are replaced at a late stage of the translation process,
10849 after @command{m4} is run, so they do not get in the way of M4 quoting.
10850 For example, the string @samp{^@@<:@@}, independently of its quotation,
10851 appears as @samp{^[} in the output.
10853 The empty quadrigraph can be used:
10855 @itemize @minus
10856 @item to mark trailing spaces explicitly
10858 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
10860 @item to produce quadrigraphs and other strings reserved by m4sugar
10862 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
10863 contrived example:
10865 @example
10866 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
10867 m4_split([a )@}>=- b -=<@{( c])
10868 @result{}[a], [], [B], [], [c]
10869 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
10870 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
10871 @end example
10873 @item to escape @emph{occurrences} of forbidden patterns
10875 For instance you might want to mention @code{AC_FOO} in a comment, while
10876 still being sure that @command{autom4te} still catches unexpanded
10877 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
10878 @end itemize
10880 The name @samp{@@&t@@} was suggested by Paul Eggert:
10882 @quotation
10883 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
10884 own invention, but the @samp{t} came from the source code of the
10885 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
10886 and which used @samp{mt} to denote the empty string.  In C, it would
10887 have looked like something like:
10889 @example
10890 char const mt[] = "";
10891 @end example
10893 @noindent
10894 but of course the source code was written in Algol 68.
10896 I don't know where he got @samp{mt} from: it could have been his own
10897 invention, and I suppose it could have been a common pun around the
10898 Cambridge University computer lab at the time.
10899 @end quotation
10902 @node Balancing Parentheses
10903 @subsection Dealing with unbalanced parentheses
10904 @cindex balancing parentheses
10905 @cindex parentheses, balancing
10906 @cindex unbalanced parentheses, managing
10908 One of the pitfalls of portable shell programming is that @command{case}
10909 statements require unbalanced parentheses (@pxref{case, , Limitations of
10910 Shell Builtins}).  With syntax highlighting
10911 editors, the presence of unbalanced @samp{)} can interfere with editors
10912 that perform syntax highlighting of macro contents based on finding the
10913 matching @samp{(}.  Another concern is how much editing must be done
10914 when transferring code snippets between shell scripts and macro
10915 definitions.  But most importantly, the presence of unbalanced
10916 parentheses can introduce expansion bugs.
10918 For an example, here is an underquoted attempt to use the macro
10919 @code{my_case}, which happens to expand to a portable @command{case}
10920 statement:
10922 @example
10923 AC_DEFUN([my_case],
10924 [case $file_name in
10925   *.c) echo "C source code";;
10926 esac])
10927 AS_IF(:, my_case)
10928 @end example
10930 @noindent
10931 In the above example, the @code{AS_IF} call underquotes its arguments.
10932 As a result, the unbalanced @samp{)} generated by the premature
10933 expansion of @code{my_case} results in expanding @code{AS_IF} with a
10934 truncated parameter, and the expansion is syntactically invalid:
10936 @example
10937 if :; then
10938   case $file_name in
10939   *.c
10940 fi echo "C source code";;
10941 esac)
10942 @end example
10944 If nothing else, this should emphasize the importance of the quoting
10945 arguments to macro calls.  On the other hand, there are several
10946 variations for defining @code{my_case} to be more robust, even when used
10947 without proper quoting, each with some benefits and some drawbacks.
10949 @itemize @w{}
10950 @item Creative literal shell comment
10951 @example
10952 AC_DEFUN([my_case],
10953 [case $file_name in #(
10954   *.c) echo "C source code";;
10955 esac])
10956 @end example
10957 @noindent
10958 This version provides balanced parentheses to several editors, and can
10959 be copied and pasted into a terminal as is.  Unfortunately, it is still
10960 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
10961 that masks the normal properties of @samp{(}.
10963 @item Quadrigraph shell comment
10964 @example
10965 AC_DEFUN([my_case],
10966 [case $file_name in @@%:@@(
10967   *.c) echo "C source code";;
10968 esac])
10969 @end example
10970 @noindent
10971 This version provides balanced parentheses to even more editors, and can
10972 be used as a balanced Autoconf argument.  Unfortunately, it requires
10973 some editing before it can be copied and pasted into a terminal, and the
10974 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
10976 @item Quoting just the parenthesis
10977 @example
10978 AC_DEFUN([my_case],
10979 [case $file_name in
10980   *.c[)] echo "C source code";;
10981 esac])
10982 @end example
10983 @noindent
10984 This version quotes the @samp{)}, so that it can be used as a balanced
10985 Autoconf argument.  As written, this is not balanced to an editor, but
10986 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
10987 still requires some edits before it can be copied and pasted into a
10988 terminal.
10990 @item Double-quoting the entire statement
10991 @example
10992 AC_DEFUN([my_case],
10993 [[case $file_name in #(
10994   *.c) echo "C source code";;
10995 esac]])
10996 @end example
10997 @noindent
10998 Since the entire macro is double-quoted, there is no problem with using
10999 this as an Autoconf argument; and since the double-quoting is over the
11000 entire statement, this code can be easily copied and pasted into a
11001 terminal.  However, the double quoting prevents the expansion of any
11002 macros inside the case statement, which may cause its own set of
11003 problems.
11005 @item Using @code{AS_CASE}
11006 @example
11007 AC_DEFUN([my_case],
11008 [AS_CASE([$file_name],
11009   [*.c], [echo "C source code"])])
11010 @end example
11011 @noindent
11012 This version avoids the balancing issue altogether, by relying on
11013 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
11014 expansion of @code{AC_REQUIRE} to occur prior to the entire case
11015 statement, rather than within a branch of the case statement that might
11016 not be taken.  However, the abstraction comes with a penalty that it is
11017 no longer a quick copy, paste, and edit to get back to shell code.
11018 @end itemize
11021 @node Quotation Rule Of Thumb
11022 @subsection Quotation Rule Of Thumb
11024 To conclude, the quotation rule of thumb is:
11026 @center @emph{One pair of quotes per pair of parentheses.}
11028 Never over-quote, never under-quote, in particular in the definition of
11029 macros.  In the few places where the macros need to use brackets
11030 (usually in C program text or regular expressions), properly quote
11031 @emph{the arguments}!
11033 It is common to read Autoconf programs with snippets like:
11035 @example
11036 AC_TRY_LINK(
11037 changequote(<<, >>)dnl
11038 <<#include <time.h>
11039 #ifndef tzname /* For SGI.  */
11040 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11041 #endif>>,
11042 changequote([, ])dnl
11043 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11044 @end example
11046 @noindent
11047 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11048 double quoting, so you just need:
11050 @example
11051 AC_TRY_LINK(
11052 [#include <time.h>
11053 #ifndef tzname /* For SGI.  */
11054 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11055 #endif],
11056             [atoi (*tzname);],
11057             [ac_cv_var_tzname=yes],
11058             [ac_cv_var_tzname=no])
11059 @end example
11061 @noindent
11062 The M4-fluent reader might note that these two examples are rigorously
11063 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11064 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11065 quotes are not part of the arguments!
11067 Simplified, the example above is just doing this:
11069 @example
11070 changequote(<<, >>)dnl
11071 <<[]>>
11072 changequote([, ])dnl
11073 @end example
11075 @noindent
11076 instead of simply:
11078 @example
11079 [[]]
11080 @end example
11082 With macros that do not double quote their arguments (which is the
11083 rule), double-quote the (risky) literals:
11085 @example
11086 AC_LINK_IFELSE([AC_LANG_PROGRAM(
11087 [[#include <time.h>
11088 #ifndef tzname /* For SGI.  */
11089 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11090 #endif]],
11091                                 [atoi (*tzname);])],
11092                [ac_cv_var_tzname=yes],
11093                [ac_cv_var_tzname=no])
11094 @end example
11096 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11097 should be using @code{AC_LINK_IFELSE} instead.
11099 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
11100 where quoting does not suffice.
11102 When you create a @command{configure} script using newly written macros,
11103 examine it carefully to check whether you need to add more quotes in
11104 your macros.  If one or more words have disappeared in the M4
11105 output, you need more quotes.  When in doubt, quote.
11107 However, it's also possible to put on too many layers of quotes.  If
11108 this happens, the resulting @command{configure} script may contain
11109 unexpanded macros.  The @command{autoconf} program checks for this problem
11110 by looking for the string @samp{AC_} in @file{configure}.  However, this
11111 heuristic does not work in general: for example, it does not catch
11112 overquoting in @code{AC_DEFINE} descriptions.
11115 @c ---------------------------------------- Using autom4te
11117 @node Using autom4te
11118 @section Using @command{autom4te}
11120 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11121 to Autoconf per se, heavily rely on M4.  All these different uses
11122 revealed common needs factored into a layer over M4:
11123 @command{autom4te}@footnote{
11125 Yet another great name from Lars J. Aas.
11129 @command{autom4te} is a preprocessor that is like @command{m4}.
11130 It supports M4 extensions designed for use in tools like Autoconf.
11132 @menu
11133 * autom4te Invocation::         A GNU M4 wrapper
11134 * Customizing autom4te::        Customizing the Autoconf package
11135 @end menu
11137 @node autom4te Invocation
11138 @subsection Invoking @command{autom4te}
11140 The command line arguments are modeled after M4's:
11142 @example
11143 autom4te @var{options} @var{files}
11144 @end example
11146 @noindent
11147 @evindex M4
11148 where the @var{files} are directly passed to @command{m4}.  By default,
11149 GNU M4 is found during configuration, but the environment
11150 variable
11151 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
11152 to the regular expansion, it handles the replacement of the quadrigraphs
11153 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11154 output.  It supports an extended syntax for the @var{files}:
11156 @table @file
11157 @item @var{file}.m4f
11158 This file is an M4 frozen file.  Note that @emph{all the previous files
11159 are ignored}.  See the option @option{--melt} for the rationale.
11161 @item @var{file}?
11162 If found in the library path, the @var{file} is included for expansion,
11163 otherwise it is ignored instead of triggering a failure.
11164 @end table
11166 @sp 1
11168 Of course, it supports the Autoconf common subset of options:
11170 @table @option
11171 @item --help
11172 @itemx -h
11173 Print a summary of the command line options and exit.
11175 @item --version
11176 @itemx -V
11177 Print the version number of Autoconf and exit.
11179 @item --verbose
11180 @itemx -v
11181 Report processing steps.
11183 @item --debug
11184 @itemx -d
11185 Don't remove the temporary files and be even more verbose.
11187 @item --include=@var{dir}
11188 @itemx -I @var{dir}
11189 Also look for input files in @var{dir}.  Multiple invocations
11190 accumulate.
11192 @item --output=@var{file}
11193 @itemx -o @var{file}
11194 Save output (script or trace) to @var{file}.  The file @option{-} stands
11195 for the standard output.
11196 @end table
11198 @sp 1
11200 As an extension of @command{m4}, it includes the following options:
11202 @table @option
11203 @item --warnings=@var{category}
11204 @itemx -W @var{category}
11205 @evindex WARNINGS
11206 @c FIXME: Point to the M4sugar macros, not Autoconf's.
11207 Report the warnings related to @var{category} (which can actually be a
11208 comma separated list).  @xref{Reporting Messages}, macro
11209 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
11210 values include:
11212 @table @samp
11213 @item all
11214 report all the warnings
11216 @item none
11217 report none
11219 @item error
11220 treats warnings as errors
11222 @item no-@var{category}
11223 disable warnings falling into @var{category}
11224 @end table
11226 Warnings about @samp{syntax} are enabled by default, and the environment
11227 variable @env{WARNINGS}, a comma separated list of categories, is
11228 honored.  @samp{autom4te -W @var{category}} actually
11229 behaves as if you had run:
11231 @example
11232 autom4te --warnings=syntax,$WARNINGS,@var{category}
11233 @end example
11235 @noindent
11236 For example, if you want to disable defaults and @env{WARNINGS}
11237 of @command{autom4te}, but enable the warnings about obsolete
11238 constructs, you would use @option{-W none,obsolete}.
11240 @cindex Back trace
11241 @cindex Macro invocation stack
11242 @command{autom4te} displays a back trace for errors, but not for
11243 warnings; if you want them, just pass @option{-W error}.
11245 @item --melt
11246 @itemx -M
11247 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
11248 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
11249 are executed only when the files are frozen, typically
11250 @code{m4_define}.  For instance, running:
11252 @example
11253 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11254 @end example
11256 @noindent
11257 is roughly equivalent to running:
11259 @example
11260 m4 1.m4 2.m4 3.m4 4.m4 input.m4
11261 @end example
11263 @noindent
11264 while
11266 @example
11267 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11268 @end example
11270 @noindent
11271 is equivalent to:
11273 @example
11274 m4 --reload-state=4.m4f input.m4
11275 @end example
11277 @item --freeze
11278 @itemx -F
11279 Produce a frozen state file.  @command{autom4te} freezing is stricter
11280 than M4's: it must produce no warnings, and no output other than empty
11281 lines (a line with white space is @emph{not} empty) and comments
11282 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
11283 this option takes no argument:
11285 @example
11286 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11287 @end example
11289 @noindent
11290 corresponds to
11292 @example
11293 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11294 @end example
11296 @item --mode=@var{octal-mode}
11297 @itemx -m @var{octal-mode}
11298 Set the mode of the non-traces output to @var{octal-mode}; by default
11299 @samp{0666}.
11300 @end table
11302 @sp 1
11304 @cindex @file{autom4te.cache}
11305 As another additional feature over @command{m4}, @command{autom4te}
11306 caches its results.  GNU M4 is able to produce a regular
11307 output and traces at the same time.  Traces are heavily used in the
11308 GNU Build System: @command{autoheader} uses them to build
11309 @file{config.h.in}, @command{autoreconf} to determine what
11310 GNU Build System components are used, @command{automake} to
11311 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
11312 traces are cached while performing regular expansion,
11313 and conversely.  This cache is (actually, the caches are) stored in
11314 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
11315 at any moment (especially if for some reason @command{autom4te}
11316 considers it trashed).
11318 @table @option
11319 @item --cache=@var{directory}
11320 @itemx -C @var{directory}
11321 Specify the name of the directory where the result should be cached.
11322 Passing an empty value disables caching.  Be sure to pass a relative
11323 file name, as for the time being, global caches are not supported.
11325 @item --no-cache
11326 Don't cache the results.
11328 @item --force
11329 @itemx -f
11330 If a cache is used, consider it obsolete (but update it anyway).
11331 @end table
11333 @sp 1
11335 Because traces are so important to the GNU Build System,
11336 @command{autom4te} provides high level tracing features as compared to
11337 M4, and helps exploiting the cache:
11339 @table @option
11340 @item --trace=@var{macro}[:@var{format}]
11341 @itemx -t @var{macro}[:@var{format}]
11342 Trace the invocations of @var{macro} according to the @var{format}.
11343 Multiple @option{--trace} arguments can be used to list several macros.
11344 Multiple @option{--trace} arguments for a single macro are not
11345 cumulative; instead, you should just make @var{format} as long as
11346 needed.
11348 The @var{format} is a regular string, with newlines if desired, and
11349 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
11350 use the following special escapes:
11352 @table @samp
11353 @item $$
11354 @c $$ restore font-lock
11355 The character @samp{$}.
11357 @item $f
11358 The file name from which @var{macro} is called.
11360 @item $l
11361 The line number from which @var{macro} is called.
11363 @item $d
11364 The depth of the @var{macro} call.  This is an M4 technical detail that
11365 you probably don't want to know about.
11367 @item $n
11368 The name of the @var{macro}.
11370 @item $@var{num}
11371 The @var{num}th argument of the call to @var{macro}.
11373 @item $@@
11374 @itemx $@var{sep}@@
11375 @itemx $@{@var{separator}@}@@
11376 All the arguments passed to @var{macro}, separated by the character
11377 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
11378 argument is quoted, i.e., enclosed in a pair of square brackets.
11380 @item $*
11381 @itemx $@var{sep}*
11382 @itemx $@{@var{separator}@}*
11383 As above, but the arguments are not quoted.
11385 @item $%
11386 @itemx $@var{sep}%
11387 @itemx $@{@var{separator}@}%
11388 As above, but the arguments are not quoted, all new line characters in
11389 the arguments are smashed, and the default separator is @samp{:}.
11391 The escape @samp{$%} produces single-line trace outputs (unless you put
11392 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11393 not.
11394 @end table
11396 @xref{autoconf Invocation}, for examples of trace uses.
11398 @item --preselect=@var{macro}
11399 @itemx -p @var{macro}
11400 Cache the traces of @var{macro}, but do not enable traces.  This is
11401 especially important to save CPU cycles in the future.  For instance,
11402 when invoked, @command{autoconf} preselects all the macros that
11403 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11404 trace, so that running @command{m4} is not needed to trace them: the
11405 cache suffices.  This results in a huge speed-up.
11406 @end table
11408 @sp 1
11410 @cindex Autom4te Library
11411 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11412 libraries}.  They consists in a powerful yet extremely simple feature:
11413 sets of combined command line arguments:
11415 @table @option
11416 @item --language=@var{language}
11417 @itemx -l @var{language}
11418 Use the @var{language} Autom4te library.  Current languages include:
11420 @table @code
11421 @item M4sugar
11422 create M4sugar output.
11424 @item M4sh
11425 create M4sh executable shell scripts.
11427 @item Autotest
11428 create Autotest executable test suites.
11430 @item Autoconf-without-aclocal-m4
11431 create Autoconf executable configure scripts without
11432 reading @file{aclocal.m4}.
11434 @item Autoconf
11435 create Autoconf executable configure scripts.  This language inherits
11436 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11437 additionally reads @file{aclocal.m4}.
11438 @end table
11440 @item --prepend-include=@var{dir}
11441 @itemx -B @var{dir}
11442 Prepend directory @var{dir} to the search path.  This is used to include
11443 the language-specific files before any third-party macros.
11445 @end table
11447 @cindex @file{autom4te.cfg}
11448 As an example, if Autoconf is installed in its default location,
11449 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11450 strictly equivalent to the command:
11452 @example
11453 autom4te --prepend-include /usr/local/share/autoconf \
11454   m4sugar/m4sugar.m4f --warnings syntax foo.m4
11455 @end example
11457 @noindent
11458 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11459 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11460 foo.m4}, i.e.:
11462 @example
11463 autom4te --prepend-include /usr/local/share/autoconf \
11464   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11465 @end example
11467 @noindent
11468 The definition of the languages is stored in @file{autom4te.cfg}.
11470 @node Customizing autom4te
11471 @subsection Customizing @command{autom4te}
11473 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11474 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11475 as found in the directory from which @command{autom4te} is run).  The
11476 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11477 then @file{./.autom4te.cfg}, and finally the command line arguments.
11479 In these text files, comments are introduced with @code{#}, and empty
11480 lines are ignored.  Customization is performed on a per-language basis,
11481 wrapped in between a @samp{begin-language: "@var{language}"},
11482 @samp{end-language: "@var{language}"} pair.
11484 Customizing a language stands for appending options (@pxref{autom4te
11485 Invocation}) to the current definition of the language.  Options, and
11486 more generally arguments, are introduced by @samp{args:
11487 @var{arguments}}.  You may use the traditional shell syntax to quote the
11488 @var{arguments}.
11490 As an example, to disable Autoconf caches (@file{autom4te.cache})
11491 globally, include the following lines in @file{~/.autom4te.cfg}:
11493 @verbatim
11494 ## ------------------ ##
11495 ## User Preferences.  ##
11496 ## ------------------ ##
11498 begin-language: "Autoconf-without-aclocal-m4"
11499 args: --no-cache
11500 end-language: "Autoconf-without-aclocal-m4"
11501 @end verbatim
11504 @node Programming in M4sugar
11505 @section Programming in M4sugar
11507 @cindex M4sugar
11508 M4 by itself provides only a small, but sufficient, set of all-purpose
11509 macros.  M4sugar introduces additional generic macros.  Its name was
11510 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11511 M4sugar''.
11513 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11514 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
11515 define your own macros into these namespaces.
11517 @menu
11518 * Redefined M4 Macros::         M4 builtins changed in M4sugar
11519 * Diagnostic Macros::           Diagnostic messages from M4sugar
11520 * Diversion support::           Diversions in M4sugar
11521 * Conditional constructs::      Conditions in M4
11522 * Looping constructs::          Iteration in M4
11523 * Evaluation Macros::           More quotation and evaluation control
11524 * Text processing Macros::      String manipulation in M4
11525 * Number processing Macros::    Arithmetic computation in M4
11526 * Set manipulation Macros::     Set manipulation in M4
11527 * Forbidden Patterns::          Catching unexpanded macros
11528 @end menu
11530 @node Redefined M4 Macros
11531 @subsection Redefined M4 Macros
11533 @msindex{builtin}
11534 @msindex{changecom}
11535 @msindex{changequote}
11536 @msindex{debugfile}
11537 @msindex{debugmode}
11538 @msindex{decr}
11539 @msindex{define}
11540 @msindex{divnum}
11541 @msindex{errprint}
11542 @msindex{esyscmd}
11543 @msindex{eval}
11544 @msindex{format}
11545 @msindex{ifdef}
11546 @msindex{incr}
11547 @msindex{index}
11548 @msindex{indir}
11549 @msindex{len}
11550 @msindex{pushdef}
11551 @msindex{shift}
11552 @msindex{substr}
11553 @msindex{syscmd}
11554 @msindex{sysval}
11555 @msindex{traceoff}
11556 @msindex{traceon}
11557 @msindex{translit}
11558 With a few exceptions, all the M4 native macros are moved in the
11559 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11560 @code{m4_define} etc.
11562 The list of macros unchanged from M4, except for their name, is:
11563 @itemize @minus
11564 @item m4_builtin
11565 @item m4_changecom
11566 @item m4_changequote
11567 @item m4_debugfile
11568 @item m4_debugmode
11569 @item m4_decr
11570 @item m4_define
11571 @item m4_divnum
11572 @item m4_errprint
11573 @item m4_esyscmd
11574 @item m4_eval
11575 @item m4_format
11576 @item m4_ifdef
11577 @item m4_incr
11578 @item m4_index
11579 @item m4_indir
11580 @item m4_len
11581 @item m4_pushdef
11582 @item m4_shift
11583 @item m4_substr
11584 @item m4_syscmd
11585 @item m4_sysval
11586 @item m4_traceoff
11587 @item m4_traceon
11588 @item m4_translit
11589 @end itemize
11591 Some M4 macros are redefined, and are slightly incompatible with their
11592 native equivalent.
11594 @defmac __file__
11595 @defmacx __line__
11596 @MSindex __file__
11597 @MSindex __line__
11598 All M4 macros starting with @samp{__} retain their original name: for
11599 example, no @code{m4__file__} is defined.
11600 @end defmac
11602 @defmac __oline__
11603 @MSindex __oline__
11604 This is not technically a macro, but a feature of Autom4te.  The
11605 sequence @code{__oline__} can be used similarly to the other m4sugar
11606 location macros, but rather than expanding to the location of the input
11607 file, it is translated to the line number where it appears in the output
11608 file after all other M4 expansions.
11609 @end defmac
11611 @defmac dnl
11612 @MSindex dnl
11613 This macro kept its original name: no @code{m4_dnl} is defined.
11614 @end defmac
11616 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11617 @msindex{bpatsubst}
11618 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
11619 is kept for future versions of M4sugar, once GNU M4 2.0 is
11620 released and supports extended regular expression syntax.
11621 @end defmac
11623 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11624 @msindex{bregexp}
11625 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
11626 is kept for future versions of M4sugar, once GNU M4 2.0 is
11627 released and supports extended regular expression syntax.
11628 @end defmac
11630 @defmac m4_copy (@var{source}, @var{dest})
11631 @defmacx m4_copy_force (@var{source}, @var{dest})
11632 @defmacx m4_rename (@var{source}, @var{dest})
11633 @defmacx m4_rename_force (@var{source}, @var{dest})
11634 @msindex{copy}
11635 @msindex{copy_force}
11636 @msindex{rename}
11637 @msindex{rename_force}
11638 These macros aren't directly builtins, but are closely related to
11639 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
11640 @code{m4_rename} ensure that @var{dest} is undefined, while
11641 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11642 definition.  All four macros then proceed to copy the entire pushdef
11643 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
11644 and @code{m4_copy_force} preserve the source (including in the special
11645 case where @var{source} is undefined), while @code{m4_rename} and
11646 @code{m4_rename_force} undefine the original macro name (making it an
11647 error to rename an undefined @var{source}).
11649 Note that attempting to invoke a renamed macro might not work, since the
11650 macro may have a dependence on helper macros accessed via composition of
11651 @samp{$0} but that were not also renamed; likewise, other macros may
11652 have a hard-coded dependence on @var{source} and could break if
11653 @var{source} has been deleted.  On the other hand, it is always safe to
11654 rename a macro to temporarily move it out of the way, then rename it
11655 back later to restore original semantics.
11656 @end defmac
11658 @defmac m4_defn (@var{macro}@dots{})
11659 @msindex{defn}
11660 This macro fails if @var{macro} is not defined, even when using older
11661 versions of M4 that did not warn.  See @code{m4_undefine}.
11662 Unfortunately, in order to support these older versions of M4, there are
11663 some situations involving unbalanced quotes where concatenating multiple
11664 macros together will work in newer M4 but not in m4sugar; use
11665 quadrigraphs to work around this.
11666 @end defmac
11668 @defmac m4_divert (@var{diversion})
11669 @msindex{divert}
11670 M4sugar relies heavily on diversions, so rather than behaving as a
11671 primitive, @code{m4_divert} behaves like:
11672 @example
11673 m4_divert_pop()m4_divert_push([@var{diversion}])
11674 @end example
11675 @noindent
11676 @xref{Diversion support}, for more details about the use of the
11677 diversion stack.  In particular, this implies that @var{diversion}
11678 should be a named diversion rather than a raw number.  But be aware that
11679 it is seldom necessary to explicitly change the diversion stack, and
11680 that when done incorrectly, it can lead to syntactically invalid
11681 scripts.
11682 @end defmac
11684 @defmac m4_dumpdef (@var{name}@dots{})
11685 @defmacx m4_dumpdefs (@var{name}@dots{})
11686 @msindex{dumpdef}
11687 @msindex{dumpdefs}
11688 @code{m4_dumpdef} is like the M4 builtin, except that this version
11689 requires at least one argument, output always goes to standard error
11690 rather than the current debug file, no sorting is done on multiple
11691 arguments, and an error is issued if any
11692 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
11693 calls @code{m4_dumpdef} for all of the
11694 @code{m4_pushdef} stack of definitions, starting with the current, and
11695 silently does nothing if @var{name} is undefined.
11697 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11698 builtin is output as the empty string.  This behavior is rectified by
11699 using M4 1.6 or newer.  However, this behavior difference means that
11700 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11701 and never in the final published form of a macro.
11702 @end defmac
11704 @defmac m4_esyscmd_s (@var{command})
11705 @msindex{esyscmd_s}
11706 Like @code{m4_esyscmd}, this macro expands to the result of running
11707 @var{command} in a shell.  The difference is that any trailing newlines
11708 are removed, so that the output behaves more like shell command
11709 substitution.
11710 @end defmac
11712 @defmac m4_exit (@var{exit-status})
11713 @msindex{exit}
11714 This macro corresponds to @code{m4exit}.
11715 @end defmac
11717 @defmac m4_if (@var{comment})
11718 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11719 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11720   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11721 @msindex{if}
11722 This macro corresponds to @code{ifelse}.  @var{string-1} and
11723 @var{string-2} are compared literally, so usually one of the two
11724 arguments is passed unquoted.  @xref{Conditional constructs}, for more
11725 conditional idioms.
11726 @end defmac
11728 @defmac m4_include (@var{file})
11729 @defmacx m4_sinclude (@var{file})
11730 @msindex{include}
11731 @msindex{sinclude}
11732 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11733 @end defmac
11735 @defmac m4_mkstemp (@var{template})
11736 @defmacx m4_maketemp (@var{template})
11737 @msindex{maketemp}
11738 @msindex{mkstemp}
11739 Posix requires @code{maketemp} to replace the trailing @samp{X}
11740 characters in @var{template} with the process id, without regards to the
11741 existence of a file by that name, but this a security hole.  When this
11742 was pointed out to the Posix folks, they agreed to invent a new macro
11743 @code{mkstemp} that always creates a uniquely named file, but not all
11744 versions of GNU M4 support the new macro.  In M4sugar,
11745 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11746 and both have the secure semantics regardless of which macro the
11747 underlying M4 provides.
11748 @end defmac
11750 @defmac m4_popdef (@var{macro}@dots{})
11751 @msindex{popdef}
11752 This macro fails if @var{macro} is not defined, even when using older
11753 versions of M4 that did not warn.  See @code{m4_undefine}.
11754 @end defmac
11756 @defmac m4_undefine (@var{macro}@dots{})
11757 @msindex{undefine}
11758 This macro fails if @var{macro} is not defined, even when using older
11759 versions of M4 that did not warn.  Use
11761 @example
11762 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11763 @end example
11765 @noindent
11766 if you are not sure whether @var{macro} is defined.
11767 @end defmac
11769 @defmac m4_undivert (@var{diversion}@dots{})
11770 @msindex{undivert}
11771 Unlike the M4 builtin, at least one @var{diversion} must be specified.
11772 Also, since the M4sugar diversion stack prefers named
11773 diversions, the use of @code{m4_undivert} to include files is risky.
11774 @xref{Diversion support}, for more details about the use of the
11775 diversion stack.  But be aware that it is seldom necessary to explicitly
11776 change the diversion stack, and that when done incorrectly, it can lead
11777 to syntactically invalid scripts.
11778 @end defmac
11780 @defmac m4_wrap (@var{text})
11781 @defmacx m4_wrap_lifo (@var{text})
11782 @msindex{wrap}
11783 @msindex{wrap_lifo}
11784 These macros correspond to @code{m4wrap}.  Posix requires arguments of
11785 multiple wrap calls to be reprocessed at EOF in the same order
11786 as the original calls (first-in, first-out).  GNU M4 versions
11787 through 1.4.10, however, reprocess them in reverse order (last-in,
11788 first-out).  Both orders are useful, therefore, you can rely on
11789 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11790 LIFO semantics, regardless of the underlying GNU M4 version.
11792 Unlike the GNU M4 builtin, these macros only recognize one
11793 argument, and avoid token pasting between consecutive invocations.  On
11794 the other hand, nested calls to @code{m4_wrap} from within wrapped text
11795 work just as in the builtin.
11796 @end defmac
11799 @node Diagnostic Macros
11800 @subsection Diagnostic messages from M4sugar
11801 @cindex Messages, from @command{M4sugar}
11803 When macros statically diagnose abnormal situations, benign or fatal,
11804 they should report them using these macros.  For issuing dynamic issues,
11805 i.e., when @command{configure} is run, see @ref{Printing Messages}.
11807 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
11808 @msindex{assert}
11809 Assert that the arithmetic @var{expression} evaluates to non-zero.
11810 Otherwise, issue a fatal error, and exit @command{autom4te} with
11811 @var{exit-status}.
11812 @end defmac
11814 @defmac m4_errprintn (@var{message})
11815 @msindex{errprintn}
11816 Similar to the builtin @code{m4_errprint}, except that a newline is
11817 guaranteed after @var{message}.
11818 @end defmac
11820 @anchor{m4_fatal}
11821 @defmac m4_fatal (@var{message})
11822 @msindex{fatal}
11823 Report a severe error @var{message} prefixed with the current location,
11824 and have @command{autom4te} die.
11825 @end defmac
11827 @defmac m4_location
11828 @msindex{location}
11829 Useful as a prefix in a message line.  Short for:
11830 @example
11831 __file__:__line__
11832 @end example
11833 @end defmac
11835 @anchor{m4_warn}
11836 @defmac m4_warn (@var{category}, @var{message})
11837 @msindex{warn}
11838 Report @var{message} as a warning (or as an error if requested by the
11839 user) if warnings of the @var{category} are turned on.  If the message
11840 is emitted, it is prefixed with the current location, and followed by a
11841 call trace of all macros defined via @code{AC_DEFUN} used to get to the
11842 current expansion.  You are encouraged to use standard categories, which
11843 currently include:
11845 @table @samp
11846 @item all
11847 messages that don't fall into one of the following categories.  Use of an
11848 empty @var{category} is equivalent.
11850 @item cross
11851 related to cross compilation issues.
11853 @item obsolete
11854 use of an obsolete construct.
11856 @item syntax
11857 dubious syntactic constructs, incorrectly ordered macro calls.
11858 @end table
11859 @end defmac
11862 @node Diversion support
11863 @subsection Diversion support
11865 M4sugar makes heavy use of diversions under the hood, because it is
11866 often the case that
11867 text that must appear early in the output is not discovered until late
11868 in the input.  Additionally, some of the topological sorting algorithms
11869 used in resolving macro dependencies use diversions.  However, most
11870 macros should not need to change diversions directly, but rather rely on
11871 higher-level M4sugar macros to manage diversions transparently.  If you
11872 change diversions improperly, you risk generating a syntactically
11873 invalid script, because an incorrect diversion will violate assumptions
11874 made by many macros about whether prerequisite text has been previously
11875 output.  In short, if you manually change the diversion, you should not
11876 expect any macros provided by the Autoconf package to work until you
11877 have restored the diversion stack back to its original state.
11879 In the rare case that it is necessary to write a macro that explicitly
11880 outputs text to a different diversion, it is important to be aware of an
11881 M4 limitation regarding diversions: text only goes to a diversion if it
11882 is not part of argument collection.  Therefore, any macro that changes
11883 the current diversion cannot be used as an unquoted argument to another
11884 macro, but must be expanded at the top level.  The macro
11885 @code{m4_expand} will diagnose any attempt to change diversions, since
11886 it is generally useful only as an argument to another macro.  The
11887 following example shows what happens when diversion manipulation is
11888 attempted within macro arguments:
11890 @example
11891 m4_do([normal text]
11892 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
11893 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
11894 @result{}normal text
11895 @result{}unwanted
11896 @end example
11898 @noindent
11899 Notice that the unquoted text @code{unwanted} is output, even though it
11900 was processed while the current diversion was @code{KILL}, because it
11901 was collected as part of the argument to @code{m4_do}.  However, the
11902 text @code{discarded} disappeared as desired, because the diversion
11903 changes were single-quoted, and were not expanded until the top-level
11904 rescan of the output of @code{m4_do}.
11906 To make diversion management easier, M4sugar uses the concept of named
11907 diversions.  Rather than using diversion numbers directly, it is nicer
11908 to associate a name with each diversion.  The diversion number associated
11909 with a particular diversion name is an implementation detail, and a
11910 syntax warning is issued if a diversion number is used instead of a
11911 name.  In general, you should not output text
11912 to a named diversion until after calling the appropriate initialization
11913 routine for your language (@code{m4_init}, @code{AS_INIT},
11914 @code{AT_INIT}, @dots{}), although there are some exceptions documented
11915 below.
11917 M4sugar defines two named diversions.
11918 @table @code
11919 @item KILL
11920 Text written to this diversion is discarded.  This is the default
11921 diversion once M4sugar is initialized.
11922 @item GROW
11923 This diversion is used behind the scenes by topological sorting macros,
11924 such as @code{AC_REQUIRE}.
11925 @end table
11927 M4sh adds several more named diversions.
11928 @table @code
11929 @item BINSH
11930 This diversion is reserved for the @samp{#!} interpreter line.
11931 @item HEADER-REVISION
11932 This diversion holds text from @code{AC_REVISION}.
11933 @item HEADER-COMMENT
11934 This diversion holds comments about the purpose of a file.
11935 @item HEADER-COPYRIGHT
11936 This diversion is managed by @code{AC_COPYRIGHT}.
11937 @item M4SH-SANITIZE
11938 This diversion contains M4sh sanitization code, used to ensure M4sh is
11939 executing in a reasonable shell environment.
11940 @item M4SH-INIT
11941 This diversion contains M4sh initialization code, initializing variables
11942 that are required by other M4sh macros.
11943 @item BODY
11944 This diversion contains the body of the shell code, and is the default
11945 diversion once M4sh is initialized.
11946 @end table
11948 Autotest inherits diversions from M4sh, and changes the default
11949 diversion from @code{BODY} back to @code{KILL}.  It also adds several
11950 more named diversions, with the following subset designed for developer
11951 use.
11952 @table @code
11953 @item PREPARE_TESTS
11954 This diversion contains initialization sequences which are executed
11955 after @file{atconfig} and @file{atlocal}, and after all command line
11956 arguments have been parsed, but prior to running any tests.  It can be
11957 used to set up state that is required across all tests.  This diversion
11958 will work even before @code{AT_INIT}.
11959 @end table
11961 Autoconf inherits diversions from M4sh, and adds the following named
11962 diversions which developers can utilize.
11963 @table @code
11964 @item DEFAULTS
11965 This diversion contains shell variable assignments to set defaults that
11966 must be in place before arguments are parsed.  This diversion is placed
11967 early enough in @file{configure} that it is unsafe to expand any
11968 autoconf macros into this diversion.
11969 @item HELP_ENABLE
11970 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
11971 diversion will be included as part of a quoted here-doc providing all of
11972 the @option{--help} output of @file{configure} related to options
11973 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
11974 @item INIT_PREPARE
11975 This diversion occurs after all command line options have been parsed,
11976 but prior to the main body of the @file{configure} script.  This
11977 diversion is the last chance to insert shell code such as variable
11978 assignments or shell function declarations that will used by the
11979 expansion of other macros.
11980 @end table
11982 For now, the remaining named diversions of Autoconf, Autoheader, and
11983 Autotest are not documented.  In other words,
11984 intentionally outputting text into an undocumented diversion is subject
11985 to breakage in a future release of Autoconf.
11987 @defmac m4_cleardivert (@var{diversion}@dots{})
11988 @msindex{cleardivert}
11989 Permanently discard any text that has been diverted into
11990 @var{diversion}.
11991 @end defmac
11993 @defmac m4_divert_once (@var{diversion}, @ovar{content})
11994 @msindex{divert_once}
11995 Similar to @code{m4_divert_text}, except that @var{content} is only
11996 output to @var{diversion} if this is the first time that
11997 @code{m4_divert_once} has been called with its particular arguments.
11998 @end defmac
12000 @defmac m4_divert_pop (@ovar{diversion})
12001 @msindex{divert_pop}
12002 If provided, check that the current diversion is indeed @var{diversion}.
12003 Then change to the diversion located earlier on the stack, giving an
12004 error if an attempt is made to pop beyond the initial m4sugar diversion
12005 of @code{KILL}.
12006 @end defmac
12008 @defmac m4_divert_push (@var{diversion})
12009 @msindex{divert_push}
12010 Remember the former diversion on the diversion stack, and output
12011 subsequent text into @var{diversion}.  M4sugar maintains a diversion
12012 stack, and issues an error if there is not a matching pop for every
12013 push.
12014 @end defmac
12016 @anchor{m4_divert_text}
12017 @defmac m4_divert_text (@var{diversion}, @ovar{content})
12018 @msindex{divert_text}
12019 Output @var{content} and a newline into @var{diversion}, without
12020 affecting the current diversion.  Shorthand for:
12021 @example
12022 m4_divert_push([@var{diversion}])@var{content}
12023 m4_divert_pop([@var{diversion}])dnl
12024 @end example
12026 One use of @code{m4_divert_text} is to develop two related macros, where
12027 macro @samp{MY_A} does the work, but adjusts what work is performed
12028 based on whether the optional macro @samp{MY_B} has also been expanded.
12029 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
12030 require that @samp{MY_B} occurs first, if it occurs at all.  But this
12031 imposes an ordering restriction on the user; it would be nicer if macros
12032 @samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
12033 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
12034 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
12035 expanded.
12037 @example
12038 AC_DEFUN([MY_A],
12039 [# various actions
12040 if test -n "$b_was_used"; then
12041   # extra action
12042 fi])
12043 AC_DEFUN([MY_B],
12044 [AC_REQUIRE([MY_A])dnl
12045 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12046 @end example
12048 @end defmac
12050 @defmac m4_init
12051 @msindex{init}
12052 Initialize the M4sugar environment, setting up the default named
12053 diversion to be @code{KILL}.
12054 @end defmac
12056 @node Conditional constructs
12057 @subsection Conditional constructs
12059 The following macros provide additional conditional constructs as
12060 convenience wrappers around @code{m4_if}.
12062 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12063   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12064 @msindex{bmatch}
12065 The string @var{string} is repeatedly compared against a series of
12066 @var{regex} arguments; if a match is found, the expansion is the
12067 corresponding @var{value}, otherwise, the macro moves on to the next
12068 @var{regex}.  If no @var{regex} match, then the result is the optional
12069 @var{default}, or nothing.
12070 @end defmac
12072 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12073   @ovar{regex-2}, @ovar{subst-2}, @dots{})
12074 @msindex{bpatsubsts}
12075 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12076 as if by:
12077 @example
12078 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12079 @end example
12081 @noindent
12082 The result of the substitution is then passed through the next set of
12083 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
12084 deletion of any matched portions in the current string.  Note that this
12085 macro over-quotes @var{string}; this behavior is intentional, so that
12086 the result of each step of the recursion remains as a quoted string.
12087 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12088 will line up with the extra quotations, and not the characters of the
12089 original string.  The overquoting is removed after the final
12090 substitution.
12091 @end defmac
12093 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12094   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12095 @msindex{case}
12096 Test @var{string} against multiple @var{value} possibilities, resulting
12097 in the first @var{if-value} for a match, or in the optional
12098 @var{default}.  This is shorthand for:
12099 @example
12100 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12101       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12102       [@var{default}])
12103 @end example
12104 @end defmac
12106 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12107   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12108 @msindex{cond}
12109 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
12110 except that each @var{test} is expanded only when it is encountered.
12111 This is useful for short-circuiting expensive tests; while @code{m4_if}
12112 requires all its strings to be expanded up front before doing
12113 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12114 tests have failed.
12116 For an example, these two sequences give the same result, but in the
12117 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12118 version only expands @code{m4_index} once, instead of five times, for
12119 faster computation if this is a common case for @samp{$1}.  Notice that
12120 every third argument is unquoted for @code{m4_if}, and quoted for
12121 @code{m4_cond}:
12123 @example
12124 m4_if(m4_index([$1], [\]), [-1], [$2],
12125       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12126       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12127       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12128       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12129       [$2])
12130 m4_cond([m4_index([$1], [\])], [-1], [$2],
12131         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12132         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12133         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12134         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12135         [$2])
12136 @end example
12137 @end defmac
12139 @defmac m4_default (@var{expr-1}, @var{expr-2})
12140 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12141 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12142 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12143 @msindex{default}
12144 @msindex{default_quoted}
12145 @msindex{default_nblank}
12146 @msindex{default_nblank_quoted}
12147 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
12148 @code{m4_default} expands the result, while @code{m4_default_quoted}
12149 does not.  Useful for providing a fixed default if the expression that
12150 results in @var{expr-1} would otherwise be empty.  The difference
12151 between @code{m4_default} and @code{m4_default_nblank} is whether an
12152 argument consisting of just blanks (space, tab, newline) is
12153 significant.  When using the expanding versions, note that an argument
12154 may contain text but still expand to an empty string.
12156 @example
12157 m4_define([active], [ACTIVE])dnl
12158 m4_define([empty], [])dnl
12159 m4_define([demo1], [m4_default([$1], [$2])])dnl
12160 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12161 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12162 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12163 demo1([active], [default])
12164 @result{}ACTIVE
12165 demo1([], [active])
12166 @result{}ACTIVE
12167 demo1([empty], [text])
12168 @result{}
12169 -demo1([ ], [active])-
12170 @result{}- -
12171 demo2([active], [default])
12172 @result{}active
12173 demo2([], [active])
12174 @result{}active
12175 demo2([empty], [text])
12176 @result{}empty
12177 -demo2([ ], [active])-
12178 @result{}- -
12179 demo3([active], [default])
12180 @result{}ACTIVE
12181 demo3([], [active])
12182 @result{}ACTIVE
12183 demo3([empty], [text])
12184 @result{}
12185 -demo3([ ], [active])-
12186 @result{}-ACTIVE-
12187 demo4([active], [default])
12188 @result{}active
12189 demo4([], [active])
12190 @result{}active
12191 demo4([empty], [text])
12192 @result{}empty
12193 -demo4([ ], [active])-
12194 @result{}-active-
12195 @end example
12196 @end defmac
12198 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
12199 @msindex{define_default}
12200 If @var{macro} does not already have a definition, then define it to
12201 @var{default-definition}.
12202 @end defmac
12204 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12205 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12206 @msindex{ifblank}
12207 @msindex{ifnblank}
12208 If @var{cond} is empty or consists only of blanks (space, tab, newline),
12209 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
12210 variants exist, in order to make it easier to select the correct logical
12211 sense when using only two parameters.  Note that this is more efficient
12212 than the equivalent behavior of:
12213 @example
12214 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12215 @end example
12216 @end defmac
12218 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12219 @msindex{ifndef}
12220 This is shorthand for:
12221 @example
12222 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12223 @end example
12224 @end defmac
12226 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12227 @msindex{ifset}
12228 If @var{macro} is undefined, or is defined as the empty string, expand
12229 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
12230 @example
12231 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12232 @end example
12233 @noindent
12234 except that it is not an error if @var{macro} is undefined.
12235 @end defmac
12237 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12238 @msindex{ifval}
12239 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12240 @var{if-false}.  This is shorthand for:
12241 @example
12242 m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12243 @end example
12244 @end defmac
12246 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12247 @msindex{ifvaln}
12248 Similar to @code{m4_ifval}, except guarantee that a newline is present
12249 after any non-empty expansion.  Often followed by @code{dnl}.
12250 @end defmac
12252 @defmac m4_n (@var{text})
12253 @msindex{n}
12254 Expand to @var{text}, and add a newline if @var{text} is not empty.
12255 Often followed by @code{dnl}.
12256 @end defmac
12259 @node Looping constructs
12260 @subsection Looping constructs
12262 The following macros are useful in implementing recursive algorithms in
12263 M4, including loop operations.  An M4 list is formed by quoting a list
12264 of quoted elements; generally the lists are comma-separated, although
12265 @code{m4_foreach_w} is whitespace-separated.  For example, the list
12266 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12267 It is common to see lists with unquoted elements when those elements are
12268 not likely to be macro names, as in @samp{[fputc_unlocked,
12269 fgetc_unlocked]}.
12271 Although not generally recommended, it is possible for quoted lists to
12272 have side effects; all side effects are expanded only once, and prior to
12273 visiting any list element.  On the other hand, the fact that unquoted
12274 macros are expanded exactly once means that macros without side effects
12275 can be used to generate lists.  For example,
12277 @example
12278 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12279 @error{}hi
12280 @result{}123
12281 m4_define([list], [[1], [2], [3]])
12282 @result{}
12283 m4_foreach([i], [list], [i])
12284 @result{}123
12285 @end example
12287 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12288 @msindex{argn}
12289 Extracts argument @var{n} (larger than 0) from the remaining arguments.
12290 If there are too few arguments, the empty string is used.  For any
12291 @var{n} besides 1, this is more efficient than the similar
12292 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12293 @end defmac
12295 @defmac m4_car (@var{arg}@dots{})
12296 @msindex{car}
12297 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
12298 to recursively iterate
12299 through a list.  Generally, when using quoted lists of quoted elements,
12300 @code{m4_car} should be called without any extra quotes.
12301 @end defmac
12303 @defmac m4_cdr (@var{arg}@dots{})
12304 @msindex{cdr}
12305 Expands to a quoted list of all but the first @var{arg}, or the empty
12306 string if there was only one argument.  Generally, when using quoted
12307 lists of quoted elements, @code{m4_cdr} should be called without any
12308 extra quotes.
12310 For example, this is a simple implementation of @code{m4_map}; note how
12311 each iteration checks for the end of recursion, then merely applies the
12312 first argument to the first element of the list, then repeats with the
12313 rest of the list.  (The actual implementation in M4sugar is a bit more
12314 involved, to gain some speed and share code with @code{m4_map_sep}, and
12315 also to avoid expanding side effects in @samp{$2} twice).
12316 @example
12317 m4_define([m4_map], [m4_ifval([$2],
12318   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12319 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12320 @result{} 1 2 a
12321 @end example
12322 @end defmac
12324 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12325   @var{expression})
12326 @msindex{for}
12327 Loop over the numeric values between @var{first} and @var{last}
12328 including bounds by increments of @var{step}.  For each iteration,
12329 expand @var{expression} with the numeric value assigned to @var{var}.
12330 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12331 on the order of the limits.  If given, @var{step} has to match this
12332 order.  The number of iterations is determined independently from
12333 definition of @var{var}; iteration cannot be short-circuited or
12334 lengthened by modifying @var{var} from within @var{expression}.
12335 @end defmac
12337 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12338 @msindex{foreach}
12339 Loop over the comma-separated M4 list @var{list}, assigning each value
12340 to @var{var}, and expand @var{expression}.  The following example
12341 outputs two lines:
12343 @example
12344 m4_foreach([myvar], [[foo], [bar, baz]],
12345            [echo myvar
12346 ])dnl
12347 @result{}echo foo
12348 @result{}echo bar, baz
12349 @end example
12351 Note that for some forms of @var{expression}, it may be faster to use
12352 @code{m4_map_args}.
12353 @end defmac
12355 @anchor{m4_foreach_w}
12356 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12357 @msindex{foreach_w}
12358 Loop over the white-space-separated list @var{list}, assigning each value
12359 to @var{var}, and expand @var{expression}.  If @var{var} is only
12360 referenced once in @var{expression}, it is more efficient to use
12361 @code{m4_map_args_w}.
12363 The deprecated macro @code{AC_FOREACH} is an alias of
12364 @code{m4_foreach_w}.
12365 @end defmac
12367 @defmac m4_map (@var{macro}, @var{list})
12368 @defmacx m4_mapall (@var{macro}, @var{list})
12369 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12370 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12371 @msindex{map}
12372 @msindex{mapall}
12373 @msindex{map_sep}
12374 @msindex{mapall_sep}
12375 Loop over the comma separated quoted list of argument descriptions in
12376 @var{list}, and invoke @var{macro} with the arguments.  An argument
12377 description is in turn a comma-separated quoted list of quoted elements,
12378 suitable for @code{m4_apply}.  The macros @code{m4_map} and
12379 @code{m4_map_sep} ignore empty argument descriptions, while
12380 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12381 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12382 additionally expand @var{separator} between invocations of @var{macro}.
12384 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
12385 separating output with commas, this means that the map result can be
12386 used as a series of arguments, by using a single-quoted comma as
12387 @var{separator}, or as a single string, by using a double-quoted comma.
12389 @example
12390 m4_map([m4_count], [])
12391 @result{}
12392 m4_map([ m4_count], [[],
12393                      [[1]],
12394                      [[1], [2]]])
12395 @result{} 1 2
12396 m4_mapall([ m4_count], [[],
12397                         [[1]],
12398                         [[1], [2]]])
12399 @result{} 0 1 2
12400 m4_map_sep([m4_eval], [,], [[[1+2]],
12401                             [[10], [16]]])
12402 @result{}3,a
12403 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12404 @result{}a,b
12405 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12406 @result{}2
12407 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12408 @result{}a,b
12409 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12410 @result{}1
12411 @end example
12412 @end defmac
12414 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12415 @msindex{map_args}
12416 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12417 argument.  In the following example, three solutions are presented with
12418 the same expansion; the solution using @code{m4_map_args} is the most
12419 efficient.
12420 @example
12421 m4_define([active], [ACTIVE])dnl
12422 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12423 @result{} plain active
12424 m4_map([ m4_echo], [[[plain]], [[active]]])
12425 @result{} plain active
12426 m4_map_args([ m4_echo], [plain], [active])
12427 @result{} plain active
12428 @end example
12430 In cases where it is useful to operate on additional parameters besides
12431 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12432 to supply the argument currying necessary to generate the desired
12433 argument list.  In the following example, @code{list_add_n} is more
12434 efficient than @code{list_add_x}.  On the other hand, using
12435 @code{m4_map_args_sep} can be even more efficient.
12437 @example
12438 m4_define([list], [[1], [2], [3]])dnl
12439 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12440 dnl list_add_n(N, ARG...)
12441 dnl Output a list consisting of each ARG added to N
12442 m4_define([list_add_n],
12443 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12444 list_add_n([1], list)
12445 @result{}2,3,4
12446 list_add_n([2], list)
12447 @result{}3,4,5
12448 m4_define([list_add_x],
12449 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12450   [,add([$1],m4_defn([var]))]))])dnl
12451 list_add_x([1], list)
12452 @result{}2,3,4
12453 @end example
12454 @end defmac
12456 @defmac m4_map_args_pair (@var{macro}, @dvarv{macro-end, macro}, @
12457   @var{arg}@dots{})
12458 @msindex{map_args_pair}
12459 For every pair of arguments @var{arg}, invoke @var{macro} with two
12460 arguments.  If there is an odd number of arguments, invoke
12461 @var{macro-end}, which defaults to @var{macro}, with the remaining
12462 argument.
12464 @example
12465 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12466 @result{}, 2, 1, 3
12467 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12468 @result{}, 2, 1, [3]
12469 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12470 @result{}, 2, 1, 4, 3
12471 @end example
12472 @end defmac
12474 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12475 @msindex{map_args_sep}
12476 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12477 argument, additionally expanding @var{sep} between arguments.  One
12478 common use of this macro is constructing a macro call, where the opening
12479 and closing parentheses are split between @var{pre} and @var{post}; in
12480 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12481 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
12482 macro provides the most efficient means for iterating over an arbitrary
12483 list of arguments, particularly when repeatedly constructing a macro
12484 call with more arguments than @var{arg}.
12485 @end defmac
12487 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12488 @msindex{map_args_w}
12489 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12490 the whitespace-separated @var{string}, additionally expanding @var{sep}
12491 between words.  This macro provides the most efficient means for
12492 iterating over a whitespace-separated string.  In particular,
12493 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12494 efficient than @code{m4_foreach_w([var], [@var{string}],
12495 [@var{action}(m4_defn([var]))])}.
12496 @end defmac
12498 @defmac m4_shiftn (@var{count}, @dots{})
12499 @defmacx m4_shift2 (@dots{})
12500 @defmacx m4_shift3 (@dots{})
12501 @msindex{shift2}
12502 @msindex{shift3}
12503 @msindex{shiftn}
12504 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12505 along with validation that enough arguments were passed in to match the
12506 shift count, and that the count is positive.  @code{m4_shift2} and
12507 @code{m4_shift3} are specializations
12508 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12509 for two and three shifts, respectively.
12510 @end defmac
12512 @defmac m4_stack_foreach (@var{macro}, @var{action})
12513 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12514 @msindex{stack_foreach}
12515 @msindex{stack_foreach_lifo}
12516 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12517 @var{action} with the single argument of a definition of @var{macro}.
12518 @code{m4_stack_foreach} starts with the oldest definition, while
12519 @code{m4_stack_foreach_lifo} starts with the current definition.
12520 @var{action} should not push or pop definitions of @var{macro}, nor is
12521 there any guarantee that the current definition of @var{macro} matches
12522 the argument that was passed to @var{action}.  The macro @code{m4_curry}
12523 can be used if @var{action} needs more than one argument, although in
12524 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12526 Due to technical limitations, there are a few low-level m4sugar
12527 functions, such as @code{m4_pushdef}, that cannot be used as the
12528 @var{macro} argument.
12530 @example
12531 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12532 m4_stack_foreach([a], [ m4_incr])
12533 @result{} 2 3
12534 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12535 @result{} cd bcd
12536 @end example
12537 @end defmac
12539 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12540 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12541   @ovar{sep})
12542 @msindex{stack_foreach_sep}
12543 @msindex{stack_foreach_sep_lifo}
12544 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12545 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12546 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
12547 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12548 the current definition first.  This macro provides the most efficient
12549 means for iterating over a pushdef stack.  In particular,
12550 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12551 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12552 @end defmac
12554 @node Evaluation Macros
12555 @subsection Evaluation Macros
12557 The following macros give some control over the order of the evaluation
12558 by adding or removing levels of quotes.
12560 @defmac m4_apply (@var{macro}, @var{list})
12561 @msindex{apply}
12562 Apply the elements of the quoted, comma-separated @var{list} as the
12563 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12564 without arguments.  Note the difference between @code{m4_indir}, which
12565 expects its first argument to be a macro name but can use names that are
12566 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12567 other text, but must end in a valid macro name.
12568 @example
12569 m4_apply([m4_count], [])
12570 @result{}0
12571 m4_apply([m4_count], [[]])
12572 @result{}1
12573 m4_apply([m4_count], [[1], [2]])
12574 @result{}2
12575 m4_apply([m4_join], [[|], [1], [2]])
12576 @result{}1|2
12577 @end example
12578 @end defmac
12580 @defmac m4_count (@var{arg}, @dots{})
12581 @msindex{count}
12582 This macro returns the decimal count of the number of arguments it was
12583 passed.
12584 @end defmac
12586 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12587 @msindex{curry}
12588 This macro performs argument currying.  The expansion of this macro is
12589 another macro name that expects exactly one argument; that argument is
12590 then appended to the @var{arg} list, and then @var{macro} is expanded
12591 with the resulting argument list.
12593 @example
12594 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12595 @result{}3, 2, 1
12596 @end example
12598 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12599 pass the definition of a builtin macro as the argument to the output of
12600 @code{m4_curry}; the empty string is used instead of the builtin token.
12601 This behavior is rectified by using M4 1.6 or newer.
12602 @end defmac
12604 @defmac m4_do (@var{arg}, @dots{})
12605 @msindex{do}
12606 This macro loops over its arguments and expands each @var{arg} in
12607 sequence.  Its main use is for readability; it allows the use of
12608 indentation and fewer @code{dnl} to result in the same expansion.  This
12609 macro guarantees that no expansion will be concatenated with subsequent
12610 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12611 @var{arg@dots{}}))}.
12613 @example
12614 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12615 m4_do([a],[b])c
12616 @result{}abc
12617 m4_unquote(m4_join([],[a],[b]))c
12618 @result{}3
12619 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12620 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12621 m4_do([a],[b])c
12622 @result{}ABC
12623 m4_unquote(m4_join([],[a],[b]))c
12624 @result{}3
12625 @end example
12626 @end defmac
12628 @defmac m4_dquote (@var{arg}, @dots{})
12629 @msindex{dquote}
12630 Return the arguments as a quoted list of quoted arguments.
12631 Conveniently, if there is just one @var{arg}, this effectively adds a
12632 level of quoting.
12633 @end defmac
12635 @defmac m4_dquote_elt (@var{arg}, @dots{})
12636 @msindex{dquote_elt}
12637 Return the arguments as a series of double-quoted arguments.  Whereas
12638 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12639 as many arguments as it was passed.
12640 @end defmac
12642 @defmac m4_echo (@var{arg}, @dots{})
12643 @msindex{echo}
12644 Return the arguments, with the same level of quoting.  Other than
12645 discarding whitespace after unquoted commas, this macro is a no-op.
12646 @end defmac
12648 @defmac m4_expand (@var{arg})
12649 @msindex{expand}
12650 Return the expansion of @var{arg} as a quoted string.  Whereas
12651 @code{m4_quote} is designed to collect expanded text into a single
12652 argument, @code{m4_expand} is designed to perform one level of expansion
12653 on quoted text.  One distinction is in the treatment of whitespace
12654 following a comma in the original @var{arg}.  Any time multiple
12655 arguments are collected into one with @code{m4_quote}, the M4 argument
12656 collection rules discard the whitespace.  However, with @code{m4_expand},
12657 whitespace is preserved, even after the expansion of macros contained in
12658 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
12659 would involve an unterminated comment, whereas expanding that same text
12660 as the argument to @code{m4_quote} runs into difficulty in finding the
12661 end of the argument.  Since manipulating diversions during argument
12662 collection is inherently unsafe, @code{m4_expand} issues an error if
12663 @var{arg} attempts to change the current diversion (@pxref{Diversion
12664 support}).
12666 @example
12667 m4_define([active], [ACT, IVE])dnl
12668 m4_define([active2], [[ACT, IVE]])dnl
12669 m4_quote(active, active)
12670 @result{}ACT,IVE,ACT,IVE
12671 m4_expand([active, active])
12672 @result{}ACT, IVE, ACT, IVE
12673 m4_quote(active2, active2)
12674 @result{}ACT, IVE,ACT, IVE
12675 m4_expand([active2, active2])
12676 @result{}ACT, IVE, ACT, IVE
12677 m4_expand([# m4_echo])
12678 @result{}# m4_echo
12679 m4_quote(# m4_echo)
12681 @result{}# m4_echo)
12682 @result{}
12683 @end example
12685 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12686 literal unbalanced quotes, but that quadrigraphs can be used when
12687 unbalanced output is necessary.  Likewise, unbalanced parentheses should
12688 be supplied with double quoting or a quadrigraph.
12690 @example
12691 m4_define([pattern], [[!@@<:@@]])dnl
12692 m4_define([bar], [BAR])dnl
12693 m4_expand([case $foo in
12694   m4_defn([pattern])@@:@}@@ bar ;;
12695   *[)] blah ;;
12696 esac])
12697 @result{}case $foo in
12698 @result{}  [![]) BAR ;;
12699 @result{}  *) blah ;;
12700 @result{}esac
12701 @end example
12702 @end defmac
12704 @defmac m4_ignore (@dots{})
12705 @msindex{ignore}
12706 This macro was introduced in Autoconf 2.62.  Expands to nothing,
12707 ignoring all of its arguments.  By itself, this isn't very useful.
12708 However, it can be used to conditionally ignore an arbitrary number of
12709 arguments, by deciding which macro name to apply to a list of arguments.
12710 @example
12711 dnl foo outputs a message only if [debug] is defined.
12712 m4_define([foo],
12713 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12714 @end example
12716 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12717 serve the same purpose, although it is less readable.
12718 @end defmac
12720 @defmac m4_make_list (@var{arg}, @dots{})
12721 @msindex{make_list}
12722 This macro exists to aid debugging of M4sugar algorithms.  Its net
12723 effect is similar to @code{m4_dquote}---it produces a quoted list of
12724 quoted arguments, for each @var{arg}.  The difference is that this
12725 version uses a comma-newline separator instead of just comma, to improve
12726 readability of the list; with the result that it is less efficient than
12727 @code{m4_dquote}.
12728 @example
12729 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12730 m4_dquote(zero, [one], [[two]])
12731 @result{}[0],[one],[[two]]
12732 m4_make_list(zero, [one], [[two]])
12733 @result{}[0],
12734 @result{}[one],
12735 @result{}[[two]]
12736 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12737 @result{} 0 1 two
12738 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12739 @result{} 0 1 two
12740 @end example
12741 @end defmac
12743 @c m4_noquote is too dangerous to document - it invokes macros that
12744 @c probably rely on @samp{[]} nested quoting for proper operation.  The
12745 @c user should generally prefer m4_unquote instead.
12747 @defmac m4_quote (@var{arg}, @dots{})
12748 @msindex{quote}
12749 Return the arguments as a single entity, i.e., wrap them into a pair of
12750 quotes.  This effectively collapses multiple arguments into one,
12751 although it loses whitespace after unquoted commas in the process.
12752 @end defmac
12754 @defmac m4_reverse (@var{arg}, @dots{})
12755 @msindex{reverse}
12756 Outputs each argument with the same level of quoting, but in reverse
12757 order, and with space following each comma for readability.
12759 @example
12760 m4_define([active], [ACT,IVE])
12761 @result{}
12762 m4_reverse(active, [active])
12763 @result{}active, IVE, ACT
12764 @end example
12765 @end defmac
12767 @defmac m4_unquote (@var{arg}, @dots{})
12768 @msindex{unquote}
12769 This macro was introduced in Autoconf 2.62.  Expand each argument,
12770 separated by commas.  For a single @var{arg}, this effectively removes a
12771 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12772 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
12773 this results in an unquoted list of expansions.  This is commonly used
12774 with @code{m4_split}, in order to convert a single quoted list into a
12775 series of quoted elements.
12776 @end defmac
12778 The following example aims at emphasizing the difference between several
12779 scenarios: not using these macros, using @code{m4_defn}, using
12780 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
12782 @example
12783 $ @kbd{cat example.m4}
12784 dnl Overquote, so that quotes are visible.
12785 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
12786 m4_define([a], [A])
12787 m4_define([mkargs], [1, 2[,] 3])
12788 m4_define([arg1], [[$1]])
12789 m4_divert([0])dnl
12790 show(a, b)
12791 show([a, b])
12792 show(m4_quote(a, b))
12793 show(m4_dquote(a, b))
12794 show(m4_expand([a, b]))
12796 arg1(mkargs)
12797 arg1([mkargs])
12798 arg1(m4_defn([mkargs]))
12799 arg1(m4_quote(mkargs))
12800 arg1(m4_dquote(mkargs))
12801 arg1(m4_expand([mkargs]))
12802 $ @kbd{autom4te -l m4sugar example.m4}
12803 $1 = A, $@@ = [A],[b]
12804 $1 = a, b, $@@ = [a, b]
12805 $1 = A,b, $@@ = [A,b]
12806 $1 = [A],[b], $@@ = [[A],[b]]
12807 $1 = A, b, $@@ = [A, b]
12810 mkargs
12811 1, 2[,] 3
12812 1,2, 3
12813 [1],[2, 3]
12814 1, 2, 3
12815 @end example
12818 @node Text processing Macros
12819 @subsection String manipulation in M4
12821 The following macros may be used to manipulate strings in M4.  Many of
12822 the macros in this section intentionally result in quoted strings as
12823 output, rather than subjecting the arguments to further expansions.  As
12824 a result, if you are manipulating text that contains active M4
12825 characters, the arguments are passed with single quoting rather than
12826 double.
12828 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
12829 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
12830   @ovar{if-uniq}, @ovar{if-duplicate})
12831 @msindex{append}
12832 @msindex{append_uniq}
12833 Redefine @var{macro-name} to its former contents with @var{separator}
12834 and @var{string} added at the end.  If @var{macro-name} was undefined
12835 before (but not if it was defined but empty), then no @var{separator} is
12836 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
12837 are expanded during this macro; instead, they are expanded when
12838 @var{macro-name} is invoked.
12840 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
12841 to grow strings without duplicating substrings.  Additionally,
12842 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
12843 @var{if-uniq} is expanded if @var{string} was appended, and
12844 @var{if-duplicate} is expanded if @var{string} was already present.
12845 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
12846 occurs within @var{string}, since that can lead to duplicates.
12848 Note that @code{m4_append} can scale linearly in the length of the final
12849 string, depending on the quality of the underlying M4 implementation,
12850 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
12851 If an algorithm can tolerate duplicates in the final string, use the
12852 former for speed.  If duplicates must be avoided, consider using
12853 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
12855 @example
12856 m4_define([active], [ACTIVE])dnl
12857 m4_append([sentence], [This is an])dnl
12858 m4_append([sentence], [ active ])dnl
12859 m4_append([sentence], [symbol.])dnl
12860 sentence
12861 @result{}This is an ACTIVE symbol.
12862 m4_undefine([active])dnl
12863 @result{}This is an active symbol.
12864 m4_append_uniq([list], [one], [, ], [new], [existing])
12865 @result{}new
12866 m4_append_uniq([list], [one], [, ], [new], [existing])
12867 @result{}existing
12868 m4_append_uniq([list], [two], [, ], [new], [existing])
12869 @result{}new
12870 m4_append_uniq([list], [three], [, ], [new], [existing])
12871 @result{}new
12872 m4_append_uniq([list], [two], [, ], [new], [existing])
12873 @result{}existing
12874 list
12875 @result{}one, two, three
12876 m4_dquote(list)
12877 @result{}[one],[two],[three]
12878 m4_append([list2], [one], [[, ]])dnl
12879 m4_append_uniq([list2], [two], [[, ]])dnl
12880 m4_append([list2], [three], [[, ]])dnl
12881 list2
12882 @result{}one, two, three
12883 m4_dquote(list2)
12884 @result{}[one, two, three]
12885 @end example
12886 @end defmac
12888 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
12889 @msindex{append_uniq_w}
12890 This macro was introduced in Autoconf 2.62.  It is similar to
12891 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
12892 separated list of words to append, and only appends unique words.
12893 @var{macro-name} is updated with a single space between new words.
12894 @example
12895 m4_append_uniq_w([numbers], [1 1 2])dnl
12896 m4_append_uniq_w([numbers], [ 2 3 ])dnl
12897 numbers
12898 @result{}1 2 3
12899 @end example
12900 @end defmac
12902 @defmac m4_chomp (@var{string})
12903 @defmacx m4_chomp_all (@var{string})
12904 @msindex{chomp}
12905 @msindex{chomp_all}
12906 Output @var{string} in quotes, but without a trailing newline.  The
12907 macro @code{m4_chomp} is slightly faster, and removes at most one
12908 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
12909 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
12910 and backslash does not influence the result.
12911 @end defmac
12913 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
12914   @var{suffix-1}, @ovar{suffix-2}, @dots{})
12915 @msindex{combine}
12916 This macro produces a quoted string containing the pairwise combination
12917 of every element of the quoted, comma-separated @var{prefix-list}, and
12918 every element from the @var{suffix} arguments.  Each pairwise
12919 combination is joined with @var{infix} in the middle, and successive
12920 pairs are joined by @var{separator}.  No expansion occurs on any of the
12921 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
12922 list is empty, but the lists can contain empty elements.
12923 @example
12924 m4_define([a], [oops])dnl
12925 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
12926 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
12927 m4_combine([, ], [[a], [b]], [-])
12928 @result{}
12929 m4_combine([, ], [[a], [b]], [-], [])
12930 @result{}a-, b-
12931 m4_combine([, ], [], [-], [1], [2])
12932 @result{}
12933 m4_combine([, ], [[]], [-], [1], [2])
12934 @result{}-1, -2
12935 @end example
12936 @end defmac
12938 @defmac m4_escape (@var{string})
12939 @msindex{escape}
12940 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
12941 within @var{string} into their respective quadrigraphs.  The result is
12942 still a quoted string.
12943 @end defmac
12945 @defmac m4_flatten (@var{string})
12946 @msindex{flatten}
12947 Flatten @var{string} into a single line.  Delete all backslash-newline
12948 pairs, and replace all remaining newlines with a space.  The result is
12949 still a quoted string.
12950 @end defmac
12952 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
12953 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
12954 @msindex{join}
12955 @msindex{joinall}
12956 Concatenate each @var{arg}, separated by @var{separator}.
12957 @code{joinall} uses every argument, while @code{join} omits empty
12958 arguments so that there are no back-to-back separators in the output.
12959 The result is a quoted string.
12960 @example
12961 m4_define([active], [ACTIVE])dnl
12962 m4_join([|], [one], [], [active], [two])
12963 @result{}one|active|two
12964 m4_joinall([|], [one], [], [active], [two])
12965 @result{}one||active|two
12966 @end example
12968 Note that if all you intend to do is join @var{args} with commas between
12969 them, to form a quoted list suitable for @code{m4_foreach}, it is more
12970 efficient to use @code{m4_dquote}.
12971 @end defmac
12973 @defmac m4_newline (@ovar{text})
12974 @msindex{newline}
12975 This macro was introduced in Autoconf 2.62, and expands to a newline,
12976 followed by any @var{text}.
12977 It is primarily useful for maintaining macro formatting, and ensuring
12978 that M4 does not discard leading whitespace during argument collection.
12979 @end defmac
12981 @defmac m4_normalize (@var{string})
12982 @msindex{normalize}
12983 Remove leading and trailing spaces and tabs, sequences of
12984 backslash-then-newline, and replace multiple spaces, tabs, and newlines
12985 with a single space.  This is a combination of @code{m4_flatten} and
12986 @code{m4_strip}.  To determine if @var{string} consists only of bytes
12987 that would be removed by @code{m4_normalize}, you can use
12988 @code{m4_ifblank}.
12989 @end defmac
12991 @defmac m4_re_escape (@var{string})
12992 @msindex{re_escape}
12993 Backslash-escape all characters in @var{string} that are active in
12994 regexps.
12995 @end defmac
12997 @c We cannot use @dvar because the macro expansion mistreats backslashes.
12998 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
12999 @msindex{split}
13000 Split @var{string} into an M4 list of elements quoted by @samp{[} and
13001 @samp{]}, while keeping white space at the beginning and at the end.
13002 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
13003 If @var{string} is empty, the result is an empty list.
13004 @end defmac
13006 @defmac m4_strip (@var{string})
13007 @msindex{strip}
13008 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
13009 reduced to a single space, then leading and trailing spaces are removed.
13010 The result is still a quoted string.  Note that this does not interfere
13011 with newlines; if you want newlines stripped as well, consider
13012 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
13013 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
13014 @end defmac
13016 @defmac m4_text_box (@var{message}, @dvar{frame, -})
13017 @msindex{text_box}
13018 Add a text box around @var{message}, using @var{frame} as the border
13019 character above and below the message.  The @var{frame} argument must be
13020 a single byte, and does not support quadrigraphs.
13021 The frame correctly accounts for
13022 the subsequent expansion of @var{message}.  For example:
13023 @example
13024 m4_define([macro], [abc])dnl
13025 m4_text_box([macro])
13026 @result{}## --- ##
13027 @result{}## abc ##
13028 @result{}## --- ##
13029 @end example
13031 The @var{message} must contain balanced quotes and parentheses, although
13032 quadrigraphs can be used to work around this.
13033 @end defmac
13035 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
13036   @dvarv{prefix1, prefix}, @dvar{width, 79})
13037 @msindex{text_wrap}
13038 Break @var{string} into a series of whitespace-separated words, then
13039 output those words separated by spaces, and wrapping lines any time the
13040 output would exceed @var{width} columns.  If given, @var{prefix1} begins
13041 the first line, and @var{prefix} begins all wrapped lines.  If
13042 @var{prefix1} is longer than @var{prefix}, then the first line consists
13043 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
13044 padding is inserted so that the first word of @var{string} begins at the
13045 same indentation as all wrapped lines.  Note that using literal tab
13046 characters in any of the arguments will interfere with the calculation
13047 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
13048 words of @var{string}, although quadrigraphs are recognized.
13050 For some examples:
13051 @example
13052 m4_text_wrap([Short string */], [   ], [/* ], [20])
13053 @result{}/* Short string */
13054 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
13055 @result{}/* Much longer
13056 @result{}   string */
13057 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
13058 @result{}  --short Short doc.
13059 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
13060 @result{}  --too-wide
13061 @result{}          Short doc.
13062 m4_text_wrap([Super long documentation.], [     ],
13063              [  --too-wide ], 30)
13064 @result{}  --too-wide
13065 @result{}     Super long
13066 @result{}     documentation.
13067 @end example
13068 @end defmac
13070 @defmac m4_tolower (@var{string})
13071 @defmacx m4_toupper (@var{string})
13072 @msindex{tolower}
13073 @msindex{toupper}
13074 Return @var{string} with letters converted to upper or lower case,
13075 respectively.
13076 @end defmac
13078 @node Number processing Macros
13079 @subsection Arithmetic computation in M4
13081 The following macros facilitate integer arithmetic operations.
13082 Where a parameter is documented as taking an arithmetic expression, you
13083 can use anything that can be parsed by @code{m4_eval}.
13085 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
13086 @msindex{cmp}
13087 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13088 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13089 equal, and @samp{1} if @var{expr-1} is larger.
13090 @end defmac
13092 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
13093 @msindex{list_cmp}
13094 Compare the two M4 lists consisting of comma-separated arithmetic
13095 expressions, left to right.  Expand to @samp{-1} for the first element
13096 pairing where the value from @var{list-1} is smaller, @samp{1} where the
13097 value from @var{list-2} is smaller, or @samp{0} if both lists have the
13098 same values.  If one list is shorter than the other, the remaining
13099 elements of the longer list are compared against zero.
13100 @example
13101 m4_list_cmp([1, 0],       [1])
13102 @result{}0
13103 m4_list_cmp([1, [1 * 0]], [1, 0])
13104 @result{}0
13105 m4_list_cmp([1, 2],       [1, 0])
13106 @result{}1
13107 m4_list_cmp([1, [1+1], 3],[1, 2])
13108 @result{}1
13109 m4_list_cmp([1, 2, -3],   [1, 2])
13110 @result{}-1
13111 m4_list_cmp([1, 0],       [1, 2])
13112 @result{}-1
13113 m4_list_cmp([1],          [1, 2])
13114 @result{}-1
13115 @end example
13116 @end defmac
13118 @defmac m4_max (@var{arg}, @dots{})
13119 @msindex{max}
13120 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13121 of the maximum arithmetic expression among all the arguments.
13122 @end defmac
13124 @defmac m4_min (@var{arg}, @dots{})
13125 @msindex{min}
13126 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13127 of the minimum arithmetic expression among all the arguments.
13128 @end defmac
13130 @defmac m4_sign (@var{expr})
13131 @msindex{sign}
13132 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13133 @samp{1} if it is positive, and @samp{0} if it is zero.
13134 @end defmac
13136 @anchor{m4_version_compare}
13137 @defmac m4_version_compare (@var{version-1}, @var{version-2})
13138 @msindex{version_compare}
13139 This macro was introduced in Autoconf 2.53, but had a number of
13140 usability limitations that were not lifted until Autoconf 2.62.  Compare
13141 the version strings @var{version-1} and @var{version-2}, and expand to
13142 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13143 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
13144 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13145 element is a number along with optional case-insensitive letters
13146 designating beta releases.  The comparison stops at the leftmost element
13147 that contains a difference, although a 0 element compares equal to a
13148 missing element.
13150 It is permissible to include commit identifiers in @var{version}, such
13151 as an abbreviated SHA1 of the commit, provided there is still a
13152 monotonically increasing prefix to allow for accurate version-based
13153 comparisons.  For example, this paragraph was written when the
13154 development snapshot of autoconf claimed to be at version
13155 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13156 abbreviated commit identification of @samp{dc51}.
13158 @example
13159 m4_version_compare([1.1], [2.0])
13160 @result{}-1
13161 m4_version_compare([2.0b], [2.0a])
13162 @result{}1
13163 m4_version_compare([1.1.1], [1.1.1a])
13164 @result{}-1
13165 m4_version_compare([1.2], [1.1.1a])
13166 @result{}1
13167 m4_version_compare([1.0], [1])
13168 @result{}0
13169 m4_version_compare([1.1pre], [1.1PRE])
13170 @result{}0
13171 m4_version_compare([1.1a], [1,10])
13172 @result{}-1
13173 m4_version_compare([2.61a], [2.61a-248-dc51])
13174 @result{}-1
13175 m4_version_compare([2.61b], [2.61a-248-dc51])
13176 @result{}1
13177 @end example
13178 @end defmac
13180 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13181   @dvar{if-old, m4_fatal})
13182 @msindex{version_prereq}
13183 Compares @var{version} against the version of Autoconf currently
13184 running.  If the running version is at @var{version} or newer, expand
13185 @var{if-new-enough}, but if @var{version} is larger than the version
13186 currently executing, expand @var{if-old}, which defaults to printing an
13187 error message and exiting m4sugar with status 63.  When given only one
13188 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13189 Remember that the autoconf philosophy favors feature checks over version
13190 checks.
13191 @end defmac
13193 @node Set manipulation Macros
13194 @subsection Set manipulation in M4
13195 @cindex Set manipulation
13196 @cindex Data structure, set
13197 @cindex Unordered set manipulation
13199 Sometimes, it is necessary to track a set of data, where the order does
13200 not matter and where there are no duplicates in the set.  The following
13201 macros facilitate set manipulations.  Each set is an opaque object,
13202 which can only be accessed via these basic operations.  The underlying
13203 implementation guarantees linear scaling for set creation, which is more
13204 efficient than using the quadratic @code{m4_append_uniq}.  Both set
13205 names and values can be arbitrary strings, except for unbalanced quotes.
13206 This implementation ties up memory for removed elements until the next
13207 operation that must traverse all the elements of a set; and although
13208 that may slow down some operations until the memory for removed elements
13209 is pruned, it still guarantees linear performance.
13211 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13212 @msindex{set_add}
13213 Adds the string @var{value} as a member of set @var{set}.  Expand
13214 @var{if-uniq} if the element was added, or @var{if-dup} if it was
13215 previously in the set.  Operates in amortized constant time, so that set
13216 creation scales linearly.
13217 @end defmac
13219 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13220 @msindex{set_add_all}
13221 Adds each @var{value} to the set @var{set}.  This is slightly more
13222 efficient than repeatedly invoking @code{m4_set_add}.
13223 @end defmac
13225 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13226  @ovar{if-absent})
13227 @msindex{set_contains}
13228 Expands @var{if-present} if the string @var{value} is a member of
13229 @var{set}, otherwise @var{if-absent}.
13231 @example
13232 m4_set_contains([a], [1], [yes], [no])
13233 @result{}no
13234 m4_set_add([a], [1], [added], [dup])
13235 @result{}added
13236 m4_set_add([a], [1], [added], [dup])
13237 @result{}dup
13238 m4_set_contains([a], [1], [yes], [no])
13239 @result{}yes
13240 m4_set_remove([a], [1], [removed], [missing])
13241 @result{}removed
13242 m4_set_contains([a], [1], [yes], [no])
13243 @result{}no
13244 m4_set_remove([a], [1], [removed], [missing])
13245 @result{}missing
13246 @end example
13247 @end defmac
13249 @defmac m4_set_contents (@var{set}, @ovar{sep})
13250 @defmacx m4_set_dump (@var{set}, @ovar{sep})
13251 @msindex{set_contents}
13252 @msindex{set_dump}
13253 Expands to a single string consisting of all the members of the set
13254 @var{set}, each separated by @var{sep}, which is not expanded.
13255 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13256 memory occupied by removed elements, while @code{m4_set_dump} is a
13257 faster one-shot action that also deletes the set.  No provision is made
13258 for disambiguating members that contain a non-empty @var{sep} as a
13259 substring; use @code{m4_set_empty} to distinguish between an empty set
13260 and the set containing only the empty string.  The order of the output
13261 is unspecified; in the current implementation, part of the speed of
13262 @code{m4_set_dump} results from using a different output order than
13263 @code{m4_set_contents}.  These macros scale linearly in the size of the
13264 set before memory pruning, and @code{m4_set_contents([@var{set}],
13265 [@var{sep}])} is faster than
13266 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13268 @example
13269 m4_set_add_all([a], [1], [2], [3])
13270 @result{}
13271 m4_set_contents([a], [-])
13272 @result{}1-2-3
13273 m4_joinall([-]m4_set_listc([a]))
13274 @result{}1-2-3
13275 m4_set_dump([a], [-])
13276 @result{}3-2-1
13277 m4_set_contents([a])
13278 @result{}
13279 m4_set_add([a], [])
13280 @result{}
13281 m4_set_contents([a], [-])
13282 @result{}
13283 @end example
13284 @end defmac
13286 @defmac m4_set_delete (@var{set})
13287 @msindex{set_delete}
13288 Delete all elements and memory associated with @var{set}.  This is
13289 linear in the set size, and faster than removing one element at a time.
13290 @end defmac
13292 @defmac m4_set_difference (@var{seta}, @var{setb})
13293 @defmacx m4_set_intersection (@var{seta}, @var{setb})
13294 @defmacx m4_set_union (@var{seta}, @var{setb})
13295 @msindex{set_difference}
13296 @msindex{set_intersection}
13297 @msindex{set_union}
13298 Compute the relation between @var{seta} and @var{setb}, and output the
13299 result as a list of quoted arguments without duplicates and with a
13300 leading comma.  Set difference selects the elements in @var{seta} but
13301 not @var{setb}, intersection selects only elements in both sets, and
13302 union selects elements in either set.  These actions are linear in the
13303 sum of the set sizes.  The leading comma is necessary to distinguish
13304 between no elements and the empty string as the only element.
13306 @example
13307 m4_set_add_all([a], [1], [2], [3])
13308 @result{}
13309 m4_set_add_all([b], [3], [], [4])
13310 @result{}
13311 m4_set_difference([a], [b])
13312 @result{},1,2
13313 m4_set_difference([b], [a])
13314 @result{},,4
13315 m4_set_intersection([a], [b])
13316 @result{},3
13317 m4_set_union([a], [b])
13318 @result{},1,2,3,,4
13319 @end example
13320 @end defmac
13322 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13323 @msindex{set_empty}
13324 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13325 expand @var{if-elements}.  This macro operates in constant time.  Using
13326 this macro can help disambiguate output from @code{m4_set_contents} or
13327 @code{m4_set_list}.
13328 @end defmac
13330 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13331 @msindex{set_foreach}
13332 For each element in the set @var{set}, expand @var{action} with the
13333 macro @var{variable} defined as the set element.  Behavior is
13334 unspecified if @var{action} recursively lists the contents of @var{set}
13335 (although listing other sets is acceptable), or if it modifies the set
13336 in any way other than removing the element currently contained in
13337 @var{variable}.  This macro is faster than the corresponding
13338 @code{m4_foreach([@var{variable}],
13339 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13340 although @code{m4_set_map} might be faster still.
13342 @example
13343 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13344 @result{}
13345 m4_set_contents([a])
13346 @result{}12345
13347 m4_set_foreach([a], [i],
13348   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13349 @result{}24
13350 m4_set_contents([a])
13351 @result{}135
13352 @end example
13353 @end defmac
13355 @defmac m4_set_list (@var{set})
13356 @defmacx m4_set_listc (@var{set})
13357 @msindex{set_list}
13358 @msindex{set_listc}
13359 Produce a list of arguments, where each argument is a quoted element
13360 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
13361 by adding a leading comma if there are any set elements, whereas the
13362 variant @code{m4_set_list} cannot distinguish between an empty set and a
13363 set containing only the empty string.  These can be directly used in
13364 macros that take multiple arguments, such as @code{m4_join} or
13365 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13366 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
13367 memory occupied by removed elements is reclaimed during these macros.
13369 @example
13370 m4_set_add_all([a], [1], [2], [3])
13371 @result{}
13372 m4_set_list([a])
13373 @result{}1,2,3
13374 m4_set_list([b])
13375 @result{}
13376 m4_set_listc([b])
13377 @result{}
13378 m4_count(m4_set_list([b]))
13379 @result{}1
13380 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13381 @result{}0
13382 m4_set_add([b], [])
13383 @result{}
13384 m4_set_list([b])
13385 @result{}
13386 m4_set_listc([b])
13387 @result{},
13388 m4_count(m4_set_list([b]))
13389 @result{}1
13390 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13391 @result{}1
13392 @end example
13393 @end defmac
13395 @defmac m4_set_map (@var{set}, @var{action})
13396 @msindex{set_map}
13397 For each element in the set @var{set}, expand @var{action} with a single
13398 argument of the set element.  Behavior is unspecified if @var{action}
13399 recursively lists the contents of @var{set} (although listing other sets
13400 is acceptable), or if it modifies the set in any way other than removing
13401 the element passed as an argument.  This macro is faster than either
13402 corresponding counterpart of
13403 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13404 @code{m4_set_foreach([@var{set}], [var],
13405 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
13406 if more than one argument is needed for @var{action}, although it is
13407 more efficient to use @code{m4_set_map_sep} in that case.
13408 @end defmac
13410 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13411 @msindex{set_map_sep}
13412 For each element in the set @var{set}, expand
13413 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13414 between elements.  Behavior is unspecified if the expansion recursively
13415 lists the contents of @var{set} (although listing other sets
13416 is acceptable), or if it modifies the set in any way other than removing
13417 the element visited by the expansion.  This macro provides the most
13418 efficient means for non-destructively visiting the elements of a set; in
13419 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13420 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13421 @end defmac
13423 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13424  @ovar{if-absent})
13425 @msindex{set_remove}
13426 If @var{value} is an element in the set @var{set}, then remove it and
13427 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
13428 operates in constant time so that multiple removals will scale linearly
13429 rather than quadratically; but when used outside of
13430 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13431 until the set is later
13432 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
13433 other set operations are then less efficient between the time of element
13434 removal and subsequent memory compaction, but still maintain their
13435 guaranteed scaling performance.
13436 @end defmac
13438 @defmac m4_set_size (@var{set})
13439 @msindex{set_size}
13440 Expand to the size of the set @var{set}.  This implementation operates
13441 in constant time, and is thus more efficient than
13442 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13443 @end defmac
13446 @node Forbidden Patterns
13447 @subsection Forbidden Patterns
13448 @cindex Forbidden patterns
13449 @cindex Patterns, forbidden
13451 M4sugar provides a means to define suspicious patterns, patterns
13452 describing tokens which should not be found in the output.  For
13453 instance, if an Autoconf @file{configure} script includes tokens such as
13454 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13455 wrong (typically a macro was not evaluated because of overquotation).
13457 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13458 Additional layers, such as M4sh and Autoconf, add additional forbidden
13459 patterns to the list.
13461 @defmac m4_pattern_forbid (@var{pattern})
13462 @msindex{pattern_forbid}
13463 Declare that no token matching @var{pattern} must be found in the
13464 output.  The output file is (temporarily) split into one word per line
13465 as part of the @command{autom4te} post-processing, with each line (and
13466 therefore word) then being checked against the Perl regular expression
13467 @var{pattern}.  If the regular expression matches, and
13468 @code{m4_pattern_allow} does not also match, then an error is raised.
13470 Comments are not checked; this can be a problem if, for instance, you
13471 have some macro left unexpanded after an @samp{#include}.  No consensus
13472 is currently found in the Autoconf community, as some people consider it
13473 should be valid to name macros in comments (which doesn't make sense to
13474 the authors of this documentation: input, such as macros, should be
13475 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13476 document the output).
13478 As an example, if you define your own macros that begin with @samp{M_}
13479 and are composed from capital letters and underscores, the specification
13480 of @code{m4_pattern_forbid([^M_[A-Z_]+])} will ensure all your macros
13481 are expanded when not used in comments.
13483 As an example of a common use of this macro, consider what happens in
13484 packages that want to use the @command{pkg-config} script via the
13485 third-party @code{PKG_CHECK_MODULES} macro.  By default, if a developer
13486 checks out the development tree but has not yet installed the pkg-config
13487 macros locally, they can manage to successfully run @command{autoconf}
13488 on the package, but the resulting @file{configure} file will likely
13489 result in a confusing shell message about a syntax error on the line
13490 mentioning the unexpanded @code{PKG_CHECK_MODULES} macro.  On the other hand,
13491 if @file{configure.ac} includes @code{m4_pattern_forbid([^PKG_])}, the
13492 missing pkg-config macros will be detected immediately without allowing
13493 @command{autoconf} to succeed.
13494 @end defmac
13496 Of course, you might encounter exceptions to these generic rules, for
13497 instance you might have to refer to @samp{$m4_flags}.
13499 @defmac m4_pattern_allow (@var{pattern})
13500 @msindex{pattern_allow}
13501 Any token matching @var{pattern} is allowed, including if it matches an
13502 @code{m4_pattern_forbid} pattern.
13504 For example, gnulib uses @code{m4_pattern_forbid([^gl_])} to reserve the
13505 @code{gl_} namespace for itself, but also uses
13506 @code{m4_pattern_allow([^gl_ES$])} to avoid a false negative on the
13507 valid locale name.
13508 @end defmac
13510 @node Debugging via autom4te
13511 @section Debugging via autom4te
13512 @cindex debugging tips
13513 @cindex autom4te debugging tips
13514 @cindex m4sugar debugging tips
13515 At times, it is desirable to see what was happening inside m4, to see
13516 why output was not matching expectations.  However, post-processing done
13517 by @command{autom4te} means that directly using the m4 builtin
13518 @code{m4_traceon} is likely to interfere with operation.  Also, frequent
13519 diversion changes and the concept of forbidden tokens make it difficult
13520 to use @code{m4_defn} to generate inline comments in the final output.
13522 There are a couple of tools to help with this.  One is the use of the
13523 @option{--trace} option provided by @command{autom4te} (as well as each
13524 of the programs that wrap @command{autom4te}, such as
13525 @command{autoconf}), in order to inspect when a macro is called and with
13526 which arguments.  For example, when this paragraph was written, the
13527 autoconf version could be found by:
13529 @example
13530 $ @kbd{autoconf --trace=AC_INIT}
13531 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13532 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13533 version is 2.63b.95-3963
13534 @end example
13536 Another trick is to print out the expansion of various m4 expressions to
13537 standard error or to an independent file, with no further m4 expansion,
13538 and without interfering with diversion changes or the post-processing
13539 done to standard output.  @code{m4_errprintn} shows a given expression
13540 on standard error.  For example, if you want to see the expansion of an
13541 autoconf primitive or of one of your autoconf macros, you can do it like
13542 this:
13544 @example
13545 $ @kbd{cat <<\EOF > configure.ac}
13546 AC_INIT
13547 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13548 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13549 AC_OUTPUT
13551 $ @kbd{autoconf}
13552 @error{}The definition of AC_DEFINE_UNQUOTED:
13553 @error{}_AC_DEFINE_Q([], $@@)
13554 @end example
13556 @node Programming in M4sh
13557 @chapter Programming in M4sh
13559 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13560 scripts.  This name was coined by Lars J. Aas, who notes that,
13561 according to the Webster's Revised Unabridged Dictionary (1913):
13563 @quotation
13564 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
13565 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
13567 @enumerate 1
13568 @item
13569 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13570 pressure@enddots{}
13572 @item
13573 A mixture of meal or bran and water fed to animals.
13575 @item
13576 A mess; trouble.  [Obs.] --Beau.@: & Fl.
13577 @end enumerate
13578 @end quotation
13580 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13581 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
13582 and environment variable namespace @samp{^as_}, and the here-document
13583 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
13584 define your own macros or output shell code that conflicts with these
13585 namespaces.
13587 @menu
13588 * Common Shell Constructs::     Portability layer for common shell constructs
13589 * Polymorphic Variables::       Support for indirect variable names
13590 * Initialization Macros::       Macros to establish a sane shell environment
13591 * File Descriptor Macros::      File descriptor macros for input and output
13592 @end menu
13594 @node Common Shell Constructs
13595 @section Common Shell Constructs
13597 M4sh provides portable alternatives for some common shell constructs
13598 that unfortunately are not portable in practice.
13600 @c Deprecated, to be replaced by a better API
13601 @ignore
13602 @defmac AS_BASENAME (@var{file-name})
13603 @asindex{BASENAME}
13604 Output the non-directory portion of @var{file-name}.  For example,
13605 if @code{$file} is @samp{/one/two/three}, the command
13606 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13607 @end defmac
13608 @end ignore
13610 @defmac AS_BOX (@var{text}, @dvar{char, -})
13611 @asindex{BOX}
13612 Expand into shell code that will output @var{text} surrounded by a box
13613 with @var{char} in the top and bottom border.  @var{text} should not
13614 contain a newline, but may contain shell expansions valid for unquoted
13615 here-documents.  @var{char} defaults to @samp{-}, but can be any
13616 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13617 @samp{&}, or @samp{`}.  This is useful for outputting a comment box into
13618 log files to separate distinct phases of script operation.
13619 @end defmac
13621 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13622   @dots{}, @ovar{default})
13623 @asindex{CASE}
13624 Expand into a shell @samp{case} statement, where @var{word} is matched
13625 against one or more patterns.  @var{if-matched} is run if the
13626 corresponding pattern matched @var{word}, else @var{default} is run.
13627 Avoids several portability issues (@pxref{case, , Limitations of Shell
13628 Builtins}).
13629 @end defmac
13631 @c Deprecated, to be replaced by a better API
13632 @defmac AS_DIRNAME (@var{file-name})
13633 @asindex{DIRNAME}
13634 Output the directory portion of @var{file-name}.  For example,
13635 if @code{$file} is @samp{/one/two/three}, the command
13636 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13638 This interface may be improved in the future to avoid forks and losing
13639 trailing newlines.
13640 @end defmac
13642 @defmac AS_ECHO (@var{word})
13643 @asindex{ECHO}
13644 Emits @var{word} to the standard output, followed by a newline.  @var{word}
13645 must be a single shell word (typically a quoted string).  The bytes of
13646 @var{word} are output as-is, even if it starts with "-" or contains "\".
13647 Redirections can be placed outside the macro invocation.  This is much
13648 more portable than using @command{echo} (@pxref{echo, , Limitations of
13649 Shell Builtins}).
13650 @end defmac
13652 @defmac AS_ECHO_N (@var{word})
13653 @asindex{ECHO_N}
13654 Emits @var{word} to the standard output, without a following newline.
13655 @var{word} must be a single shell word (typically a quoted string) and,
13656 for portability, should not include more than one newline.  The bytes of
13657 @var{word} are output as-is, even if it starts with "-" or contains "\".
13658 Redirections can be placed outside the macro invocation.
13659 @end defmac
13661 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13662 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13663 @asindex{ESCAPE}
13664 Expands to @var{string}, with any characters in @var{chars} escaped with
13665 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
13666 and only contain characters from the set @samp{`\"$}; however,
13667 characters may be safely listed more than once in @var{chars} for the
13668 sake of syntax highlighting editors.  The current implementation expands
13669 @var{string} after adding escapes; if @var{string} contains macro calls
13670 that in turn expand to text needing shell quoting, you can use
13671 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13673 The default for @var{chars} (@samp{\"$`}) is the set of characters
13674 needing escapes when @var{string} will be used literally within double
13675 quotes.  One common variant is the set of characters to protect when
13676 @var{string} will be used literally within back-ticks or an unquoted
13677 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
13678 be used to form a double-quoted string containing the same expansions
13679 that would have occurred if @var{string} were expanded in an unquoted
13680 here-document; however, when using this variant, care must be taken that
13681 @var{string} does not use double quotes within complex variable
13682 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13683 with improper escapes.
13685 This macro is often used with @code{AS_ECHO}.  For an example, observe
13686 the output generated by the shell code generated from this snippet:
13688 @example
13689 foo=bar
13690 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13691 @result{}"$foo" = "bar"
13692 m4_define([macro], [a, [\b]])
13693 AS_ECHO(["AS_ESCAPE([[macro]])"])
13694 @result{}macro
13695 AS_ECHO(["AS_ESCAPE([macro])"])
13696 @result{}a, b
13697 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13698 @result{}a, \b
13699 @end example
13701 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13702 @comment the case of @var{string} that does not contain '.
13703 To escape a string that will be placed within single quotes, use:
13705 @example
13706 m4_bpatsubst([[@var{string}]], ['], ['\\''])
13707 @end example
13708 @end defmac
13710 @defmac AS_EXECUTABLE_P (@var{file})
13711 @asindex{EXECUTABLE_P}
13712 Emit code to probe whether @var{file} is a regular file with executable
13713 permissions (and not a directory with search permissions).  The caller
13714 is responsible for quoting @var{file}.
13715 @end defmac
13717 @defmac AS_EXIT (@dvar{status, $?})
13718 @asindex{EXIT}
13719 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13720 This macro
13721 works around shells that see the exit status of the command prior to
13722 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13723 of Shell Builtins}).
13724 @end defmac
13726 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13727 @asindex{IF}
13728 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
13729 run shell code @var{run-if-true1}, else examine further tests.  If no test
13730 exits with a zero status, run shell code @var{run-if-false}, with
13731 simplifications if either @var{run-if-true1} or @var{run-if-false}
13732 is empty.  For example,
13734 @example
13735 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13736       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13737       [echo foo not specified])
13738 @end example
13740 @noindent
13741 ensures any required macros of @code{HANDLE_FOO}
13742 are expanded before the first test.
13743 @end defmac
13745 @defmac AS_MKDIR_P (@var{file-name})
13746 @asindex{MKDIR_P}
13747 Make the directory @var{file-name}, including intervening directories
13748 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
13749 except that it is portable to older versions of @command{mkdir} that
13750 lack support for the @option{-p} option or for the @option{--}
13751 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
13752 @code{AS_MKDIR_P}
13753 succeeds if @var{file-name} is a symbolic link to an existing directory,
13754 even though Posix is unclear whether @samp{mkdir -p} should
13755 succeed in that case.  If creation of @var{file-name} fails, exit the
13756 script.
13758 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
13759 @end defmac
13761 @defmac AS_SET_STATUS (@var{status})
13762 @asindex{SET_STATUS}
13763 Emit shell code to set the value of @samp{$?} to @var{status}, as
13764 efficiently as possible.  However, this is not guaranteed to abort a
13765 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
13766 Builtins}).  This should also be used at the end of a complex shell
13767 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
13768 a DJGPP shell bug.
13769 @end defmac
13771 @defmac AS_TR_CPP (@var{expression})
13772 @asindex{TR_CPP}
13773 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
13774 For example:
13776 @example
13777 # This outputs "#define HAVE_CHAR_P 1".
13778 # Notice the m4 quoting around #, to prevent an m4 comment
13779 type="char *"
13780 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
13781 @end example
13782 @end defmac
13784 @defmac AS_TR_SH (@var{expression})
13785 @asindex{TR_SH}
13786 Transform @var{expression} into shell code that generates a valid shell
13787 variable name.  The result is literal when possible at m4 time, but must
13788 be used with @code{eval} if @var{expression} causes shell indirections.
13789 For example:
13791 @example
13792 # This outputs "Have it!".
13793 header="sys/some file.h"
13794 eval AS_TR_SH([HAVE_$header])=yes
13795 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
13796 @end example
13797 @end defmac
13799 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
13800 @asindex{SET_CATFILE}
13801 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
13802 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
13803 @var{file} is absolute, etc.).
13804 @end defmac
13806 @defmac AS_UNSET (@var{var})
13807 @asindex{UNSET}
13808 Unsets the shell variable @var{var}, working around bugs in older
13809 shells (@pxref{unset, , Limitations of Shell
13810 Builtins}).  @var{var} can be a literal or indirect variable name.
13811 @end defmac
13813 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
13814   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
13815 @asindex{VERSION_COMPARE}
13816 Compare two strings @var{version-1} and @var{version-2}, possibly
13817 containing shell variables, as version strings, and expand
13818 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
13819 depending upon the result.
13820 The algorithm to compare is similar to the one used by strverscmp in
13821 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
13822 The GNU C Library}).
13823 @end defmac
13825 @node Polymorphic Variables
13826 @section Support for indirect variable names
13827 @cindex variable name indirection
13828 @cindex polymorphic variable name
13829 @cindex indirection, variable name
13831 Often, it is convenient to write a macro that will emit shell code
13832 operating on a shell variable.  The simplest case is when the variable
13833 name is known.  But a more powerful idiom is writing shell code that can
13834 work through an indirection, where another variable or command
13835 substitution produces the name of the variable to actually manipulate.
13836 M4sh supports the notion of polymorphic shell variables, making it easy
13837 to write a macro that can deal with either literal or indirect variable
13838 names and output shell code appropriate for both use cases.  Behavior is
13839 undefined if expansion of an indirect variable does not result in a
13840 literal variable name.
13842 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
13843   @dvarv{if-simple-ref, if-not})
13844 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
13845   @ovar{if-not}, @dvarv{if-simple-ref, if-not})
13846 @asindex{LITERAL_IF}
13847 @asindex{LITERAL_WORD_IF}
13848 If the expansion of @var{expression} is definitely a shell literal,
13849 expand @var{if-literal}.  If the expansion of @var{expression} looks
13850 like it might contain shell indirections (such as @code{$var} or
13851 @code{`expr`}), then @var{if-not} is expanded.  Sometimes, it is
13852 possible to output optimized code if @var{expression} consists only of
13853 shell variable expansions (such as @code{$@{var@}}), in which case
13854 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
13855 should always be safe.  @code{AS_LITERAL_WORD_IF} only expands
13856 @var{if-literal} if @var{expression} looks like a single shell word,
13857 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
13858 in @var{expression}.
13860 In order to reduce the time spent recognizing whether an
13861 @var{expression} qualifies as a literal or a simple indirection, the
13862 implementation is somewhat conservative: @var{expression} must be a
13863 single shell word (possibly after stripping whitespace), consisting only
13864 of bytes that would have the same meaning whether unquoted or enclosed
13865 in double quotes (for example, @samp{a.b} results in @var{if-literal},
13866 even though it is not a valid shell variable name; while both @samp{'a'}
13867 and @samp{[$]} result in @var{if-not}, because they behave differently
13868 than @samp{"'a'"} and @samp{"[$]"}).  This macro can be used in contexts
13869 for recognizing portable file names (such as in the implementation of
13870 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
13871 valid variable names (such as in the implementation of @code{AS_TR_SH},
13872 which uses an additional @code{m4_translit} to convert @samp{.} to
13873 @samp{_}).
13875 This example shows how to read the contents of the shell variable
13876 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}.  It
13877 results in a script that will output the line @samp{hello} three times.
13879 @example
13880 AC_DEFUN([MY_ACTION],
13881 [AS_LITERAL_IF([$1],
13882   [echo "$$1"],
13883 @c $$
13884   [AS_VAR_COPY([var], [$1])
13885    echo "$var"],
13886   [eval 'echo "$'"$1"\"])])
13887 foo=bar bar=hello
13888 MY_ACTION([bar])
13889 MY_ACTION([`echo bar`])
13890 MY_ACTION([$foo])
13891 @end example
13892 @end defmac
13894 @defmac AS_VAR_APPEND (@var{var}, @var{text})
13895 @asindex{VAR_APPEND}
13896 Emit shell code to append the shell expansion of @var{text} to the end
13897 of the current contents of the polymorphic shell variable @var{var},
13898 taking advantage of shells that provide the @samp{+=} extension for more
13899 efficient scaling.
13901 For situations where the final contents of @var{var} are relatively
13902 short (less than 256 bytes), it is more efficient to use the simpler
13903 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
13904 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
13905 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}).  But in the case
13906 when the script will be repeatedly appending text into @code{var},
13907 issues of scaling start to become apparent.  A naive implementation
13908 requires execution time linear to the length of the current contents of
13909 @var{var} as well as the length of @var{text} for a single append, for
13910 an overall quadratic scaling with multiple appends.  This macro takes
13911 advantage of shells which provide the extension
13912 @code{@var{var}+=@var{text}}, which can provide amortized constant time
13913 for a single append, for an overall linear scaling with multiple
13914 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
13915 @var{text} be quoted properly to avoid field splitting and file name
13916 expansion.
13917 @end defmac
13919 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
13920 @asindex{VAR_ARITH}
13921 Emit shell code to compute the arithmetic expansion of @var{expression},
13922 assigning the result as the contents of the polymorphic shell variable
13923 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
13924 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
13925 syntax for a valid @var{expression} is rather limited: all operators
13926 must occur as separate shell arguments and with proper quoting, there is
13927 no portable equality operator, all variables containing numeric values
13928 must be expanded prior to the computation, all numeric values must be
13929 provided in decimal without leading zeroes, and the first shell argument
13930 should not be a negative number.  In the following example, this snippet
13931 will print @samp{(2+3)*4 == 20}.
13933 @example
13934 bar=3
13935 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
13936 echo "(2+$bar)*4 == $foo"
13937 @end example
13938 @end defmac
13940 @defmac AS_VAR_COPY (@var{dest}, @var{source})
13941 @asindex{VAR_COPY}
13942 Emit shell code to assign the contents of the polymorphic shell variable
13943 @var{source} to the polymorphic shell variable @var{dest}.  For example,
13944 executing this M4sh snippet will output @samp{bar hi}:
13946 @example
13947 foo=bar bar=hi
13948 AS_VAR_COPY([a], [foo])
13949 AS_VAR_COPY([b], [$foo])
13950 echo "$a $b"
13951 @end example
13953 When it is necessary to access the contents of an indirect variable
13954 inside a shell double-quoted context, the recommended idiom is to first
13955 copy the contents into a temporary literal shell variable.
13957 @smallexample
13958 for header in stdint_h inttypes_h ; do
13959   AS_VAR_COPY([var], [ac_cv_header_$header])
13960   echo "$header detected: $var"
13961 done
13962 @end smallexample
13963 @end defmac
13965 @comment AS_VAR_GET is intentionally undocumented; it can't handle
13966 @comment trailing newlines uniformly, and forks too much.
13968 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
13969   @ovar{if-not-equal})
13970 @asindex{VAR_IF}
13971 Output a shell conditional statement.  If the contents of the
13972 polymorphic shell variable @var{var} match the string @var{word},
13973 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  @var{word}
13974 must be a single shell word (typically a quoted string).  Avoids
13975 shell bugs if an interrupt signal arrives while a command substitution
13976 in @var{var} is being expanded.
13977 @end defmac
13979 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
13980 @defmacx AS_VAR_POPDEF (@var{m4-name})
13981 @asindex{VAR_PUSHDEF}
13982 @asindex{VAR_POPDEF}
13983 @cindex composing variable names
13984 @cindex variable names, composing
13985 A common M4sh idiom involves composing shell variable names from an m4
13986 argument (for example, writing a macro that uses a cache variable).
13987 @var{value} can be an arbitrary string, which will be transliterated
13988 into a valid shell name by @code{AS_TR_SH}.  In order to access the
13989 composed variable name based on @var{value}, it is easier to declare a
13990 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
13991 that macro as the argument to subsequent @code{AS_VAR} macros as a
13992 polymorphic variable name, and finally free the temporary macro with
13993 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
13994 to avoid excess newlines in the output.
13996 Here is an involved example, that shows the power of writing macros that
13997 can handle composed shell variable names:
13999 @example
14000 m4_define([MY_CHECK_HEADER],
14001 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
14002 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
14003 AS_VAR_POPDEF([my_Header])dnl
14005 MY_CHECK_HEADER([stdint.h])
14006 for header in inttypes.h stdlib.h ; do
14007   MY_CHECK_HEADER([$header])
14008 done
14009 @end example
14011 @noindent
14012 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
14013 variable names.  In the first invocation, the m4 argument is
14014 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
14015 As a result, the temporary macro @code{my_Header} expands to the literal
14016 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
14017 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
14018 temporary macro @code{my_Header} expands to the indirect shell name
14019 @samp{$as_my_Header}.  During the shell execution of the for loop, when
14020 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
14021 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
14022 platform where all three headers have been previously detected, the
14023 output of the script will include:
14025 @smallexample
14026 header stdint.h detected
14027 header inttypes.h detected
14028 header stdlib.h detected
14029 @end smallexample
14030 @end defmac
14032 @defmac AS_VAR_SET (@var{var}, @ovar{value})
14033 @asindex{VAR_SET}
14034 Emit shell code to assign the contents of the polymorphic shell variable
14035 @var{var} to the shell expansion of @var{value}.  @var{value} is not
14036 subject to field splitting or file name expansion, so if command
14037 substitution is used, it may be done with @samp{`""`} rather than using
14038 an intermediate variable (@pxref{Shell Substitutions}).  However,
14039 @var{value} does undergo rescanning for additional macro names; behavior
14040 is unspecified if late expansion results in any shell meta-characters.
14041 @end defmac
14043 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
14044 @asindex{VAR_SET_IF}
14045 Emit a shell conditional statement, which executes @var{if-set} if the
14046 polymorphic shell variable @code{var} is set to any value, and
14047 @var{if-undef} otherwise.
14048 @end defmac
14050 @defmac AS_VAR_TEST_SET (@var{var})
14051 @asindex{VAR_TEST_SET}
14052 Emit a shell statement that results in a successful exit status only if
14053 the polymorphic shell variable @code{var} is set.
14054 @end defmac
14056 @node Initialization Macros
14057 @section Initialization Macros
14059 @defmac AS_BOURNE_COMPATIBLE
14060 @asindex{BOURNE_COMPATIBLE}
14061 Set up the shell to be more compatible with the Bourne shell as
14062 standardized by Posix, if possible.  This may involve setting
14063 environment variables, or setting options, or similar
14064 implementation-specific actions.  This macro is deprecated, since
14065 @code{AS_INIT} already invokes it.
14066 @end defmac
14068 @defmac AS_INIT
14069 @asindex{INIT}
14070 @evindex LC_ALL
14071 @evindex SHELL
14072 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
14073 outputs the @code{#! /bin/sh} line, a notice about where the output was
14074 generated from, and code to sanitize the environment for the rest of the
14075 script.  Among other initializations, this sets @env{SHELL} to the shell
14076 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14077 ensure the C locale.  Finally, it changes the current diversion to
14078 @code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
14079 and @code{AT_INIT}, so shell code in @file{configure},
14080 @file{config.status}, and @file{testsuite} all benefit from a sanitized
14081 shell environment.
14082 @end defmac
14084 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14085 @asindex{INIT_GENERATED}
14086 Emit shell code to start the creation of a subsidiary shell script in
14087 @var{file}, including changing @var{file} to be executable.  This macro
14088 populates the child script with information learned from the parent
14089 (thus, the emitted code is equivalent in effect, but more efficient,
14090 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14091 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
14092 beginning of the child, prior to the shell initialization code, and is
14093 subject to parameter expansion, command substitution, and backslash
14094 quote removal.  The
14095 parent script should check the exit status after this macro, in case
14096 @var{file} could not be properly created (for example, if the disk was
14097 full).  If successfully created, the parent script can then proceed to
14098 append additional M4sh constructs into the child script.
14100 Note that the child script starts life without a log file open, so if
14101 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14102 must temporarily disable any attempts to use the log file until after
14103 emitting code to open a log within the child.  On the other hand, if the
14104 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14105 @samp{1}, then the child script already has code that copies stdout to
14106 that descriptor.  Currently, the suggested
14107 idiom for writing a M4sh shell script from within another script is:
14109 @example
14110 AS_INIT_GENERATED([@var{file}], [[# My child script.
14111 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14112 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14113 cat >> "@var{file}" <<\__EOF__
14114 # Code to initialize AS_MESSAGE_LOG_FD
14115 m4_popdef([AS_MESSAGE_LOG_FD])dnl
14116 # Additional code
14117 __EOF__
14118 @end example
14120 This, however, may change in the future as the M4sh interface is
14121 stabilized further.
14123 Also, be aware that use of @env{LINENO} within the child script may
14124 report line numbers relative to their location in the parent script,
14125 even when using @code{AS_LINENO_PREPARE}, if the parent script was
14126 unable to locate a shell with working @env{LINENO} support.
14127 @end defmac
14129 @defmac AS_LINENO_PREPARE
14130 @asindex{LINENO_PREPARE}
14131 @evindex LINENO
14132 Find a shell that supports the special variable @env{LINENO}, which
14133 contains the number of the currently executing line.  This macro is
14134 automatically invoked by @code{AC_INIT} in configure scripts.
14135 @end defmac
14137 @defmac AS_ME_PREPARE
14138 @asindex{ME_PREPARE}
14139 Set up variable @env{as_me} to be the basename of the currently executing
14140 script.  This macro is automatically invoked by @code{AC_INIT} in
14141 configure scripts.
14142 @end defmac
14144 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14145 @asindex{TMPDIR}
14146 @evindex TMPDIR
14147 @ovindex tmp
14148 Create, as safely as possible, a temporary sub-directory within
14149 @var{dir} with a name starting with @var{prefix}.  @var{prefix} should
14150 be 2--4 characters, to make it slightly easier to identify the owner of
14151 the directory.  If @var{dir} is omitted, then the value of @env{TMPDIR}
14152 will be used (defaulting to @samp{/tmp}).  On success, the name of the
14153 newly created directory is stored in the shell variable @code{tmp}.  On
14154 error, the script is aborted.
14156 Typically, this macro is coupled with some exit traps to delete the created
14157 directory and its contents on exit or interrupt.  However, there is a
14158 slight window between when the directory is created and when the name is
14159 actually known to the shell, so an interrupt at the right moment might
14160 leave the temporary directory behind.  Hence it is important to use a
14161 @var{prefix} that makes it easier to determine if a leftover temporary
14162 directory from an interrupted script is safe to delete.
14164 The use of the output variable @samp{$tmp} rather than something in the
14165 @samp{as_} namespace is historical; it has the unfortunate consequence
14166 that reusing this otherwise common name for any other purpose inside
14167 your script has the potential to break any cleanup traps designed to
14168 remove the temporary directory.
14169 @end defmac
14171 @defmac AS_SHELL_SANITIZE
14172 @asindex{SHELL_SANITIZE}
14173 Initialize the shell suitably for @command{configure} scripts.  This has
14174 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14175 environment variables for predictable results from configuration tests.
14176 For example, it sets @env{LC_ALL} to change to the default C locale.
14177 @xref{Special Shell Variables}.  This macro is deprecated, since
14178 @code{AS_INIT} already invokes it.
14179 @end defmac
14182 @node File Descriptor Macros
14183 @section File Descriptor Macros
14184 @cindex input
14185 @cindex standard input
14186 @cindex file descriptors
14187 @cindex descriptors
14188 @cindex low-level output
14189 @cindex output, low-level
14191 The following macros define file descriptors used to output messages
14192 (or input values) from @file{configure} scripts.
14193 For example:
14195 @example
14196 echo "$wombats found" >&AS_MESSAGE_LOG_FD
14197 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
14198 read kangaroos <&AS_ORIGINAL_STDIN_FD`
14199 @end example
14201 @noindent
14202 However doing so is seldom needed, because Autoconf provides higher
14203 level macros as described below.
14205 @defmac AS_MESSAGE_FD
14206 @asindex{MESSAGE_FD}
14207 The file descriptor for @samp{checking for...}  messages and results.
14208 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14209 clients.  However, @code{AC_INIT} shuffles things around to another file
14210 descriptor, in order to allow the @option{-q} option of
14211 @command{configure} to choose whether messages should go to the script's
14212 standard output or be discarded.
14214 If you want to display some messages, consider using one of the printing
14215 macros (@pxref{Printing Messages}) instead.  Copies of messages output
14216 via these macros are also recorded in @file{config.log}.
14217 @end defmac
14219 @anchor{AS_MESSAGE_LOG_FD}
14220 @defmac AS_MESSAGE_LOG_FD
14221 @asindex{MESSAGE_LOG_FD}
14222 This must either be empty, or expand to a file descriptor for log
14223 messages.  By default, @code{AS_INIT} sets this macro to the empty
14224 string for standalone M4sh clients, thus disabling logging.  However,
14225 @code{AC_INIT} shuffles things around so that both @command{configure}
14226 and @command{config.status} use @file{config.log} for log messages.
14227 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14228 Compiler}), redirect all output to this descriptor.  You may want to do
14229 so if you develop such a low-level macro.
14230 @end defmac
14232 @defmac AS_ORIGINAL_STDIN_FD
14233 @asindex{ORIGINAL_STDIN_FD}
14234 This must expand to a file descriptor for the original standard input.
14235 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14236 M4sh clients.  However, @code{AC_INIT} shuffles things around for
14237 safety.
14239 When @command{configure} runs, it may accidentally execute an
14240 interactive command that has the same name as the non-interactive meant
14241 to be used or checked.  If the standard input was the terminal, such
14242 interactive programs would cause @command{configure} to stop, pending
14243 some user input.  Therefore @command{configure} redirects its standard
14244 input from @file{/dev/null} during its initialization.  This is not
14245 normally a problem, since @command{configure} normally does not need
14246 user input.
14248 In the extreme case where your @file{configure} script really needs to
14249 obtain some values from the original standard input, you can read them
14250 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14251 @end defmac
14254 @c =================================================== Writing Autoconf Macros.
14256 @node Writing Autoconf Macros
14257 @chapter Writing Autoconf Macros
14259 When you write a feature test that could be applicable to more than one
14260 software package, the best thing to do is encapsulate it in a new macro.
14261 Here are some instructions and guidelines for writing Autoconf macros.
14263 @menu
14264 * Macro Definitions::           Basic format of an Autoconf macro
14265 * Macro Names::                 What to call your new macros
14266 * Reporting Messages::          Notifying @command{autoconf} users
14267 * Dependencies Between Macros::  What to do when macros depend on other macros
14268 * Obsoleting Macros::           Warning about old ways of doing things
14269 * Coding Style::                Writing Autoconf macros @`a la Autoconf
14270 @end menu
14272 @node Macro Definitions
14273 @section Macro Definitions
14275 @defmac AC_DEFUN (@var{name}, @ovar{body})
14276 @acindex{DEFUN}
14277 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14278 similar to the M4 builtin @code{m4_define} macro; this creates a macro
14279 named @var{name} and with @var{body} as its expansion.  In addition to
14280 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14281 constrain the order in which macros are called, while avoiding redundant
14282 output (@pxref{Prerequisite Macros}).
14283 @end defmac
14285 An Autoconf macro definition looks like this:
14287 @example
14288 AC_DEFUN(@var{macro-name}, @var{macro-body})
14289 @end example
14291 You can refer to any arguments passed to the macro as @samp{$1},
14292 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4,
14293 GNU M4}, for more complete information on writing M4 macros.
14295 Most macros fall in one of two general categories.  The first category
14296 includes macros which take arguments, in order to generate output
14297 parameterized by those arguments.  Macros in this category are designed
14298 to be directly expanded, often multiple times, and should not be used as
14299 the argument to @code{AC_REQUIRE}.  The other category includes macros
14300 which are shorthand for a fixed block of text, and therefore do not take
14301 arguments.  For this category of macros, directly expanding the macro
14302 multiple times results in redundant output, so it is more common to use
14303 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14304 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14306 Be sure to properly quote both the @var{macro-body} @emph{and} the
14307 @var{macro-name} to avoid any problems if the macro happens to have
14308 been previously defined.
14310 Each macro should have a header comment that gives its prototype, and a
14311 brief description.  When arguments have default values, display them in
14312 the prototype.  For example:
14314 @example
14315 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14316 # --------------------------------------
14317 m4_define([AC_MSG_ERROR],
14318   [@{ AS_MESSAGE([error: $1], [2])
14319      exit m4_default([$2], [1]); @}])
14320 @end example
14322 Comments about the macro should be left in the header comment.  Most
14323 other comments make their way into @file{configure}, so just keep
14324 using @samp{#} to introduce comments.
14326 @cindex @code{dnl}
14327 If you have some special comments about pure M4 code, comments
14328 that make no sense in @file{configure} and in the header comment, then
14329 use the builtin @code{dnl}: it causes M4 to discard the text
14330 through the next newline.
14332 Keep in mind that @code{dnl} is rarely needed to introduce comments;
14333 @code{dnl} is more useful to get rid of the newlines following macros
14334 that produce no output, such as @code{AC_REQUIRE}.
14336 Public third-party macros need to use @code{AC_DEFUN}, and not
14337 @code{m4_define}, in order to be found by @command{aclocal}
14338 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14339 Additionally, if it is ever determined that a macro should be made
14340 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14341 in order to have @command{autoupdate} assist the user in choosing a
14342 better alternative, but there is no corresponding way to make
14343 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14345 There is another subtle, but important, difference between using
14346 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14347 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
14348 block of text with a @code{m4_define} macro that will expand to the same
14349 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
14350 the same content does not necessarily give the same results, because it
14351 changes the location where any embedded but unsatisfied
14352 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
14353 example of this, see @ref{Expanded Before Required}.
14355 @node Macro Names
14356 @section Macro Names
14358 All of the public Autoconf macros have all-uppercase names in the
14359 namespace @samp{^AC_} to prevent them from accidentally conflicting with
14360 other text; Autoconf also reserves the namespace @samp{^_AC_} for
14361 internal macros.  All shell variables that they use for internal
14362 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
14363 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
14364 @command{configure}, files produced by Autoconf make heavy use of the
14365 file system namespace @samp{^conf}.
14367 Since Autoconf is built on top of M4sugar (@pxref{Programming in
14368 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14369 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
14370 @file{configure.ac} is also designed to be scanned by Autoheader,
14371 Autoscan, Autoupdate, and Automake, you should be aware of the
14372 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
14373 the namespace of a package that does not own the macro or shell code you
14374 are writing.
14376 To ensure that your macros don't conflict with present or future
14377 Autoconf macros, you should prefix your own macro names and any shell
14378 variables they use with some other sequence.  Possibilities include your
14379 initials, or an abbreviation for the name of your organization or
14380 software package.  Historically, people have not always followed the
14381 rule of using a namespace appropriate for their package, and this has
14382 made it difficult for determining the origin of a macro (and where to
14383 report bugs about that macro), as well as difficult for the true
14384 namespace owner to add new macros without interference from pre-existing
14385 uses of third-party macros.  Perhaps the best example of this confusion
14386 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14387 to Gettext.
14389 Most of the Autoconf macros' names follow a structured naming convention
14390 that indicates the kind of feature check by the name.  The macro names
14391 consist of several words, separated by underscores, going from most
14392 general to most specific.  The names of their cache variables use the
14393 same convention (@pxref{Cache Variable Names}, for more information on
14394 them).
14396 The first word of the name after the namespace initials (such as
14397 @samp{AC_}) usually tells the category
14398 of the feature being tested.  Here are the categories used in Autoconf for
14399 specific test macros, the kind of macro that you are more likely to
14400 write.  They are also used for cache variables, in all-lowercase.  Use
14401 them where applicable; where they're not, invent your own categories.
14403 @table @code
14404 @item C
14405 C language builtin features.
14406 @item DECL
14407 Declarations of C variables in header files.
14408 @item FUNC
14409 Functions in libraries.
14410 @item GROUP
14411 Posix group owners of files.
14412 @item HEADER
14413 Header files.
14414 @item LIB
14415 C libraries.
14416 @item PROG
14417 The base names of programs.
14418 @item MEMBER
14419 Members of aggregates.
14420 @item SYS
14421 Operating system features.
14422 @item TYPE
14423 C builtin or declared types.
14424 @item VAR
14425 C variables in libraries.
14426 @end table
14428 After the category comes the name of the particular feature being
14429 tested.  Any further words in the macro name indicate particular aspects
14430 of the feature.  For example, @code{AC_PROG_MAKE_SET} checks whether
14431 @command{make} sets a variable to its own name.
14433 An internal macro should have a name that starts with an underscore;
14434 Autoconf internals should therefore start with @samp{_AC_}.
14435 Additionally, a macro that is an internal subroutine of another macro
14436 should have a name that starts with an underscore and the name of that
14437 other macro, followed by one or more words saying what the internal
14438 macro does.  For example, @code{AC_PATH_X} has internal macros
14439 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14441 @node Reporting Messages
14442 @section Reporting Messages
14443 @cindex Messages, from @command{autoconf}
14445 When macros statically diagnose abnormal situations, benign or fatal, it
14446 is possible to make @command{autoconf} detect the problem, and refuse to
14447 create @file{configure} in the case of an error.  The macros in this
14448 section are considered obsolescent, and new code should use M4sugar
14449 macros for this purpose, see @ref{Diagnostic Macros}.
14451 On the other hand, it is possible to want to detect errors when
14452 @command{configure} is run, which are dependent on the environment of
14453 the user rather than the maintainer.  For dynamic diagnostics, see
14454 @ref{Printing Messages}.
14456 @defmac AC_DIAGNOSE (@var{category}, @var{message})
14457 @acindex{DIAGNOSE}
14458 Report @var{message} as a warning (or as an error if requested by the
14459 user) if warnings of the @var{category} are turned on.  This macro is
14460 obsolescent; you are encouraged to use:
14461 @example
14462 m4_warn([@var{category}], [@var{message}])
14463 @end example
14464 @noindent
14465 instead.  @xref{m4_warn}, for more details, including valid
14466 @var{category} names.
14467 @end defmac
14469 @defmac AC_WARNING (@var{message})
14470 @acindex{WARNING}
14471 Report @var{message} as a syntax warning.  This macro is obsolescent;
14472 you are encouraged to use:
14473 @example
14474 m4_warn([syntax], [@var{message}])
14475 @end example
14476 @noindent
14477 instead.  @xref{m4_warn}, for more details, as well as better
14478 finer-grained categories of warnings (not all problems have to do with
14479 syntax).
14480 @end defmac
14482 @defmac AC_FATAL (@var{message})
14483 @acindex{FATAL}
14484 Report a severe error @var{message}, and have @command{autoconf} die.
14485 This macro is obsolescent; you are encouraged to use:
14486 @example
14487 m4_fatal([@var{message}])
14488 @end example
14489 @noindent
14490 instead.  @xref{m4_fatal}, for more details.
14491 @end defmac
14493 When the user runs @samp{autoconf -W error}, warnings from
14494 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
14495 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
14497 @node Dependencies Between Macros
14498 @section Dependencies Between Macros
14499 @cindex Dependencies between macros
14501 Some Autoconf macros depend on other macros having been called first in
14502 order to work correctly.  Autoconf provides a way to ensure that certain
14503 macros are called if needed and a way to warn the user if macros are
14504 called in an order that might cause incorrect operation.
14506 @menu
14507 * Prerequisite Macros::         Ensuring required information
14508 * Suggested Ordering::          Warning about possible ordering problems
14509 * One-Shot Macros::             Ensuring a macro is called only once
14510 @end menu
14512 @node Prerequisite Macros
14513 @subsection Prerequisite Macros
14514 @cindex Prerequisite macros
14515 @cindex Macros, prerequisites
14517 A macro that you write might need to use values that have previously
14518 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
14519 examines the output of @code{flex} or @code{lex}, so it depends on
14520 @code{AC_PROG_LEX} having been called first to set the shell variable
14521 @code{LEX}.
14523 Rather than forcing the user of the macros to keep track of the
14524 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14525 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
14526 called if it is needed, and only called once.
14528 @defmac AC_REQUIRE (@var{macro-name})
14529 @acindex{REQUIRE}
14530 If the M4 macro @var{macro-name} has not already been called, call it
14531 (without any arguments).  Make sure to quote @var{macro-name} with
14532 square brackets.  @var{macro-name} must have been defined using
14533 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14534 that it has been called.
14536 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14537 must not be called from the top level.  Also, it does not make sense to
14538 require a macro that takes parameters.
14539 @end defmac
14541 @code{AC_REQUIRE} is often misunderstood.  It really implements
14542 dependencies between macros in the sense that if one macro depends upon
14543 another, the latter is expanded @emph{before} the body of the
14544 former.  To be more precise, the required macro is expanded before
14545 the outermost defined macro in the current expansion stack.
14546 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14547 @code{FOO}.  For instance, this definition of macros:
14549 @example
14550 @group
14551 AC_DEFUN([TRAVOLTA],
14552 [test "$body_temperature_in_celsius" -gt "38" &&
14553   dance_floor=occupied])
14554 AC_DEFUN([NEWTON_JOHN],
14555 [test "x$hair_style" = xcurly &&
14556   dance_floor=occupied])
14557 @end group
14559 @group
14560 AC_DEFUN([RESERVE_DANCE_FLOOR],
14561 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14562   AC_REQUIRE([TRAVOLTA])
14563   AC_REQUIRE([NEWTON_JOHN])
14564 fi])
14565 @end group
14566 @end example
14568 @noindent
14569 with this @file{configure.ac}
14571 @example
14572 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14573 RESERVE_DANCE_FLOOR
14574 if test "x$dance_floor" = xoccupied; then
14575   AC_MSG_ERROR([cannot pick up here, let's move])
14577 @end example
14579 @noindent
14580 does not leave you with a better chance to meet a kindred soul at
14581 other times than Saturday night since it expands into:
14583 @example
14584 @group
14585 test "$body_temperature_in_Celsius" -gt "38" &&
14586   dance_floor=occupied
14587 test "x$hair_style" = xcurly &&
14588   dance_floor=occupied
14590 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14594 @end group
14595 @end example
14597 This behavior was chosen on purpose: (i) it prevents messages in
14598 required macros from interrupting the messages in the requiring macros;
14599 (ii) it avoids bad surprises when shell conditionals are used, as in:
14601 @example
14602 @group
14603 if @dots{}; then
14604   AC_REQUIRE([SOME_CHECK])
14606 @dots{}
14607 SOME_CHECK
14608 @end group
14609 @end example
14611 However, this implementation can lead to another class of problems.
14612 Consider the case where an outer macro first expands, then indirectly
14613 requires, an inner macro:
14615 @example
14616 AC_DEFUN([TESTA], [[echo in A
14617 if test -n "$SEEN_A" ; then echo duplicate ; fi
14618 SEEN_A=:]])
14619 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14620 if test -z "$SEEN_A" ; then echo bug ; fi]])
14621 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14622 AC_DEFUN([OUTER], [[echo in OUTER]
14623 TESTA
14624 TESTC])
14625 OUTER
14626 @end example
14628 @noindent
14629 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14630 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14631 of @code{OUTER}, but because @code{TESTA} had already been directly
14632 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
14633 @code{TESTB} occurs prior to its prerequisites, leading to the following
14634 output:
14636 @example
14637 in B
14639 in OUTER
14640 in A
14641 in C
14642 @end example
14644 @noindent
14645 Newer Autoconf is smart enough to recognize this situation, and hoists
14646 @code{TESTA} even though it has already been expanded, but issues a
14647 syntax warning in the process.  This is because the hoisted expansion of
14648 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14649 redundant code, and causes its own set of problems if the hoisted macro
14650 is not idempotent:
14652 @example
14653 in A
14654 in B
14655 in OUTER
14656 in A
14657 duplicate
14658 in C
14659 @end example
14661 The bug is not in Autoconf, but in the macro definitions.  If you ever
14662 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14663 that the macro only needs to be expanded once.  But to enforce this,
14664 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14665 this only helps in Autoconf 2.64 or newer), or all
14666 uses of that macro should be through @code{AC_REQUIRE}; directly
14667 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14668 eliminate redundant expansion.  In the example, this rule of thumb was
14669 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14670 directly expands it.  One way of fixing the bug is to factor
14671 @code{TESTA} into two macros, the portion designed for direct and
14672 repeated use (here, named @code{TESTA}), and the portion designed for
14673 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14674 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
14675 calling convention according to their needs:
14677 @example
14678 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14679 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14680 if test -n "$SEEN_A" ; then echo duplicate ; fi
14681 SEEN_A=:]])
14682 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14683 if test -z "$SEEN_A" ; then echo bug ; fi]])
14684 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14685 AC_DEFUN([OUTER], [[echo in OUTER]
14686 TESTA
14687 TESTC])
14688 OUTER
14689 @end example
14691 @noindent
14692 the resulting output will then obey all dependency rules and avoid any
14693 syntax warnings, whether the script is built with old or new Autoconf
14694 versions:
14696 @example
14697 in A_PREREQ
14698 in B
14699 in OUTER
14700 in A
14701 in C
14702 @end example
14704 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
14705 enforce expansion of required macros outside of shell conditional
14706 constructs.  You are furthermore encouraged, although not required, to
14707 put all @code{AC_REQUIRE} calls
14708 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
14709 lines they leave.
14711 Autoconf will normally warn if an @code{AC_REQUIRE} call refers to a
14712 macro that has not been defined.  However, the @command{aclocal} tool
14713 relies on parsing an incomplete set of input files to trace which macros
14714 have been required, in order to then pull in additional files that
14715 provide those macros; for this particular use case, pre-defining the
14716 macro @code{m4_require_silent_probe} will avoid the warnings.
14718 @node Suggested Ordering
14719 @subsection Suggested Ordering
14720 @cindex Macros, ordering
14721 @cindex Ordering macros
14723 Some macros should be run before another macro if both are called, but
14724 neither @emph{requires} that the other be called.  For example, a macro
14725 that changes the behavior of the C compiler should be called before any
14726 macros that run the C compiler.  Many of these dependencies are noted in
14727 the documentation.
14729 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14730 with this kind of dependency appear out of order in a
14731 @file{configure.ac} file.  The warning occurs when creating
14732 @command{configure} from @file{configure.ac}, not when running
14733 @command{configure}.
14735 For example, @code{AC_PROG_CPP} checks whether the C compiler
14736 can run the C preprocessor when given the @option{-E} option.  It should
14737 therefore be called after any macros that change which C compiler is
14738 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
14740 @example
14741 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14742 @end example
14744 @noindent
14745 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14746 when @code{AC_PROG_CC} is called.
14748 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14749 @acindex{BEFORE}
14750 Make M4 print a warning message to the standard error output if
14751 @var{called-macro-name} has already been called.  @var{this-macro-name}
14752 should be the name of the macro that is calling @code{AC_BEFORE}.  The
14753 macro @var{called-macro-name} must have been defined using
14754 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14755 that it has been called.
14756 @end defmac
14758 @node One-Shot Macros
14759 @subsection One-Shot Macros
14760 @cindex One-shot macros
14761 @cindex Macros, called once
14763 Some macros should be called only once, either because calling them
14764 multiple time is unsafe, or because it is bad style.  For instance
14765 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14766 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
14767 sense to run these expensive checks more than once.  Such one-shot
14768 macros can be defined using @code{AC_DEFUN_ONCE}.
14770 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14771 @acindex{DEFUN_ONCE}
14772 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14773 Definitions}), but add additional logic that guarantees that only the
14774 first use of the macro (whether by direct expansion or
14775 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14776 expansion will occur before the start of any enclosing macro defined by
14777 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
14778 Generally, it does not make sense for @var{macro-body} to use parameters
14779 such as @code{$1}.
14780 @end defmac
14782 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14783 emit a warning if it was directly expanded a second time, so for
14784 portability, it is better to use @code{AC_REQUIRE} than direct
14785 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14786 (@pxref{Prerequisite Macros}).
14788 @node Obsoleting Macros
14789 @section Obsoleting Macros
14790 @cindex Obsoleting macros
14791 @cindex Macros, obsoleting
14793 Configuration and portability technology has evolved over the years.
14794 Often better ways of solving a particular problem are developed, or
14795 ad-hoc approaches are systematized.  This process has occurred in many
14796 parts of Autoconf.  One result is that some of the macros are now
14797 considered @dfn{obsolete}; they still work, but are no longer considered
14798 the best thing to do, hence they should be replaced with more modern
14799 macros.  Ideally, @command{autoupdate} should replace the old macro calls
14800 with their modern implementation.
14802 Autoconf provides a simple means to obsolete a macro.
14804 @anchor{AU_DEFUN}
14805 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
14806 @auindex{DEFUN}
14807 Define @var{old-macro} as @var{implementation}.  The only difference
14808 with @code{AC_DEFUN} is that the user is warned that
14809 @var{old-macro} is now obsolete.
14811 If she then uses @command{autoupdate}, the call to @var{old-macro} is
14812 replaced by the modern @var{implementation}.  @var{message} should
14813 include information on what to do after running @command{autoupdate};
14814 @command{autoupdate} prints it as a warning, and includes it
14815 in the updated @file{configure.ac} file.
14817 The details of this macro are hairy: if @command{autoconf} encounters an
14818 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
14819 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
14820 macros are expanded here, while all other macros are disabled and
14821 appear literally in the updated @file{configure.ac}.
14822 @end defmac
14824 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
14825 @auindex{ALIAS}
14826 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
14827 with the same parameters.  This happens for example if the macro was renamed.
14828 @end defmac
14830 @node Coding Style
14831 @section Coding Style
14832 @cindex Coding style
14834 The Autoconf macros follow a strict coding style.  You are encouraged to
14835 follow this style, especially if you intend to distribute your macro,
14836 either by contributing it to Autoconf itself or the
14837 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
14838 Archive}, or by other means.
14840 The first requirement is to pay great attention to the quotation.  For
14841 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
14843 Do not try to invent new interfaces.  It is likely that there is a macro
14844 in Autoconf that resembles the macro you are defining: try to stick to
14845 this existing interface (order of arguments, default values, etc.).  We
14846 @emph{are} conscious that some of these interfaces are not perfect;
14847 nevertheless, when harmless, homogeneity should be preferred over
14848 creativity.
14850 Be careful about clashes both between M4 symbols and between shell
14851 variables.
14853 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
14854 you are unlikely to generate conflicts.  Nevertheless, when you need to
14855 set a special value, @emph{avoid using a regular macro name}; rather,
14856 use an ``impossible'' name.  For instance, up to version 2.13, the macro
14857 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
14858 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
14859 But since there is a macro named @code{AC_SUBST_FILE}, it was just
14860 impossible to @samp{AC_SUBST(FILE)}!  In this case,
14861 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
14862 have been used (yes, with the parentheses).
14863 @c or better yet, high-level macros such as @code{m4_expand_once}
14865 No Autoconf macro should ever enter the user-variable name space; i.e.,
14866 except for the variables that are the actual result of running the
14867 macro, all shell variables should start with @code{ac_}.  In
14868 addition, small macros or any macro that is likely to be embedded in
14869 other macros should be careful not to use obvious names.
14871 @cindex @code{dnl}
14872 Do not use @code{dnl} to introduce comments: most of the comments you
14873 are likely to write are either header comments which are not output
14874 anyway, or comments that should make their way into @file{configure}.
14875 There are exceptional cases where you do want to comment special M4
14876 constructs, in which case @code{dnl} is right, but keep in mind that it
14877 is unlikely.
14879 M4 ignores the leading blanks and newlines before each argument.
14880 Use this feature to
14881 indent in such a way that arguments are (more or less) aligned with the
14882 opening parenthesis of the macro being called.  For instance, instead of
14884 @example
14885 AC_CACHE_CHECK(for EMX OS/2 environment,
14886 ac_cv_emxos2,
14887 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
14888 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
14889 @end example
14891 @noindent
14892 write
14894 @example
14895 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14896 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14897                    [ac_cv_emxos2=yes],
14898                    [ac_cv_emxos2=no])])
14899 @end example
14901 @noindent
14902 or even
14904 @example
14905 AC_CACHE_CHECK([for EMX OS/2 environment],
14906                [ac_cv_emxos2],
14907                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
14908                                                    [return __EMX__;])],
14909                                   [ac_cv_emxos2=yes],
14910                                   [ac_cv_emxos2=no])])
14911 @end example
14913 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
14914 cross-compiling, provide a pessimistic value (typically @samp{no}).
14916 Feel free to use various tricks to prevent auxiliary tools, such as
14917 syntax-highlighting editors, from behaving improperly.  For instance,
14918 instead of:
14920 @example
14921 m4_bpatsubst([$1], [$"])
14922 @end example
14924 @noindent
14927 @example
14928 m4_bpatsubst([$1], [$""])
14929 @end example
14931 @noindent
14932 so that Emacsen do not open an endless ``string'' at the first quote.
14933 For the same reasons, avoid:
14935 @example
14936 test $[#] != 0
14937 @end example
14939 @noindent
14940 and use:
14942 @example
14943 test $[@@%:@@] != 0
14944 @end example
14946 @noindent
14947 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
14948 breaking the bracket-matching highlighting from Emacsen.  Note the
14949 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
14950 not escape when it is unnecessary.  Common examples of useless quotation
14951 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
14952 etc.  If you add portability issues to the picture, you'll prefer
14953 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
14954 better than hacking Autoconf @code{:-)}.
14956 When using @command{sed}, don't use @option{-e} except for indenting
14957 purposes.  With the @code{s} and @code{y} commands, the preferred
14958 separator is @samp{/} unless @samp{/} itself might appear in the pattern
14959 or replacement, in which case you should use @samp{|}, or optionally
14960 @samp{,} if you know the pattern and replacement cannot contain a file
14961 name.  If none of these characters will do, choose a printable character
14962 that cannot appear in the pattern or replacement.  Characters from the
14963 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
14964 replacement might contain a file name, since they have special meaning
14965 to the shell and are less likely to occur in file names.
14967 @xref{Macro Definitions}, for details on how to define a macro.  If a
14968 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
14969 of an @code{AC_REQUIRE} directive, and macros required by other macros
14970 inside arguments do not need to be expanded before this macro, then
14971 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
14972 Also take into account that public third-party macros need to use
14973 @code{AC_DEFUN} in order to be found by @command{aclocal}
14974 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14975 All the @code{AC_REQUIRE} statements should be at the beginning of the
14976 macro, and each statement should be followed by @code{dnl}.
14978 You should not rely on the number of arguments: instead of checking
14979 whether an argument is missing, test that it is not empty.  It provides
14980 both a simpler and a more predictable interface to the user, and saves
14981 room for further arguments.
14983 Unless the macro is short, try to leave the closing @samp{])} at the
14984 beginning of a line, followed by a comment that repeats the name of the
14985 macro being defined.  This introduces an additional newline in
14986 @command{configure}; normally, that is not a problem, but if you want to
14987 remove it you can use @samp{[]dnl} on the last line.  You can similarly
14988 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
14989 is recommended instead of @samp{dnl} to ensure that M4 does not
14990 interpret the @samp{dnl} as being attached to the preceding text or
14991 macro output.  For example, instead of:
14993 @example
14994 AC_DEFUN([AC_PATH_X],
14995 [AC_MSG_CHECKING([for X])
14996 AC_REQUIRE_CPP()
14997 @r{# @dots{}omitted@dots{}}
14998   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14999 fi])
15000 @end example
15002 @noindent
15003 you would write:
15005 @example
15006 AC_DEFUN([AC_PATH_X],
15007 [AC_REQUIRE_CPP()[]dnl
15008 AC_MSG_CHECKING([for X])
15009 @r{# @dots{}omitted@dots{}}
15010   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15011 fi[]dnl
15012 ])# AC_PATH_X
15013 @end example
15015 If the macro is long, try to split it into logical chunks.  Typically,
15016 macros that check for a bug in a function and prepare its
15017 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
15018 this setup.  Do not hesitate to introduce auxiliary macros to factor
15019 your code.
15021 In order to highlight the recommended coding style, here is a macro
15022 written the old way:
15024 @example
15025 dnl Check for EMX on OS/2.
15026 dnl _AC_EMXOS2
15027 AC_DEFUN(_AC_EMXOS2,
15028 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
15029 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
15030 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
15031 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
15032 @end example
15034 @noindent
15035 and the new way:
15037 @example
15038 # _AC_EMXOS2
15039 # ----------
15040 # Check for EMX on OS/2.
15041 m4_define([_AC_EMXOS2],
15042 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15043 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15044                    [ac_cv_emxos2=yes],
15045                    [ac_cv_emxos2=no])])
15046 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
15047 ])# _AC_EMXOS2
15048 @end example
15053 @c ============================================= Portable Shell Programming
15055 @node Portable Shell
15056 @chapter Portable Shell Programming
15057 @cindex Portable shell programming
15059 When writing your own checks, there are some shell-script programming
15060 techniques you should avoid in order to make your code portable.  The
15061 Bourne shell and upward-compatible shells like the Korn shell and Bash
15062 have evolved over the years, and many features added to the original
15063 System7 shell are now supported on all interesting porting targets.
15064 However, the following discussion between Russ Allbery and Robert Lipe
15065 is worth reading:
15067 @noindent
15068 Russ Allbery:
15070 @quotation
15071 The GNU assumption that @command{/bin/sh} is the one and only shell
15072 leads to a permanent deadlock.  Vendors don't want to break users'
15073 existing shell scripts, and there are some corner cases in the Bourne
15074 shell that are not completely compatible with a Posix shell.  Thus,
15075 vendors who have taken this route will @emph{never} (OK@dots{}``never say
15076 never'') replace the Bourne shell (as @command{/bin/sh}) with a
15077 Posix shell.
15078 @end quotation
15080 @noindent
15081 Robert Lipe:
15083 @quotation
15084 This is exactly the problem.  While most (at least most System V's) do
15085 have a Bourne shell that accepts shell functions most vendor
15086 @command{/bin/sh} programs are not the Posix shell.
15088 So while most modern systems do have a shell @emph{somewhere} that meets the
15089 Posix standard, the challenge is to find it.
15090 @end quotation
15092 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15093 is to find such a shell.  But to prevent trouble, if you're not using
15094 M4sh you should not take advantage of features that were added after Unix
15095 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15096 negated character classes, or even @command{unset}.  @code{#} comments,
15097 while not in Unix version 7, were retrofitted in the original Bourne
15098 shell and can be assumed to be part of the least common denominator.
15100 On the other hand, if you're using M4sh you can assume that the shell
15101 has the features that were added in SVR2 (circa 1984), including shell
15102 functions,
15103 @command{return}, @command{unset}, and I/O redirection for builtins.  For
15104 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15105 However, some pitfalls have to be avoided for portable use of these
15106 constructs; these will be documented in the rest of this chapter.
15107 See in particular @ref{Shell Functions} and @ref{Limitations of
15108 Builtins, , Limitations of Shell Builtins}.
15110 Some ancient systems have quite
15111 small limits on the length of the @samp{#!} line; for instance, 32
15112 bytes (not including the newline) on SunOS 4.
15113 However, these ancient systems are no longer of practical concern.
15115 The set of external programs you should run in a @command{configure} script
15116 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
15117 Makefiles, standards, The GNU Coding Standards}, for the list.  This
15118 restriction allows users to start out with a fairly small set of
15119 programs and build the rest, avoiding too many interdependencies between
15120 packages.
15122 Some of these external utilities have a portable subset of features; see
15123 @ref{Limitations of Usual Tools}.
15125 There are other sources of documentation about shells.  The
15126 specification for the Posix
15127 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
15128 Command Language}, though more generous than the restrictive shell
15129 subset described above, is fairly portable nowadays.  Also please see
15130 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15132 @menu
15133 * Shellology::                  A zoology of shells
15134 * Invoking the Shell::          Invoking the shell as a command
15135 * Here-Documents::              Quirks and tricks
15136 * File Descriptors::            FDs and redirections
15137 * Signal Handling::             Shells, signals, and headaches
15138 * File System Conventions::     File names
15139 * Shell Pattern Matching::      Pattern matching
15140 * Shell Substitutions::         Variable and command expansions
15141 * Assignments::                 Varying side effects of assignments
15142 * Parentheses::                 Parentheses in shell scripts
15143 * Slashes::                     Slashes in shell scripts
15144 * Special Shell Variables::     Variables you should not change
15145 * Shell Functions::             What to look out for if you use them
15146 * Limitations of Builtins::     Portable use of not so portable /bin/sh
15147 * Limitations of Usual Tools::  Portable use of portable tools
15148 @end menu
15150 @node Shellology
15151 @section Shellology
15152 @cindex Shellology
15154 There are several families of shells, most prominently the Bourne family
15155 and the C shell family which are deeply incompatible.  If you want to
15156 write portable shell scripts, avoid members of the C shell family.  The
15157 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15158 Shell difference FAQ} includes a small history of Posix shells, and a
15159 comparison between several of them.
15161 Below we describe some of the members of the Bourne shell family.
15163 @table @asis
15164 @item Ash
15165 @cindex Ash
15166 Ash is often used on GNU/Linux and BSD
15167 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
15168 bugs that are fixed in the 0.3.x series, but portable shell scripts
15169 should work around them, since version 0.2 is still shipped with many
15170 GNU/Linux distributions.
15172 To be compatible with Ash 0.2:
15174 @itemize @minus
15175 @item
15176 don't use @samp{$?} after expanding empty or unset variables,
15177 or at the start of an @command{eval}:
15179 @example
15180 foo=
15181 false
15182 $foo
15183 echo "Do not use it: $?"
15184 false
15185 eval 'echo "Do not use it: $?"'
15186 @end example
15188 @item
15189 don't use command substitution within variable expansion:
15191 @example
15192 cat $@{FOO=`bar`@}
15193 @end example
15195 @item
15196 beware that single builtin substitutions are not performed by a
15197 subshell, hence their effect applies to the current shell!  @xref{Shell
15198 Substitutions}, item ``Command Substitution''.
15199 @end itemize
15201 @item Bash
15202 @cindex Bash
15203 To detect whether you are running Bash, test whether
15204 @code{BASH_VERSION} is set.  To require
15205 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
15206 Mode, , Bash Posix Mode, bash, The GNU Bash Reference
15207 Manual}, for details.
15209 @item Bash 2.05 and later
15210 @cindex Bash 2.05 and later
15211 Versions 2.05 and later of Bash use a different format for the
15212 output of the @command{set} builtin, designed to make evaluating its
15213 output easier.  However, this output is not compatible with earlier
15214 versions of Bash (or with many other shells, probably).  So if
15215 you use Bash 2.05 or higher to execute @command{configure},
15216 you'll need to use Bash 2.05 for all other build tasks as well.
15218 @item Ksh
15219 @cindex Ksh
15220 @cindex Korn shell
15221 @prindex @samp{ksh}
15222 @prindex @samp{ksh88}
15223 @prindex @samp{ksh93}
15224 The Korn shell is compatible with the Bourne family and it mostly
15225 conforms to Posix.  It has two major variants commonly
15226 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15227 release.  It is usually called @command{ksh}, but is called @command{sh}
15228 on some hosts if you set your path appropriately.
15230 Solaris systems have three variants:
15231 @prindex @command{/usr/bin/ksh} on Solaris
15232 @command{/usr/bin/ksh} is @samp{ksh88}; it is
15233 standard on Solaris 2.0 and later.
15234 @prindex @command{/usr/xpg4/bin/sh} on Solaris
15235 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
15236 @samp{ksh88}; it is standard on Solaris 9 and later.
15237 @prindex @command{/usr/dt/bin/dtksh} on Solaris
15238 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15239 Variants that are not standard may be parts of optional
15240 packages.  There is no extra charge for these packages, but they are
15241 not part of a minimal OS install and therefore some installations may
15242 not have it.
15244 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
15245 is also available as @command{/usr/bin/posix/sh}.  If the environment
15246 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15247 the standard shell conform to Posix.
15249 @item Pdksh
15250 @prindex @samp{pdksh}
15251 A public-domain clone of the Korn shell called @command{pdksh} is widely
15252 available: it has most of the @samp{ksh88} features along with a few of
15253 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
15254 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15255 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
15256 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
15257 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
15258 at least one respect, see @ref{Shell Substitutions}.
15260 @item Zsh
15261 @cindex Zsh
15262 To detect whether you are running @command{zsh}, test whether
15263 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
15264 compatible with the Bourne shell: you must execute @samp{emulate sh},
15265 and for @command{zsh} versions before 3.1.6-dev-18 you must also
15266 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
15267 zsh, The Z Shell Manual}, for details.
15269 The default Mac OS X @command{sh} was originally Zsh; it was changed to
15270 Bash in Mac OS X 10.2.
15271 @end table
15273 @node Invoking the Shell
15274 @section Invoking the Shell
15275 @cindex invoking the shell
15276 @cindex shell invocation
15278 The Korn shell (up to at least version M-12/28/93d) has a bug when
15279 invoked on a file whose name does not contain a slash.  It first
15280 searches for the file's name in @env{PATH}, and if found it executes
15281 that rather than the original file.  For example, assuming there is a
15282 binary executable @file{/usr/bin/script} in your @env{PATH}, the last
15283 command in the following example fails because the Korn shell finds
15284 @file{/usr/bin/script} and refuses to execute it as a shell script:
15286 @example
15287 $ @kbd{touch xxyzzyz script}
15288 $ @kbd{ksh xxyzzyz}
15289 $ @kbd{ksh ./script}
15290 $ @kbd{ksh script}
15291 ksh: script: cannot execute
15292 @end example
15294 Bash 2.03 has a bug when invoked with the @option{-c} option: if the
15295 option-argument ends in backslash-newline, Bash incorrectly reports a
15296 syntax error.  The problem does not occur if a character follows the
15297 backslash:
15299 @example
15300 $ @kbd{$ bash -c 'echo foo \}
15301 > @kbd{'}
15302 bash: -c: line 2: syntax error: unexpected end of file
15303 $ @kbd{bash -c 'echo foo \}
15304 > @kbd{ '}
15306 @end example
15308 @noindent
15309 @xref{Backslash-Newline-Empty}, for how this can cause problems in makefiles.
15311 @node Here-Documents
15312 @section Here-Documents
15313 @cindex Here-documents
15314 @cindex Shell here-documents
15316 Don't rely on @samp{\} being preserved just because it has no special
15317 meaning together with the next symbol.  In the native @command{sh}
15318 on OpenBSD 2.7 @samp{\"} expands to @samp{"} in here-documents with
15319 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
15320 use @samp{\\} to get @samp{\}.
15322 With OpenBSD 2.7's @command{sh}
15324 @example
15325 @group
15326 $ @kbd{cat <<EOF
15327 > \" \\
15328 > EOF}
15329 " \
15330 @end group
15331 @end example
15333 @noindent
15334 and with Bash:
15336 @example
15337 @group
15338 bash-2.04$ @kbd{cat <<EOF
15339 > \" \\
15340 > EOF}
15341 \" \
15342 @end group
15343 @end example
15345 Using command substitutions in a here-document that is fed to a shell
15346 function is not portable.  For example, with Solaris 10 @command{/bin/sh}:
15348 @example
15349 $ @kbd{kitty () @{ cat; @}}
15350 $ @kbd{kitty <<EOF
15351 > `echo ok`
15352 > EOF}
15353 /tmp/sh199886: cannot open
15354 $ @kbd{echo $?}
15356 @end example
15358 Some shells mishandle large here-documents: for example,
15359 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
15360 derived from Korn shell version M-12/28/93d, mishandle braced variable
15361 expansion that crosses a 1024- or 4096-byte buffer boundary
15362 within a here-document.  Only the part of the variable name after the boundary
15363 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
15364 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
15365 boundary, the shell reports an error, as if you used @code{$@{@}}.
15366 Instead of @code{$@{variable-default@}}, the shell may expand
15367 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
15368 be worked around by omitting the braces: @code{$variable}.  The bug was
15369 fixed in
15370 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15371 still shipping older versions with the bug.
15373 Empty here-documents are not portable either; with the following code,
15374 @command{zsh} up to at least version 4.3.10 creates a file with a single
15375 newline, whereas other shells create an empty file:
15377 @example
15378 cat >file <<EOF
15380 @end example
15382 Many shells (including the Bourne shell) implement here-documents
15383 inefficiently.  In particular, some shells can be extremely inefficient when
15384 a single statement contains many here-documents.  For instance if your
15385 @file{configure.ac} includes something like:
15387 @example
15388 @group
15389 if <cross_compiling>; then
15390   assume this and that
15391 else
15392   check this
15393   check that
15394   check something else
15395   @dots{}
15396   on and on forever
15397   @dots{}
15399 @end group
15400 @end example
15402 A shell parses the whole @code{if}/@code{fi} construct, creating
15403 temporary files for each here-document in it.  Some shells create links
15404 for such here-documents on every @code{fork}, so that the clean-up code
15405 they had installed correctly removes them.  It is creating the links
15406 that can take the shell forever.
15408 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15409 @code{if}/@code{fi} constructs, would improve the performance
15410 significantly.  Anyway, this kind of construct is not exactly the
15411 typical use of Autoconf.  In fact, it's even not recommended, because M4
15412 macros can't look into shell conditionals, so we may fail to expand a
15413 macro when it was expanded before in a conditional path, and the
15414 condition turned out to be false at runtime, and we end up not
15415 executing the macro at all.
15417 Be careful with the use of @samp{<<-} to unindent here-documents.  The
15418 behavior is only portable for stripping leading @key{TAB}s, and things
15419 can silently break if an overzealous editor converts to using leading
15420 spaces (not all shells are nice enough to warn about unterminated
15421 here-documents).
15423 @example
15424 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
15427 done
15428 $ @kbd{printf 'cat <<-x\n 1\n  2\n x\n' | bash-3.2 && echo done}
15430   2
15432 done
15433 @end example
15435 @node File Descriptors
15436 @section File Descriptors
15437 @cindex Descriptors
15438 @cindex File descriptors
15439 @cindex Shell file descriptors
15441 Most shells, if not all (including Bash, Zsh, Ash), output traces on
15442 stderr, even for subshells.  This might result in undesirable content
15443 if you meant to capture the standard-error output of the inner command:
15445 @example
15446 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15447 $ @kbd{cat stderr}
15448 + eval echo foo >&2
15449 + echo foo
15451 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15452 $ @kbd{cat stderr}
15453 + eval 'echo foo >&2'
15454 ++ echo foo
15456 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15457 @i{# Traces on startup files deleted here.}
15458 $ @kbd{cat stderr}
15459 +zsh:1> eval echo foo >&2
15460 +zsh:1> echo foo
15462 @end example
15464 @noindent
15465 One workaround is to grep out uninteresting lines, hoping not to remove
15466 good ones.
15468 If you intend to redirect both standard error and standard output,
15469 redirect standard output first.  This works better with HP-UX,
15470 since its shell mishandles tracing if standard error is redirected
15471 first:
15473 @example
15474 $ @kbd{sh -x -c ': 2>err >out'}
15475 + :
15476 + 2> err $ @kbd{cat err}
15477 1> out
15478 @end example
15480 Don't try to redirect the standard error of a command substitution.  It
15481 must be done @emph{inside} the command substitution.  When running
15482 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15483 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15485 On the other hand, some shells, such as Solaris or FreeBSD
15486 @command{/bin/sh}, warn about missing programs before performing
15487 redirections.  Therefore, to silently check whether a program exists, it
15488 is necessary to perform redirections on a subshell or brace group:
15489 @example
15490 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15491 nosuch: not found
15492 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15493 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15494 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15495 @end example
15497 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15498 shell pipeline.
15500 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15501 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15503 Some shells, like @command{ash}, don't recognize bi-directional
15504 redirection (@samp{<>}).  And even on shells that recognize it, it is
15505 not portable to use on fifos: Posix does not require read-write support
15506 for named pipes, and Cygwin does not support it:
15508 @example
15509 $ @kbd{mkfifo fifo}
15510 $ @kbd{exec 5<>fifo}
15511 $ @kbd{echo hi >&5}
15512 bash: echo: write error: Communication error on send
15513 @end example
15515 @noindent
15516 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15517 regular files when using @samp{<>}:
15519 @example
15520 $ @kbd{echo a > file}
15521 $ @kbd{bash -c ': 1<>file'; cat file}
15523 $ @kbd{dash -c ': 1<>file'; cat file}
15524 $ rm a
15525 @end example
15527 When catering to old systems, don't redirect the same file descriptor
15528 several times, as you are doomed to failure under Ultrix.
15530 @example
15531 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
15532 UWS V4.4 (Rev. 11)
15533 $ @kbd{eval 'echo matter >fullness' >void}
15534 illegal io
15535 $ @kbd{eval '(echo matter >fullness)' >void}
15536 illegal io
15537 $ @kbd{(eval '(echo matter >fullness)') >void}
15538 Ambiguous output redirect.
15539 @end example
15541 @noindent
15542 In each case the expected result is of course @file{fullness} containing
15543 @samp{matter} and @file{void} being empty.  However, this bug is
15544 probably not of practical concern to modern platforms.
15546 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15547 (even if it is redirected) in a loop after the first iteration, or in a
15548 shell function after the first call:
15550 @example
15551 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15552 $ @kbd{ls x*}
15554 $ @kbd{f () @{ : >$1; @}; f y1; f y2; f y3;}
15555 $ @kbd{ls y*}
15557 @end example
15559 @noindent
15560 As a workaround, @command{echo} or @command{eval} can be used.
15562 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15563 subsidiary program.  If any of these descriptors is closed, the
15564 operating system may open an unspecified file for the descriptor in the
15565 new process image.  Posix 2008 says this may be done only if the
15566 subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15567 it even for ordinary programs, and the next version of Posix will allow
15568 HP-UX behavior.
15570 If you want a file descriptor above 2 to be inherited into a child
15571 process, then you must use redirections specific to that command or a
15572 containing subshell or command group, rather than relying on
15573 @command{exec} in the shell. In @command{ksh} as well as HP-UX
15574 @command{sh}, file descriptors above 2 which are opened using
15575 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15576 that involved in the fork-and-exec which runs a program or script):
15578 @example
15579 $ @kbd{echo 'echo hello >&5' >k}
15580 $ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15581 hello
15582 $ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15583 hello
15584 $ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15585 ./k[1]: 5: cannot open [Bad file number]
15586 $ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
15587 hello
15588 $ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
15589 hello
15590 $ @kbd{ksh -c '5>t ksh ./k; cat t}
15591 hello
15592 @end example
15594 Don't rely on duplicating a closed file descriptor to cause an
15595 error.  With Solaris @command{/bin/sh}, failed duplication is silently
15596 ignored, which can cause unintended leaks to the original file
15597 descriptor.  In this example, observe the leak to standard output:
15599 @example
15600 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15601 bash: 3: Bad file descriptor
15603 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15606 @end example
15608 Fortunately, an attempt to close an already closed file descriptor will
15609 portably succeed.  Likewise, it is safe to use either style of
15610 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15611 even if it doesn't match the read/write mode that the file descriptor
15612 was opened with.
15614 DOS variants cannot rename or remove open files, such as in
15615 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15616 perfectly portable among Posix hosts.
15618 A few ancient systems reserved some file descriptors.  By convention,
15619 file descriptor 3 was opened to @file{/dev/tty} when you logged into
15620 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
15621 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
15622 1990), though we don't now remember what it was.  Both these systems are
15623 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15624 other file descriptors.
15626 On the other hand, you can't portably use multi-digit file descriptors.
15627 Solaris @command{ksh} doesn't understand any file descriptor larger than
15628 @samp{9}:
15630 @example
15631 $ @kbd{bash -c 'exec 10>&-'; echo $?}
15633 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
15635 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
15636 ksh[1]: exec: 10: not found
15638 @end example
15640 @c <http://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
15641 @node Signal Handling
15642 @section Signal Handling
15643 @cindex Signal handling in the shell
15644 @cindex Signals, shells and
15646 Portable handling of signals within the shell is another major source of
15647 headaches.  This is worsened by the fact that various different, mutually
15648 incompatible approaches are possible in this area, each with its
15649 distinctive merits and demerits.  A detailed description of these possible
15650 approaches, as well as of their pros and cons, can be found in
15651 @uref{http://www.cons.org/cracauer/sigint.html, this article}.
15653 Solaris 10 @command{/bin/sh} automatically traps most signals by default;
15654 @c See: <http://dbaspot.com/shell/396118-bourne-shell-exit-code-term.html>
15655 the shell still exits with error upon termination by one of those signals,
15656 but in such a case the exit status might be somewhat unexpected (even if
15657 allowed by POSIX, strictly speaking):
15659 @example
15660 $ @kbd{bash -c 'kill -1 $$'; echo $?} # Will exit 128 + (signal number).
15661 Hangup
15663 $ @kbd{/bin/ksh -c 'kill -15 $$'; echo $?} # Likewise.
15664 Terminated
15666 $ @kbd{for sig in 1 2 3 15; do}
15667 > @kbd{  echo $sig:}
15668 > @kbd{  /bin/sh -c "kill -$s \$\$"; echo $?}
15669 > @kbd{done}
15670 signal 1:
15671 Hangup
15673 signal 2:
15675 signal 3:
15677 signal 15:
15679 @end example
15681 This gets even worse if one is using the POSIX ``wait'' interface to get
15682 details about the shell process terminations: it will result in the shell
15683 having exited normally, rather than by receiving a signal.
15685 @example
15686 $ @kbd{cat > foo.c <<'END'}
15687 #include <stdio.h>    /* for printf */
15688 #include <stdlib.h>   /* for system */
15689 #include <sys/wait.h> /* for WIF* macros */
15690 int main(void)
15692   int status = system ("kill -15 $$");
15693   printf ("Terminated by signal: %s\n",
15694           WIFSIGNALED (status) ? "yes" : "no");
15695   printf ("Exited normally: %s\n",
15696           WIFEXITED (status) ? "yes" : "no");
15697   return 0;
15700 @c $$ font-lock
15701 $ @kbd{cc -o foo foo.c}
15702 $ @kbd{./a.out} # On GNU/Linux
15703 Terminated by signal: no
15704 Exited normally: yes
15705 $ @kbd{./a.out} # On Solaris 10
15706 Terminated by signal: yes
15707 Exited normally: no
15708 @end example
15710 Various shells seem to handle @code{SIGQUIT} specially: they ignore it even
15711 if it is not blocked, and even if the shell is not running interactively
15712 (in fact, even if the shell has no attached tty); among these shells
15713 are at least Bash (from version 2 onwards), Zsh 4.3.12, Solaris 10
15714 @code{/bin/ksh} and @code{/usr/xpg4/bin/sh}, and AT&T @code{ksh93} (2011).
15715 Still, @code{SIGQUIT} seems to be trappable quite portably within all
15716 these shells.  OTOH, some other shells doesn't special-case the handling
15717 of @code{SIGQUIT}; among these shells are at least @code{pdksh} 5.2.14,
15718 Solaris 10 and NetBSD 5.1 @code{/bin/sh}, and the Almquist Shell 0.5.5.1.
15720 @c See: <http://mail.opensolaris.org/pipermail/ksh93-integration-discuss/2009-February/004121.html>
15721 Some shells (especially Korn shells and derivatives) might try to
15722 propagate to themselves a signal that has killed a child process; this is
15723 not a bug, but a conscious design choice (although its overall value might
15724 be debatable).  The exact details of how this is attained vary from shell
15725 to shell.  For example, upon running @code{perl -e 'kill 2, $$'}, after
15726 the perl process has been interrupted AT&T @code{ksh93} (2011) will
15727 proceed to send itself a @code{SIGINT}, while Solaris 10 @code{/bin/ksh}
15728 and @code{/usr/xpg4/bin/sh} will proceed to exit with status 130 (i.e.,
15729 128 + 2). In any case, if there is an active trap associated with
15730 @code{SIGINT}, those shells will correctly execute it.
15732 @c See: <http://www.austingroupbugs.net/view.php?id=51>
15733 Some Korn shells, when a child process die due receiving a signal with
15734 signal number @var{n}, can leave in @samp{$?} an exit status of
15735 256+@var{n} instead of the more common 128+@var{n}.  Observe the
15736 difference between AT&T @code{ksh93} (2011) and @code{bash} 4.1.5 on
15737 Debian:
15739 @example
15740 $ @kbd{/bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?'}
15741 /bin/ksh: line 1: 7837: Hangup
15743 $ @kbd{/bin/bash -c 'sh -c "kill -1 \$\$"; echo $?'}
15744 /bin/bash: line 1:  7861 Hangup        (sh -c "kill -1 \$\$")
15746 @end example
15748 @noindent
15749 This @command{ksh} behavior is allowed by POSIX, if implemented with
15750 due care; see this @uref{http://www.austingroupbugs.net/view.php?id=51,
15751 Austin Group discussion} for more background.  However, if it is not
15752 implemented with proper care, such a behavior might cause problems
15753 in some corner cases.  To see why, assume we have a ``wrapper'' script
15754 like this:
15756 @example
15757 #!/bin/sh
15758 # Ignore some signals in the shell only, not in its child processes.
15759 trap : 1 2 13 15
15760 wrapped_command "$@@"
15761 ret=$?
15762 other_command
15763 exit $ret
15764 @end example
15766 @noindent
15767 If @command{wrapped_command} is interrupted by a @code{SIGHUP} (which
15768 has signal number 1), @code{ret} will be set to 257.  Unless the
15769 @command{exit} shell builtin is smart enough to understand that such
15770 a value can only have originated from a signal, and adjust the final
15771 wait status of the shell appropriately, the value 257 will just get
15772 truncated to 1 by the closing @code{exit} call, so that a caller of
15773 the script will have no way to determine that termination by a signal
15774 was involved.  Observe the different behavior of AT&T @code{ksh93}
15775 (2011) and @code{bash} 4.1.5 on Debian:
15777 @example
15778 $ @kbd{cat foo.sh}
15779 #!/bin/sh
15780 sh -c 'kill -1 $$'
15781 ret=$?
15782 echo $ret
15783 exit $ret
15784 $ @kbd{/bin/ksh foo.sh; echo $?}
15785 foo.sh: line 2: 12479: Hangup
15788 $ @kbd{/bin/bash foo.sh; echo $?}
15789 foo.sh: line 2: 12487 Hangup        (sh -c 'kill -1 $$')
15792 @end example
15794 @node File System Conventions
15795 @section File System Conventions
15796 @cindex File system conventions
15798 Autoconf uses shell-script processing extensively, so the file names
15799 that it processes should not contain characters that are special to the
15800 shell.  Special characters include space, tab, newline, NUL, and
15801 the following:
15803 @example
15804 " # $ & ' ( ) * ; < = > ? [ \ ` |
15805 @end example
15807 Also, file names should not begin with @samp{~} or @samp{-}, and should
15808 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
15809 immediately after @samp{:}.  On Posix-like platforms, directory names
15810 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
15811 path separator.
15813 These restrictions apply not only to the files that you distribute, but
15814 also to the absolute file names of your source, build, and destination
15815 directories.
15817 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
15818 they should be avoided.
15820 Posix lets implementations treat leading @file{//} specially, but
15821 requires leading @file{///} and beyond to be equivalent to @file{/}.
15822 Most Unix variants treat @file{//} like @file{/}.  However, some treat
15823 @file{//} as a ``super-root'' that can provide access to files that are
15824 not otherwise reachable from @file{/}.  The super-root tradition began
15825 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
15826 has revived it.
15828 While @command{autoconf} and friends are usually run on some Posix
15829 variety, they can be used on other systems, most notably DOS
15830 variants.  This impacts several assumptions regarding file names.
15832 @noindent
15833 For example, the following code:
15835 @example
15836 case $foo_dir in
15837   /*) # Absolute
15838      ;;
15839   *)
15840      foo_dir=$dots$foo_dir ;;
15841 esac
15842 @end example
15844 @noindent
15845 fails to properly detect absolute file names on those systems, because
15846 they can use a drivespec, and usually use a backslash as directory
15847 separator.  If you want to be portable to DOS variants (at the
15848 price of rejecting valid but oddball Posix file names like @file{a:\b}),
15849 you can check for absolute file names like this:
15851 @cindex absolute file names, detect
15852 @example
15853 case $foo_dir in
15854   [\\/]* | ?:[\\/]* ) # Absolute
15855      ;;
15856   *)
15857      foo_dir=$dots$foo_dir ;;
15858 esac
15859 @end example
15861 @noindent
15862 Make sure you quote the brackets if appropriate and keep the backslash as
15863 first character (@pxref{case, , Limitations of Shell Builtins}).
15865 Also, because the colon is used as part of a drivespec, these systems don't
15866 use it as path separator.  When creating or accessing paths, you can use the
15867 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
15868 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
15869 starts up.
15871 File names need extra care as well.  While DOS variants
15872 that are Posixy enough to run @command{autoconf} (such as DJGPP)
15873 are usually able to handle long file names properly, there are still
15874 limitations that can seriously break packages.  Several of these issues
15875 can be easily detected by the
15876 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
15877 package.
15879 A short overview follows; problems are marked with SFN/LFN to
15880 indicate where they apply: SFN means the issues are only relevant to
15881 plain DOS, not to DOS under Microsoft Windows
15882 variants, while LFN identifies problems that exist even under
15883 Microsoft Windows variants.
15885 @table @asis
15886 @item No multiple dots (SFN)
15887 DOS cannot handle multiple dots in file names.  This is an especially
15888 important thing to remember when building a portable configure script,
15889 as @command{autoconf} uses a .in suffix for template files.
15891 This is perfectly OK on Posix variants:
15893 @example
15894 AC_CONFIG_HEADERS([config.h])
15895 AC_CONFIG_FILES([source.c foo.bar])
15896 AC_OUTPUT
15897 @end example
15899 @noindent
15900 but it causes problems on DOS, as it requires @samp{config.h.in},
15901 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
15902 to DOS-based environments, you should use this instead:
15904 @example
15905 AC_CONFIG_HEADERS([config.h:config.hin])
15906 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
15907 AC_OUTPUT
15908 @end example
15910 @item No leading dot (SFN)
15911 DOS cannot handle file names that start with a dot.  This is usually
15912 not important for @command{autoconf}.
15914 @item Case insensitivity (LFN)
15915 DOS is case insensitive, so you cannot, for example, have both a
15916 file called @samp{INSTALL} and a directory called @samp{install}.  This
15917 also affects @command{make}; if there's a file called @samp{INSTALL} in
15918 the directory, @samp{make install} does nothing (unless the
15919 @samp{install} target is marked as PHONY).
15921 @item The 8+3 limit (SFN)
15922 Because the DOS file system only stores the first 8 characters of
15923 the file name and the first 3 of the extension, those must be unique.
15924 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
15925 @file{foobar-prettybird.c} all resolve to the same file name
15926 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
15927 @file{foo.bartender}.
15929 The 8+3 limit is not usually a problem under Microsoft Windows, as it
15930 uses numeric
15931 tails in the short version of file names to make them unique.  However, a
15932 registry setting can turn this behavior off.  While this makes it
15933 possible to share file trees containing long file names between SFN
15934 and LFN environments, it also means the above problem applies there
15935 as well.
15937 @item Invalid characters (LFN)
15938 Some characters are invalid in DOS file names, and should therefore
15939 be avoided.  In a LFN environment, these are @samp{/}, @samp{\},
15940 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
15941 In a SFN environment, other characters are also invalid.  These
15942 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
15944 @item Invalid names (LFN)
15945 Some DOS file names are reserved, and cause problems if you
15946 try to use files with those names.  These names include @file{CON},
15947 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
15948 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
15949 File names are case insensitive, so even names like
15950 @file{aux/config.guess} are disallowed.
15952 @end table
15954 @node Shell Pattern Matching
15955 @section Shell Pattern Matching
15956 @cindex Shell pattern matching
15958 Nowadays portable patterns can use negated character classes like
15959 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
15960 some shells but not others; hence portable scripts should never use
15961 @samp{^} as the first character of a bracket pattern.
15963 Outside the C locale, patterns like @samp{[a-z]} are problematic since
15964 they may match characters that are not lower-case letters.
15966 @node Shell Substitutions
15967 @section Shell Substitutions
15968 @cindex Shell substitutions
15970 Contrary to a persistent urban legend, the Bourne shell does not
15971 systematically split variables and back-quoted expressions, in particular
15972 on the right-hand side of assignments and in the argument of @code{case}.
15973 For instance, the following code:
15975 @example
15976 case "$given_srcdir" in
15977 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
15978 *)  top_srcdir="$dots$given_srcdir" ;;
15979 esac
15980 @end example
15982 @noindent
15983 is more readable when written as:
15985 @example
15986 case $given_srcdir in
15987 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
15988 *)  top_srcdir=$dots$given_srcdir ;;
15989 esac
15990 @end example
15992 @noindent
15993 and in fact it is even @emph{more} portable: in the first case of the
15994 first attempt, the computation of @code{top_srcdir} is not portable,
15995 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
15996 for example Solaris 10 ksh:
15998 @example
15999 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
16000 ksh: : cannot execute
16001 ksh: bar | sed 's, ,,': cannot execute
16002 @end example
16004 @noindent
16005 Posix does not specify behavior for this sequence.  On the other hand,
16006 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by Posix,
16007 but in practice, not all shells understand it the same way: pdksh 5.2.14
16008 prints spurious quotes when in Posix mode:
16010 @example
16011 $ @kbd{echo "`echo \"hello\"`"}
16012 hello
16013 $ @kbd{set -o posix}
16014 $ @kbd{echo "`echo \"hello\"`"}
16015 "hello"
16016 @end example
16018 @noindent
16019 There is just no portable way to use double-quoted strings inside
16020 double-quoted back-quoted expressions (pfew!).
16022 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
16023 parameter expansions are elided during word splitting.  Meanwhile, zsh
16024 does not perform word splitting except when in Bourne compatibility
16025 mode.  In the example below, the correct behavior is to have five
16026 arguments to the function, and exactly two spaces on either side of the
16027 middle @samp{-}, since word splitting collapses multiple spaces in
16028 @samp{$f} but leaves empty arguments intact.
16030 @example
16031 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16032 3- - -
16033 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16034 5-  -  -
16035 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16036 3-   -   -
16037 $ @kbd{zsh -c 'emulate sh;}
16038 > @kbd{n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16039 5-  -  -
16040 @end example
16042 @noindent
16043 You can work around this by doing manual word splitting, such as using
16044 @samp{"$str" $list} rather than @samp{"$str"$list}.
16046 There are also portability pitfalls with particular expansions:
16048 @table @code
16049 @item $@@
16050 @cindex @code{"$@@"}
16051 One of the most famous shell-portability issues is related to
16052 @samp{"$@@"}.  When there are no positional arguments, Posix says
16053 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
16054 original Unix version 7 Bourne shell treated it as equivalent to
16055 @samp{""} instead, and this behavior survives in later implementations
16056 like Digital Unix 5.0.
16058 The traditional way to work around this portability problem is to use
16059 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
16060 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
16061 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
16063 @example
16064 zsh $ @kbd{emulate sh}
16065 zsh $ @kbd{for i in "$@@"; do echo $i; done}
16066 Hello World
16068 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
16069 Hello
16070 World
16072 @end example
16074 @noindent
16075 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
16076 @samp{"$@@"} because of the portability problems mentioned above.
16077 One workaround relies on Zsh's ``global aliases'' to convert
16078 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
16080 @example
16081 test $@{ZSH_VERSION+y@} && alias -g '$@{1+"$@@"@}'='"$@@"'
16082 @end example
16084 Zsh only recognizes this alias when a shell word matches it exactly;
16085 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
16086 case always yields at least one shell word, use plain @samp{"$@@"}.
16088 A more conservative workaround is to avoid @samp{"$@@"} if it is
16089 possible that there may be no positional arguments.  For example,
16090 instead of:
16092 @example
16093 cat conftest.c "$@@"
16094 @end example
16096 you can use this instead:
16098 @example
16099 case $# in
16100 0) cat conftest.c;;
16101 *) cat conftest.c "$@@";;
16102 esac
16103 @end example
16105 Autoconf macros often use the @command{set} command to update
16106 @samp{$@@}, so if you are writing shell code intended for
16107 @command{configure} you should not assume that the value of @samp{$@@}
16108 persists for any length of time.
16111 @item $@{10@}
16112 @cindex positional parameters
16113 The 10th, 11th, @dots{} positional parameters can be accessed only after
16114 a @code{shift}.  The 7th Edition shell reported an error if given
16115 @code{$@{10@}}, and
16116 Solaris 10 @command{/bin/sh} still acts that way:
16118 @example
16119 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
16120 $ @kbd{echo $@{10@}}
16121 bad substitution
16122 @end example
16124 Conversely, not all shells obey the Posix rule that when braces are
16125 omitted, multiple digits beyond a @samp{$} imply the single-digit
16126 positional parameter expansion concatenated with the remaining literal
16127 digits.  To work around the issue, you must use braces.
16129 @example
16130 $ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16131 a0 a0
16132 $ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16133 j a0
16134 @end example
16136 @item $@{@var{var}:-@var{value}@}
16137 @c Info cannot handle ':' in index entries.
16138 @ifnotinfo
16139 @cindex @code{$@{@var{var}:-@var{value}@}}
16140 @end ifnotinfo
16141 @cindex @code{$@{@var{var}-@var{value}@}}
16142 Old BSD shells, including the Ultrix @code{sh}, don't accept the
16143 colon for any shell substitution, and complain and die.
16144 Similarly for @code{$@{@var{var}:=@var{value}@}},
16145 @code{$@{@var{var}:?@var{value}@}}, etc.
16146 However, all shells that support functions allow the use of colon in
16147 shell substitution, and since m4sh requires functions, you can portably
16148 use null variable substitution patterns in configure scripts.
16150 @item $@{@var{var}+@var{value}@}
16151 @cindex @code{$@{@var{var}+@var{value}@}}
16152 When using @samp{$@{@var{var}-@var{value}@}} or
16153 @samp{$@{@var{var}-@var{value}@}} for providing alternate substitutions,
16154 @var{value} must either be a single shell word, quoted, or in the
16155 context of an unquoted here-document.  Solaris
16156 @command{/bin/sh} complains otherwise.
16158 @example
16159 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
16160 /bin/sh: bad substitution
16161 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
16162 b c
16163 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
16164 b c
16165 $ @kbd{/bin/sh -c 'cat <<EOF
16166 $@{a-b c@}
16167 EOF}
16168 b c
16169 @end example
16171 Most shells treat the special parameters @code{*} and @code{@@} as being
16172 unset if there are no positional parameters.  However, some shells treat
16173 them as being set to the empty string.  Posix does not clearly specify
16174 either behavior.
16176 @example
16177 $ @kbd{bash -c 'echo "* is $@{*-unset@}."'}
16178 * is unset.
16179 $ @kbd{dash -c 'echo "* is $@{*-unset@}."'}
16180 * is .
16181 @end example
16183 According to Posix, if an expansion occurs inside double quotes, then
16184 the use of unquoted double quotes within @var{value} is unspecified, and
16185 any single quotes become literal characters; in that case, escaping must
16186 be done with backslash.  Likewise, the use of unquoted here-documents is
16187 a case where double quotes have unspecified results:
16189 @example
16190 $ @kbd{/bin/sh -c 'echo "$@{a-"b  c"@}"'}
16191 /bin/sh: bad substitution
16192 $ @kbd{ksh -c 'echo "$@{a-"b  c"@}"'}
16193 b c
16194 $ @kbd{bash -c 'echo "$@{a-"b  c"@}"'}
16195 b  c
16196 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b  c'\''@}'}
16197 b  c
16198 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b  c'\''@}"'}
16199 'b  c'
16200 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b  c\"@}"'}
16201 "b  c"
16202 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b  c@}"'}
16203 b  c
16204 $ @kbd{/bin/sh -c 'cat <<EOF
16205 $@{a-"b  c"@}
16206 EOF'}
16207 "b  c"
16208 $ @kbd{/bin/sh -c 'cat <<EOF
16209 $@{a-'b  c'@}
16210 EOF'}
16211 'b  c'
16212 $ @kbd{bash -c 'cat <<EOF
16213 $@{a-"b  c"@}
16214 EOF'}
16215 b  c
16216 $ @kbd{bash -c 'cat <<EOF
16217 $@{a-'b  c'@}
16218 EOF'}
16219 'b  c'
16220 @end example
16222 Perhaps the easiest way to work around quoting issues in a manner
16223 portable to all shells is to place the results in a temporary variable,
16224 then use @samp{$t} as the @var{value}, rather than trying to inline
16225 the expression needing quoting.
16227 @example
16228 $ @kbd{/bin/sh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16229 b  c"'@}\
16230 $ @kbd{ksh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16231 b  c"'@}\
16232 $ @kbd{bash -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16233 b  c"'@}\
16234 @end example
16236 @item $@{@var{var}=@var{value}@}
16237 @cindex @code{$@{@var{var}=@var{value}@}}
16238 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
16239 to @var{var}, remember that even though the assignment to @var{var} does
16240 not undergo file name expansion, the result of the variable expansion
16241 does unless the expansion occurred within double quotes.  In particular,
16242 when using @command{:} followed by unquoted variable expansion for the
16243 side effect of setting a default value, if the final value of
16244 @samp{$var} contains any globbing characters (either from @var{value} or
16245 from prior contents), the shell has to spend time performing file name
16246 expansion and field splitting even though those results will not be
16247 used.  Therefore, it is a good idea to consider double quotes when performing
16248 default initialization; while remembering how this impacts any quoting
16249 characters appearing in @var{value}.
16251 @example
16252 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
16253 /usr/bin/*
16255 real    0m0.005s
16256 user    0m0.002s
16257 sys     0m0.003s
16258 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
16259 /usr/bin/*
16261 real    0m0.039s
16262 user    0m0.026s
16263 sys     0m0.009s
16264 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
16265 /usr/bin/*
16267 real    0m0.031s
16268 user    0m0.020s
16269 sys     0m0.010s
16271 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
16272 /usr/bin/*
16274 real    0m0.006s
16275 user    0m0.002s
16276 sys     0m0.003s
16277 @end example
16279 As with @samp{+} and @samp{-}, you must use quotes when using @samp{=}
16280 if the @var{value} contains more than one shell word; either single
16281 quotes for just the @var{value}, or double quotes around the entire
16282 expansion:
16284 @example
16285 $ @kbd{: $@{var1='Some words'@}}
16286 $ @kbd{: "$@{var2=like this@}"}
16287 $ @kbd{echo $var1 $var2}
16288 Some words like this
16289 @end example
16291 @noindent
16292 otherwise some shells, such as Solaris @command{/bin/sh} or on Digital
16293 Unix V 5.0, die because of a ``bad substitution''.  Meanwhile, Posix
16294 requires that with @samp{=}, quote removal happens prior to the
16295 assignment, and the expansion be the final contents of @var{var} without
16296 quoting (and thus subject to field splitting), in contrast to the
16297 behavior with @samp{-} passing the quoting through to the final
16298 expansion.  However, @command{bash} 4.1 does not obey this rule.
16300 @example
16301 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16302 a  b
16303 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16304 a b
16305 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16306 a  b
16307 @end example
16309 Finally, Posix states that when mixing @samp{$@{a=b@}} with regular
16310 commands, it is unspecified whether the assignments affect the parent
16311 shell environment.  It is best to perform assignments independently from
16312 commands, to avoid the problems demonstrated in this example:
16314 @example
16315 $ @kbd{bash -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16316 +b+b+
16318 $ @kbd{/bin/sh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16319 ++b+
16321 $ @kbd{ksh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16322 +b+b+
16324 @end example
16326 @item $@{@var{var}=@var{value}@}
16327 @cindex @code{$@{@var{var}=@var{literal}@}}
16328 Solaris @command{/bin/sh} has a frightening bug in its handling of
16329 literal assignments.  Imagine you need set a variable to a string containing
16330 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
16331 when the affected variable was already set.  This bug can be exercised
16332 by running:
16334 @example
16335 $ @kbd{unset foo}
16336 $ @kbd{foo=$@{foo='@}'@}}
16337 $ @kbd{echo $foo}
16339 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
16340 $ @kbd{echo $foo}
16342 $ @kbd{foo=$@{foo='@}'@}}
16343 $ @kbd{echo $foo}
16344 @}@}
16345  ^ ugh!
16346 @end example
16348 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16349 though it is enclosed in single quotes.  The problem doesn't happen
16350 using double quotes, or when using a temporary variable holding the
16351 problematic string.
16353 @item $@{@var{var}=@var{expanded-value}@}
16354 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
16355 On Ultrix,
16356 running
16358 @example
16359 default="yu,yaa"
16360 : $@{var="$default"@}
16361 @end example
16363 @noindent
16364 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
16365 each char is set.  You don't observe the phenomenon using a simple
16366 @samp{echo $var} since apparently the shell resets the 8th bit when it
16367 expands $var.  Here are two means to make this shell confess its sins:
16369 @example
16370 $ @kbd{cat -v <<EOF
16371 $var
16372 EOF}
16373 @end example
16375 @noindent
16378 @example
16379 $ @kbd{set | grep '^var=' | cat -v}
16380 @end example
16382 One classic incarnation of this bug is:
16384 @example
16385 default="a b c"
16386 : $@{list="$default"@}
16387 for c in $list; do
16388   echo $c
16389 done
16390 @end example
16392 @noindent
16393 You'll get @samp{a b c} on a single line.  Why?  Because there are no
16394 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
16395 bit set, hence no IFS splitting is performed!!!
16397 One piece of good news is that Ultrix works fine with @samp{:
16398 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
16399 then that QNX 4.25 then sets @var{list} to the @emph{last} item of
16400 @var{default}!
16402 The portable way out consists in using a double assignment, to switch
16403 the 8th bit twice on Ultrix:
16405 @example
16406 list=$@{list="$default"@}
16407 @end example
16409 @noindent
16410 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
16411 use:
16413 @example
16414 test $@{var+y@} || var=@var{@{value@}}
16415 @end example
16417 @item $@{#@var{var}@}
16418 @itemx $@{@var{var}%@var{word}@}
16419 @itemx $@{@var{var}%%@var{word}@}
16420 @itemx $@{@var{var}#@var{word}@}
16421 @itemx $@{@var{var}##@var{word}@}
16422 @cindex @code{$@{#@var{var}@}}
16423 @cindex @code{$@{@var{var}%@var{word}@}}
16424 @cindex @code{$@{@var{var}%%@var{word}@}}
16425 @cindex @code{$@{@var{var}#@var{word}@}}
16426 @cindex @code{$@{@var{var}##@var{word}@}}
16427 Posix requires support for these usages, but they do not work with many
16428 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16430 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
16431 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16432 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16433 yields the empty string.
16436 @item `@var{commands}`
16437 @cindex @code{`@var{commands}`}
16438 @cindex Command Substitution
16439 Posix requires shells to trim all trailing newlines from command
16440 output before substituting it, so assignments like
16441 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
16442 @samp{$file} ends in a newline.
16444 While in general it makes no sense, do not substitute a single builtin
16445 with side effects, because Ash 0.2, trying to optimize, does not fork a
16446 subshell to perform the command.
16448 For instance, if you wanted to check that @command{cd} is silent, do not
16449 use @samp{test -z "`cd /`"} because the following can happen:
16451 @example
16452 $ @kbd{pwd}
16453 /tmp
16454 $ @kbd{test -z "`cd /`" && pwd}
16456 @end example
16458 @noindent
16459 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16461 The MSYS shell leaves a stray byte in the expansion of a double-quoted
16462 command substitution of a native program, if the end of the substitution
16463 is not aligned with the end of the double quote.  This may be worked
16464 around by inserting another pair of quotes:
16466 @example
16467 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16468 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16469 - broken differ: char 4, line 1
16470 @end example
16472 Upon interrupt or SIGTERM, some shells may abort a command substitution,
16473 replace it with a null string, and wrongly evaluate the enclosing
16474 command before entering the trap or ending the script.  This can lead to
16475 spurious errors:
16477 @example
16478 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16479 $ @kbd{^C}
16480 sh: test: hi: unexpected operator/operand
16481 @end example
16483 @noindent
16484 You can avoid this by assigning the command substitution to a temporary
16485 variable:
16487 @example
16488 $ @kbd{sh -c 'res=`sleep 5; echo hi`
16489          if test "x$res" = xhi; then echo yes; fi'}
16490 $ @kbd{^C}
16491 @end example
16493 @item $(@var{commands})
16494 @cindex @code{$(@var{commands})}
16495 This construct is meant to replace @samp{`@var{commands}`},
16496 and it has most of the problems listed under @code{`@var{commands}`}.
16498 This construct can be
16499 nested while this is impossible to do portably with back quotes.
16500 Although it is almost universally supported, unfortunately Solaris 10
16501 and earlier releases lack it:
16503 @example
16504 $ @kbd{showrev -c /bin/sh | grep version}
16505 Command version: SunOS 5.10 Generic 142251-02 Sep 2010
16506 $ @kbd{echo $(echo blah)}
16507 syntax error: `(' unexpected
16508 @end example
16510 @noindent
16511 nor does IRIX 6.5's Bourne shell:
16512 @example
16513 $ @kbd{uname -a}
16514 IRIX firebird-image 6.5 07151432 IP22
16515 $ @kbd{echo $(echo blah)}
16516 $(echo blah)
16517 @end example
16519 If you do use @samp{$(@var{commands})}, make sure that the commands
16520 do not start with a parenthesis, as that would cause confusion with
16521 a different notation @samp{$((@var{expression}))} that in modern
16522 shells is an arithmetic expression not a command.  To avoid the
16523 confusion, insert a space between the two opening parentheses.
16525 Avoid @var{commands} that contain unbalanced parentheses in
16526 here-documents, comments, or case statement patterns, as many shells
16527 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
16528 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16530 @example
16531 echo $(case x in x) echo hello;; esac)
16532 @end example
16535 @item $((@var{expression}))
16536 @cindex @code{$((@var{expression}))}
16537 Arithmetic expansion is not portable as some shells (most
16538 notably Solaris 10 @command{/bin/sh}) don't support it.
16540 Among shells that do support @samp{$(( ))}, not all of them obey the
16541 Posix rule that octal and hexadecimal constants must be recognized:
16543 @example
16544 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
16546 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
16548 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
16550 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16551 pdksh:  010 + 0x10 : bad number `0x10'
16552 $ @kbd{pdksh -c 'echo $(( 010 ))'}
16554 @end example
16556 When it is available, using arithmetic expansion provides a noticeable
16557 speedup in script execution; but testing for support requires
16558 @command{eval} to avoid syntax errors.  The following construct is used
16559 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16560 arguments are provided in decimal and without a leading zero, and all
16561 operators are properly quoted and appear as distinct arguments:
16563 @example
16564 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16565   eval 'func_arith ()
16566   @{
16567     func_arith_result=$(( $* ))
16568   @}'
16569 else
16570   func_arith ()
16571   @{
16572     func_arith_result=`expr "$@@"`
16573   @}
16575 func_arith 1 + 1
16576 foo=$func_arith_result
16577 @end example
16580 @item ^
16581 @cindex @code{^} quoting
16582 Always quote @samp{^}, otherwise traditional shells such as
16583 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
16585 @end table
16588 @node Assignments
16589 @section Assignments
16590 @cindex Shell assignments
16592 When setting several variables in a row, be aware that the order of the
16593 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
16594 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
16595 You must use
16596 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
16598 Don't rely on the following to find @file{subdir/program}:
16600 @example
16601 PATH=subdir$PATH_SEPARATOR$PATH program
16602 @end example
16604 @noindent
16605 as this does not work with Zsh 3.0.6.  Use something like this
16606 instead:
16608 @example
16609 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
16610 @end example
16612 Don't rely on the exit status of an assignment: Ash 0.2 does not change
16613 the status and propagates that of the last statement:
16615 @example
16616 $ @kbd{false || foo=bar; echo $?}
16618 $ @kbd{false || foo=`:`; echo $?}
16620 @end example
16622 @noindent
16623 and to make things even worse, QNX 4.25 just sets the exit status
16624 to 0 in any case:
16626 @example
16627 $ @kbd{foo=`exit 1`; echo $?}
16629 @end example
16631 To assign default values, follow this algorithm:
16633 @enumerate
16634 @item
16635 If the default value is a literal and does not contain any closing
16636 brace, use:
16638 @example
16639 : "$@{var='my literal'@}"
16640 @end example
16642 @item
16643 If the default value contains no closing brace, has to be expanded, and
16644 the variable being initialized is not intended to be IFS-split
16645 (i.e., it's not a list), then use:
16647 @example
16648 : $@{var="$default"@}
16649 @end example
16651 @item
16652 If the default value contains no closing brace, has to be expanded, and
16653 the variable being initialized is intended to be IFS-split (i.e., it's a list),
16654 then use:
16656 @example
16657 var=$@{var="$default"@}
16658 @end example
16660 @item
16661 If the default value contains a closing brace, then use:
16663 @example
16664 test $@{var+y@} || var="has a '@}'"
16665 @end example
16666 @end enumerate
16668 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
16669 doubt, just use the last form.  @xref{Shell Substitutions}, items
16670 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
16671 for the rationale.
16673 @node Parentheses
16674 @section Parentheses in Shell Scripts
16675 @cindex Shell parentheses
16677 Beware of two opening parentheses in a row, as many shell
16678 implementations treat them specially, and Posix says that a portable
16679 script cannot use @samp{((} outside the @samp{$((} form used for shell
16680 arithmetic.  In traditional shells, @samp{((cat))} behaves like
16681 @samp{(cat)}; but many shells, including
16682 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
16683 expression equivalent to @samp{let "cat"}, and may or may not report an
16684 error when they detect that @samp{cat} is not a number.  As another
16685 example, @samp{pdksh} 5.2.14 does not treat the following code
16686 as a traditional shell would:
16688 @example
16689 if ((true) || false); then
16690   echo ok
16692 @end example
16694 @noindent
16695 To work around this problem, insert a space between the two opening
16696 parentheses.  There is a similar problem and workaround with
16697 @samp{$((}; see @ref{Shell Substitutions}.
16699 @node Slashes
16700 @section Slashes in Shell Scripts
16701 @cindex Shell slashes
16703 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
16704 arguments that contain two trailing slashes:
16706 @example
16707 $ @kbd{echo / // /// //// .// //.}
16708 / / // /// ./ //.
16709 $ @kbd{x=//}
16710 $ @kbd{eval "echo \$x"}
16712 $ @kbd{set -x}
16713 $ @kbd{echo abc | tr -t ab //}
16714 + echo abc
16715 + tr -t ab /
16717 @end example
16719 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
16720 variable is empty and the second double-quote is followed by a word that
16721 begins and ends with slash:
16723 @example
16724 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
16726 + echo //ouch/
16727 //ouch/
16728 @end example
16730 However, our understanding is that patches are available, so perhaps
16731 it's not worth worrying about working around these horrendous bugs.
16733 @node Special Shell Variables
16734 @section Special Shell Variables
16735 @cindex Shell variables
16736 @cindex Special shell variables
16738 Some shell variables should not be used, since they can have a deep
16739 influence on the behavior of the shell.  In order to recover a sane
16740 behavior from the shell, some variables should be unset; M4sh takes
16741 care of this and provides fallback values, whenever needed, to cater
16742 for a very old @file{/bin/sh} that does not support @command{unset}.
16743 (@pxref{Portable Shell, , Portable Shell Programming}).
16745 As a general rule, shell variable names containing a lower-case letter
16746 are safe; you can define and use these variables without worrying about
16747 their effect on the underlying system, and without worrying about
16748 whether the shell changes them unexpectedly.  (The exception is the
16749 shell variable @code{status}, as described below.)
16751 Here is a list of names that are known to cause trouble.  This list is
16752 not exhaustive, but you should be safe if you avoid the name
16753 @code{status} and names containing only upper-case letters and
16754 underscores.
16756 @c Alphabetical order, case insensitive, `A' before `a'.
16757 @table @code
16758 @item ?
16759 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
16760 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
16761 correctly in shell functions (@pxref{Shell Functions}) or in traps
16762 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
16763 @samp{$?} to zero after an empty command.
16765 @example
16766 $ @kbd{bash -c 'false; $empty; echo $?'}
16768 $ @kbd{zsh -c 'false; $empty; echo $?'}
16770 @end example
16772 @item _
16773 @evindex _
16774 Many shells reserve @samp{$_} for various purposes, e.g., the name of
16775 the last command executed.
16777 @item BIN_SH
16778 @evindex BIN_SH
16779 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
16780 the standard shell conform to Posix.
16782 @item CDPATH
16783 @evindex CDPATH
16784 When this variable is set it specifies a list of directories to search
16785 when invoking @code{cd} with a relative file name that did not start
16786 with @samp{./} or @samp{../}.  Posix
16787 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
16788 is used successfully, @code{cd} prints the resulting absolute
16789 file name.  Unfortunately this output can break idioms like
16790 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
16791 Also, many shells do not conform to this part of Posix; for
16792 example, @command{zsh} prints the result only if a directory name
16793 other than @file{.} was chosen from @env{CDPATH}.
16795 In practice the shells that have this problem also support
16796 @command{unset}, so you can work around the problem as follows:
16798 @example
16799 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
16800 @end example
16802 You can also avoid output by ensuring that your directory name is
16803 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
16805 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
16806 possible, so you need not worry about this problem in those scripts.
16808 @item CLICOLOR_FORCE
16809 @evindex CLICOLOR_FORCE
16810 When this variable is set, some implementations of tools like
16811 @command{ls} attempt to add color to their output via terminal escape
16812 sequences, even when the output is not directed to a terminal, and can
16813 thus cause spurious failures in scripts.  Configure scripts use M4sh,
16814 which automatically unsets this variable.
16816 @item DUALCASE
16817 @evindex DUALCASE
16818 In the MKS shell, case statements and file name generation are
16819 case-insensitive unless @env{DUALCASE} is nonzero.
16820 Autoconf-generated scripts export this variable when they start up.
16822 @item ENV
16823 @itemx MAIL
16824 @itemx MAILPATH
16825 @itemx PS1
16826 @itemx PS2
16827 @itemx PS4
16828 @evindex ENV
16829 @evindex MAIL
16830 @evindex MAILPATH
16831 @evindex PS1
16832 @evindex PS2
16833 @evindex PS4
16834 These variables should not matter for shell scripts, since they are
16835 supposed to affect only interactive shells.  However, at least one
16836 shell (the pre-3.0 UWIN Korn shell) gets confused about
16837 whether it is interactive, which means that (for example) a @env{PS1}
16838 with a side effect can unexpectedly modify @samp{$?}.  To work around
16839 this bug, M4sh scripts (including @file{configure} scripts) do something
16840 like this:
16842 @example
16843 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
16844 PS1='$ '
16845 PS2='> '
16846 PS4='+ '
16847 @end example
16849 @noindent
16850 (actually, there is some complication due to bugs in @command{unset};
16851 @pxref{unset, , Limitations of Shell Builtins}).
16853 @item FPATH
16854 @evindex FPATH
16855 The Korn shell uses @env{FPATH} to find shell functions, so avoid
16856 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
16857 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
16858 to find whether a command exists, since they might report the wrong
16859 result if @env{FPATH} is also set.
16861 @item GREP_OPTIONS
16862 @evindex GREP_OPTIONS
16863 When this variable is set, some implementations of @command{grep} honor
16864 these options, even if the options include direction to enable colored
16865 output via terminal escape sequences, and the result can cause spurious
16866 failures when the output is not directed to a terminal.  Configure
16867 scripts use M4sh, which automatically unsets this variable.
16869 @item IFS
16870 @evindex IFS
16871 Long ago, shell scripts inherited @env{IFS} from the environment,
16872 but this caused many problems so modern shells ignore any environment
16873 settings for @env{IFS}.
16875 Don't set the first character of @env{IFS} to backslash.  Indeed,
16876 Bourne shells use the first character (backslash) when joining the
16877 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
16878 backslash escapes, so you can end up with backspace and other strange
16879 characters.
16881 The proper value for @env{IFS} (in regular code, not when performing
16882 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
16883 especially important, as it is used to join the arguments in @samp{$*};
16884 however, note that traditional shells, but also bash-2.04, fail to adhere
16885 to this and join with a space anyway.
16887 M4sh guarantees that @env{IFS} will have the default value at the
16888 beginning of a script, and many macros within autoconf rely on this
16889 setting.  It is okay to use blocks of shell code that temporarily change
16890 the value of @env{IFS} in order to split on another character, but
16891 remember to restore it before expanding further macros.
16893 Unsetting @code{IFS} instead of resetting it to the default sequence
16894 is not suggested, since code that tries to save and restore the
16895 variable's value will incorrectly reset it to an empty value, thus
16896 disabling field splitting:
16898 @example
16899 unset IFS
16900 # default separators used for field splitting
16902 save_IFS=$IFS
16903 IFS=:
16904 # ...
16905 IFS=$save_IFS
16906 # no field splitting performed
16907 @end example
16909 @item LANG
16910 @itemx LC_ALL
16911 @itemx LC_COLLATE
16912 @itemx LC_CTYPE
16913 @itemx LC_MESSAGES
16914 @itemx LC_MONETARY
16915 @itemx LC_NUMERIC
16916 @itemx LC_TIME
16917 @evindex LANG
16918 @evindex LC_ALL
16919 @evindex LC_COLLATE
16920 @evindex LC_CTYPE
16921 @evindex LC_MESSAGES
16922 @evindex LC_MONETARY
16923 @evindex LC_NUMERIC
16924 @evindex LC_TIME
16926 You should set all these variables to @samp{C} because so much
16927 configuration code assumes the C locale and Posix requires that locale
16928 environment variables be set to @samp{C} if the C locale is desired;
16929 @file{configure} scripts and M4sh do that for you.
16930 Export these variables after setting them.
16932 @c  However, some older, nonstandard
16933 @c  systems (notably SCO) break if locale environment variables
16934 @c  are set to @samp{C}, so when running on these systems
16935 @c  Autoconf-generated scripts unset the variables instead.
16937 @item LANGUAGE
16938 @evindex LANGUAGE
16940 @env{LANGUAGE} is not specified by Posix, but it is a GNU
16941 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
16942 should set it too.
16944 @item LC_ADDRESS
16945 @itemx LC_IDENTIFICATION
16946 @itemx LC_MEASUREMENT
16947 @itemx LC_NAME
16948 @itemx LC_PAPER
16949 @itemx LC_TELEPHONE
16950 @evindex LC_ADDRESS
16951 @evindex LC_IDENTIFICATION
16952 @evindex LC_MEASUREMENT
16953 @evindex LC_NAME
16954 @evindex LC_PAPER
16955 @evindex LC_TELEPHONE
16957 These locale environment variables are GNU extensions.  They
16958 are treated like their Posix brethren (@env{LC_COLLATE},
16959 etc.)@: as described above.
16961 @item LINENO
16962 @evindex LINENO
16963 Most modern shells provide the current line number in @code{LINENO}.
16964 Its value is the line number of the beginning of the current command.
16965 M4sh, and hence Autoconf, attempts to execute @command{configure} with
16966 a shell that supports @code{LINENO}.  If no such shell is available, it
16967 attempts to implement @code{LINENO} with a Sed prepass that replaces each
16968 instance of the string @code{$LINENO} (not followed by an alphanumeric
16969 character) with the line's number.  In M4sh scripts you should execute
16970 @code{AS_LINENO_PREPARE} so that these workarounds are included in
16971 your script; configure scripts do this automatically in @code{AC_INIT}.
16973 You should not rely on @code{LINENO} within @command{eval} or shell
16974 functions, as the behavior differs in practice.  The presence of a
16975 quoted newline within simple commands can alter which line number is
16976 used as the starting point for @code{$LINENO} substitutions within that
16977 command.  Also, the possibility of the Sed prepass means that you should
16978 not rely on @code{$LINENO} when quoted, when in here-documents, or when
16979 line continuations are used.  Subshells should be OK, though.  In the
16980 following example, lines 1, 9, and 14 are portable, but the other
16981 instances of @code{$LINENO} do not have deterministic values:
16983 @example
16984 @group
16985 $ @kbd{cat lineno}
16986 echo 1. $LINENO
16987 echo "2. $LINENO
16988 3. $LINENO"
16989 cat <<EOF
16990 5. $LINENO
16991 6. $LINENO
16992 7. \$LINENO
16994 ( echo 9. $LINENO )
16995 eval 'echo 10. $LINENO'
16996 eval 'echo 11. $LINENO
16997 echo 12. $LINENO'
16998 echo 13. '$LINENO'
16999 echo 14. $LINENO '
17000 15.' $LINENO
17001 f () @{ echo $1 $LINENO;
17002 echo $1 $LINENO @}
17003 f 18.
17004 echo 19. \
17005 $LINENO
17006 @end group
17007 @group
17008 $ @kbd{bash-3.2 ./lineno}
17009 1. 1
17010 2. 3
17011 3. 3
17012 5. 4
17013 6. 4
17014 7. $LINENO
17015 9. 9
17016 10. 10
17017 11. 12
17018 12. 13
17019 13. $LINENO
17020 14. 14
17021 15. 14
17022 18. 16
17023 18. 17
17024 19. 19
17025 @end group
17026 @group
17027 $ @kbd{zsh-4.3.4 ./lineno}
17028 1. 1
17029 2. 2
17030 3. 2
17031 5. 4
17032 6. 4
17033 7. $LINENO
17034 9. 9
17035 10. 1
17036 11. 1
17037 12. 2
17038 13. $LINENO
17039 14. 14
17040 15. 14
17041 18. 0
17042 18. 1
17043 19. 19
17044 @end group
17045 @group
17046 $ @kbd{pdksh-5.2.14 ./lineno}
17047 1. 1
17048 2. 2
17049 3. 2
17050 5. 4
17051 6. 4
17052 7. $LINENO
17053 9. 9
17054 10. 0
17055 11. 0
17056 12. 0
17057 13. $LINENO
17058 14. 14
17059 15. 14
17060 18. 16
17061 18. 17
17062 19. 19
17063 @end group
17064 @group
17065 $ @kbd{sed '=' <lineno |}
17066 > @kbd{  sed '}
17067 > @kbd{    N}
17068 > @kbd{    s,$,-,}
17069 > @kbd{    t loop}
17070 > @kbd{    :loop}
17071 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
17072 > @kbd{    t loop}
17073 > @kbd{    s,-$,,}
17074 > @kbd{    s,^[0-9]*\n,,}
17075 > @kbd{  ' |}
17076 > @kbd{  sh}
17077 1. 1
17078 2. 2
17079 3. 3
17080 5. 5
17081 6. 6
17082 7. \7
17083 9. 9
17084 10. 10
17085 11. 11
17086 12. 12
17087 13. 13
17088 14. 14
17089 15. 15
17090 18. 16
17091 18. 17
17092 19. 20
17093 @end group
17094 @end example
17096 In particular, note that @file{config.status} (and any other subsidiary
17097 script created by @code{AS_INIT_GENERATED}) might report line numbers
17098 relative to the parent script as a result of the potential Sed pass.
17100 @item NULLCMD
17101 @evindex NULLCMD
17102 When executing the command @samp{>foo}, @command{zsh} executes
17103 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
17104 compatibility mode and the @command{zsh} version is newer
17105 than 3.1.6-dev-18.  If you are using an older @command{zsh}
17106 and forget to set @env{NULLCMD},
17107 your script might be suspended waiting for data on its standard input.
17109 @item options
17110 @evindex options
17111 For @command{zsh} 4.3.10, @env{options} is treated as an associative
17112 array even after @code{emulate sh}, so it should not be used.
17114 @item PATH_SEPARATOR
17115 @evindex PATH_SEPARATOR
17116 On DJGPP systems, the @env{PATH_SEPARATOR} environment
17117 variable can be set to either @samp{:} or @samp{;} to control the path
17118 separator Bash uses to set up certain environment variables (such as
17119 @env{PATH}).  You can set this variable to @samp{;} if you want
17120 @command{configure} to use @samp{;} as a separator; this might be useful
17121 if you plan to use non-Posix shells to execute files.  @xref{File System
17122 Conventions}, for more information about @code{PATH_SEPARATOR}.
17124 @item POSIXLY_CORRECT
17125 @evindex POSIXLY_CORRECT
17126 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
17127 (even empty) causes programs to try harder to conform to Posix.
17128 Autoconf does not directly manipulate this variable, but @command{bash}
17129 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
17130 running in Posix mode.  Therefore, take care when exporting or unsetting
17131 this variable, so as not to change whether @command{bash} is in Posix
17132 mode.
17134 @example
17135 $ @kbd{bash --posix -c 'set -o | grep posix}
17136 > @kbd{unset POSIXLY_CORRECT}
17137 > @kbd{set -o | grep posix'}
17138 posix           on
17139 posix           off
17140 @end example
17142 @item PWD
17143 @evindex PWD
17144 Posix 1003.1-2001 requires that @command{cd} and
17145 @command{pwd} must update the @env{PWD} environment variable to point
17146 to the logical name of the current directory, but traditional shells
17147 do not support this.  This can cause confusion if one shell instance
17148 maintains @env{PWD} but a subsidiary and different shell does not know
17149 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
17150 points to the wrong directory.  Use @samp{`pwd`} rather than
17151 @samp{$PWD}.
17153 @item RANDOM
17154 @evindex RANDOM
17155 Many shells provide @code{RANDOM}, a variable that returns a different
17156 integer each time it is used.  Most of the time, its value does not
17157 change when it is not used, but on IRIX 6.5 the value changes all
17158 the time.  This can be observed by using @command{set}.  It is common
17159 practice to use @code{$RANDOM} as part of a file name, but code
17160 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
17162 @item status
17163 @evindex status
17164 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
17165 hence read-only.  Do not use it.
17166 @end table
17168 @node Shell Functions
17169 @section Shell Functions
17170 @cindex Shell Functions
17172 Nowadays, it is difficult to find a shell that does not support
17173 shell functions at all.  However, some differences should be expected.
17175 When declaring a shell function, you must include whitespace between the
17176 @samp{)} after the function name and the start of the compound
17177 expression, to avoid upsetting @command{ksh}.  While it is possible to
17178 use any compound command, most scripts use @samp{@{@dots{}@}}.
17180 @example
17181 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
17183 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
17184 ksh: syntax error at line 1: `@}' unexpected
17185 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
17187 @end example
17189 Inside a shell function, you should not rely on the error status of a
17190 subshell if the last command of that subshell was @code{exit} or
17191 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
17192 find a shell that does not exhibit the bug, zsh might be the only shell
17193 present on the user's machine.
17195 Likewise, the state of @samp{$?} is not reliable when entering a shell
17196 function.  This has the effect that using a function as the first
17197 command in a @command{trap} handler can cause problems.
17199 @example
17200 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17203 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17206 @end example
17208 DJGPP bash 2.04 has a bug in that @command{return} from a
17209 shell function which also used a command substitution causes a
17210 segmentation fault.  To work around the issue, you can use
17211 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
17212 in the execution flow of the function (@pxref{Common Shell Constructs}).
17214 Not all shells treat shell functions as simple commands impacted by
17215 @samp{set -e}, for example with Solaris 10 @command{/bin/sh}:
17217 @example
17218 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17219 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17220 oops
17221 @end example
17223 Shell variables and functions may share the same namespace, for example
17224 with Solaris 10 @command{/bin/sh}:
17226 @example
17227 $ @kbd{f () @{ :; @}; f=; f}
17228 f: not found
17229 @end example
17231 @noindent
17232 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
17233 uses the prefix @samp{as_fn_} for its functions.
17235 Handling of positional parameters and shell options varies among shells.
17236 For example, Korn shells reset and restore trace output (@samp{set -x})
17237 and other options upon function entry and exit.  Inside a function,
17238 IRIX sh sets @samp{$0} to the function name.
17240 It is not portable to pass temporary environment variables to shell
17241 functions.  Solaris @command{/bin/sh} does not see the variable.
17242 Meanwhile, not all shells follow the Posix rule that the assignment must
17243 affect the current environment in the same manner as special built-ins.
17245 @example
17246 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17247 @result{}
17248 @result{}
17249 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17250 @result{}1
17251 @result{}
17252 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
17253 @result{}1
17254 @result{}1
17255 @end example
17257 Some ancient Bourne shell variants with function support did not reset
17258 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
17259 arguments of the script were lost after the first function invocation.
17260 It is probably not worth worrying about these shells any more.
17262 With AIX sh, a @command{trap} on 0 installed in a shell function
17263 triggers at function exit rather than at script exit.  @xref{trap, ,
17264 Limitations of Shell Builtins}.
17266 @node Limitations of Builtins
17267 @section Limitations of Shell Builtins
17268 @cindex Shell builtins
17269 @cindex Limitations of shell builtins
17271 No, no, we are serious: some shells do have limitations!  :)
17273 You should always keep in mind that any builtin or command may support
17274 options, and therefore differ in behavior with arguments
17275 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
17276 can give unexpected results when @code{word} starts with a dash.  It is
17277 often possible to avoid this problem using @samp{echo "x$word"}, taking
17278 the @samp{x} into account later in the pipe.  Many of these limitations
17279 can be worked around using M4sh (@pxref{Programming in M4sh}).
17281 @c This table includes things like `@command{test} (files)', so we can't
17282 @c use @table @command.
17283 @table @asis
17284 @item @command{.}
17285 @c --------------
17286 @prindex @command{.}
17287 Use @command{.} only with regular files (use @samp{test -f}).  Bash
17288 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
17289 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
17290 some shells, including bash 3.2, implicitly append the current directory
17291 to this @env{PATH} search, even though Posix forbids it.  So if you want
17292 to use @command{.} on a file @file{foo} in the current directory, you
17293 must use @samp{. ./foo}.
17295 Not all shells gracefully handle syntax errors within a sourced file.
17296 On one extreme, some non-interactive shells abort the entire script.  On
17297 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17298 syntax error.
17300 @example
17301 $ @kbd{echo 'fi' > syntax}
17302 $ @kbd{bash -c '. ./syntax; echo $?'}
17303 ./syntax: line 1: syntax error near unexpected token `fi'
17304 ./syntax: line 1: `fi'
17306 $ @kbd{ash -c '. ./syntax; echo $?'}
17307 ./syntax: 1: Syntax error: "fi" unexpected
17308 $ @kbd{zsh -c '. ./syntax; echo $?'}
17309 ./syntax:1: parse error near `fi'
17311 @end example
17313 @item @command{!}
17314 @c --------------
17315 @prindex @command{!}
17316 The Unix version 7 shell did not support
17317 negating the exit status of commands with @command{!}, and this feature
17318 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
17319 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17320 bugs when using @command{!}:
17322 @example
17323 $ @kbd{sh -c '! : | :'; echo $?}
17325 $ @kbd{ash -c '! : | :'; echo $?}
17327 $ @kbd{sh -c '! @{ :; @}'; echo $?}
17329 $ @kbd{ash -c '! @{ :; @}'; echo $?}
17330 @{: not found
17331 Syntax error: "@}" unexpected
17333 @end example
17335 Shell code like this:
17337 @example
17338 if ! cmp file1 file2 >/dev/null 2>&1; then
17339   echo files differ or trouble
17341 @end example
17343 is therefore not portable in practice.  Typically it is easy to rewrite
17344 such code, e.g.:
17346 @example
17347 cmp file1 file2 >/dev/null 2>&1 ||
17348   echo files differ or trouble
17349 @end example
17351 More generally, one can always rewrite @samp{! @var{command}} as:
17353 @example
17354 if @var{command}; then (exit 1); else :; fi
17355 @end example
17358 @item @command{@{...@}}
17359 @c --------------------
17360 @prindex @command{@{...@}}
17361 Bash 3.2 (and earlier versions) sometimes does not properly set
17362 @samp{$?} when failing to write redirected output of a compound command.
17363 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17364 not occur with @samp{(@dots{})}.  For example:
17366 @example
17367 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17368 bash: line 1: /bad: Permission denied
17370 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17371 bash: line 1: /bad: Permission denied
17373 @end example
17375 To work around the bug, prepend @samp{:;}:
17377 @example
17378 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17379 bash: line 1: /bad: Permission denied
17381 @end example
17383 Posix requires a syntax error if a brace list has no contents.  However,
17384 not all shells obey this rule; and on shells where empty lists are
17385 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
17386 ensure that a brace list is never empty.
17388 @example
17389 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17390 bash: line 1: syntax error near unexpected token `@}'
17391 bash: line 1: `false; @{ @}; echo $?'
17393 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
17395 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
17397 @end example
17400 @item @command{break}
17401 @c ------------------
17402 @prindex @command{break}
17403 The use of @samp{break 2} etc.@: is safe.
17406 @anchor{case}
17407 @item @command{case}
17408 @c -----------------
17409 @prindex @command{case}
17410 You don't need to quote the argument; no splitting is performed.
17412 You don't need the final @samp{;;}, but you should use it.
17414 Posix requires support for @code{case} patterns with opening
17415 parentheses like this:
17417 @example
17418 case $file_name in
17419   (*.c) echo "C source code";;
17420 esac
17421 @end example
17423 @noindent
17424 but the @code{(} in this example is not portable to many Bourne
17425 shell implementations, which is a pity for those of us using tools that
17426 rely on balanced parentheses.  For instance, with Solaris
17427 @command{/bin/sh}:
17429 @example
17430 $ @kbd{case foo in (foo) echo foo;; esac}
17431 @error{}syntax error: `(' unexpected
17432 @end example
17434 @noindent
17435 The leading @samp{(} can be omitted safely.  Unfortunately, there are
17436 contexts where unbalanced parentheses cause other problems, such as when
17437 using a syntax-highlighting editor that searches for the balancing
17438 counterpart, or more importantly, when using a case statement as an
17439 underquoted argument to an Autoconf macro.  @xref{Balancing
17440 Parentheses}, for tradeoffs involved in various styles of dealing with
17441 unbalanced @samp{)}.
17443 Zsh handles pattern fragments derived from parameter expansions or
17444 command substitutions as though quoted:
17446 @example
17447 $ pat=\?; case aa in ?$pat) echo match;; esac
17448 $ pat=\?; case a? in ?$pat) echo match;; esac
17449 match
17450 @end example
17452 @noindent
17453 Because of a bug in its @code{fnmatch}, Bash fails to properly
17454 handle backslashes in character classes:
17456 @example
17457 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17458 bash-2.02$
17459 @end example
17461 @noindent
17462 This is extremely unfortunate, since you are likely to use this code to
17463 handle Posix or MS-DOS absolute file names.  To work around this
17464 bug, always put the backslash first:
17466 @example
17467 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17469 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17471 @end example
17473 Many Bourne shells cannot handle closing brackets in character classes
17474 correctly.
17476 Some shells also have problems with backslash escaping in case you do not want
17477 to match the backslash: both a backslash and the escaped character match this
17478 pattern.  To work around this, specify the character class in a variable, so
17479 that quote removal does not apply afterwards, and the special characters don't
17480 have to be backslash-escaped:
17482 @example
17483 $ @kbd{case '\' in [\<]) echo OK;; esac}
17485 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17487 @end example
17489 Even with this, Solaris @command{ksh} matches a backslash if the set
17490 contains any
17491 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17493 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
17494 a closing parenthesis if not specified in a character class:
17496 @example
17497 $ @kbd{case foo in *\)*) echo fail ;; esac}
17498 fail
17499 $ @kbd{case foo in *')'*) echo fail ;; esac}
17500 fail
17501 @end example
17503 Some shells, such as Ash 0.3.8, are confused by an empty
17504 @code{case}/@code{esac}:
17506 @example
17507 ash-0.3.8 $ @kbd{case foo in esac;}
17508 @error{}Syntax error: ";" unexpected (expecting ")")
17509 @end example
17511 Posix requires @command{case} to give an exit status of 0 if no cases
17512 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
17513 rule.  Meanwhile, it is unclear whether a case that matches, but
17514 contains no statements, must also change the exit status to 0.  The M4sh
17515 macro @code{AS_CASE} works around these inconsistencies.
17517 @example
17518 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
17520 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17522 @end example
17525 @item @command{cd}
17526 @c ---------------
17527 @prindex @command{cd}
17528 Posix 1003.1-2001 requires that @command{cd} must support
17529 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17530 with @option{-L} being the default.  However, traditional shells do
17531 not support these options, and their @command{cd} command has the
17532 @option{-P} behavior.
17534 Portable scripts should assume neither option is supported, and should
17535 assume neither behavior is the default.  This can be a bit tricky,
17536 since the Posix default behavior means that, for example,
17537 @samp{ls ..} and @samp{cd ..} may refer to different directories if
17538 the current logical directory is a symbolic link.  It is safe to use
17539 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17540 Also, Autoconf-generated scripts check for this problem when computing
17541 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17542 so it is safe to @command{cd} to these variables.
17544 Posix states that behavior is undefined if @command{cd} is given an
17545 explicit empty argument.  Some shells do nothing, some change to the
17546 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
17547 the shell rather than returning an error.  Unfortunately, this means
17548 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
17549 than @samp{cd $var} (at least the latter is well-behaved in all shells
17550 at changing to @env{HOME}, although this is probably not what you wanted
17551 in a script).  You should check that a directory name was supplied
17552 before trying to change locations.
17554 @xref{Special Shell Variables}, for portability problems involving
17555 @command{cd} and the @env{CDPATH} environment variable.
17556 Also please see the discussion of the @command{pwd} command.
17559 @anchor{echo}
17560 @item @command{echo}
17561 @c -----------------
17562 @prindex @command{echo}
17563 The simple @command{echo} is probably the most surprising source of
17564 portability troubles.  It is not possible to use @samp{echo} portably
17565 unless both options and escape sequences are omitted.  Don't expect any
17566 option.
17568 Do not use backslashes in the arguments, as there is no consensus on
17569 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
17570 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
17571 The problem is truly @command{echo}: all the shells
17572 understand @samp{'\n'} as the string composed of a backslash and an
17573 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
17574 mess up the internal state of ksh88 on AIX 6.1 so that it will print
17575 the first character @samp{s} only, followed by a newline, and then
17576 entirely drop the output of the next echo in a command substitution.
17578 Because of these problems, do not pass a string containing arbitrary
17579 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
17580 only if you know that @var{foo}'s value cannot contain backslashes and
17581 cannot start with @samp{-}.
17583 Normally, @command{printf} is safer and easier to use than @command{echo}
17584 and @command{echo -n}.  Thus, you should use @command{printf "%s\n"}
17585 instead of @command{echo}, and similarly use @command{printf %s} instead
17586 of @command{echo -n}.
17588 Older scripts, written before @command{printf} was portable,
17589 sometimes used a here-document as a safer alternative to @command{echo},
17590 like this:
17592 @example
17593 cat <<EOF
17594 $foo
17596 @end example
17599 @item @command{eval}
17600 @c -----------------
17601 @prindex @command{eval}
17602 The @command{eval} command is useful in limited circumstances, e.g.,
17603 using commands like @samp{eval table_$key=\$value} and @samp{eval
17604 value=table_$key} to simulate a hash table when the key is known to be
17605 alphanumeric.
17607 You should also be wary of common bugs in @command{eval} implementations.
17608 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
17609 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
17610 4.2.5), the arguments of @samp{eval} are evaluated in a context where
17611 @samp{$?} is 0, so they exhibit behavior like this:
17613 @example
17614 $ @kbd{false; eval 'echo $?'}
17616 @end example
17618 The correct behavior here is to output a nonzero value,
17619 but portable scripts should not rely on this.
17621 You should not rely on @code{LINENO} within @command{eval}.
17622 @xref{Special Shell Variables}.
17624 Note that, even though these bugs are easily avoided,
17625 @command{eval} is tricky to use on arbitrary arguments.
17626 It is obviously unwise to use @samp{eval $cmd} if the string value of
17627 @samp{cmd} was derived from an untrustworthy source.  But even if the
17628 string value is valid, @samp{eval $cmd} might not work as intended,
17629 since it causes field splitting and file name expansion to occur twice,
17630 once for the @command{eval} and once for the command itself.  It is
17631 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
17632 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
17633 equivalent of @samp{cat test;.c} if there happens to be a file named
17634 @file{test;.c} in the current directory; and this in turn
17635 mistakenly attempts to invoke @command{cat} on the file @file{test} and
17636 then execute the command @command{.c}.  To avoid this problem, use
17637 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
17639 However, suppose that you want to output the text of the evaluated
17640 command just before executing it.  Assuming the previous example,
17641 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
17642 this output doesn't show the user that @samp{test;.c} is the actual name
17643 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
17644 works on this example, but it fails with @samp{cmd='cat foo >bar'},
17645 since it mistakenly replaces the contents of @file{bar} by the
17646 string @samp{cat foo}.  No simple, general, and portable solution to
17647 this problem is known.
17649 @item @command{exec}
17650 @c -----------------
17651 @prindex @command{exec}
17652 Posix describes several categories of shell built-ins.  Special
17653 built-ins (such as @command{exit}) must impact the environment of the
17654 current shell, and need not be available through @command{exec}.  All
17655 other built-ins are regular, and must not propagate variable assignments
17656 to the environment of the current shell.  However, the group of regular
17657 built-ins is further distinguished by commands that do not require a
17658 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
17659 are offered as a more efficient version of something that must still be
17660 found in a @env{PATH} search (such as @command{echo}).  Posix is not
17661 clear on whether @command{exec} must work with the list of 17 utilities
17662 that are invoked without a @env{PATH} search, and many platforms lack an
17663 executable for some of those built-ins:
17665 @example
17666 $ @kbd{sh -c 'exec cd /tmp'}
17667 sh: line 0: exec: cd: not found
17668 @end example
17670 All other built-ins that provide utilities specified by Posix must have
17671 a counterpart executable that exists on @env{PATH}, although Posix
17672 allows @command{exec} to use the built-in instead of the executable.
17673 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
17675 @example
17676 $ @kbd{bash -c 'pwd --version' | head -n1}
17677 bash: line 0: pwd: --: invalid option
17678 pwd: usage: pwd [-LP]
17679 $ @kbd{bash -c 'exec pwd --version' | head -n1}
17680 pwd (GNU coreutils) 6.10
17681 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
17682 pdksh: pwd: --: unknown option
17683 @end example
17685 When it is desired to avoid a regular shell built-in, the workaround is
17686 to use some other forwarding command, such as @command{env} or
17687 @command{nice}, that will ensure a path search:
17689 @example
17690 $ @kbd{pdksh -c 'exec true --version' | head -n1}
17691 $ @kbd{pdksh -c 'nice true --version' | head -n1}
17692 true (GNU coreutils) 6.10
17693 $ @kbd{pdksh -c 'env true --version' | head -n1}
17694 true (GNU coreutils) 6.10
17695 @end example
17697 @item @command{exit}
17698 @c -----------------
17699 @prindex @command{exit}
17700 The default value of @command{exit} is supposed to be @code{$?};
17701 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17702 perform @samp{exit 0}.
17704 @example
17705 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17706 fail
17707 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17708 fail
17709 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17710 bash-2.04$
17711 @end example
17713 Using @samp{exit $?} restores the expected behavior.
17715 Some shell scripts, such as those generated by @command{autoconf}, use a
17716 trap to clean up before exiting.  If the last shell command exited with
17717 nonzero status, the trap also exits with nonzero status so that the
17718 invoker can tell that an error occurred.
17720 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
17721 trap ignores the @code{exit} command's argument.  In these shells, a trap
17722 cannot determine whether it was invoked by plain @code{exit} or by
17723 @code{exit 1}.  Instead of calling @code{exit} directly, use the
17724 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
17727 @anchor{export}
17728 @item @command{export}
17729 @c -------------------
17730 @prindex @command{export}
17731 The builtin @command{export} dubs a shell variable @dfn{environment
17732 variable}.  Each update of exported variables corresponds to an update
17733 of the environment variables.  Conversely, each environment variable
17734 received by the shell when it is launched should be imported as a shell
17735 variable marked as exported.
17737 Alas, many shells, such as Solaris @command{/bin/sh},
17738 IRIX 6.3, IRIX 5.2,
17739 AIX 4.1.5, and Digital Unix 4.0, forget to
17740 @command{export} the environment variables they receive.  As a result,
17741 two variables coexist: the environment variable and the shell
17742 variable.  The following code demonstrates this failure:
17744 @example
17745 #!/bin/sh
17746 echo $FOO
17747 FOO=bar
17748 echo $FOO
17749 exec /bin/sh $0
17750 @end example
17752 @noindent
17753 when run with @samp{FOO=foo} in the environment, these shells print
17754 alternately @samp{foo} and @samp{bar}, although they should print only
17755 @samp{foo} and then a sequence of @samp{bar}s.
17757 Therefore you should @command{export} again each environment variable
17758 that you update; the export can occur before or after the assignment.
17760 Posix is not clear on whether the @command{export} of an undefined
17761 variable causes the variable to be defined with the value of an empty
17762 string, or merely marks any future definition of a variable by that name
17763 for export.  Various shells behave differently in this regard:
17765 @example
17766 $ @kbd{sh -c 'export foo; env | grep foo'}
17767 $ @kbd{ash -c 'export foo; env | grep foo'}
17768 foo=
17769 @end example
17771 Posix requires @command{export} to honor assignments made as arguments,
17772 but older shells do not support this, including @command{/bin/sh} in
17773 Solaris 10.  Portable scripts should separate assignments and exports
17774 into different statements.
17776 @example
17777 $ @kbd{bash -c 'export foo=bar; echo $foo'}
17779 $ @kbd{/bin/sh -c 'export foo=bar; echo $foo'}
17780 /bin/sh: foo=bar: is not an identifier
17781 $ @kbd{/bin/sh -c 'export foo; foo=bar; echo $foo'}
17783 @end example
17785 Posix requires @command{export} to work with any arbitrary value for the
17786 contents of the variable being exported, as long as the total size of
17787 the environment combined with arguments doesn't exceed @code{ARG_MAX}
17788 when executing a child process.  However, some shells have extensions
17789 that involve interpreting some environment values specially, regardless
17790 of the variable name.  We currently know of one case: all versions of
17791 Bash released prior to 27 September 2014 intepret an environment
17792 variable with an initial content substring of @code{() @{} as an
17793 exported function definition (this is the ``Shellshock'' remote
17794 execution bug, CVE-2014-6271 and friends, where it was possible to
17795 eploit the function parser to cause remote code execution on child bash
17796 startup; newer versions of Bash use special environment variable
17797 @emph{names} instead of values to implement the same feature).
17799 There may be entries inherited into the environment that are not valid
17800 as shell variable names; Posix states that processes should be tolerant
17801 of these names.  Some shells such as @command{dash} do this by removing
17802 those names from the environment at startup, while others such as
17803 @command{bash} hide the entry from shell access but still pass it on to
17804 child processes.  While you can set such names using @command{env} for a
17805 direct child process, you cannot rely on them being preserved through an
17806 intermediate pass through the shell.
17808 @item @command{false}
17809 @c ------------------
17810 @prindex @command{false}
17811 Don't expect @command{false} to exit with status 1: in native
17812 Solaris @file{/bin/false} exits with status 255.
17815 @item @command{for}
17816 @c ----------------
17817 @prindex @command{for}
17818 To loop over positional arguments, use:
17820 @example
17821 for arg
17823   echo "$arg"
17824 done
17825 @end example
17827 @noindent
17828 You may @emph{not} leave the @code{do} on the same line as @code{for},
17829 since some shells improperly grok:
17831 @example
17832 for arg; do
17833   echo "$arg"
17834 done
17835 @end example
17837 If you want to explicitly refer to the positional arguments, given the
17838 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
17840 @example
17841 for arg in $@{1+"$@@"@}; do
17842   echo "$arg"
17843 done
17844 @end example
17846 @noindent
17847 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
17848 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
17849 item @samp{$@@}, for more.
17851 Posix requires support for a @command{for} loop with no list after
17852 @code{in}.  However, Solaris @command{/bin/sh} treats that as a syntax
17853 error.  It is possible to work around this by providing any shell word
17854 that expands to nothing, or by ignoring an obvious sentinel.
17856 @example
17857 $ @kbd{/bin/sh -c 'for a in $empty; do echo hi; done'}
17858 $ @kbd{/bin/sh -c 'for a in ; do echo hi; done'}
17859 /bin/sh: syntax error at line 1: `;' unexpected
17860 @end example
17862 This syntax problem is most frequently encountered in code that goes
17863 through several layers of expansion, such as an m4 macro or makefile
17864 variable used as a list body, where the first layer of expansion (m4 or
17865 make) can end up expanding to nothing in the version handed to the
17866 shell.  In the makefile context, one common workaround is to use a shell
17867 variable rather than a make variable as the source of the list.
17869 @example
17870 $ @kbd{cat Makefile}
17871 list =
17872 bad:
17873         @@for arg in $(list); do echo $$arg; done
17874 good:
17875         @@list='$(list)'; for arg in $$list; do echo $$arg; done
17876 $ @kbd{make bad 2&>1 | head -n1}
17877 sh: syntax error at line 1: `;' unexpected
17878 $ @kbd{make bad list='a b'}
17881 $ @kbd{make good}
17882 $ @kbd{make good list='a b'}
17885 @end example
17887 In Solaris @command{/bin/sh}, when the list of arguments of a
17888 @command{for} loop starts with @emph{unquoted} tokens looking like
17889 variable assignments, the loop is not executed on those tokens:
17891 @example
17892 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
17895 @end example
17897 @noindent
17898 Thankfully, quoting the assignment-like tokens, or starting the list
17899 with other tokens (including unquoted variable expansion that results in
17900 an assignment-like result), avoids the problem, so it is easy to work
17901 around:
17903 @example
17904 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
17906 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
17909 @end example
17911 @anchor{if}
17912 @item @command{if}
17913 @c ---------------
17914 @prindex @command{if}
17915 Using @samp{!} is not portable.  Instead of:
17917 @example
17918 if ! cmp -s file file.new; then
17919   mv file.new file
17921 @end example
17923 @noindent
17924 use:
17926 @example
17927 if cmp -s file file.new; then :; else
17928   mv file.new file
17930 @end example
17932 @noindent
17933 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
17934 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17935 of conditionals:
17937 @example
17938 AS_IF([cmp -s file file.new], [], [mv file.new file])
17939 @end example
17941 This is especially useful in other M4 macros, where the @dfn{then} and
17942 @dfn{else} branches might be macro arguments.
17944 Some very old shells did not reset the exit status from an @command{if}
17945 with no @command{else}:
17947 @example
17948 $ @kbd{if (exit 42); then true; fi; echo $?}
17950 @end example
17952 @noindent
17953 whereas a proper shell should have printed @samp{0}.  But this is no
17954 longer a portability problem; any shell that supports functions gets it
17955 correct.  However, it explains why some makefiles have lengthy
17956 constructs:
17958 @example
17959 if test -f "$file"; then
17960   install "$file" "$dest"
17961 else
17962   :
17964 @end example
17967 @item @command{printf}
17968 @c ------------------
17969 @prindex @command{printf}
17970 A format string starting with a @samp{-} can cause problems.
17971 Bash interprets it as an option and
17972 gives an error.  And @samp{--} to mark the end of options is not good
17973 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
17974 literally as the format string.  Putting the @samp{-} in a @samp{%c}
17975 or @samp{%s} is probably easiest:
17977 @example
17978 printf %s -foo
17979 @end example
17981 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
17983 @example
17984 $ @kbd{printf '\045'}
17985 bash: printf: `%': missing format character
17986 @end example
17988 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
17989 example, @file{/usr/bin/printf} is buggy, so when using
17990 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
17991 core.
17993 Since @command{printf} is not always a shell builtin, there is a
17994 potential speed penalty for using @code{printf '%s\n'} as a replacement
17995 for an @command{echo} that does not interpret @samp{\} or leading
17996 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
17997 -r --} for this role instead.
17999 @xref{echo, , Limitations of Shell Builtins}, for a discussion of
18000 portable alternatives to both @command{printf} and @command{echo}.
18003 @item @command{pwd}
18004 @c ----------------
18005 @prindex @command{pwd}
18006 With modern shells, plain @command{pwd} outputs a ``logical''
18007 directory name, some of whose components may be symbolic links.  These
18008 directory names are in contrast to ``physical'' directory names, whose
18009 components are all directories.
18011 Posix 1003.1-2001 requires that @command{pwd} must support
18012 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
18013 with @option{-L} being the default.  However, traditional shells do
18014 not support these options, and their @command{pwd} command has the
18015 @option{-P} behavior.
18017 Portable scripts should assume neither option is supported, and should
18018 assume neither behavior is the default.  Also, on many hosts
18019 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
18020 does not require this behavior and portable scripts should not rely on
18023 Typically it's best to use plain @command{pwd}.  On modern hosts this
18024 outputs logical directory names, which have the following advantages:
18026 @itemize @bullet
18027 @item
18028 Logical names are what the user specified.
18029 @item
18030 Physical names may not be portable from one installation
18031 host to another due to network file system gymnastics.
18032 @item
18033 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
18034 some parent directory, but plain @command{pwd} cannot fail for this
18035 reason.
18036 @end itemize
18038 Also please see the discussion of the @command{cd} command.
18041 @item @command{read}
18042 @c -----------------
18043 @prindex @command{read}
18044 No options are portable, not even support @option{-r} (Solaris
18045 @command{/bin/sh} for example).  Tru64/OSF 5.1 @command{sh} treats
18046 @command{read} as a special built-in, so it may exit if input is
18047 redirected from a non-existent or unreadable file.
18050 @anchor{set}
18051 @item @command{set}
18052 @c ----------------
18053 @prindex @command{set}
18054 With the FreeBSD 6.0 shell, the @command{set} command (without
18055 any options) does not sort its output.
18057 The @command{set} builtin faces the usual problem with arguments
18058 starting with a
18059 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
18060 the end of the options (any argument after @option{--} is a parameter,
18061 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
18062 10 @command{/bin/sh}) simply stop option
18063 processing as soon as a non-option argument is found.  Therefore, use
18064 @samp{dummy} or simply @samp{x} to end the option processing, and use
18065 @command{shift} to pop it out:
18067 @example
18068 set x $my_list; shift
18069 @end example
18071 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
18072 longer requires support for this command, and in traditional shells
18073 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
18074 makes scripts harder to debug.
18076 Some nonstandard shells do not recognize more than one option
18077 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
18078 better to combine them:
18080 @example
18081 set -ex
18082 @end example
18084 @cindex @command{set -e}
18085 The option @option{-e} has historically been underspecified, with enough
18086 ambiguities to cause numerous differences across various shell
18087 implementations; see for example
18088 @uref{http://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
18089 or @uref{http://www.austingroupbugs.net/@/view.php?id=52, this link},
18090 documenting a change to Posix 2008 to match @command{ksh88} behavior.
18091 Note that mixing @code{set -e} and shell functions is asking for surprises:
18093 @example
18094 set -e
18095 doit()
18097   rm file
18098   echo one
18100 doit || echo two
18101 @end example
18103 @noindent
18104 According to the recommendation, @samp{one} should always be output
18105 regardless of whether the @command{rm} failed, because it occurs within
18106 the body of the shell function @samp{doit} invoked on the left side of
18107 @samp{||}, where the effects of @samp{set -e} are not enforced.
18108 Likewise, @samp{two} should never be printed, since the failure of
18109 @command{rm} does not abort the function, such that the status of
18110 @samp{doit} is 0.
18112 The BSD shell has had several problems with the @option{-e}
18113 option.  Older versions of the BSD
18114 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
18115 @samp{case} when @option{-e} was in effect, causing the shell to exit
18116 unexpectedly in some cases.  This was particularly a problem with
18117 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
18118 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
18119 wrapper works around the bug (@pxref{Failure in Make Rules}).
18121 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
18122 wrongly exit with @option{-e} if the last command within a compound
18123 statement fails and is guarded by an @samp{&&} only.  For example:
18125 @example
18126 #! /bin/sh
18127 set -e
18128 foo=''
18129 test -n "$foo" && exit 1
18130 echo one
18131 if :; then
18132   test -n "$foo" && exit 1
18133   echo two
18134   test -n "$foo" && exit 1
18136 echo three
18137 @end example
18139 @noindent
18140 does not print @samp{three}.  One workaround is to change the last
18141 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
18142 "$foo"; then exit 1; fi} instead.  Another possibility is to warn BSD
18143 users not to use @samp{sh -e}.
18145 When @samp{set -e} is in effect, a failed command substitution in
18146 Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
18148 @example
18149 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
18150 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
18153 @end example
18155 @noindent
18156 Moreover, a command substitution, successful or not, causes this shell to
18157 exit from a failing outer command even in presence of an @samp{&&} list:
18159 @example
18160 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
18162 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
18164 @end example
18166 Portable scripts should not use @samp{set -e} if @command{trap} is used
18167 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
18168 sometimes enters the trap handler with the exit status of the command
18169 prior to the one that triggered the errexit handler:
18171 @example
18172 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
18174 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
18176 @end example
18178 @noindent
18179 Thus, when writing a script in M4sh, rather than trying to rely on
18180 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
18181 statement where it is desirable to abort on failure.
18183 @cindex @command{set -b}
18184 @cindex @command{set -m}
18185 Job control is not provided by all shells, so the use of @samp{set -m}
18186 or @samp{set -b} must be done with care.  When using @command{zsh} in
18187 native mode, asynchronous notification (@samp{set -b}) is enabled by
18188 default, and using @samp{emulate sh} to switch to Posix mode does not
18189 clear this setting (although asynchronous notification has no impact
18190 unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
18191 earlier have a bug where job control can be manipulated in interactive
18192 shells, but not in subshells or scripts.  Furthermore, some shells, like
18193 @command{pdksh}, fail to treat subshells as interactive, even though the
18194 parent shell was.
18196 @example
18197 $ @kbd{echo $ZSH_VERSION}
18198 4.3.10
18199 $ @kbd{set -m; echo $?}
18201 $ @kbd{zsh -c 'set -m; echo $?'}
18202 set: can't change option: -m
18203 $ @kbd{(set -m); echo $?}
18204 set: can't change option: -m
18206 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
18209 @end example
18211 @cindex @command{set -n}
18212 Use of @command{set -n} (typically via @command{sh -n script}) to
18213 validate a script is not foolproof.  Modern @command{ksh93} tries to be
18214 helpful by informing you about better syntax, but switching the script
18215 to use the suggested syntax in order to silence the warnings would
18216 render the script no longer portable to older shells:
18218 @example
18219 $ @kbd{ksh -nc '``'}
18220 ksh: warning: line 1: `...` obsolete, use $(...)
18222 @end example
18224 Furthermore, on ancient hosts, such as SunOS 4, @command{sh -n} could go
18225 into an infinite loop; even with that bug fixed, Solaris 8
18226 @command{/bin/sh} takes extremely long to parse large scripts.  Autoconf
18227 itself uses @command{sh -n} within its testsuite to check that correct
18228 scripts were generated, but only after first probing for other shell
18229 features (such as @code{test $@{BASH_VERSION+y@}}) that indicate
18230 a reasonably fast and working implementation.
18232 @item @command{shift}
18233 @c ------------------
18234 @prindex @command{shift}
18235 Not only is @command{shift}ing a bad idea when there is nothing left to
18236 shift, but in addition it is not portable: the shell of MIPS
18237 RISC/OS 4.52 refuses to do it.
18239 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
18240 it is also absent in many pre-Posix shells.
18243 @item @command{source}
18244 @c -------------------
18245 @prindex @command{source}
18246 This command is not portable, as Posix does not require it; use
18247 @command{.} instead.
18250 @item @command{test}
18251 @c -----------------
18252 @prindex @command{test}
18253 The @code{test} program is the way to perform many file and string
18254 tests.  It is often invoked by the alternate name @samp{[}, but using
18255 that name in Autoconf code is asking for trouble since it is an M4 quote
18256 character.
18258 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
18259 present in all implementations, and have been marked obsolete by Posix
18260 2008.  This is because there are inherent ambiguities in using them.
18261 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
18262 check whether two strings are both non-empty, but if @samp{$1} is the
18263 literal @samp{!}, then some implementations of @command{test} treat it
18264 as a negation of the unary operator @option{-a}.
18266 Thus, portable uses of @command{test} should never have more than four
18267 arguments, and scripts should use shell constructs like @samp{&&} and
18268 @samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
18269 statement, keep in mind that they have equal precedence, so it is often
18270 better to parenthesize even when this is redundant.  For example:
18272 @smallexample
18273 # Not portable:
18274 test "X$a" = "X$b" -a \
18275   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
18277 # Portable:
18278 test "X$a" = "X$b" &&
18279   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
18280 @end smallexample
18282 @command{test} does not process options like most other commands do; for
18283 example, it does not recognize the @option{--} argument as marking the
18284 end of options.
18286 It is safe to use @samp{!} as a @command{test} operator.  For example,
18287 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
18288 -d foo; @dots{}} is not.
18291 @item @command{test} (files)
18292 @c -------------------------
18293 To enable @command{configure} scripts to support cross-compilation, they
18294 shouldn't do anything that tests features of the build system instead of
18295 the host system.  But occasionally you may find it necessary to check
18296 whether some arbitrary file exists.  To do so, use @samp{test -f},
18297 @samp{test -r}, or @samp{test -x}.  Do not use @samp{test -e}, because
18298 Solaris 10 @command{/bin/sh}
18299 lacks it.  To test for symbolic links on systems that have them, use
18300 @samp{test -h} rather than @samp{test -L}; either form conforms to
18301 Posix 1003.1-2001, but older shells like Solaris 8
18302 @code{/bin/sh} support only @option{-h}.
18304 For historical reasons, Posix reluctantly allows implementations of
18305 @samp{test -x} that will succeed for the root user, even if no execute
18306 permissions are present.  Furthermore, shells do not all agree on
18307 whether Access Control Lists should affect @samp{test -r}, @samp{test
18308 -w}, and @samp{test -x}; some shells base test results strictly on the
18309 current user id compared to file owner and mode, as if by
18310 @code{stat(2)}; while other shells base test results on whether the
18311 current user has the given right, even if that right is only granted by
18312 an ACL, as if by @code{faccessat(2)}.  Furthermore, there is a classic
18313 time of check to time of use race between any use of @command{test}
18314 followed by operating on the just-checked file.  Therefore, it is a good
18315 idea to write scripts that actually attempt an operation, and are
18316 prepared for the resulting failure if permission is denied, rather than
18317 trying to avoid an operation based solely on whether @command{test}
18318 guessed that it might not be permitted.
18320 @item @command{test} (strings)
18321 @c ---------------------------
18322 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
18323 not null, but this usage is not portable to traditional platforms like
18324 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
18325 @samp{-n}.  However, it @emph{is} portable to test if a variable is set
18326 to a non-empty value, by using @samp{test $@{var+y@}}, since all known
18327 implementations properly distinguish between no arguments and a
18328 known-safe string of @samp{y}.
18330 Posix also says that @samp{test ! "@var{string}"},
18331 @samp{test -n "@var{string}"} and
18332 @samp{test -z "@var{string}"} work with any string, but many
18333 shells (such as Solaris, AIX 3.2, UNICOS 10.0.0.6,
18334 Digital Unix 4, etc.)@: get confused if
18335 @var{string} looks like an operator:
18337 @example
18338 $ @kbd{test -n =}
18339 test: argument expected
18340 $ @kbd{test ! -n}
18341 test: argument expected
18342 $ @kbd{test -z ")"; echo $?}
18344 @end example
18346 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
18347 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
18348 strings, but in practice this is not true for troublesome strings that
18349 look like operators or parentheses, or that begin with @samp{-}.
18351 It is best to protect such strings with a leading @samp{X}, e.g.,
18352 @samp{test "X@var{string}" != X} rather than @samp{test -n
18353 "@var{string}"} or @samp{test ! "@var{string}"}.
18355 It is common to find variations of the following idiom:
18357 @example
18358 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
18359   @var{action}
18360 @end example
18362 @noindent
18363 to take an action when a token matches a given pattern.  Such constructs
18364 should be avoided by using:
18366 @example
18367 case $ac_feature in
18368   *[!-a-zA-Z0-9_]*) @var{action};;
18369 esac
18370 @end example
18372 If the pattern is a complicated regular expression that cannot be
18373 expressed as a shell pattern, use something like this instead:
18375 @example
18376 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
18377   @var{action}
18378 @end example
18380 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
18381 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
18382 @samp{@var{foo}} contains backslashes.
18385 @anchor{trap}
18386 @item @command{trap}
18387 @c -----------------
18388 @prindex @command{trap}
18389 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
18390 trap 0, i.e., have the @command{trap} run when the script ends (either via an
18391 explicit @command{exit}, or the end of the script).  The trap for 0 should be
18392 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
18393 will invoke the trap at the end of this function.
18395 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
18396 specified signals to their default values, but many common shells (e.g.,
18397 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
18398 ``command'' named @command{-} when the specified conditions arise.
18399 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18400 reset traps, as this is supported by a larger set of shells, but there
18401 are still shells like @command{dash} that mistakenly try to execute
18402 @command{1} instead of resetting the traps.  Therefore, there is no
18403 portable workaround, except for @samp{trap - 0}, for which
18404 @samp{trap '' 0} is a portable substitute.
18406 Although Posix is not absolutely clear on this point, it is widely
18407 admitted that when entering the trap @samp{$?} should be set to the exit
18408 status of the last command run before the trap.  The ambiguity can be
18409 summarized as: ``when the trap is launched by an @command{exit}, what is
18410 the @emph{last} command run: that before @command{exit}, or
18411 @command{exit} itself?''
18413 Bash considers @command{exit} to be the last command, while Zsh and
18414 Solaris @command{/bin/sh} consider that when the trap is run it is
18415 @emph{still} in the @command{exit}, hence it is the previous exit status
18416 that the trap receives:
18418 @example
18419 $ @kbd{cat trap.sh}
18420 trap 'echo $?' 0
18421 (exit 42); exit 0
18422 $ @kbd{zsh trap.sh}
18424 $ @kbd{bash trap.sh}
18426 @end example
18428 The portable solution is then simple: when you want to @samp{exit 42},
18429 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18430 set the exit status to 42 for Zsh, and the second to trigger the trap
18431 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
18432 @code{AS_EXIT}.
18434 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18435 reset to 0 by empty lines if the code is inside @command{trap}.
18437 @example
18438 $ @kbd{trap 'false}
18440 echo $?' 0
18441 $ @kbd{exit}
18443 @end example
18445 @noindent
18446 Fortunately, this bug only affects @command{trap}.
18448 Several shells fail to execute an exit trap that is defined inside a
18449 subshell, when the last command of that subshell is not a builtin.  A
18450 workaround is to use @samp{exit $?} as the shell builtin.
18452 @example
18453 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18455 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18456 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18458 @end example
18460 @noindent
18461 Likewise, older implementations of @command{bash} failed to preserve
18462 @samp{$?} across an exit trap consisting of a single cleanup command.
18464 @example
18465 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
18467 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
18469 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
18471 @end example
18473 Be aware that a trap can be called from any number of places in your
18474 script, and therefore the trap handler should not make assumptions about
18475 shell state.  For some examples, if your script temporarily modifies
18476 @env{IFS}, then the trap should include an initialization back to its
18477 typical value of space-tab-newline (autoconf does this for generated
18478 @file{configure} files).  Likewise, if your script changes the current
18479 working directory at some point after the trap is installed, then your
18480 trap cannot assume which directory it is in, and should begin by
18481 changing directories to an absolute path if that is important to the
18482 cleanup efforts (autotest does this for generated @file{testsuite}
18483 files).
18485 @item @command{true}
18486 @c -----------------
18487 @prindex @command{true}
18488 @c Info cannot handle `:' in index entries.
18489 @c @prindex @command{:}
18490 Don't worry: as far as we know @command{true} is portable.
18491 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18492 portable shell community tends to prefer using @command{:}.  This has a
18493 funny side effect: when asked whether @command{false} is more portable
18494 than @command{true} Alexandre Oliva answered:
18496 @quotation
18497 In a sense, yes, because if it doesn't exist, the shell will produce an
18498 exit status of failure, which is correct for @command{false}, but not
18499 for @command{true}.
18500 @end quotation
18502 Remember that even though @samp{:} ignores its arguments, it still takes
18503 time to compute those arguments.  It is a good idea to use double quotes
18504 around any arguments to @samp{:} to avoid time spent in field splitting
18505 and file name expansion.
18508 @anchor{unset}
18509 @item @command{unset}
18510 @c ------------------
18511 @prindex @command{unset}
18512 In some nonconforming shells (e.g., Solaris 10 @command{/bin/ksh} and
18513 @command{/usr/xpg4/bin/sh}, NetBSD 5.99.43 sh, or Bash 2.05a),
18514 @code{unset FOO} fails when @code{FOO} is not set.  This can interfere
18515 with @code{set -e} operation.  You can use
18517 @smallexample
18518 FOO=; unset FOO
18519 @end smallexample
18521 @noindent
18522 if you are not sure that @code{FOO} is set.
18524 A few ancient shells lack @command{unset} entirely.  For some variables
18525 such as @code{PS1}, you can use a neutralizing value instead:
18527 @smallexample
18528 PS1='$ '
18529 @end smallexample
18531 Usually, shells that do not support @command{unset} need less effort to
18532 make the environment sane, so for example is not a problem if you cannot
18533 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
18534 @code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18535 So, you should do something like
18537 @smallexample
18538 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18539 @end smallexample
18541 @noindent
18542 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
18543 @ref{export, , Limitations of Builtins}, for
18544 the case of environment variables.
18546 @item @command{wait}
18547 @c -----------------
18548 @prindex @command{wait}
18549 The exit status of @command{wait} is not always reliable.
18550 @end table
18552 @node Limitations of Usual Tools
18553 @section Limitations of Usual Tools
18554 @cindex Limitations of usual tools
18556 The small set of tools you can expect to find on any machine can still
18557 include some limitations you should be aware of.
18559 @comment Between this list and the list of builtins above, we should
18560 @comment mention all the tools in GNU Coding Standards ``Utilities in
18561 @comment Makefiles''.
18563 @c This table includes things like `@command{expr} (|)', so we can't
18564 @c use @table @command.
18565 @table @asis
18566 @anchor{awk}
18567 @item @command{awk}
18568 @c ----------------
18569 @prindex @command{awk}
18570 Don't leave white space before the opening parenthesis in a user function call.
18571 Posix does not allow this and GNU Awk rejects it:
18573 @example
18574 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18575         BEGIN @{ die () @}'}
18576 gawk: cmd. line:2:         BEGIN @{ die () @}
18577 gawk: cmd. line:2:                      ^ parse error
18578 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18579         BEGIN @{ die() @}'}
18580 Aaaaarg!
18581 @end example
18583 Posix says that if a program contains only @samp{BEGIN} actions, and
18584 contains no instances of @code{getline}, then the program merely
18585 executes the actions without reading input.  However, traditional Awk
18586 implementations (such as Solaris 10 @command{awk}) read and discard
18587 input in this case.  Portable scripts can redirect input from
18588 @file{/dev/null} to work around the problem.  For example:
18590 @example
18591 awk 'BEGIN @{print "hello world"@}' </dev/null
18592 @end example
18594 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
18595 @samp{$1}) retain their value from the last record read, if no
18596 intervening @samp{getline} occurred.  However, some implementations
18597 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
18598 @samp{awk}) reset these variables.  A workaround is to use an
18599 intermediate variable prior to the @samp{END} block.  For example:
18601 @example
18602 $ @kbd{cat end.awk}
18603 @{ tmp = $1 @}
18604 END @{ print "a", $1, $NF, "b", tmp @}
18605 $ @kbd{echo 1 | awk -f end.awk}
18606 a   b 1
18607 $ @kbd{echo 1 | gawk -f end.awk}
18608 a 1 1 b 1
18609 @end example
18611 If you want your program to be deterministic, don't depend on @code{for}
18612 on arrays:
18614 @example
18615 $ @kbd{cat for.awk}
18616 END @{
18617   arr["foo"] = 1
18618   arr["bar"] = 1
18619   for (i in arr)
18620     print i
18622 $ @kbd{gawk -f for.awk </dev/null}
18625 $ @kbd{nawk -f for.awk </dev/null}
18628 @end example
18630 Some Awk implementations, such as HP-UX 11.0's native one,
18631 mishandle anchors:
18633 @example
18634 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
18635 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
18637 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
18638 xfoo
18639 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
18641 @end example
18643 @noindent
18644 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
18645 or use a simple test to reject such implementations.
18647 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
18648 after @code{%u}:
18650 @example
18651 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
18652 0 0
18653 @end example
18655 AIX version 5.2 has an arbitrary limit of 399 on the
18656 length of regular expressions and literal strings in an Awk program.
18658 Traditional Awk implementations derived from Unix version 7, such as
18659 Solaris @command{/bin/awk}, have many limitations and do not
18660 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
18661 Programs}) finds you an Awk that doesn't have these problems, but if
18662 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
18663 address them.  For more detailed descriptions, see @ref{Language
18664 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
18666 Traditional Awk does not support multidimensional arrays or user-defined
18667 functions.
18669 Traditional Awk does not support the @option{-v} option.  You can use
18670 assignments after the program instead, e.g., @code{$AWK '@{print v
18671 $1@}' v=x}; however, don't forget that such assignments are not
18672 evaluated until they are encountered (e.g., after any @code{BEGIN}
18673 action).
18675 Traditional Awk does not support the keywords @code{delete} or @code{do}.
18677 Traditional Awk does not support the expressions
18678 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
18679 or @code{@var{a}^=@var{b}}.
18681 Traditional Awk does not support the predefined @code{CONVFMT} or
18682 @code{ENVIRON} variables.
18684 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
18685 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
18686 @code{sqrt}, and @code{substr}.
18688 Traditional Awk @code{getline} is not at all compatible with Posix;
18689 avoid it.
18691 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
18692 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
18694 In code portable to both traditional and modern Awk, @code{FS} must be a
18695 string containing just one ordinary character, and similarly for the
18696 field-separator argument to @code{split}.
18698 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
18699 implementations, like Tru64's, split the input even if you don't refer
18700 to any field in the script, to circumvent this problem, set @samp{FS}
18701 to an unusual character and use @code{split}.
18703 Traditional Awk has a limit of at most 99 bytes in a number formatted by
18704 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
18705 dumps core.
18707 The original version of Awk had a limit of at most 99 bytes per
18708 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
18709 per run of non-special characters in a @code{printf} format, but these
18710 bugs have been fixed on all practical hosts that we know of.
18712 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
18713 of at most 3070 bytes.
18715 @item @command{basename}
18716 @c ---------------------
18717 @prindex @command{basename}
18718 Not all hosts have a working @command{basename}.
18719 You can use @command{expr} instead.
18721 @c AS_BASENAME is to be replaced by a better API.
18722 @ignore
18723 Not all hosts have a working @command{basename}, and you should instead
18724 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
18725 @command{expr} if you need to strip a suffix.  For example:
18727 @example
18728 a=`basename "$aname"`       # This is not portable.
18729 a=`AS_BASENAME(["$aname"])` # This is more portable.
18731 # This is not portable.
18732 c=`basename "$cname" .c`
18734 # This is more portable.
18735 c=`AS_BASENAME(["$cname"])`
18736 case $c in
18737 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
18738 esac
18739 @end example
18740 @end ignore
18743 @item @command{cat}
18744 @c ----------------
18745 @prindex @command{cat}
18746 Don't rely on any option.
18749 @item @command{cc}
18750 @c ---------------
18751 @prindex @command{cc}
18752 The command @samp{cc -c foo.c} traditionally produces an object file
18753 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
18754 with @option{-o} to specify a different object file name, but
18755 Posix does not require this combination and a few compilers
18756 lack support for it.  @xref{C Compiler}, for how GNU Make
18757 tests for this feature with @code{AC_PROG_CC_C_O}.
18759 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
18760 (such as CDS on Reliant Unix) leave a @file{foo.o}.
18762 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
18763 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
18764 nothing.
18766 The default executable, produced by @samp{cc foo.c}, can be
18768 @itemize
18769 @item @file{a.out} -- usual Posix convention.
18770 @item @file{b.out} -- i960 compilers (including @command{gcc}).
18771 @item @file{a.exe} -- DJGPP port of @command{gcc}.
18772 @item @file{a_out.exe} -- GNV @command{cc} wrapper for DEC C on OpenVMS.
18773 @item @file{foo.exe} -- various MS-DOS compilers.
18774 @end itemize
18776 The C compiler's traditional name is @command{cc}, but other names like
18777 @command{gcc} are common.  Posix 1003.1-2001 and 1003.1-2008 specify the
18778 name @command{c99}, but older Posix editions specified
18779 @command{c89}, future POSIX standards will likely specify
18780 @command{c11}, and anyway these standard names are rarely used in
18781 practice.  Typically the C compiler is invoked from makefiles that use
18782 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
18783 compiler name.
18785 @item @command{chgrp}
18786 @itemx @command{chown}
18787 @c -------------------
18788 @prindex @command{chgrp}
18789 @prindex @command{chown}
18790 It is not portable to change a file's group to a group that the owner
18791 does not belong to.
18793 @item @command{chmod}
18794 @c ------------------
18795 @prindex @command{chmod}
18796 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
18797 instead, for two reasons.  First, plain @option{-w} does not necessarily
18798 make the file unwritable, since it does not affect mode bits that
18799 correspond to bits in the file mode creation mask.  Second,
18800 Posix says that the @option{-w} might be interpreted as an
18801 implementation-specific option, not as a mode; Posix suggests
18802 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
18803 @samp{--} does not work on some older hosts.
18806 @item @command{cmp}
18807 @c ----------------
18808 @prindex @command{cmp}
18809 @command{cmp} performs a raw data comparison of two files, while
18810 @command{diff} compares two text files.  Therefore, if you might compare
18811 DOS files, even if only checking whether two files are different, use
18812 @command{diff} to avoid spurious differences due to differences of
18813 newline encoding.
18816 @item @command{cp}
18817 @c ---------------
18818 @prindex @command{cp}
18819 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
18820 obsolescent and its behavior on special files is implementation-defined.
18821 Use @option{-R} instead.  On GNU hosts the two options
18822 are equivalent, but on Solaris hosts (for example) @code{cp -r}
18823 reads from pipes instead of replicating them.  AIX 5.3 @code{cp -R} may
18824 corrupt its own memory with some directory hierarchies and error out or
18825 dump core:
18827 @example
18828 @kbd{mkdir -p 12345678/12345678/12345678/12345678}
18829 @kbd{touch 12345678/12345678/x}
18830 @kbd{cp -R 12345678 t}
18831 cp: 0653-440 12345678/12345678/: name too long.
18832 @end example
18834 Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
18835 trailing slashes at the end of nonexistent destination directories.  To
18836 avoid this problem, omit the trailing slashes.  For example, use
18837 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
18838 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
18840 The @option{-f} option is portable nowadays.
18842 @cindex timestamp resolution
18843 Traditionally, file timestamps had 1-second resolution, and @samp{cp
18844 -p} copied the timestamps exactly.  However, many modern file systems
18845 have timestamps with 1-nanosecond resolution.  Unfortunately, some older
18846 @samp{cp -p} implementations truncate timestamps when copying files,
18847 which can cause the destination file to appear to be older than the
18848 source.  The exact amount of truncation depends on the resolution of
18849 the system calls that @command{cp} uses.  Traditionally this was
18850 @code{utime}, which has 1-second resolution.  Less-ancient @command{cp}
18851 implementations such as GNU Core Utilities 5.0.91 (2003) use
18852 @code{utimes}, which has 1-microsecond resolution.  Modern
18853 implementations such as GNU Core Utilities 6.12 (2008) can set timestamps to
18854 the full nanosecond resolution, using the modern system calls
18855 @code{futimens} and @code{utimensat} when they are available.  As of
18856 2011, though, many platforms do not yet fully support these new system
18857 calls.
18859 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
18860 ownerships.  But whether it actually does copy ownerships or not is a
18861 system dependent policy decision implemented by the kernel.  If the
18862 kernel allows it then it happens.  If the kernel does not allow it then
18863 it does not happen.  It is not something @command{cp} itself has control
18864 over.
18866 In Unix System V any user can chown files to any other user, and System
18867 V also has a non-sticky @file{/tmp}.  That probably derives from the
18868 heritage of System V in a business environment without hostile users.
18869 BSD changed this
18870 to be a more secure model where only root can @command{chown} files and
18871 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
18872 of BSD in a campus environment.
18874 GNU/Linux and Solaris by default follow BSD, but
18875 can be configured to allow a System V style @command{chown}.  On the
18876 other hand, HP-UX follows System V, but can
18877 be configured to use the modern security model and disallow
18878 @command{chown}.  Since it is an administrator-configurable parameter
18879 you can't use the name of the kernel as an indicator of the behavior.
18883 @item @command{date}
18884 @c -----------------
18885 @prindex @command{date}
18886 Some versions of @command{date} do not recognize special @samp{%} directives,
18887 and unfortunately, instead of complaining, they just pass them through,
18888 and exit with success:
18890 @example
18891 $ @kbd{uname -a}
18892 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
18893 $ @kbd{date "+%s"}
18895 @end example
18898 @item @command{diff}
18899 @c -----------------
18900 @prindex @command{diff}
18901 Option @option{-u} is nonportable.
18903 Some implementations, such as Tru64's, fail when comparing to
18904 @file{/dev/null}.  Use an empty file instead.
18907 @item @command{dirname}
18908 @c --------------------
18909 @prindex @command{dirname}
18910 Not all hosts have a working @command{dirname}, and you should instead
18911 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
18913 @example
18914 dir=`dirname "$file"`       # This is not portable.
18915 dir=`AS_DIRNAME(["$file"])` # This is more portable.
18916 @end example
18919 @item @command{egrep}
18920 @c ------------------
18921 @prindex @command{egrep}
18922 Posix 1003.1-2001 no longer requires @command{egrep},
18923 but many hosts do not yet support the Posix
18924 replacement @code{grep -E}.  Also, some traditional implementations do
18925 not work on long input lines.  To work around these problems, invoke
18926 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
18928 Portable extended regular expressions should use @samp{\} only to escape
18929 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
18930 is not portable, even though it typically matches @samp{@}}.
18932 The empty alternative is not portable.  Use @samp{?} instead.  For
18933 instance with Digital Unix v5.0:
18935 @example
18936 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
18937 |foo
18938 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
18939 bar|
18940 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
18942 |bar
18943 @end example
18945 @command{$EGREP} also suffers the limitations of @command{grep}
18946 (@pxref{grep, , Limitations of Usual Tools}).
18948 @item @command{expr}
18949 @c -----------------
18950 @prindex @command{expr}
18951 Not all implementations obey the Posix rule that @samp{--} separates
18952 options from arguments; likewise, not all implementations provide the
18953 extension to Posix that the first argument can be treated as part of a
18954 valid expression rather than an invalid option if it begins with
18955 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
18956 @samp{$var} might be a negative number, to keep @command{expr} from
18957 interpreting it as an option.
18959 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
18960 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
18961 misinterpreting @var{word}.
18963 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
18965 @item @command{expr} (@samp{|})
18966 @prindex @command{expr} (@samp{|})
18967 You can use @samp{|}.  Although Posix does require that @samp{expr
18968 ''} return the empty string, it does not specify the result when you
18969 @samp{|} together the empty string (or zero) with the empty string.  For
18970 example:
18972 @example
18973 expr '' \| ''
18974 @end example
18976 Posix 1003.2-1992 returns the empty string
18977 for this case, but traditional Unix returns @samp{0} (Solaris is
18978 one such example).  In Posix 1003.1-2001, the specification was
18979 changed to match traditional Unix's behavior (which is
18980 bizarre, but it's too late to fix this).  Please note that the same
18981 problem does arise when the empty string results from a computation,
18982 as in:
18984 @example
18985 expr bar : foo \| foo : bar
18986 @end example
18988 @noindent
18989 Avoid this portability problem by avoiding the empty string.
18992 @item @command{expr} (@samp{:})
18993 @c ----------------------------
18994 @prindex @command{expr}
18995 Portable @command{expr} regular expressions should use @samp{\} to
18996 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
18997 For example, alternation, @samp{\|}, is common but Posix does not
18998 require its support, so it should be avoided in portable scripts.
18999 Similarly, @samp{\+} and @samp{\?} should be avoided.
19001 Portable @command{expr} regular expressions should not begin with
19002 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
19003 not needed anyway.
19005 On the other hand, the behavior of the @samp{$} anchor is not portable
19006 on multi-line strings.  Posix is ambiguous whether the anchor applies to
19007 each line, as was done in older versions of the GNU Core Utilities, or
19008 whether it applies only to the end of the overall string, as in
19009 Coreutils 6.0 and most other implementations.
19011 @example
19012 $ @kbd{baz='foo}
19013 > @kbd{bar'}
19014 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
19016 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
19018 @end example
19020 The Posix standard is ambiguous as to whether
19021 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
19022 In practice, it outputs the empty string on most platforms, but portable
19023 scripts should not assume this.  For instance, the QNX 4.25 native
19024 @command{expr} returns @samp{0}.
19026 One might think that a way to get a uniform behavior would be to use
19027 the empty string as a default value:
19029 @example
19030 expr a : '\(b\)' \| ''
19031 @end example
19033 @noindent
19034 Unfortunately this behaves exactly as the original expression; see the
19035 @command{expr} (@samp{|}) entry for more information.
19037 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
19038 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
19039 @command{expr} to fail if the matched substring is longer than 120
19040 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
19041 @command{expr} fails.  Nowadays this is of practical importance only for
19042 the rare installer who mistakenly puts @file{/usr/ucb} before
19043 @file{/usr/bin} in @env{PATH}.
19045 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
19046 some cases.  For example, the command
19047 @example
19048 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
19049 @end example
19051 @noindent
19052 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
19053 This particular case can be worked around by substituting @samp{[^--]}
19054 for @samp{[^-]}.
19056 Don't leave, there is some more!
19058 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
19059 the empty string, has a funny behavior in its exit status: it's always 1
19060 when parentheses are used!
19062 @example
19063 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
19064 0: 1
19065 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
19066 1: 0
19068 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
19069 1: a
19070 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
19071 1: 0
19072 @end example
19074 @noindent
19075 In practice this can be a big problem if you are ready to catch failures
19076 of @command{expr} programs with some other method (such as using
19077 @command{sed}), since you may get twice the result.  For instance
19079 @example
19080 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
19081 @end example
19083 @noindent
19084 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25.  A
19085 simple workaround consists of testing @command{expr} and using a variable
19086 set to @command{expr} or to @command{false} according to the result.
19088 Tru64 @command{expr} incorrectly treats the result as a number, if it
19089 can be interpreted that way:
19091 @example
19092 $ @kbd{expr 00001 : '.*\(...\)'}
19094 @end example
19096 On HP-UX 11, @command{expr} only supports a single
19097 sub-expression.
19099 @example
19100 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
19101 expr: More than one '\(' was used.
19102 @end example
19105 @item @command{fgrep}
19106 @c ------------------
19107 @prindex @command{fgrep}
19108 Posix 1003.1-2001 no longer requires @command{fgrep},
19109 but many hosts do not yet support the Posix
19110 replacement @code{grep -F}.  Also, some traditional implementations do
19111 not work on long input lines.  To work around these problems, invoke
19112 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
19114 Tru64/OSF 5.1 @command{fgrep} does not match an empty pattern.
19117 @item @command{find}
19118 @c -----------------
19119 @prindex @command{find}
19120 The option @option{-maxdepth} seems to be GNU specific.
19121 Tru64 v5.1, NetBSD 1.5 and Solaris @command{find}
19122 commands do not understand it.
19124 The replacement of @samp{@{@}} is guaranteed only if the argument is
19125 exactly @emph{@{@}}, not if it's only a part of an argument.  For
19126 instance on DU, and HP-UX 10.20 and HP-UX 11:
19128 @example
19129 $ @kbd{touch foo}
19130 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
19131 @{@}-@{@}
19132 @end example
19134 @noindent
19135 while GNU @command{find} reports @samp{./foo-./foo}.
19138 @anchor{grep}
19139 @item @command{grep}
19140 @c -----------------
19141 @prindex @command{grep}
19142 Portable scripts can rely on the @command{grep} options @option{-c},
19143 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
19144 options.  For example, don't use @option{-w}, as Posix does not require
19145 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
19146 portable scripts should not combine @option{-c} with @option{-l},
19147 as Posix does not allow this.
19149 Some of the options required by Posix are not portable in practice.
19150 Don't use @samp{grep -q} to suppress output, because many @command{grep}
19151 implementations (e.g., Solaris) do not support @option{-q}.
19152 Don't use @samp{grep -s} to suppress output either, because Posix
19153 says @option{-s} does not suppress output, only some error messages;
19154 also, the @option{-s} option of traditional @command{grep} behaved
19155 like @option{-q} does in most modern implementations.  Instead,
19156 redirect the standard output and standard error (in case the file
19157 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
19158 status of @code{grep} to determine whether it found a match.
19160 The QNX4 implementation fails to count lines with @code{grep -c '$'},
19161 but works with @code{grep -c '^'}.  Other alternatives for counting
19162 lines are to use @code{sed -n '$='} or @code{wc -l}.
19164 Some traditional @command{grep} implementations do not work on long
19165 input lines.  On AIX the default @code{grep} silently truncates long
19166 lines on the input before matching.
19168 Also, many implementations do not support multiple regexps
19169 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
19170 or honor only the last pattern (e.g., IRIX 6.5 and NeXT).  To
19171 work around these problems, invoke @code{AC_PROG_GREP} and then use
19172 @code{$GREP}.
19174 Another possible workaround for the multiple @option{-e} problem is to
19175 separate the patterns by newlines, for example:
19177 @example
19178 grep 'foo
19179 bar' in.txt
19180 @end example
19182 @noindent
19183 except that this fails with traditional @command{grep}
19184 implementations and with OpenBSD 3.8 @command{grep}.
19186 Traditional @command{grep} implementations (e.g., Solaris) do not
19187 support the @option{-E} or @option{-F} options.  To work around these
19188 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
19189 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
19190 willing to require support for Posix @command{grep}, your script should
19191 not use both @option{-E} and @option{-F}, since Posix does not allow
19192 this combination.
19194 Portable @command{grep} regular expressions should use @samp{\} only to
19195 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
19196 alternation, @samp{\|}, is common but Posix does not require its
19197 support in basic regular expressions, so it should be avoided in
19198 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
19199 Similarly, the following escape sequences should also be avoided:
19200 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
19201 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
19203 Posix does not specify the behavior of @command{grep} on binary files.
19204 An example where this matters is using BSD @command{grep} to
19205 search text that includes embedded ANSI escape sequences for
19206 colored output to terminals (@samp{\033[m} is the sequence to restore
19207 normal output); the behavior depends on whether input is seekable:
19209 @example
19210 $ @kbd{printf 'esc\033[mape\n' > sample}
19211 $ @kbd{grep . sample}
19212 Binary file sample matches
19213 $ @kbd{cat sample | grep .}
19214 escape
19215 @end example
19218 @item @command{join}
19219 @c -----------------
19220 @prindex @command{join}
19221 Solaris 8 @command{join} has bugs when the second operand is standard
19222 input, and when standard input is a pipe.  For example, the following
19223 shell script causes Solaris 8 @command{join} to loop forever:
19225 @example
19226 cat >file <<'EOF'
19227 1 x
19228 2 y
19230 cat file | join file -
19231 @end example
19233 Use @samp{join - file} instead.
19235 On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
19236 @command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
19237 the workaround is to use @command{join -a1 file1 file2} instead.
19239 @item @command{ln}
19240 @c ---------------
19241 @prindex @command{ln}
19242 The @option{-f} option is portable nowadays.
19244 @cindex Symbolic links
19245 Symbolic links are not available on some systems; use @samp{$(LN_S)} as
19246 a portable substitute.
19248 For versions of the DJGPP before 2.04,
19249 @command{ln} emulates symbolic links
19250 to executables by generating a stub that in turn calls the real
19251 program.  This feature also works with nonexistent files like in the
19252 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
19253 which attempts to call @file{file.exe} if run.  But this feature only
19254 works for executables, so @samp{cp -p} is used instead for these
19255 systems.  DJGPP versions 2.04 and later have full support
19256 for symbolic links.
19259 @item @command{ls}
19260 @c ---------------
19261 @prindex @command{ls}
19262 @cindex Listing directories
19263 The portable options are @option{-acdilrtu}.  Current practice is for
19264 @option{-l} to output both owner and group, even though ancient versions
19265 of @command{ls} omitted the group.
19267 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
19268 to standard output if @file{foo} did not exist.  Hence a shell command
19269 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
19270 was equivalent to @samp{sources='*.c not found'} in the absence of
19271 @samp{.c} files.  This is no longer a practical problem, since current
19272 @command{ls} implementations send diagnostics to standard error.
19274 The behavior of @command{ls} on a directory that is being concurrently
19275 modified is not always predictable, because of a data race where cached
19276 information returned by @code{readdir} does not match the current
19277 directory state.  In fact, MacOS 10.5 has an intermittent bug where
19278 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
19279 once if other files were added or removed from the directory immediately
19280 prior to the @command{ls} call.  Since @command{ls} already sorts its
19281 output, the duplicate entries can be avoided by piping the results
19282 through @code{uniq}.
19284 @anchor{mkdir}
19285 @item @command{mkdir}
19286 @c ------------------
19287 @prindex @command{mkdir}
19288 @cindex Making directories
19289 No @command{mkdir} option is portable to older systems.  Instead of
19290 @samp{mkdir -p @var{file-name}}, you should use
19291 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
19292 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
19294 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
19295 go-w -p @var{dir}}, often leads to trouble.  FreeBSD
19296 @command{mkdir} incorrectly attempts to change the permissions of
19297 @var{dir} even if it already exists.  HP-UX 11.23 and
19298 IRIX 6.5 @command{mkdir} often assign the wrong permissions to
19299 any newly-created parents of @var{dir}.
19301 Posix does not clearly specify whether @samp{mkdir -p foo}
19302 should succeed when @file{foo} is a symbolic link to an already-existing
19303 directory.  The GNU Core Utilities 5.1.0 @command{mkdir}
19304 succeeds, but Solaris @command{mkdir} fails.
19306 Traditional @code{mkdir -p} implementations suffer from race conditions.
19307 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
19308 at the same time, both processes might detect that @file{a} is missing,
19309 one might create @file{a}, then the other might try to create @file{a}
19310 and fail with a @code{File exists} diagnostic.  The GNU Core
19311 Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
19312 NetBSD 2.0.2, and OpenBSD 2.4 are known to be
19313 race-free when two processes invoke @code{mkdir -p} simultaneously, but
19314 earlier versions are vulnerable.  Solaris @command{mkdir} is still
19315 vulnerable as of Solaris 10, and other traditional Unix systems are
19316 probably vulnerable too.  This possible race is harmful in parallel
19317 builds when several Make rules call @code{mkdir -p} to
19318 construct directories.  You may use
19319 @code{install-sh -d} as a safe replacement, provided this script is
19320 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
19321 OK, but copies from older versions are vulnerable.
19324 @item @command{mkfifo}
19325 @itemx @command{mknod}
19326 @c -------------------
19327 @prindex @command{mkfifo}
19328 @prindex @command{mknod}
19329 The GNU Coding Standards state that @command{mknod} is safe to use on
19330 platforms where it has been tested to exist; but it is generally portable
19331 only for creating named FIFOs, since device numbers are
19332 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
19333 testsuites.  Posix states that behavior is unspecified when opening a
19334 named FIFO for both reading and writing; on at least Cygwin, this
19335 results in failure on any attempt to read or write to that file
19336 descriptor.
19338 @item @command{mktemp}
19339 @c -------------------
19340 @prindex @command{mktemp}
19341 @cindex Creating temporary files
19342 Shell scripts can use temporary files safely with @command{mktemp}, but
19343 it does not exist on all systems.  A portable way to create a safe
19344 temporary file name is to create a temporary directory with mode 700 and
19345 use a file inside this directory.  Both methods prevent attackers from
19346 gaining control, though @command{mktemp} is far less likely to fail
19347 gratuitously under attack.
19349 Here is sample code to create a new temporary directory @samp{$dir} safely:
19351 @example
19352 # Create a temporary directory $dir in $TMPDIR (default /tmp).
19353 # Use mktemp if possible; otherwise fall back on mkdir,
19354 # with $RANDOM to make collisions less likely.
19355 : "$@{TMPDIR:=/tmp@}"
19357   dir=`
19358     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
19359   ` &&
19360   test -d "$dir"
19361 @} || @{
19362   dir=$TMPDIR/foo$$-$RANDOM
19363 @c $$ restore font-lock
19364   (umask 077 && mkdir "$dir")
19365 @} || exit $?
19366 @end example
19369 @item @command{mv}
19370 @c ---------------
19371 @prindex @command{mv}
19372 @cindex Moving open files
19373 The only portable options are @option{-f} and @option{-i}.
19375 Moving individual files between file systems is portable (it was in Unix
19376 version 6),
19377 but it is not always atomic: when doing @samp{mv new existing}, there's
19378 a critical section where neither the old nor the new version of
19379 @file{existing} actually exists.
19381 On some systems moving files from @file{/tmp} can sometimes cause
19382 undesirable (but perfectly valid) warnings, even if you created these
19383 files.  This is because @file{/tmp} belongs to a group that ordinary
19384 users are not members of, and files created in @file{/tmp} inherit
19385 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
19386 a diagnostic without failing:
19388 @smallexample
19389 $ @kbd{touch /tmp/foo}
19390 $ @kbd{mv /tmp/foo .}
19391 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
19392 $ @kbd{echo $?}
19394 $ @kbd{ls foo}
19396 @end smallexample
19398 @noindent
19399 This annoying behavior conforms to Posix, unfortunately.
19401 Moving directories across mount points is not portable, use @command{cp}
19402 and @command{rm}.
19404 DOS variants cannot rename or remove open files, and do not
19405 support commands like @samp{mv foo bar >foo}, even though this is
19406 perfectly portable among Posix hosts.
19409 @item @command{od}
19410 @c ---------------
19411 @prindex @command{od}
19413 In Mac OS X 10.3, @command{od} does not support the
19414 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
19415 @option{-t}, or the XSI option @option{-s}.  The only
19416 supported Posix option is @option{-v}, and the only supported
19417 XSI options are those in @option{-bcdox}.  The BSD
19418 @command{hexdump} program can be used instead.
19420 This problem no longer exists in Mac OS X 10.4.3.
19423 @item @command{rm}
19424 @c ---------------
19425 @prindex @command{rm}
19426 The @option{-f} and @option{-r} options are portable.
19428 It is not portable to invoke @command{rm} without options or operands.
19429 On the other hand, Posix now requires @command{rm -f} to silently
19430 succeed when there are no operands (useful for constructs like
19431 @command{rm -rf $filelist} without first checking if @samp{$filelist}
19432 was empty).  But this was not always portable; at least NetBSD
19433 @command{rm} built before 2008 would fail with a diagnostic.
19435 A file might not be removed even if its parent directory is writable
19436 and searchable.  Many Posix hosts cannot remove a mount point, a named
19437 stream, a working directory, or a last link to a file that is being
19438 executed.
19440 DOS variants cannot rename or remove open files, and do not
19441 support commands like @samp{rm foo >foo}, even though this is
19442 perfectly portable among Posix hosts.
19444 @item @command{rmdir}
19445 @c ------------------
19446 @prindex @command{rmdir}
19447 Just as with @command{rm}, some platforms refuse to remove a working
19448 directory.
19450 @anchor{sed}
19451 @item @command{sed}
19452 @c ----------------
19453 @prindex @command{sed}
19454 Patterns should not include the separator (unless escaped), even as part
19455 of a character class.  In conformance with Posix, the Cray
19456 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
19457 Even when escaped, patterns should not include separators that are also
19458 used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
19459 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19460 before evaluating the basic regular expression.
19462 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
19463 not require support for empty patterns, and Unicos 9 @command{sed} rejects
19464 them.
19466 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
19468 Sed scripts should not use branch labels longer than 7 characters and
19469 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
19470 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
19471 48 labels, which cannot be circumvented by using more than one script
19472 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
19473 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
19474 about 6000 bytes for the internal representation of commands.
19476 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
19477 NetBSD 1.4.2's, incorrectly try to interpret the second
19478 @samp{;} as a command:
19480 @example
19481 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
19482 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
19483 @end example
19485 Some @command{sed} implementations have a buffer limited to 4000 bytes,
19486 and this limits the size of input lines, output lines, and internal
19487 buffers that can be processed portably.  Likewise,
19488 not all @command{sed} implementations can handle embedded @code{NUL} or
19489 a missing trailing newline.
19491 Remember that ranges within a bracket expression of a regular expression
19492 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19493 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19494 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19495 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19496 than to rely on @samp{[A-Z]}.
19498 Additionally, Posix states that regular expressions are only
19499 well-defined on characters.  Unfortunately, there exist platforms such
19500 as MacOS X 10.5 where not all 8-bit byte values are valid characters,
19501 even though that platform has a single-byte @samp{C} locale.  And Posix
19502 allows the existence of a multi-byte @samp{C} locale, although that does
19503 not yet appear to be a common implementation.  At any rate, it means
19504 that not all bytes will be matched by the regular expression @samp{.}:
19506 @example
19507 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
19509 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
19511 @end example
19513 Portable @command{sed} regular expressions should use @samp{\} only to escape
19514 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
19515 alternation, @samp{\|}, is common but Posix does not require its
19516 support, so it should be avoided in portable scripts.  Solaris
19517 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19518 deletes only lines that contain the literal string @samp{a|b}.
19519 Similarly, @samp{\+} and @samp{\?} should be avoided.
19521 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19523 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
19524 quite portable to current hosts, but was not supported by some ancient
19525 @command{sed} implementations like SVR3.
19527 Some @command{sed} implementations, e.g., Solaris, restrict the special
19528 role of the asterisk @samp{*} to one-character regular expressions and
19529 back-references, and the special role of interval expressions
19530 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19531 to one-character regular expressions.  This may lead to unexpected behavior:
19533 @example
19534 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19535 x2x4
19536 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19538 @end example
19540 The @option{-e} option is mostly portable.
19541 However, its argument
19542 cannot start with @samp{a}, @samp{c}, or @samp{i},
19543 as this runs afoul of a Tru64 5.1 bug.
19544 Also, its argument cannot be empty, as this fails on AIX 5.3.
19545 Some people prefer to use @samp{-e}:
19547 @example
19548 sed -e '@var{command-1}' \
19549     -e '@var{command-2}'
19550 @end example
19552 @noindent
19553 as opposed to the equivalent:
19555 @example
19556 sed '
19557   @var{command-1}
19558   @var{command-2}
19560 @end example
19562 @noindent
19563 The following usage is sometimes equivalent:
19565 @example
19566 sed '@var{command-1};@var{command-2}'
19567 @end example
19569 but Posix says that this use of a semicolon has undefined effect if
19570 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
19571 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
19572 should use semicolon only with simple scripts that do not use these
19573 verbs.
19575 Posix up to the 2008 revision requires the argument of the @option{-e}
19576 option to be a syntactically complete script.  GNU @command{sed} allows
19577 to pass multiple script fragments, each as argument of a separate
19578 @option{-e} option, that are then combined, with newlines between the
19579 fragments, and a future Posix revision may allow this as well.  This
19580 approach is not portable with script fragments ending in backslash; for
19581 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
19582 don't allow splitting in this case:
19584 @example
19585 $ @kbd{echo a | sed -n -e 'i\}
19586 @kbd{0'}
19588 $ @kbd{echo a | sed -n -e 'i\' -e 0}
19589 Unrecognized command: 0
19590 @end example
19592 @noindent
19593 In practice, however, this technique of joining fragments
19594 through @option{-e} works for multiple @command{sed} functions within
19595 @samp{@{} and @samp{@}}, even if that is not specified by Posix:
19597 @example
19598 @c The quote around the closing brace silences interactive zsh.
19599 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
19601 @end example
19603 Commands inside @{ @} brackets are further restricted.  Posix 2008 says that
19604 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
19605 each command must be followed immediately by a newline, without any
19606 intervening blanks or semicolons.  The closing bracket must be alone on
19607 a line, other than white space preceding or following it.  However, a
19608 future version of Posix may standardize the use of addresses within brackets.
19610 Contrary to yet another urban legend, you may portably use @samp{&} in
19611 the replacement part of the @code{s} command to mean ``what was
19612 matched''.  All descendants of Unix version 7 @command{sed}
19613 (at least; we
19614 don't have first hand experience with older @command{sed} implementations) have
19615 supported it.
19617 Posix requires that you must not have any white space between
19618 @samp{!} and the following command.  It is OK to have blanks between
19619 the address and the @samp{!}.  For instance, on Solaris:
19621 @example
19622 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
19623 @error{}Unrecognized command: /bar/ ! p
19624 $ @kbd{echo "foo" | sed -n '/bar/! p'}
19625 @error{}Unrecognized command: /bar/! p
19626 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
19628 @end example
19630 Posix also says that you should not combine @samp{!} and @samp{;}.  If
19631 you use @samp{!}, it is best to put it on a command that is delimited by
19632 newlines rather than @samp{;}.
19634 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
19635 @samp{w} commands be followed by exactly one space before their argument.
19636 On the other hand, no white space is allowed between @samp{:} and the
19637 subsequent label name.
19639 If a sed script is specified on the command line and ends in an
19640 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
19641 should be followed by a newline.  Otherwise some @command{sed}
19642 implementations (e.g., OpenBSD 3.9) do not append a newline to the
19643 inserted text.
19645 Many @command{sed} implementations (e.g., MacOS X 10.4,
19646 OpenBSD 3.9, Solaris 10
19647 @command{/usr/ucb/sed}) strip leading white space from the text of
19648 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
19649 work around this incompatibility with Posix:
19651 @example
19652 $ @kbd{echo flushleft | sed 'a\}
19653 > @kbd{   indented}
19654 > @kbd{'}
19655 flushleft
19656 indented
19657 $ @kbd{echo foo | sed 'a\}
19658 > @kbd{\   indented}
19659 > @kbd{'}
19660 flushleft
19661    indented
19662 @end example
19664 Posix requires that with an empty regular expression, the last non-empty
19665 regular expression from either an address specification or substitution
19666 command is applied.  However, busybox 1.6.1 complains when using a
19667 substitution command with a replacement containing a back-reference to
19668 an empty regular expression; the workaround is repeating the regular
19669 expression.
19671 @example
19672 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
19673 sed: No previous regexp.
19674 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
19676 @end example
19678 Portable scripts should be aware of the inconsistencies and options for
19679 handling word boundaries, as these are not specified by POSIX.
19681 @example
19682                 \<      \b      [[:<:]]
19683 Solaris 10      yes     no      no
19684 Solaris XPG4    yes     no      error
19685 NetBSD 5.1      no      no      yes
19686 FreeBSD 9.1     no      no      yes
19687 GNU             yes     yes     error
19688 busybox         yes     yes     error
19689 @end example
19691 @item @command{sed} (@samp{t})
19692 @c ---------------------------
19693 @prindex @command{sed} (@samp{t})
19694 Some old systems have @command{sed} that ``forget'' to reset their
19695 @samp{t} flag when starting a new cycle.  For instance on MIPS
19696 RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
19697 script (the line numbers are not actual part of the texts):
19699 @example
19700 s/keep me/kept/g  # a
19701 t end             # b
19702 s/.*/deleted/g    # c
19703 :end              # d
19704 @end example
19706 @noindent
19709 @example
19710 delete me         # 1
19711 delete me         # 2
19712 keep me           # 3
19713 delete me         # 4
19714 @end example
19716 @noindent
19717 you get
19719 @example
19720 deleted
19721 delete me
19722 kept
19723 deleted
19724 @end example
19726 @noindent
19727 instead of
19729 @example
19730 deleted
19731 deleted
19732 kept
19733 deleted
19734 @end example
19736 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
19737 flag, and the output is produced.  When processing
19738 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
19739 fails to match, but @command{sed} is not supposed to clear the @samp{t}
19740 flag when a substitution fails.  Command (b) sees that the flag is set,
19741 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
19742 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
19743 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
19744 Finally, since the flag is clear, line 4 is processed properly.
19746 There are two things one should remember about @samp{t} in @command{sed}.
19747 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
19748 succeeded, not only the immediately preceding substitution.  Therefore,
19749 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
19750 line, to reset the @samp{t} flag where needed.
19752 Secondly, you cannot rely on @command{sed} to clear the flag at each new
19753 cycle.
19755 One portable implementation of the script above is:
19757 @example
19758 t clear
19759 :clear
19760 s/keep me/kept/g
19761 t end
19762 s/.*/deleted/g
19763 :end
19764 @end example
19766 @item @command{sleep}
19767 @c ------------------
19768 @prindex @command{sleep}
19769 Using @command{sleep} is generally portable.  However, remember that
19770 adding a @command{sleep} to work around timestamp issues, with a minimum
19771 granularity of one second, doesn't scale well for parallel builds on
19772 modern machines with sub-second process completion.
19774 @item @command{sort}
19775 @c -----------------
19776 @prindex @command{sort}
19777 Remember that sort order is influenced by the current locale.  Inside
19778 @file{configure}, the C locale is in effect, but in Makefile snippets,
19779 you may need to specify @code{LC_ALL=C sort}.
19781 @item @command{tar}
19782 @c ----------------
19783 @prindex @command{tar}
19784 There are multiple file formats for @command{tar}; if you use Automake,
19785 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
19786 level of portability to use.
19788 @anchor{touch}
19789 @item @command{touch}
19790 @c ------------------
19791 @prindex @command{touch}
19792 @cindex timestamp resolution
19793 If you specify the desired timestamp (e.g., with the @option{-r}
19794 option), older @command{touch} implementations use the @code{utime} or
19795 @code{utimes} system call, which can result in the same kind of
19796 timestamp truncation problems that @samp{cp -p} has.
19798 On ancient BSD systems, @command{touch} or any command that
19799 results in an empty file does not update the timestamps, so use a
19800 command like @command{echo} as a workaround.
19801 Also,
19802 GNU @command{touch} 3.16r (and presumably all before that)
19803 fails to work on SunOS 4.1.3 when the empty file is on an
19804 NFS-mounted 4.2 volume.
19805 However, these problems are no longer of practical concern.
19807 @item @command{tr}
19808 @c ---------------
19809 @prindex @command{tr}
19810 @cindex carriage return, deleting
19811 @cindex newline, deleting
19812 @cindex deleting carriage return
19813 Not all versions of @command{tr} handle all backslash character escapes.
19814 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
19815 Solaris contains more modern @command{tr} in other locations.
19816 Using octal escapes is more portable for carriage returns, since
19817 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
19818 literal carriage returns in scripts causes a number of other problems.
19819 But for other characters, like newline, using octal escapes ties the
19820 operation to ASCII, so it is better to use literal characters.
19822 @example
19823 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
19825 light
19826 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
19827 moonlight
19828 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
19829 moonlight
19830 $ @kbd{nl='}
19831 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
19832 moonlight
19833 @end example
19835 Not all versions of @command{tr} recognize direct ranges of characters: at
19836 least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
19837 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in Posix
19838 transliterate to themselves).
19840 @example
19841 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
19842 HAZy FAntAZy
19843 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
19844 HAZY FANTAZY
19845 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
19846 HAZY FANTAZY
19847 @end example
19849 When providing two arguments, be sure the second string is at least as
19850 long as the first.
19852 @example
19853 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
19855 $ @kbd{echo abc | coreutils/tr bc d}
19857 @end example
19859 Posix requires @command{tr} to operate on binary files.  But at least
19860 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
19861 @code{NUL} in the input prior to doing any translation.  When using
19862 @command{tr} to process a binary file that may contain @code{NUL} bytes,
19863 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
19864 @command{/usr/xpg6/bin/tr} if that is available.
19866 @example
19867 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
19868  61 62
19869 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
19870  61 62
19871 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
19872  61 00 62
19873 @end example
19875 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
19876 octal escape for @code{NUL}.
19878 @example
19879 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
19880  61 62 63
19881 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
19882  61 00 64
19883 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
19884  61 00 64
19885 @end example
19887 @end table
19890 @node Portable Make
19891 @chapter Portable Make Programming
19892 @prindex @command{make}
19893 @cindex Limitations of @command{make}
19895 Writing portable makefiles is an art.  Since a makefile's commands are
19896 executed by the shell, you must consider the shell portability issues
19897 already mentioned.  However, other issues are specific to @command{make}
19898 itself.
19900 @menu
19901 * $< in Ordinary Make Rules::   $< in ordinary rules
19902 * Failure in Make Rules::       Failing portably in rules
19903 * Special Chars in Names::      Special Characters in Macro Names
19904 * Backslash-Newline-Empty::     Empty lines after backslash-newline
19905 * Backslash-Newline Comments::  Spanning comments across line boundaries
19906 * Long Lines in Makefiles::     Line length limitations
19907 * Macros and Submakes::         @code{make macro=value} and submakes
19908 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
19909 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
19910 * Parallel Make::               Parallel @command{make} quirks
19911 * Comments in Make Rules::      Other problems with Make comments
19912 * Newlines in Make Rules::      Using literal newlines in rules
19913 * Comments in Make Macros::     Other problems with Make comments in macros
19914 * Trailing whitespace in Make Macros::  Macro substitution problems
19915 * Command-line Macros and whitespace::  Whitespace trimming of values
19916 * obj/ and Make::               Don't name a subdirectory @file{obj}
19917 * make -k Status::              Exit status of @samp{make -k}
19918 * VPATH and Make::              @code{VPATH} woes
19919 * Single Suffix Rules::         Single suffix rules and separated dependencies
19920 * Timestamps and Make::         Subsecond timestamp resolution
19921 @end menu
19923 @node $< in Ordinary Make Rules
19924 @section @code{$<} in Ordinary Make Rules
19926 Posix says that the @samp{$<} construct in makefiles can be
19927 used only in inference rules and in the @samp{.DEFAULT} rule; its
19928 meaning in ordinary rules is unspecified.  Solaris @command{make}
19929 for instance replaces it with the empty string.  OpenBSD (3.0 and
19930 later) @command{make} diagnoses these uses and errors out.
19932 @node Failure in Make Rules
19933 @section Failure in Make Rules
19935 Posix 2008 requires that @command{make} must invoke each command with
19936 the equivalent of a @samp{sh -e -c} subshell, which causes the
19937 subshell to exit immediately if a subsidiary simple-command fails,
19938 although not all @command{make} implementations have historically
19939 followed this rule.  For
19940 example, the command @samp{touch T; rm -f U} may attempt to
19941 remove @file{U} even if the @command{touch} fails, although this is not
19942 permitted with Posix make.  One way to work around failures in simple
19943 commands is to reword them so that they always succeed, e.g., @samp{touch
19944 T || :; rm -f U}.
19945 However, even this approach can run into common bugs in BSD
19946 implementations of the @option{-e} option of @command{sh} and
19947 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
19948 are worried
19949 about porting to buggy BSD shells it may be simpler to migrate
19950 complicated @command{make} actions into separate scripts.
19952 @node Special Chars in Names
19953 @section Special Characters in Make Macro Names
19955 Posix limits macro names to nonempty strings containing only
19956 ASCII letters and digits, @samp{.}, and @samp{_}.  Many
19957 @command{make} implementations allow a wider variety of characters, but
19958 portable makefiles should avoid them.  It is portable to start a name
19959 with a special character, e.g., @samp{$(.FOO)}.
19961 Some ancient @command{make} implementations don't support leading
19962 underscores in macro names.  An example is NEWS-OS 4.2R.
19964 @example
19965 $ @kbd{cat Makefile}
19966 _am_include = #
19967 _am_quote =
19968 all:; @@echo this is test
19969 $ @kbd{make}
19970 Make: Must be a separator on rules line 2.  Stop.
19971 $ @kbd{cat Makefile2}
19972 am_include = #
19973 am_quote =
19974 all:; @@echo this is test
19975 $ @kbd{make -f Makefile2}
19976 this is test
19977 @end example
19979 @noindent
19980 However, this problem is no longer of practical concern.
19982 @node Backslash-Newline-Empty
19983 @section Backslash-Newline Before Empty Lines
19985 A bug in Bash 2.03 can cause problems if a Make rule contains a
19986 backslash-newline followed by line that expands to nothing.
19987 For example, on Solaris 8:
19989 @example
19990 SHELL = /bin/bash
19991 EMPTY =
19992 foo:
19993         touch foo \
19994         $(EMPTY)
19995 @end example
19997 @noindent
19998 executes
20000 @example
20001 /bin/bash -c 'touch foo \
20003 @end example
20005 @noindent
20006 which fails with a syntax error, due to the Bash bug.  To avoid this
20007 problem, avoid nullable macros in the last line of a multiline command.
20009 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
20010 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
20011 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
20012 On some versions of HP-UX, @command{make} reads multiple newlines
20013 following a backslash, continuing to the next non-empty line.  For
20014 example,
20016 @example
20017 FOO = one \
20019 BAR = two
20021 test:
20022         : FOO is "$(FOO)"
20023         : BAR is "$(BAR)"
20024 @end example
20026 @noindent
20027 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
20028 sensibly let a backslash continue only to the immediately following
20029 line.
20031 @node Backslash-Newline Comments
20032 @section Backslash-Newline in Make Comments
20034 According to Posix, Make comments start with @code{#}
20035 and continue until an unescaped newline is reached.
20037 @example
20038 $ @kbd{cat Makefile}
20039 # A = foo \
20040       bar \
20041       baz
20043 all:
20044         @@echo ok
20045 $ @kbd{make}   # GNU make
20047 @end example
20049 @noindent
20050 However this is not always the case.  Some implementations
20051 discard everything from @code{#} through the end of the line, ignoring any
20052 trailing backslash.
20054 @example
20055 $ @kbd{pmake}  # BSD make
20056 "Makefile", line 3: Need an operator
20057 Fatal errors encountered -- cannot continue
20058 @end example
20060 @noindent
20061 Therefore, if you want to comment out a multi-line definition, prefix each
20062 line with @code{#}, not only the first.
20064 @example
20065 # A = foo \
20066 #     bar \
20067 #     baz
20068 @end example
20070 @node Long Lines in Makefiles
20071 @section Long Lines in Makefiles
20073 Tru64 5.1's @command{make} has been reported to crash when given a
20074 makefile with lines longer than around 20 kB.  Earlier versions are
20075 reported to exit with @code{Line too long} diagnostics.
20077 @node Macros and Submakes
20078 @section @code{make macro=value} and Submakes
20080 A command-line variable definition such as @code{foo=bar} overrides any
20081 definition of @code{foo} in a makefile.  Some @command{make}
20082 implementations (such as GNU @command{make}) propagate this
20083 override to subsidiary invocations of @command{make}.  Some other
20084 implementations do not pass the substitution along to submakes.
20086 @example
20087 $ @kbd{cat Makefile}
20088 foo = foo
20089 one:
20090         @@echo $(foo)
20091         $(MAKE) two
20092 two:
20093         @@echo $(foo)
20094 $ @kbd{make foo=bar}            # GNU make 3.79.1
20096 make two
20097 make[1]: Entering directory `/home/adl'
20099 make[1]: Leaving directory `/home/adl'
20100 $ @kbd{pmake foo=bar}           # BSD make
20102 pmake two
20104 @end example
20106 You have a few possibilities if you do want the @code{foo=bar} override
20107 to propagate to submakes.  One is to use the @option{-e}
20108 option, which causes all environment variables to have precedence over
20109 the makefile macro definitions, and declare foo as an environment
20110 variable:
20112 @example
20113 $ @kbd{env foo=bar make -e}
20114 @end example
20116 The @option{-e} option is propagated to submakes automatically,
20117 and since the environment is inherited between @command{make}
20118 invocations, the @code{foo} macro is overridden in
20119 submakes as expected.
20121 This syntax (@code{foo=bar make -e}) is portable only when used
20122 outside of a makefile, for instance from a script or from the
20123 command line.  When run inside a @command{make} rule, GNU
20124 @command{make} 3.80 and prior versions forget to propagate the
20125 @option{-e} option to submakes.
20127 Moreover, using @option{-e} could have unexpected side effects if your
20128 environment contains some other macros usually defined by the
20129 makefile.  (See also the note about @code{make -e} and @code{SHELL}
20130 below.)
20132 If you can foresee all macros that a user might want to override, then
20133 you can propagate them to submakes manually, from your makefile:
20135 @example
20136 foo = foo
20137 one:
20138         @@echo $(foo)
20139         $(MAKE) foo=$(foo) two
20140 two:
20141         @@echo $(foo)
20142 @end example
20144 Another way to propagate a variable to submakes in a portable way is to
20145 expand an extra variable in every invocation of @samp{$(MAKE)} within
20146 your makefile:
20148 @example
20149 foo = foo
20150 one:
20151         @@echo $(foo)
20152         $(MAKE) $(SUBMAKEFLAGS) two
20153 two:
20154         @@echo $(foo)
20155 @end example
20157 Users must be aware that this technique is in use to take advantage of
20158 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
20159 allows any macro to be overridden.  Makefiles generated by
20160 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
20161 on the command lines of submakes (@pxref{Subdirectories, , Automake,
20162 automake, GNU Automake}).
20164 @node The Make Macro MAKEFLAGS
20165 @section The Make Macro MAKEFLAGS
20166 @cindex @code{MAKEFLAGS} and @command{make}
20167 @cindex @command{make} and @code{MAKEFLAGS}
20169 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
20170 current and recursive invocations of make, but allows implementations
20171 several formats for the variable.  It is tricky to parse
20172 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
20173 or @option{-k} for continued execution are in effect.  For example, you
20174 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
20175 contains single-letter options, since in the Cygwin version of
20176 GNU @command{make} it is either @option{--unix} or
20177 @option{--win32} with the second word containing single-letter options.
20179 @example
20180 $ @kbd{cat Makefile}
20181 all:
20182         @@echo MAKEFLAGS = $(MAKEFLAGS)
20183 $ @kbd{make}
20184 MAKEFLAGS = --unix
20185 $ @kbd{make -k}
20186 MAKEFLAGS = --unix -k
20187 @end example
20189 @node The Make Macro SHELL
20190 @section The Make Macro @code{SHELL}
20191 @cindex @code{SHELL} and @command{make}
20192 @cindex @command{make} and @code{SHELL}
20194 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
20195 macro to spawn shell processes and execute Make rules.  This
20196 is a builtin macro supplied by @command{make}, but it can be modified
20197 by a makefile or by a command-line argument.
20199 Not all @command{make} implementations define this @code{SHELL} macro.
20200 Tru64
20201 @command{make} is an example; this implementation always uses
20202 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
20203 your makefiles.  If you use Autoconf, do
20205 @example
20206 SHELL = @@SHELL@@
20207 @end example
20209 @noindent
20210 If you use Automake, this is done for you.
20212 Do not force @code{SHELL = /bin/sh} because that is not correct
20213 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
20214 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
20215 Additionally, DJGPP lacks @code{/bin/sh}, and when its
20216 GNU @command{make} port sees such a setting it enters a
20217 special emulation mode where features like pipes and redirections are
20218 emulated on top of DOS's @command{command.com}.  Unfortunately this
20219 emulation is incomplete; for instance it does not handle command
20220 substitutions.  Using @code{@@SHELL@@} means that your makefile will
20221 benefit from the same improved shell, such as @command{bash} or
20222 @command{ksh}, that was discovered during @command{configure}, so that
20223 you aren't fighting two different sets of shell bugs between the two
20224 contexts.
20226 Posix-compliant @command{make} should never acquire the value of
20227 $(SHELL) from the environment, even when @code{make -e} is used
20228 (otherwise, think about what would happen to your rules if
20229 @code{SHELL=/bin/tcsh}).
20231 However not all @command{make} implementations have this exception.
20232 For instance it's not surprising that Tru64 @command{make} doesn't
20233 protect @code{SHELL}, since it doesn't use it.
20235 @example
20236 $ @kbd{cat Makefile}
20237 SHELL = /bin/sh
20238 FOO = foo
20239 all:
20240         @@echo $(SHELL)
20241         @@echo $(FOO)
20242 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
20243 /bin/tcsh
20245 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
20246 /bin/sh
20248 @end example
20250 Conversely, @command{make} is not supposed to export any changes to the
20251 macro @code{SHELL} to child processes.  Again, many implementations
20252 break this rule:
20254 @example
20255 $ @kbd{cat Makefile}
20256 all:
20257         @@echo $(SHELL)
20258         @@printenv SHELL
20259 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
20260 /bin/ksh
20261 /bin/ksh
20262 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
20263 /bin/ksh
20265 @end example
20267 @node Parallel Make
20268 @section Parallel Make
20269 @cindex Parallel @command{make}
20271 Support for parallel execution in @command{make} implementation varies.
20272 Generally, using GNU make is your best bet.
20274 When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
20275 reuse the same shell for multiple commands within one recipe.  This can
20276 have various unexpected consequences.  For example, changes of directories
20277 or variables persist between recipes, so that:
20279 @example
20280 all:
20281         @@var=value; cd /; pwd; echo $$var; echo $$$$
20282         @@pwd; echo $$var; echo $$$$
20283 @end example
20285 @noindent
20286 may output the following with @code{make -j1}, at least on NetBSD up to
20287 5.1 and FreeBSD up to 8.2:
20289 @example
20291 value
20292 32235
20294 value
20295 32235
20296 @end example
20298 @noindent
20299 while without @option{-j1}, or with @option{-B}, the output looks less
20300 surprising:
20302 @example
20304 value
20305 32238
20306 /tmp
20308 32239
20309 @end example
20311 @noindent
20312 Another consequence is that, if one command in a recipe uses @code{exit 0}
20313 to indicate a successful exit, the shell will be gone and the remaining
20314 commands of this recipe will not be executed.
20316 The BSD @command{make} implementations, when run in parallel mode,
20317 will also pass the @command{Makefile} recipes to the shell through
20318 its standard input, thus making it unusable from the recipes:
20320 @example
20321 $ @kbd{cat Makefile}
20322 read:
20323         @@read line; echo LINE: $$line
20324 @c $$ @c restore font-lock
20325 $ @kbd{echo foo | make read}
20326 LINE: foo
20327 $ @kbd{echo foo | make -j1 read} # NetBSD 5.1 and FreeBSD 8.2
20328 LINE:
20329 @end example
20331 @noindent
20332 Moreover, when FreeBSD @command{make} (up at least to 8.2) is run in
20333 parallel mode, it implements the @code{@@} and @code{-} ``recipe
20334 modifiers'' by dynamically modifying the active shell flags.  This
20335 behavior has the effects of potentially clobbering the exit status
20336 of recipes silenced with the @code{@@} modifier if they also unset
20337 the @option{errexit} shell flag, and of mangling the output in
20338 unexpected ways:
20340 @example
20341 $ @kbd{cat Makefile}
20343         @@echo $$-; set +e; false
20345         -echo $$-; false; echo set -
20346 $ @kbd{make a; echo status: $?}
20347 ehBc
20348 *** Error code 1
20349 status: 1
20350 $ @kbd{make -j1 a; echo status: $?}
20352 status: 0
20353 $ @kbd{make b}
20354 echo $-; echo set -
20356 set -
20357 $ @kbd{make -j1 b}
20358 echo $-; echo hvB
20359 @end example
20361 @noindent
20362 You can avoid all these issues by using the @option{-B} option to enable
20363 compatibility semantics.  However, that will effectively also disable
20364 all parallelism as that will cause prerequisites to be updated in the
20365 order they are listed in a rule.
20367 Some make implementations (among them, FreeBSD @command{make}, NetBSD
20368 @command{make}, and Solaris @command{dmake}), when invoked with a
20369 @option{-j@var{N}} option, connect the standard output and standard
20370 error of all their child processes to pipes or temporary regular
20371 files.  This can lead to subtly different semantics in the behavior
20372 of the spawned processes.  For example, even if the @command{make}
20373 standard output is connected to a tty, the recipe command will not be:
20375 @example
20376 $ @kbd{cat Makefile}
20377 all:
20378         @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
20379 $ @kbd{make -j 2} # FreeBSD 8.2 make
20380 Is not a tty
20381 $ @kbd{make -j 2} # NetBSD 5.1 make
20382 --- all ---
20383 Is not a tty
20384 $ @kbd{dmake -j 2} # Solaris 10 dmake
20385 @var{hostname} --> 1 job
20386 @var{hostname} --> Job output
20387 Is not a tty
20388 @end example
20390 @noindent
20391 On the other hand:
20393 @example
20394 $ @kbd{make -j 2} # GNU make, Heirloom make
20395 Is a tty
20396 @end example
20398 @noindent
20399 The above examples also show additional status output produced in parallel
20400 mode for targets being updated by Solaris @command{dmake} and NetBSD
20401 @command{make} (but @emph{not} by FreeBSD @command{make}).
20403 Furthermore, parallel runs of those @command{make} implementations will
20404 route standard error from commands that they spawn into their own
20405 standard output, and may remove leading whitespace from output lines.
20408 @node Comments in Make Rules
20409 @section Comments in Make Rules
20410 @cindex Comments in @file{Makefile} rules
20411 @cindex @file{Makefile} rules and comments
20413 Never put comments in a rule.
20415 Some @command{make} treat anything starting with a tab as a command for
20416 the current rule, even if the tab is immediately followed by a @code{#}.
20417 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
20418 makefile runs @code{# foo} through the shell.
20420 @example
20421 all:
20422         # foo
20423 @end example
20425 As a workaround, you can use the @command{:} no-op command with a string
20426 argument that gets ignored:
20428 @example
20429 all:
20430         : "foo"
20431 @end example
20433 Conversely, if you want to use the @samp{#} character in some command,
20434 you can only do so by expanding it inside a rule (@pxref{Comments in
20435 Make Macros}).  So for example, if @samp{COMMENT_CHAR} is substituted by
20436 @command{config.status} as @samp{#}, then the following substitutes
20437 @samp{@@COMMENT_CHAR@@} in a generated header:
20439 @example
20440 foo.h: foo.h.in
20441         sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
20442             $(srcdir)/foo.h.in > $@@
20443 @end example
20445 The funny shell quoting avoids a substitution at @command{config.status}
20446 run time of the left-hand side of the @command{sed} @samp{s} command.
20448 @node Newlines in Make Rules
20449 @section Newlines in Make Rules
20450 @cindex Newlines in @file{Makefile} rules
20451 @cindex @file{Makefile} rules and newlines
20453 In shell scripts, newlines can be used inside string literals.  But in
20454 the shell statements of @file{Makefile} rules, this is not possible:
20455 A newline not preceded by a backslash is a separator between shell
20456 statements.  Whereas a newline that is preceded by a backslash becomes
20457 part of the shell statement according to POSIX, but gets replaced,
20458 together with the backslash that precedes it, by a space in GNU
20459 @command{make} 3.80 and older.  So, how can a newline be used in a string
20460 literal?
20462 The trick is to set up a shell variable that contains a newline:
20464 @example
20465 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"
20466 @end example
20468 For example, in order to create a multiline @samp{sed} expression that
20469 inserts a blank line after every line of a file, this code can be used:
20471 @example
20472 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"; \
20473 sed -e "s/\$$/\\$$@{nl@}/" < input > output
20474 @end example
20476 @node Comments in Make Macros
20477 @section Comments in Make Macros
20478 @cindex Comments in @file{Makefile} macros
20479 @cindex @file{Makefile} macros and comments
20481 Avoid putting comments in macro values as far as possible.  Posix
20482 specifies that the text starting from the @samp{#} sign until the end of
20483 the line is to be ignored, which has the unfortunate effect of
20484 disallowing them even within quotes.  Thus, the following might lead to
20485 a syntax error at compile time:
20487 @example
20488 CPPFLAGS = "-DCOMMENT_CHAR='#'"
20489 @end example
20491 @noindent
20492 as @samp{CPPFLAGS} may be expanded to @samp{"-DCOMMENT_CHAR='}.
20494 Most @command{make} implementations disregard this and treat single and
20495 double quotes specially here.  Also, GNU @command{make} lets you put
20496 @samp{#} into a macro value by escaping it with a backslash, i.e.,
20497 @samp{\#}.  However, neither of these usages are portable.
20498 @xref{Comments in Make Rules}, for a portable alternative.
20500 Even without quoting involved, comments can have surprising effects,
20501 because the whitespace before them is part of the variable value:
20503 @example
20504 foo = bar # trailing comment
20505 print: ; @@echo "$(foo)."
20506 @end example
20508 @noindent
20509 prints @samp{bar .}, which is usually not intended, and can expose
20510 @command{make} bugs as described below.
20512 @node Trailing whitespace in Make Macros
20513 @section Trailing whitespace in Make Macros
20514 @cindex whitespace in @file{Makefile} macros
20515 @cindex @file{Makefile} macros and whitespace
20517 GNU @command{make} 3.80 mistreats trailing whitespace in macro
20518 substitutions and appends another spurious suffix:
20520 @example
20521 empty =
20522 foo = bar $(empty)
20523 print: ; @@echo $(foo:=.test)
20524 @end example
20526 @noindent
20527 prints @samp{bar.test .test}.
20529 BSD and Solaris @command{make} implementations do not honor trailing
20530 whitespace in macro definitions as Posix requires:
20532 @example
20533 foo = bar # Note the space after "bar".
20534 print: ; @@echo $(foo)t
20535 @end example
20537 @noindent
20538 prints @samp{bart} instead of @samp{bar t}.  To work around this, you
20539 can use a helper macro as in the previous example.
20542 @node Command-line Macros and whitespace
20543 @section Command-line Macros and whitespace
20544 @cindex whitespace in command-line macros
20545 @cindex command-line, macros set on
20546 @cindex environment, macros set from
20548 Some @command{make} implementations may strip trailing whitespace off
20549 of macros set on the command line in addition to leading whitespace.
20550 Further, some may strip leading whitespace off of macros set from
20551 environment variables:
20553 @example
20554 $ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
20555   foo=' f f ' make -f - bar=' b b '}
20556 x f f xb b x  # AIX, BSD, GNU make
20557 xf f xb b x   # HP-UX, IRIX, Tru64/OSF make
20558 x f f xb bx   # Solaris make
20559 @end example
20562 @node obj/ and Make
20563 @section The @file{obj/} Subdirectory and Make
20564 @cindex @file{obj/}, subdirectory
20565 @cindex BSD @command{make} and @file{obj/}
20567 Never name one of your subdirectories @file{obj/} if you don't like
20568 surprises.
20570 If an @file{obj/} directory exists, BSD @command{make} enters it
20571 before reading the makefile.  Hence the makefile in the
20572 current directory is not read.
20574 @example
20575 $ @kbd{cat Makefile}
20576 all:
20577         echo Hello
20578 $ @kbd{cat obj/Makefile}
20579 all:
20580         echo World
20581 $ @kbd{make}      # GNU make
20582 echo Hello
20583 Hello
20584 $ @kbd{pmake}     # BSD make
20585 echo World
20586 World
20587 @end example
20589 @node make -k Status
20590 @section Exit Status of @code{make -k}
20591 @cindex @code{make -k}
20593 Do not rely on the exit status of @code{make -k}.  Some implementations
20594 reflect whether they encountered an error in their exit status; other
20595 implementations always succeed.
20597 @example
20598 $ @kbd{cat Makefile}
20599 all:
20600         false
20601 $ @kbd{make -k; echo exit status: $?}    # GNU make
20602 false
20603 make: *** [all] Error 1
20604 exit status: 2
20605 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
20606 false
20607 *** Error code 1 (continuing)
20608 exit status: 0
20609 @end example
20611 @node VPATH and Make
20612 @section @code{VPATH} and Make
20613 @cindex @code{VPATH}
20615 Posix does not specify the semantics of @code{VPATH}.  Typically,
20616 @command{make} supports @code{VPATH}, but its implementation is not
20617 consistent.
20619 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
20620 portable to recent-enough popular implementations of @command{make}, but
20621 to keep the resulting makefiles portable, a package's makefile
20622 prototypes must take the following issues into account.  These issues
20623 are complicated and are often poorly understood, and installers who use
20624 @code{VPATH} should expect to find many bugs in this area.  If you use
20625 @code{VPATH}, the simplest way to avoid these portability bugs is to
20626 stick with GNU @command{make}, since it is the most
20627 commonly-used @command{make} among Autoconf users.
20629 Here are some known issues with some @code{VPATH}
20630 implementations.
20632 @menu
20633 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
20634 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
20635 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
20636 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
20637 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
20638 * Make Target Lookup::          More details about @code{VPATH} lookup
20639 @end menu
20641 @node Variables listed in VPATH
20642 @subsection Variables listed in @code{VPATH}
20643 @cindex @code{VPATH} and variables
20644 @cindex variables and @code{VPATH}
20646 Do not set @code{VPATH} to the value of another variable, for example
20647 @samp{VPATH = $(srcdir)}, because some ancient versions of
20648 @command{make} do not do variable substitutions on the value of
20649 @code{VPATH}.  For example, use this
20651 @example
20652 srcdir = @@srcdir@@
20653 VPATH = @@srcdir@@
20654 @end example
20656 @noindent
20657 rather than @samp{VPATH = $(srcdir)}.  Note that with GNU
20658 Automake, there is no need to set this yourself.
20660 @node VPATH and Double-colon
20661 @subsection @code{VPATH} and Double-colon Rules
20662 @cindex @code{VPATH} and double-colon rules
20663 @cindex double-colon rules and @code{VPATH}
20665 With ancient versions of Sun @command{make},
20666 any assignment to @code{VPATH} causes @command{make} to execute only
20667 the first set of double-colon rules.
20668 However, this problem is no longer of practical concern.
20670 @node $< in Explicit Rules
20671 @subsection @code{$<} Not Supported in Explicit Rules
20672 @cindex explicit rules, @code{$<}, and @code{VPATH}
20673 @cindex @code{$<}, explicit rules, and @code{VPATH}
20674 @cindex @code{VPATH}, explicit rules, and @code{$<}
20676 Using @code{$<} in explicit rules is not portable.
20677 The prerequisite file must be named explicitly in the rule.  If you want
20678 to find the prerequisite via a @code{VPATH} search, you have to code the
20679 whole thing manually.  @xref{Build Directories}.
20681 @node Automatic Rule Rewriting
20682 @subsection Automatic Rule Rewriting
20683 @cindex @code{VPATH} and automatic rule rewriting
20684 @cindex automatic rule rewriting and @code{VPATH}
20686 Some @command{make} implementations, such as Solaris and Tru64,
20687 search for prerequisites in @code{VPATH} and
20688 then rewrite each occurrence as a plain word in the rule.
20689 For instance:
20691 @example
20692 # This isn't portable to GNU make.
20693 VPATH = ../pkg/src
20694 f.c: if.c
20695         cp if.c f.c
20696 @end example
20698 @noindent
20699 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
20700 found in @file{../pkg/src}.
20702 However, this rule leads to real problems in practice.  For example, if
20703 the source directory contains an ordinary file named @file{test} that is
20704 used in a dependency, Solaris @command{make} rewrites commands like
20705 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
20706 @dots{}}, which is typically undesirable.  In fact, @command{make} is
20707 completely unaware of shell syntax used in the rules, so the VPATH
20708 rewrite can potentially apply to @emph{any} whitespace-separated word
20709 in a rule, including shell variables, functions, and keywords.
20711 @example
20712 $ @kbd{mkdir build}
20713 $ @kbd{cd build}
20714 $ @kbd{cat > Makefile <<'END'}
20715 VPATH = ..
20716 all: arg func for echo
20717         func () @{ for arg in "$$@@"; do echo $$arg; done; @}; \
20718         func "hello world"
20720 $ @kbd{touch ../arg ../func ../for ../echo}
20721 $ @kbd{make}
20722 ../func () @{ ../for ../arg in "$@@"; do ../echo $arg; done; @}; \
20723 ../func "hello world"
20724 sh: syntax error at line 1: `do' unexpected
20725 *** Error code 2
20726 @end example
20728 @noindent
20729 To avoid this problem, portable makefiles should never mention a source
20730 file or dependency whose name is that of a shell keyword like @file{for}
20731 or @file{until}, a shell command like @command{cat} or @command{gcc} or
20732 @command{test}, or a shell function or variable used in the corresponding
20733 @command{Makefile} recipe.
20735 Because of these problems GNU @command{make} and many other @command{make}
20736 implementations do not rewrite commands, so portable makefiles should
20737 search @code{VPATH} manually.  It is tempting to write this:
20739 @smallexample
20740 # This isn't portable to Solaris make.
20741 VPATH = ../pkg/src
20742 f.c: if.c
20743         cp `test -f if.c || echo $(VPATH)/`if.c f.c
20744 @end smallexample
20746 @noindent
20747 However, the ``prerequisite rewriting'' still applies here.  So if
20748 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
20749 execute
20751 @smallexample
20752 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
20753 @end smallexample
20755 @noindent
20756 which reduces to
20758 @example
20759 cp if.c f.c
20760 @end example
20762 @noindent
20763 and thus fails.  Oops.
20765 A simple workaround, and good practice anyway, is to use @samp{$?} and
20766 @samp{$@@} when possible:
20768 @smallexample
20769 VPATH = ../pkg/src
20770 f.c: if.c
20771         cp $? $@@
20772 @end smallexample
20774 @noindent
20775 but this does not generalize well to commands with multiple
20776 prerequisites.  A more general workaround is to rewrite the rule so that
20777 the prerequisite @file{if.c} never appears as a plain word.  For
20778 example, these three rules would be safe, assuming @file{if.c} is in
20779 @file{../pkg/src} and the other files are in the working directory:
20781 @smallexample
20782 VPATH = ../pkg/src
20783 f.c: if.c f1.c
20784         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
20785 g.c: if.c g1.c
20786         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
20787 h.c: if.c h1.c
20788         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
20789 @end smallexample
20791 Things get worse when your prerequisites are in a macro.
20793 @example
20794 VPATH = ../pkg/src
20795 HEADERS = f.h g.h h.h
20796 install-HEADERS: $(HEADERS)
20797         for i in $(HEADERS); do \
20798           $(INSTALL) -m 644 \
20799             `test -f $$i || echo $(VPATH)/`$$i \
20800             $(DESTDIR)$(includedir)/$$i; \
20801 @c $$ restore font-lock
20802         done
20803 @end example
20805 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
20806 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
20807 where @code{f.h} and @code{g.h} are plain words and are hence
20808 subject to @code{VPATH} adjustments.
20810 If the three files are in @file{../pkg/src}, the rule is run as:
20812 @example
20813 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
20814   install -m 644 \
20815      `test -f $i || echo ../pkg/src/`$i \
20816      /usr/local/include/$i; \
20817 done
20818 @end example
20820 where the two first @command{install} calls fail.  For instance,
20821 consider the @code{f.h} installation:
20823 @example
20824 install -m 644 \
20825   `test -f ../pkg/src/f.h || \
20826     echo ../pkg/src/ \
20827   `../pkg/src/f.h \
20828   /usr/local/include/../pkg/src/f.h;
20829 @end example
20831 @noindent
20832 It reduces to:
20834 @example
20835 install -m 644 \
20836   ../pkg/src/f.h \
20837   /usr/local/include/../pkg/src/f.h;
20838 @end example
20840 Note that the manual @code{VPATH} search did not cause any problems here;
20841 however this command installs @file{f.h} in an incorrect directory.
20843 Trying to quote @code{$(HEADERS)} in some way, as we did for
20844 @code{foo.c} a few makefiles ago, does not help:
20846 @example
20847 install-HEADERS: $(HEADERS)
20848         headers='$(HEADERS)'; \
20849         for i in $$headers; do \
20850           $(INSTALL) -m 644 \
20851             `test -f $$i || echo $(VPATH)/`$$i \
20852             $(DESTDIR)$(includedir)/$$i; \
20853         done
20854 @end example
20856 Now, @code{headers='$(HEADERS)'} macro-expands to:
20858 @example
20859 headers='f.h g.h h.h'
20860 @end example
20862 @noindent
20863 but @code{g.h} is still a plain word.  (As an aside, the idiom
20864 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
20865 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
20866 syntax error on @code{for i in;}.)
20868 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
20870 @example
20871 VPATH = ../pkg/src
20872 HEADERS = f.h g.h h.h
20873 install-HEADERS: $(HEADERS)
20874         headers='$(HEADERS)'; \
20875         for i in $$headers; do \
20876           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
20877           $(INSTALL) -m 644 \
20878             `test -f $$i || echo $(VPATH)/`$$i \
20879             $(DESTDIR)$(includedir)/$$i; \
20880 @c $$ restore font-lock
20881         done
20882 @end example
20884 Automake does something similar.  However the above hack works only if
20885 the files listed in @code{HEADERS} are in the current directory or a
20886 subdirectory; they should not be in an enclosing directory.  If we had
20887 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
20888 build with Tru64 @command{make}.  The reason is that not only does
20889 Tru64 @command{make} rewrite dependencies, but it also simplifies
20890 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
20891 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
20892 a leading @file{../pkg/src/} component.
20894 The following example makes the behavior of Tru64 @command{make}
20895 more apparent.
20897 @example
20898 $ @kbd{cat Makefile}
20899 VPATH = sub
20900 all: ../foo
20901         echo ../foo
20902 $ @kbd{ls}
20903 Makefile foo
20904 $ @kbd{make}
20905 echo foo
20907 @end example
20909 @noindent
20910 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
20911 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
20912 directory does not even exist, this just means that the simplification
20913 occurred before the file was checked for.)
20915 For the record here is how SunOS 4 @command{make} behaves on this
20916 example.
20918 @smallexample
20919 $ @kbd{make}
20920 make: Fatal error: Don't know how to make target `../foo'
20921 $ @kbd{mkdir sub}
20922 $ @kbd{make}
20923 echo sub/../foo
20924 sub/../foo
20925 @end smallexample
20928 @node Tru64 Directory Magic
20929 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
20930 @cindex @code{VPATH} and prerequisite directories
20931 @cindex prerequisite directories and @code{VPATH}
20933 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
20934 @command{make} creates it in the current directory.
20936 @example
20937 $ @kbd{mkdir -p foo/bar build}
20938 $ @kbd{cd build}
20939 $ @kbd{cat >Makefile <<END
20940 VPATH = ..
20941 all: foo/bar
20942 END}
20943 $ @kbd{make}
20944 mkdir foo
20945 mkdir foo/bar
20946 @end example
20948 This can yield unexpected results if a rule uses a manual @code{VPATH}
20949 search as presented before.
20951 @example
20952 VPATH = ..
20953 all : foo/bar
20954         command `test -d foo/bar || echo ../`foo/bar
20955 @end example
20957 The above @command{command} is run on the empty @file{foo/bar}
20958 directory that was created in the current directory.
20960 @node Make Target Lookup
20961 @subsection Make Target Lookup
20962 @cindex @code{VPATH}, resolving target pathnames
20964 GNU @command{make} uses a complex algorithm to decide when it
20965 should use files found via a @code{VPATH} search.  @xref{Search
20966 Algorithm, , How Directory Searches are Performed, make, The GNU Make
20967 Manual}.
20969 If a target needs to be rebuilt, GNU @command{make} discards the
20970 file name found during the @code{VPATH} search for this target, and
20971 builds the file locally using the file name given in the makefile.
20972 If a target does not need to be rebuilt, GNU @command{make} uses the
20973 file name found during the @code{VPATH} search.
20975 Other @command{make} implementations, like NetBSD @command{make}, are
20976 easier to describe: the file name found during the @code{VPATH} search
20977 is used whether the target needs to be rebuilt or not.  Therefore
20978 new files are created locally, but existing files are updated at their
20979 @code{VPATH} location.
20981 OpenBSD and FreeBSD @command{make}, however,
20982 never perform a
20983 @code{VPATH} search for a dependency that has an explicit rule.
20984 This is extremely annoying.
20986 When attempting a @code{VPATH} build for an autoconfiscated package
20987 (e.g., @code{mkdir build && cd build && ../configure}), this means
20989 @command{make} builds everything locally in the @file{build}
20990 directory, while BSD @command{make} builds new files locally and
20991 updates existing files in the source directory.
20993 @example
20994 $ @kbd{cat Makefile}
20995 VPATH = ..
20996 all: foo.x bar.x
20997 foo.x bar.x: newer.x
20998         @@echo Building $@@
20999 $ @kbd{touch ../bar.x}
21000 $ @kbd{touch ../newer.x}
21001 $ @kbd{make}        # GNU make
21002 Building foo.x
21003 Building bar.x
21004 $ @kbd{pmake}       # NetBSD make
21005 Building foo.x
21006 Building ../bar.x
21007 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21008 Building foo.x
21009 Building bar.x
21010 $ @kbd{tmake}       # Tru64 make
21011 Building foo.x
21012 Building bar.x
21013 $ @kbd{touch ../bar.x}
21014 $ @kbd{make}        # GNU make
21015 Building foo.x
21016 $ @kbd{pmake}       # NetBSD make
21017 Building foo.x
21018 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21019 Building foo.x
21020 Building bar.x
21021 $ @kbd{tmake}       # Tru64 make
21022 Building foo.x
21023 Building bar.x
21024 @end example
21026 Note how NetBSD @command{make} updates @file{../bar.x} in its
21027 VPATH location, and how FreeBSD, OpenBSD, and Tru64
21028 @command{make} always
21029 update @file{bar.x}, even when @file{../bar.x} is up to date.
21031 Another point worth mentioning is that once GNU @command{make} has
21032 decided to ignore a @code{VPATH} file name (e.g., it ignored
21033 @file{../bar.x} in the above example) it continues to ignore it when
21034 the target occurs as a prerequisite of another rule.
21036 The following example shows that GNU @command{make} does not look up
21037 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
21038 because it ignored the @code{VPATH} result of @file{bar.x} while running
21039 the @code{bar.x: newer.x} rule.
21041 @example
21042 $ @kbd{cat Makefile}
21043 VPATH = ..
21044 all: bar.y
21045 bar.x: newer.x
21046         @@echo Building $@@
21047 .SUFFIXES: .x .y
21048 .x.y:
21049         cp $< $@@
21050 $ @kbd{touch ../bar.x}
21051 $ @kbd{touch ../newer.x}
21052 $ @kbd{make}        # GNU make
21053 Building bar.x
21054 cp bar.x bar.y
21055 cp: cannot stat `bar.x': No such file or directory
21056 make: *** [bar.y] Error 1
21057 $ @kbd{pmake}       # NetBSD make
21058 Building ../bar.x
21059 cp ../bar.x bar.y
21060 $ @kbd{rm bar.y}
21061 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21062 echo Building bar.x
21063 cp bar.x bar.y
21064 cp: cannot stat `bar.x': No such file or directory
21065 *** Error code 1
21066 $ @kbd{tmake}       # Tru64 make
21067 Building bar.x
21068 cp: bar.x: No such file or directory
21069 *** Exit 1
21070 @end example
21072 Note that if you drop away the command from the @code{bar.x: newer.x}
21073 rule, GNU @command{make} magically starts to work: it
21074 knows that @code{bar.x} hasn't been updated, therefore it doesn't
21075 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
21076 uses.  Tru64 also works, but FreeBSD and OpenBSD
21077 still don't.
21079 @example
21080 $ @kbd{cat Makefile}
21081 VPATH = ..
21082 all: bar.y
21083 bar.x: newer.x
21084 .SUFFIXES: .x .y
21085 .x.y:
21086         cp $< $@@
21087 $ @kbd{touch ../bar.x}
21088 $ @kbd{touch ../newer.x}
21089 $ @kbd{make}        # GNU make
21090 cp ../bar.x bar.y
21091 $ @kbd{rm bar.y}
21092 $ @kbd{pmake}       # NetBSD make
21093 cp ../bar.x bar.y
21094 $ @kbd{rm bar.y}
21095 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21096 cp bar.x bar.y
21097 cp: cannot stat `bar.x': No such file or directory
21098 *** Error code 1
21099 $ @kbd{tmake}       # Tru64 make
21100 cp ../bar.x bar.y
21101 @end example
21103 It seems the sole solution that would please every @command{make}
21104 implementation is to never rely on @code{VPATH} searches for targets.
21105 In other words, @code{VPATH} should be reserved to unbuilt sources.
21108 @node Single Suffix Rules
21109 @section Single Suffix Rules and Separated Dependencies
21110 @cindex Single Suffix Inference Rule
21111 @cindex Rule, Single Suffix Inference
21112 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
21113 (@samp{.from.to:}), but which @emph{destination} suffix is empty
21114 (@samp{.from:}).
21116 @cindex Separated Dependencies
21117 @dfn{Separated dependencies} simply refers to listing the prerequisite
21118 of a target, without defining a rule.  Usually one can list on the one
21119 hand side, the rules, and on the other hand side, the dependencies.
21121 Solaris @command{make} does not support separated dependencies for
21122 targets defined by single suffix rules:
21124 @example
21125 $ @kbd{cat Makefile}
21126 .SUFFIXES: .in
21127 foo: foo.in
21128 .in:
21129         cp $< $@@
21130 $ @kbd{touch foo.in}
21131 $ @kbd{make}
21132 $ @kbd{ls}
21133 Makefile  foo.in
21134 @end example
21136 @noindent
21137 while GNU Make does:
21139 @example
21140 $ @kbd{gmake}
21141 cp foo.in foo
21142 $ @kbd{ls}
21143 Makefile  foo       foo.in
21144 @end example
21146 Note it works without the @samp{foo: foo.in} dependency.
21148 @example
21149 $ @kbd{cat Makefile}
21150 .SUFFIXES: .in
21151 .in:
21152         cp $< $@@
21153 $ @kbd{make foo}
21154 cp foo.in foo
21155 @end example
21157 @noindent
21158 and it works with double suffix inference rules:
21160 @example
21161 $ @kbd{cat Makefile}
21162 foo.out: foo.in
21163 .SUFFIXES: .in .out
21164 .in.out:
21165         cp $< $@@
21166 $ @kbd{make}
21167 cp foo.in foo.out
21168 @end example
21170 As a result, in such a case, you have to write target rules.
21172 @node Timestamps and Make
21173 @section Timestamp Resolution and Make
21174 @cindex timestamp resolution
21175 Traditionally, file timestamps had 1-second resolution, and
21176 @command{make} used those timestamps to determine whether one file was
21177 newer than the other.  However, many modern file systems have
21178 timestamps with 1-nanosecond resolution.  Some @command{make}
21179 implementations look at the entire timestamp; others ignore the
21180 fractional part, which can lead to incorrect results.  Normally this
21181 is not a problem, but in some extreme cases you may need to use tricks
21182 like @samp{sleep 1} to work around timestamp truncation bugs.
21184 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
21185 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
21186 Tools}).  Hence you should be wary of rules like this:
21188 @example
21189 dest: src
21190         cp -p src dest
21191 @end example
21193 as @file{dest} often appears to be older than @file{src} after the
21194 timestamp is truncated, and this can cause @command{make} to do
21195 needless rework the next time it is invoked.  To work around this
21196 problem, you can use a timestamp file, e.g.:
21198 @example
21199 dest-stamp: src
21200         cp -p src dest
21201         date >dest-stamp
21202 @end example
21204 Apart from timestamp resolution, there are also differences in handling
21205 equal timestamps.  HP-UX @command{make} updates targets if it has the
21206 same time stamp as one of its prerequisites, in violation of Posix rules.
21208 This can cause spurious rebuilds for repeated runs of @command{make}.
21209 This in turn can cause @command{make} to fail if it tries to rebuild
21210 generated files in a possibly read-only source tree with tools not
21211 present on the end-user machine.  Use GNU @command{make} instead.
21215 @c ======================================== Portable C and C++ Programming
21217 @node Portable C and C++
21218 @chapter Portable C and C++ Programming
21219 @cindex Portable C and C++ programming
21221 C and C++ programs often use low-level features of the underlying
21222 system, and therefore are often more difficult to make portable to other
21223 platforms.
21225 Several standards have been developed to help make your programs more
21226 portable.  If you write programs with these standards in mind, you can
21227 have greater confidence that your programs work on a wide variety
21228 of systems.
21229 @ifhtml
21230 @uref{http://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
21231 Standards Supported by GCC}
21232 @end ifhtml
21233 @ifnothtml
21234 @xref{Standards, , Language Standards Supported by
21235 GCC, gcc, Using the GNU Compiler Collection
21236 (GCC)},
21237 @end ifnothtml
21238 for a list of C-related standards.  Many programs also assume the
21239 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
21241 Some old code is written to be portable to K&R C, which predates any C
21242 standard.  K&R C compilers are no longer of practical interest, though,
21243 and the rest of section assumes at least C89, the first C standard.
21245 Program portability is a huge topic, and this section can only briefly
21246 introduce common pitfalls.  @xref{System Portability, , Portability
21247 between System Types, standards, The GNU Coding Standards}, for
21248 more information.
21250 @menu
21251 * Varieties of Unportability::  How to make your programs unportable
21252 * Integer Overflow::            When integers get too large
21253 * Preprocessor Arithmetic::     @code{#if} expression problems
21254 * Null Pointers::               Properties of null pointers
21255 * Buffer Overruns::             Subscript errors and the like
21256 * Volatile Objects::            @code{volatile} and signals
21257 * Floating Point Portability::  Portable floating-point arithmetic
21258 * Exiting Portably::            Exiting and the exit status
21259 @end menu
21261 @node Varieties of Unportability
21262 @section Varieties of Unportability
21263 @cindex portability
21265 Autoconf tests and ordinary programs often need to test what is allowed
21266 on a system, and therefore they may need to deliberately exceed the
21267 boundaries of what the standards allow, if only to see whether an
21268 optional feature is present.  When you write such a program, you should
21269 keep in mind the difference between constraints, unspecified behavior,
21270 and undefined behavior.
21272 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
21273 example constraint is that C programs must not declare a bit-field with
21274 negative width.  Tests can therefore reliably assume that programs with
21275 negative-width bit-fields are rejected by a compiler that conforms
21276 to the standard.
21278 @dfn{Unspecified behavior} is valid behavior, where the standard allows
21279 multiple possibilities.  For example, the order of evaluation of
21280 function arguments is unspecified.  Some unspecified behavior is
21281 @dfn{implementation-defined}, i.e., documented by the implementation,
21282 but since Autoconf tests cannot read the documentation they cannot
21283 distinguish between implementation-defined and other unspecified
21284 behavior.  It is common for Autoconf tests to probe implementations to
21285 determine otherwise-unspecified behavior.
21287 @dfn{Undefined behavior} is invalid behavior, where the standard allows
21288 the implementation to do anything it pleases.  For example,
21289 dereferencing a null pointer leads to undefined behavior.  If possible,
21290 test programs should avoid undefined behavior, since a program with
21291 undefined behavior might succeed on a test that should fail.
21293 The above rules apply to programs that are intended to conform to the
21294 standard.  However, strictly-conforming programs are quite rare, since
21295 the standards are so limiting.  A major goal of Autoconf is to support
21296 programs that use implementation features not described by the standard,
21297 and it is fairly common for test programs to violate the above rules, if
21298 the programs work well enough in practice.
21300 @node Integer Overflow
21301 @section Integer Overflow
21302 @cindex integer overflow
21303 @cindex overflow, signed integer
21304 @cindex signed integer overflow
21305 @cindex wraparound arithmetic
21307 In practice many portable C programs assume that signed integer overflow wraps
21308 around reliably using two's complement arithmetic.  Yet the C standard
21309 says that program behavior is undefined on overflow, and in a few cases
21310 C programs do not work on some modern implementations because their
21311 overflows do not wrap around as their authors expected.  Conversely, in
21312 signed integer remainder, the C standard requires overflow
21313 behavior that is commonly not implemented.
21315 @menu
21316 * Integer Overflow Basics::     Why integer overflow is a problem
21317 * Signed Overflow Examples::    Examples of code assuming wraparound
21318 * Optimization and Wraparound::  Optimizations that break uses of wraparound
21319 * Signed Overflow Advice::      Practical advice for signed overflow issues
21320 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
21321 @end menu
21323 @node Integer Overflow Basics
21324 @subsection Basics of Integer Overflow
21325 @cindex integer overflow
21326 @cindex overflow, signed integer
21327 @cindex signed integer overflow
21328 @cindex wraparound arithmetic
21330 In languages like C, unsigned integer overflow reliably wraps around;
21331 e.g., @code{UINT_MAX + 1} yields zero.
21332 This is guaranteed by the C standard and is
21333 portable in practice, unless you specify aggressive,
21334 nonstandard optimization options
21335 suitable only for special applications.
21337 In contrast, the C standard says that signed integer overflow leads to
21338 undefined behavior where a program can do anything, including dumping
21339 core or overrunning a buffer.  The misbehavior can even precede the
21340 overflow.  Such an overflow can occur during addition, subtraction,
21341 multiplication, division, and left shift.
21343 Despite this requirement of the standard, many C programs and Autoconf
21344 tests assume that signed integer overflow silently wraps around modulo a
21345 power of two, using two's complement arithmetic, so long as you cast the
21346 resulting value to a signed integer type or store it into a signed
21347 integer variable.  If you use conservative optimization flags, such
21348 programs are generally portable to the vast majority of modern
21349 platforms, with a few exceptions discussed later.
21351 For historical reasons the C standard also allows implementations with
21352 ones' complement or signed magnitude arithmetic, but it is safe to
21353 assume two's complement nowadays.
21355 Also, overflow can occur when converting an out-of-range value to a
21356 signed integer type.  Here a standard implementation must define what
21357 happens, but this might include raising an exception.  In practice all
21358 known implementations support silent wraparound in this case, so you need
21359 not worry about other possibilities.
21361 @node Signed Overflow Examples
21362 @subsection Examples of Code Assuming Wraparound Overflow
21363 @cindex integer overflow
21364 @cindex overflow, signed integer
21365 @cindex signed integer overflow
21366 @cindex wraparound arithmetic
21368 There has long been a tension between what the C standard requires for
21369 signed integer overflow, and what C programs commonly assume.  The
21370 standard allows aggressive optimizations based on assumptions that
21371 overflow never occurs, but many practical C programs rely on overflow
21372 wrapping around.  These programs do not conform to the standard, but
21373 they commonly work in practice because compiler writers are
21374 understandably reluctant to implement optimizations that would break
21375 many programs, unless perhaps a user specifies aggressive optimization.
21377 The C Standard says that if a program has signed integer overflow its
21378 behavior is undefined, and the undefined behavior can even precede the
21379 overflow.  To take an extreme example:
21381 @c Inspired by Robert Dewar's example in
21382 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
21383 @example
21384 if (password == expected_password)
21385   allow_superuser_privileges ();
21386 else if (counter++ == INT_MAX)
21387   abort ();
21388 else
21389   printf ("%d password mismatches\n", counter);
21390 @end example
21392 @noindent
21393 If the @code{int} variable @code{counter} equals @code{INT_MAX},
21394 @code{counter++} must overflow and the behavior is undefined, so the C
21395 standard allows the compiler to optimize away the test against
21396 @code{INT_MAX} and the @code{abort} call.
21397 Worse, if an earlier bug in the program lets the compiler deduce that
21398 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
21399 the C standard allows the compiler to optimize away the password test
21400 and generate code that allows superuser privileges unconditionally.
21402 Despite this requirement by the standard, it has long been common for C
21403 code to assume wraparound arithmetic after signed overflow, and all
21404 known practical C implementations support some C idioms that assume
21405 wraparound signed arithmetic, even if the idioms do not conform
21406 strictly to the standard.  If your code looks like the following
21407 examples it will almost surely work with real-world compilers.
21409 Here is an example derived from the 7th Edition Unix implementation of
21410 @code{atoi} (1979-01-10):
21412 @example
21413 char *p;
21414 int f, n;
21415 @dots{}
21416 while (*p >= '0' && *p <= '9')
21417   n = n * 10 + *p++ - '0';
21418 return (f ? -n : n);
21419 @end example
21421 @noindent
21422 Even if the input string is in range, on most modern machines this has
21423 signed overflow when computing the most negative integer (the @code{-n}
21424 overflows) or a value near an extreme integer (the first @code{+}
21425 overflows).
21427 Here is another example, derived from the 7th Edition implementation of
21428 @code{rand} (1979-01-10).  Here the programmer expects both
21429 multiplication and addition to wrap on overflow:
21431 @example
21432 static long int randx = 1;
21433 @dots{}
21434 randx = randx * 1103515245 + 12345;
21435 return (randx >> 16) & 077777;
21436 @end example
21438 In the following example, derived from the GNU C Library 2.5
21439 implementation of @code{mktime} (2006-09-09), the code assumes
21440 wraparound arithmetic in @code{+} to detect signed overflow:
21442 @example
21443 time_t t, t1, t2;
21444 int sec_requested, sec_adjustment;
21445 @dots{}
21446 t1 = t + sec_requested;
21447 t2 = t1 + sec_adjustment;
21448 if (((t1 < t) != (sec_requested < 0))
21449     | ((t2 < t1) != (sec_adjustment < 0)))
21450   return -1;
21451 @end example
21453 If your code looks like these examples, it is probably safe even though
21454 it does not strictly conform to the C standard.  This might lead one to
21455 believe that one can generally assume wraparound on overflow, but that
21456 is not always true, as can be seen in the next section.
21458 @node Optimization and Wraparound
21459 @subsection Optimizations That Break Wraparound Arithmetic
21460 @cindex loop induction
21462 Compilers sometimes generate code that is incompatible with wraparound
21463 integer arithmetic.  A simple example is an algebraic simplification: a
21464 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
21465 because it assumes that @code{i * 2000} does not overflow.  The
21466 translation is not equivalent to the original when overflow occurs:
21467 e.g., in the typical case of 32-bit signed two's complement wraparound
21468 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
21469 the original expression returns @minus{}2147483 but the optimized
21470 version returns the mathematically correct value 2147484.
21472 More subtly, loop induction optimizations often exploit the undefined
21473 behavior of signed overflow.  Consider the following contrived function
21474 @code{sumc}:
21476 @example
21478 sumc (int lo, int hi)
21480   int sum = 0;
21481   int i;
21482   for (i = lo; i <= hi; i++)
21483     sum ^= i * 53;
21484   return sum;
21486 @end example
21488 @noindent
21489 To avoid multiplying by 53 each time through the loop, an optimizing
21490 compiler might internally transform @code{sumc} to the equivalent of the
21491 following:
21493 @example
21495 transformed_sumc (int lo, int hi)
21497   int sum = 0;
21498   int hic = hi * 53;
21499   int ic;
21500   for (ic = lo * 53; ic <= hic; ic += 53)
21501     sum ^= ic;
21502   return sum;
21504 @end example
21506 @noindent
21507 This transformation is allowed by the C standard, but it is invalid for
21508 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
21509 overflow in computing expressions like @code{hi * 53} can cause the
21510 expression @code{i <= hi} to yield a different value from the
21511 transformed expression @code{ic <= hic}.
21513 For this reason, compilers that use loop induction and similar
21514 techniques often do not support reliable wraparound arithmetic when a
21515 loop induction variable like @code{ic} is involved.  Since loop
21516 induction variables are generated by the compiler, and are not visible
21517 in the source code, it is not always trivial to say whether the problem
21518 affects your code.
21520 Hardly any code actually depends on wraparound arithmetic in cases like
21521 these, so in practice these loop induction optimizations are almost
21522 always useful.  However, edge cases in this area can cause problems.
21523 For example:
21525 @example
21526 int j;
21527 for (j = 1; 0 < j; j *= 2)
21528   test (j);
21529 @end example
21531 @noindent
21532 Here, the loop attempts to iterate through all powers of 2 that
21533 @code{int} can represent, but the C standard allows a compiler to
21534 optimize away the comparison and generate an infinite loop,
21535 under the argument that behavior is undefined on overflow.  As of this
21536 writing this optimization is not done by any production version of
21537 GCC with @option{-O2}, but it might be performed by other
21538 compilers, or by more aggressive GCC optimization options,
21539 and the GCC developers have not decided whether it will
21540 continue to work with GCC and @option{-O2}.
21542 @node Signed Overflow Advice
21543 @subsection Practical Advice for Signed Overflow Issues
21544 @cindex integer overflow
21545 @cindex overflow, signed integer
21546 @cindex signed integer overflow
21547 @cindex wraparound arithmetic
21549 Ideally the safest approach is to avoid signed integer overflow
21550 entirely.  For example, instead of multiplying two signed integers, you
21551 can convert them to unsigned integers, multiply the unsigned values,
21552 then test whether the result is in signed range.
21554 Rewriting code in this way will be inconvenient, though, particularly if
21555 the signed values might be negative.  Also, it may hurt
21556 performance.  Using unsigned arithmetic to check for overflow is
21557 particularly painful to do portably and efficiently when dealing with an
21558 integer type like @code{uid_t} whose width and signedness vary from
21559 platform to platform.
21561 Furthermore, many C applications pervasively assume wraparound behavior
21562 and typically it is not easy to find and remove all these assumptions.
21563 Hence it is often useful to maintain nonstandard code that assumes
21564 wraparound on overflow, instead of rewriting the code.  The rest of this
21565 section attempts to give practical advice for this situation.
21567 If your code wants to detect signed integer overflow in @code{sum = a +
21568 b}, it is generally safe to use an expression like @code{(sum < a) != (b
21569 < 0)}.
21571 If your code uses a signed loop index, make sure that the index cannot
21572 overflow, along with all signed expressions derived from the index.
21573 Here is a contrived example of problematic code with two instances of
21574 overflow.
21576 @example
21577 for (i = INT_MAX - 10; i <= INT_MAX; i++)
21578   if (i + 1 < 0)
21579     @{
21580       report_overflow ();
21581       break;
21582     @}
21583 @end example
21585 @noindent
21586 Because of the two overflows, a compiler might optimize away or
21587 transform the two comparisons in a way that is incompatible with the
21588 wraparound assumption.
21590 If your code uses an expression like @code{(i * 2000) / 1000} and you
21591 actually want the multiplication to wrap around on overflow, use
21592 unsigned arithmetic
21593 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
21595 If your code assumes wraparound behavior and you want to insulate it
21596 against any GCC optimizations that would fail to support that
21597 behavior, you should use GCC's @option{-fwrapv} option, which
21598 causes signed overflow to wrap around reliably (except for division and
21599 remainder, as discussed in the next section).
21601 If you need to port to platforms where signed integer overflow does not
21602 reliably wrap around (e.g., due to hardware overflow checking, or to
21603 highly aggressive optimizations), you should consider debugging with
21604 GCC's @option{-ftrapv} option, which causes signed overflow to
21605 raise an exception.
21607 @node Signed Integer Division
21608 @subsection Signed Integer Division and Integer Overflow
21609 @cindex division, integer
21611 Overflow in signed
21612 integer division is not always harmless: for example, on CPUs of the
21613 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
21614 which by default terminates the program.  Worse, taking the remainder
21615 of these two values typically yields the same signal on these CPUs,
21616 even though the C standard requires @code{INT_MIN % -1} to yield zero
21617 because the expression does not overflow.
21619 @node Preprocessor Arithmetic
21620 @section Preprocessor Arithmetic
21621 @cindex preprocessor arithmetic
21623 In C99 and later, preprocessor arithmetic, used for @code{#if}
21624 expressions, must
21625 be evaluated as if all signed values are of type @code{intmax_t} and all
21626 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
21627 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
21628 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
21629 @code{long long int}.  Also, some older preprocessors mishandle
21630 constants ending in @code{LL}.  To work around these problems, you can
21631 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
21632 @code{configure}-time rather than at @code{#if}-time.
21634 @node Null Pointers
21635 @section Properties of Null Pointers
21636 @cindex null pointers
21638 Most modern hosts reliably fail when you attempt to dereference a null
21639 pointer.
21641 On almost all modern hosts, null pointers use an all-bits-zero internal
21642 representation, so you can reliably use @code{memset} with 0 to set all
21643 the pointers in an array to null values.
21645 If @code{p} is a null pointer to an object type, the C expression
21646 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
21647 the standard says that it has undefined behavior.
21649 @node Buffer Overruns
21650 @section Buffer Overruns and Subscript Errors
21651 @cindex buffer overruns
21653 Buffer overruns and subscript errors are the most common dangerous
21654 errors in C programs.  They result in undefined behavior because storing
21655 outside an array typically modifies storage that is used by some other
21656 object, and most modern systems lack runtime checks to catch these
21657 errors.  Programs should not rely on buffer overruns being caught.
21659 There is one exception to the usual rule that a portable program cannot
21660 address outside an array.  In C, it is valid to compute the address just
21661 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
21662 so long as you do not dereference the resulting pointer.  But it is not
21663 valid to compute the address just before an object, e.g., @code{&a[-1]};
21664 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
21665 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
21666 reliable in general, and it is usually easy enough to avoid the
21667 potential portability problem, e.g., by allocating an extra unused array
21668 element at the start or end.
21670 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
21672 users might also consider using the @option{-fmudflap} option to catch
21673 overruns.
21675 Buffer overruns are usually caused by off-by-one errors, but there are
21676 more subtle ways to get them.
21678 Using @code{int} values to index into an array or compute array sizes
21679 causes problems on typical 64-bit hosts where an array index might
21680 be @math{2^{31}} or larger.  Index values of type @code{size_t} avoid this
21681 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
21682 are signed, and are wide enough in practice.
21684 If you add or multiply two numbers to calculate an array size, e.g.,
21685 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
21686 multiplication overflows.
21688 Many implementations of the @code{alloca} function silently misbehave
21689 and can generate buffer overflows if given sizes that are too large.
21690 The size limits are implementation dependent, but are at least 4000
21691 bytes on all platforms that we know about.
21693 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
21694 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
21695 portable code should not use them unless the inputs are known to be
21696 within certain limits.  The time-related functions can overflow their
21697 buffers if given timestamps out of range (e.g., a year less than -999
21698 or greater than 9999).  Time-related buffer overflows cannot happen with
21699 recent-enough versions of the GNU C library, but are possible
21700 with other
21701 implementations.  The @code{gets} function is the worst, since it almost
21702 invariably overflows its buffer when presented with an input line larger
21703 than the buffer.
21705 @node Volatile Objects
21706 @section Volatile Objects
21707 @cindex volatile objects
21709 The keyword @code{volatile} is often misunderstood in portable code.
21710 Its use inhibits some memory-access optimizations, but programmers often
21711 wish that it had a different meaning than it actually does.
21713 @code{volatile} was designed for code that accesses special objects like
21714 memory-mapped device registers whose contents spontaneously change.
21715 Such code is inherently low-level, and it is difficult to specify
21716 portably what @code{volatile} means in these cases.  The C standard
21717 says, ``What constitutes an access to an object that has
21718 volatile-qualified type is implementation-defined,'' so in theory each
21719 implementation is supposed to fill in the gap by documenting what
21720 @code{volatile} means for that implementation.  In practice, though,
21721 this documentation is usually absent or incomplete.
21723 One area of confusion is the distinction between objects defined with
21724 volatile types, and volatile lvalues.  From the C standard's point of
21725 view, an object defined with a volatile type has externally visible
21726 behavior.  You can think of such objects as having little oscilloscope
21727 probes attached to them, so that the user can observe some properties of
21728 accesses to them, just as the user can observe data written to output
21729 files.  However, the standard does not make it clear whether users can
21730 observe accesses by volatile lvalues to ordinary objects.  For example:
21732 @example
21733 /* Declare and access a volatile object.
21734    Accesses to X are "visible" to users.  */
21735 static int volatile x;
21736 x = 1;
21738 /* Access two ordinary objects via a volatile lvalue.
21739    It's not clear whether accesses to *P are "visible".  */
21740 int y;
21741 int *z = malloc (sizeof (int));
21742 int volatile *p;
21743 p = &y;
21744 *p = 1;
21745 p = z;
21746 *p = 1;
21747 @end example
21749 Programmers often wish that @code{volatile} meant ``Perform the memory
21750 access here and now, without merging several memory accesses, without
21751 changing the memory word size, and without reordering.''  But the C
21752 standard does not require this.  For objects defined with a volatile
21753 type, accesses must be done before the next sequence point; but
21754 otherwise merging, reordering, and word-size change is allowed.  Worse,
21755 it is not clear from the standard whether volatile lvalues provide more
21756 guarantees in general than nonvolatile lvalues, if the underlying
21757 objects are ordinary.
21759 Even when accessing objects defined with a volatile type,
21760 the C standard allows only
21761 extremely limited signal handlers: in C99 the behavior is undefined if a signal
21762 handler reads any nonlocal object, or writes to any nonlocal object
21763 whose type is not @code{sig_atomic_t volatile}, or calls any standard
21764 library function other than @code{abort}, @code{signal}, and
21765 @code{_Exit}.  Hence C compilers need not worry about a signal handler
21766 disturbing ordinary computation.  C11 and Posix allow some additional
21767 behavior in a portable signal handler, but are still quite restrictive.
21769 Some C implementations allow memory-access optimizations within each
21770 translation unit, such that actual behavior agrees with the behavior
21771 required by the standard only when calling a function in some other
21772 translation unit, and a signal handler acts like it was called from a
21773 different translation unit.  The C99 standard hints that in these
21774 implementations, objects referred to by signal handlers ``would require
21775 explicit specification of @code{volatile} storage, as well as other
21776 implementation-defined restrictions.''  But unfortunately even for this
21777 special case these other restrictions are often not documented well.
21778 This area was significantly changed in C11, and eventually implementations
21779 will probably head in the C11 direction, but this will take some time.
21780 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
21781 GNU Compiler Collection (GCC)}, for some
21782 restrictions imposed by GCC.  @xref{Defining Handlers, ,
21783 Defining Signal Handlers, libc, The GNU C Library}, for some
21784 restrictions imposed by the GNU C library.  Restrictions
21785 differ on other platforms.
21787 If possible, it is best to use a signal handler that fits within the
21788 limits imposed by the C and Posix standards.
21790 If this is not practical, you can try the following rules of thumb.  A
21791 signal handler should access only volatile lvalues, preferably lvalues
21792 that refer to objects defined with a volatile type, and should not
21793 assume that the accessed objects have an internally consistent state
21794 if they are larger than a machine word.  Furthermore, installers
21795 should employ compilers and compiler options that are commonly used
21796 for building operating system kernels, because kernels often need more
21797 from @code{volatile} than the C Standard requires, and installers who
21798 compile an application in a similar environment can sometimes benefit
21799 from the extra constraints imposed by kernels on compilers.
21800 Admittedly we are handwaving somewhat here, as there are few
21801 guarantees in this area; the rules of thumb may help to fix some bugs
21802 but there is a good chance that they will not fix them all.
21804 For @code{volatile}, C++ has the same problems that C does.
21805 Multithreaded applications have even more problems with @code{volatile},
21806 but they are beyond the scope of this section.
21808 The bottom line is that using @code{volatile} typically hurts
21809 performance but should not hurt correctness.  In some cases its use
21810 does help correctness, but these cases are often so poorly understood
21811 that all too often adding @code{volatile} to a data structure merely
21812 alleviates some symptoms of a bug while not fixing the bug in general.
21814 @node Floating Point Portability
21815 @section Floating Point Portability
21816 @cindex floating point
21818 Almost all modern systems use IEEE-754 floating point, and it is safe to
21819 assume IEEE-754 in most portable code these days.  For more information,
21820 please see David Goldberg's classic paper
21821 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
21822 Scientist Should Know About Floating-Point Arithmetic}.
21824 @node Exiting Portably
21825 @section Exiting Portably
21826 @cindex exiting portably
21828 A C or C++ program can exit with status @var{N} by returning
21829 @var{N} from the @code{main} function.  Portable programs are supposed
21830 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
21831 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
21832 fail by exiting with status 1, and test programs that assume Posix can
21833 fail by exiting with status values from 1 through 255.  Programs on
21834 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
21835 status when @code{main} returned nonzero, but ancient systems like these
21836 are no longer of practical concern.
21838 A program can also exit with status @var{N} by passing @var{N} to the
21839 @code{exit} function, and a program can fail by calling the @code{abort}
21840 function.  If a program is specialized to just some platforms, it can fail
21841 by calling functions specific to those platforms, e.g., @code{_exit}
21842 (Posix).  However, like other functions, an exit
21843 function should be declared, typically by including a header.  For
21844 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
21845 either directly or via the default includes (@pxref{Default Includes}).
21847 A program can fail due to undefined behavior such as dereferencing a null
21848 pointer, but this is not recommended as undefined behavior allows an
21849 implementation to do whatever it pleases and this includes exiting
21850 successfully.
21853 @c ================================================== Manual Configuration
21855 @node Manual Configuration
21856 @chapter Manual Configuration
21858 A few kinds of features can't be guessed automatically by running test
21859 programs.  For example, the details of the object-file format, or
21860 special options that need to be passed to the compiler or linker.  You
21861 can check for such features using ad-hoc means, such as having
21862 @command{configure} check the output of the @code{uname} program, or
21863 looking for libraries that are unique to particular systems.  However,
21864 Autoconf provides a uniform method for handling unguessable features.
21866 @menu
21867 * Specifying Target Triplets::  Specifying target triplets
21868 * Canonicalizing::              Getting the canonical system type
21869 * Using System Type::           What to do with the system type
21870 @end menu
21872 @node Specifying Target Triplets
21873 @section Specifying target triplets
21874 @cindex System type
21875 @cindex Target triplet
21876 @c This node used to be named Specifying Names.  The @anchor allows old
21877 @c links to still work.
21878 @anchor{Specifying Names}
21880 Autoconf-generated
21881 @command{configure} scripts can make decisions based on a canonical name
21882 for the system type, or @dfn{target triplet}, which has the form:
21883 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
21884 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
21886 @command{configure} can usually guess the canonical name for the type of
21887 system it's running on.  To do so it runs a script called
21888 @command{config.guess}, which infers the name using the @code{uname}
21889 command or symbols predefined by the C preprocessor.
21891 Alternately, the user can specify the system type with command line
21892 arguments to @command{configure} (@pxref{System Type}.  Doing so is
21893 necessary when
21894 cross-compiling.  In the most complex case of cross-compiling, three
21895 system types are involved.  The options to specify them are:
21897 @table @option
21898 @item --build=@var{build-type}
21899 the type of system on which the package is being configured and
21900 compiled.  It defaults to the result of running @command{config.guess}.
21901 Specifying a @var{build-type} that differs from @var{host-type} enables
21902 cross-compilation mode.
21904 @item --host=@var{host-type}
21905 the type of system on which the package runs.  By default it is the
21906 same as the build machine.  Specifying a @var{host-type} that differs
21907 from @var{build-type}, when @var{build-type} was also explicitly
21908 specified, enables cross-compilation mode.
21910 @item --target=@var{target-type}
21911 the type of system for which any compiler tools in the package
21912 produce code (rarely needed).  By default, it is the same as host.
21913 @end table
21915 If you mean to override the result of @command{config.guess}, use
21916 @option{--build}, not @option{--host}, since the latter enables
21917 cross-compilation.  For historical reasons,
21918 whenever you specify @option{--host},
21919 be sure to specify @option{--build} too; this will be fixed in the
21920 future.  So, to enter cross-compilation mode, use a command like this
21922 @example
21923 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
21924 @end example
21926 @noindent
21927 Note that if you do not specify @option{--host}, @command{configure}
21928 fails if it can't run the code generated by the specified compiler.  For
21929 example, configuring as follows fails:
21931 @example
21932 ./configure CC=m68k-coff-gcc
21933 @end example
21935 When cross-compiling, @command{configure} will warn about any tools
21936 (compilers, linkers, assemblers) whose name is not prefixed with the
21937 host type.  This is an aid to users performing cross-compilation.
21938 Continuing the example above, if a cross-compiler named @command{cc} is
21939 used with a native @command{pkg-config}, then libraries found by
21940 @command{pkg-config} will likely cause subtle build failures; but using
21941 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
21942 avoids any confusion.  Avoiding the warning is as simple as creating the
21943 correct symlinks naming the cross tools.
21945 @cindex @command{config.sub}
21946 @command{configure} recognizes short aliases for many system types; for
21947 example, @samp{decstation} can be used instead of
21948 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
21949 @command{config.sub} to canonicalize system type aliases.
21951 This section deliberately omits the description of the obsolete
21952 interface; see @ref{Hosts and Cross-Compilation}.
21955 @node Canonicalizing
21956 @section Getting the Canonical System Type
21957 @cindex System type
21958 @cindex Canonical system type
21960 The following macros make the system type available to @command{configure}
21961 scripts.
21963 @ovindex build_alias
21964 @ovindex host_alias
21965 @ovindex target_alias
21967 The variables @samp{build_alias}, @samp{host_alias}, and
21968 @samp{target_alias} are always exactly the arguments of @option{--build},
21969 @option{--host}, and @option{--target}; in particular, they are left empty
21970 if the user did not use them, even if the corresponding
21971 @code{AC_CANONICAL} macro was run.  Any configure script may use these
21972 variables anywhere.  These are the variables that should be used when in
21973 interaction with the user.
21975 If you need to recognize some special environments based on their system
21976 type, run the following macros to get canonical system names.  These
21977 variables are not set before the macro call.
21979 If you use these macros, you must distribute @command{config.guess} and
21980 @command{config.sub} along with your source code.  @xref{Output}, for
21981 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
21982 to control in which directory @command{configure} looks for those scripts.
21985 @defmac AC_CANONICAL_BUILD
21986 @acindex{CANONICAL_BUILD}
21987 @ovindex build
21988 @ovindex build_cpu
21989 @ovindex build_vendor
21990 @ovindex build_os
21991 Compute the canonical build-system type variable, @code{build}, and its
21992 three individual parts @code{build_cpu}, @code{build_vendor}, and
21993 @code{build_os}.
21995 If @option{--build} was specified, then @code{build} is the
21996 canonicalization of @code{build_alias} by @command{config.sub},
21997 otherwise it is determined by the shell script @command{config.guess}.
21998 @end defmac
22000 @defmac AC_CANONICAL_HOST
22001 @acindex{CANONICAL_HOST}
22002 @ovindex host
22003 @ovindex host_cpu
22004 @ovindex host_vendor
22005 @ovindex host_os
22006 Compute the canonical host-system type variable, @code{host}, and its
22007 three individual parts @code{host_cpu}, @code{host_vendor}, and
22008 @code{host_os}.
22010 If @option{--host} was specified, then @code{host} is the
22011 canonicalization of @code{host_alias} by @command{config.sub},
22012 otherwise it defaults to @code{build}.
22013 @end defmac
22015 @defmac AC_CANONICAL_TARGET
22016 @acindex{CANONICAL_TARGET}
22017 @ovindex target
22018 @ovindex target_cpu
22019 @ovindex target_vendor
22020 @ovindex target_os
22021 Compute the canonical target-system type variable, @code{target}, and its
22022 three individual parts @code{target_cpu}, @code{target_vendor}, and
22023 @code{target_os}.
22025 If @option{--target} was specified, then @code{target} is the
22026 canonicalization of @code{target_alias} by @command{config.sub},
22027 otherwise it defaults to @code{host}.
22028 @end defmac
22030 Note that there can be artifacts due to the backward compatibility
22031 code.  @xref{Hosts and Cross-Compilation}, for more.
22033 @node Using System Type
22034 @section Using the System Type
22036 In @file{configure.ac} the system type is generally used by one or more
22037 @code{case} statements to select system-specifics.  Shell wildcards can
22038 be used to match a group of system types.
22040 For example, an extra assembler code object file could be chosen, giving
22041 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
22042 following would be used in a makefile to add the object to a
22043 program or library.
22045 @example
22046 AS_CASE([$host],
22047   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
22048   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
22049   [CYCLE_OBJ=""]
22051 AC_SUBST([CYCLE_OBJ])
22052 @end example
22054 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
22055 to select variant source files, for example optimized code for some
22056 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
22057 so some runtime capability checks may be necessary too.
22059 @example
22060 case $host in
22061   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
22062   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
22063   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
22064 esac
22065 @end example
22067 The host system type can also be used to find cross-compilation tools
22068 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
22070 The above examples all show @samp{$host}, since this is where the code
22071 is going to run.  Only rarely is it necessary to test @samp{$build}
22072 (which is where the build is being done).
22074 Whenever you're tempted to use @samp{$host} it's worth considering
22075 whether some sort of probe would be better.  New system types come along
22076 periodically or previously missing features are added.  Well-written
22077 probes can adapt themselves to such things, but hard-coded lists of
22078 names can't.  Here are some guidelines,
22080 @itemize @bullet
22081 @item
22082 Availability of libraries and library functions should always be checked
22083 by probing.
22084 @item
22085 Variant behavior of system calls is best identified with runtime tests
22086 if possible, but bug workarounds or obscure difficulties might have to
22087 be driven from @samp{$host}.
22088 @item
22089 Assembler code is inevitably highly CPU-specific and is best selected
22090 according to @samp{$host_cpu}.
22091 @item
22092 Assembler variations like underscore prefix on globals or ELF versus
22093 COFF type directives are however best determined by probing, perhaps
22094 even examining the compiler output.
22095 @end itemize
22097 @samp{$target} is for use by a package creating a compiler or similar.
22098 For ordinary packages it's meaningless and should not be used.  It
22099 indicates what the created compiler should generate code for, if it can
22100 cross-compile.  @samp{$target} generally selects various hard-coded CPU
22101 and system conventions, since usually the compiler or tools under
22102 construction themselves determine how the target works.
22105 @c ===================================================== Site Configuration.
22107 @node Site Configuration
22108 @chapter Site Configuration
22110 @command{configure} scripts support several kinds of local configuration
22111 decisions.  There are ways for users to specify where external software
22112 packages are, include or exclude optional features, install programs
22113 under modified names, and set default values for @command{configure}
22114 options.
22116 @menu
22117 * Help Formatting::             Customizing @samp{configure --help}
22118 * External Software::           Working with other optional software
22119 * Package Options::             Selecting optional features
22120 * Pretty Help Strings::         Formatting help string
22121 * Option Checking::             Controlling checking of @command{configure} options
22122 * Site Details::                Configuring site details
22123 * Transforming Names::          Changing program names when installing
22124 * Site Defaults::               Giving @command{configure} local defaults
22125 @end menu
22127 @node Help Formatting
22128 @section Controlling Help Output
22130 Users consult @samp{configure --help} to learn of configuration
22131 decisions specific to your package.  By default, @command{configure}
22132 breaks this output into sections for each type of option; within each
22133 section, help strings appear in the order @file{configure.ac} defines
22134 them:
22136 @example
22137 Optional Features:
22138   @dots{}
22139   --enable-bar            include bar
22141 Optional Packages:
22142   @dots{}
22143   --with-foo              use foo
22144 @end example
22146 @defmac AC_PRESERVE_HELP_ORDER
22147 @acindex{PRESERVE_HELP_ORDER}
22149 Request an alternate @option{--help} format, in which options of all
22150 types appear together, in the order defined.  Call this macro before any
22151 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
22153 @example
22154 Optional Features and Packages:
22155   @dots{}
22156   --enable-bar            include bar
22157   --with-foo              use foo
22158 @end example
22160 @end defmac
22162 @node External Software
22163 @section Working With External Software
22164 @cindex External software
22166 Some packages require, or can optionally use, other software packages
22167 that are already installed.  The user can give @command{configure}
22168 command line options to specify which such external software to use.
22169 The options have one of these forms:
22171 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22172 @c awful.
22173 @example
22174 --with-@var{package}@r{[}=@var{arg}@r{]}
22175 --without-@var{package}
22176 @end example
22178 For example, @option{--with-gnu-ld} means work with the GNU linker
22179 instead of some other linker.  @option{--with-x} means work with The X
22180 Window System.
22182 The user can give an argument by following the package name with
22183 @samp{=} and the argument.  Giving an argument of @samp{no} is for
22184 packages that are used by default; it says to @emph{not} use the
22185 package.  An argument that is neither @samp{yes} nor @samp{no} could
22186 include a name or number of a version of the other package, to specify
22187 more precisely which other package this program is supposed to work
22188 with.  If no argument is given, it defaults to @samp{yes}.
22189 @option{--without-@var{package}} is equivalent to
22190 @option{--with-@var{package}=no}.
22192 Normally @command{configure} scripts complain about
22193 @option{--with-@var{package}} options that they do not support.
22194 @xref{Option Checking}, for details, and for how to override the
22195 defaults.
22197 For each external software package that may be used, @file{configure.ac}
22198 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
22199 user asked to use it.  Whether each package is used or not by default,
22200 and which arguments are valid, is up to you.
22202 @anchor{AC_ARG_WITH}
22203 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
22204   @ovar{action-if-given}, @ovar{action-if-not-given})
22205 @acindex{ARG_WITH}
22206 If the user gave @command{configure} the option @option{--with-@var{package}}
22207 or @option{--without-@var{package}}, run shell commands
22208 @var{action-if-given}.  If neither option was given, run shell commands
22209 @var{action-if-not-given}.  The name @var{package} indicates another
22210 software package that this program should work with.  It should consist
22211 only of alphanumeric characters, dashes, plus signs, and dots.
22213 The option's argument is available to the shell commands
22214 @var{action-if-given} in the shell variable @code{withval}, which is
22215 actually just the value of the shell variable named
22216 @code{with_@var{package}}, with any non-alphanumeric characters in
22217 @var{package} changed into @samp{_}.  You may use that variable instead,
22218 if you wish.
22220 Note that @var{action-if-not-given} is not expanded until the point that
22221 @code{AC_ARG_WITH} was expanded.  If you need the value of
22222 @code{with_@var{package}} set to a default value by the time argument
22223 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22224 diversion (@pxref{m4_divert_text}) (if done as an argument to
22225 @code{AC_ARG_WITH}, also provide non-diverted text to avoid a shell
22226 syntax error).
22228 The argument @var{help-string} is a description of the option that
22229 looks like this:
22230 @example
22231   --with-readline         support fancy command line editing
22232 @end example
22234 @noindent
22235 @var{help-string} may be more than one line long, if more detail is
22236 needed.  Just make sure the columns line up in @samp{configure
22237 --help}.  Avoid tabs in the help string.  The easiest way to provide the
22238 proper leading whitespace is to format your @var{help-string} with the macro
22239 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22241 The following example shows how to use the @code{AC_ARG_WITH} macro in
22242 a common situation.  You want to let the user decide whether to enable
22243 support for an external library (e.g., the readline library); if the user
22244 specified neither @option{--with-readline} nor @option{--without-readline},
22245 you want to enable support for readline only if the library is available
22246 on the system.
22248 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22249 @example
22250 AC_ARG_WITH([readline],
22251   [AS_HELP_STRING([--with-readline],
22252     [support fancy command line editing @@<:@@default=check@@:>@@])],
22253   [],
22254   [: m4_divert_text([DEFAULTS], [with_readline=check])])
22256 LIBREADLINE=
22257 AS_IF([test "x$with_readline" != xno],
22258   [AC_CHECK_LIB([readline], [main],
22259     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22260      AC_DEFINE([HAVE_LIBREADLINE], [1],
22261                [Define if you have libreadline])
22262     ],
22263     [if test "x$with_readline" != xcheck; then
22264        AC_MSG_FAILURE(
22265          [--with-readline was given, but test for readline failed])
22266      fi
22267     ], -lncurses)])
22268 @end example
22270 The next example shows how to use @code{AC_ARG_WITH} to give the user the
22271 possibility to enable support for the readline library, in case it is still
22272 experimental and not well tested, and is therefore disabled by default.
22274 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22275 @example
22276 AC_ARG_WITH([readline],
22277   [AS_HELP_STRING([--with-readline],
22278     [enable experimental support for readline])],
22279   [],
22280   [with_readline=no])
22282 LIBREADLINE=
22283 AS_IF([test "x$with_readline" != xno],
22284   [AC_CHECK_LIB([readline], [main],
22285     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22286      AC_DEFINE([HAVE_LIBREADLINE], [1],
22287                [Define if you have libreadline])
22288     ],
22289     [AC_MSG_FAILURE(
22290        [--with-readline was given, but test for readline failed])],
22291     [-lncurses])])
22292 @end example
22294 The last example shows how to use @code{AC_ARG_WITH} to give the user the
22295 possibility to disable support for the readline library, given that it is
22296 an important feature and that it should be enabled by default.
22298 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22299 @example
22300 AC_ARG_WITH([readline],
22301   [AS_HELP_STRING([--without-readline],
22302     [disable support for readline])],
22303   [],
22304   [with_readline=yes])
22306 LIBREADLINE=
22307 AS_IF([test "x$with_readline" != xno],
22308   [AC_CHECK_LIB([readline], [main],
22309     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22310      AC_DEFINE([HAVE_LIBREADLINE], [1],
22311                [Define if you have libreadline])
22312     ],
22313     [AC_MSG_FAILURE(
22314        [readline test failed (--without-readline to disable)])],
22315     [-lncurses])])
22316 @end example
22318 These three examples can be easily adapted to the case where
22319 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
22320 @ref{Package Options}).
22321 @end defmac
22323 @node Package Options
22324 @section Choosing Package Options
22325 @cindex Package options
22326 @cindex Options, package
22328 If a software package has optional compile-time features, the user can
22329 give @command{configure} command line options to specify whether to
22330 compile them.  The options have one of these forms:
22332 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22333 @c awful.
22334 @example
22335 --enable-@var{feature}@r{[}=@var{arg}@r{]}
22336 --disable-@var{feature}
22337 @end example
22339 These options allow users to choose which optional features to build and
22340 install.  @option{--enable-@var{feature}} options should never make a
22341 feature behave differently or cause one feature to replace another.
22342 They should only cause parts of the program to be built rather than left
22343 out.
22345 The user can give an argument by following the feature name with
22346 @samp{=} and the argument.  Giving an argument of @samp{no} requests
22347 that the feature @emph{not} be made available.  A feature with an
22348 argument looks like @option{--enable-debug=stabs}.  If no argument is
22349 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
22350 equivalent to @option{--enable-@var{feature}=no}.
22352 Normally @command{configure} scripts complain about
22353 @option{--enable-@var{package}} options that they do not support.
22354 @xref{Option Checking}, for details, and for how to override the
22355 defaults.
22357 For each optional feature, @file{configure.ac} should call
22358 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
22359 to include it.  Whether each feature is included or not by default, and
22360 which arguments are valid, is up to you.
22362 @anchor{AC_ARG_ENABLE}
22363 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
22364   @ovar{action-if-given}, @ovar{action-if-not-given})
22365 @acindex{ARG_ENABLE}
22366 If the user gave @command{configure} the option
22367 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
22368 shell commands @var{action-if-given}.  If neither option was given, run
22369 shell commands @var{action-if-not-given}.  The name @var{feature}
22370 indicates an optional user-level facility.  It should consist only of
22371 alphanumeric characters, dashes, plus signs, and dots.
22373 The option's argument is available to the shell commands
22374 @var{action-if-given} in the shell variable @code{enableval}, which is
22375 actually just the value of the shell variable named
22376 @code{enable_@var{feature}}, with any non-alphanumeric characters in
22377 @var{feature} changed into @samp{_}.  You may use that variable instead,
22378 if you wish.  The @var{help-string} argument is like that of
22379 @code{AC_ARG_WITH} (@pxref{External Software}).
22381 Note that @var{action-if-not-given} is not expanded until the point that
22382 @code{AC_ARG_ENABLE} was expanded.  If you need the value of
22383 @code{enable_@var{feature}} set to a default value by the time argument
22384 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22385 diversion (@pxref{m4_divert_text}) (if done as an argument to
22386 @code{AC_ARG_ENABLE}, also provide non-diverted text to avoid a shell
22387 syntax error).
22389 You should format your @var{help-string} with the macro
22390 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22392 See the examples suggested with the definition of @code{AC_ARG_WITH}
22393 (@pxref{External Software}) to get an idea of possible applications of
22394 @code{AC_ARG_ENABLE}.
22395 @end defmac
22397 @node Pretty Help Strings
22398 @section Making Your Help Strings Look Pretty
22399 @cindex Help strings
22401 Properly formatting the @samp{help strings} which are used in
22402 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
22403 (@pxref{Package Options}) can be challenging.  Specifically, you want
22404 your own @samp{help strings} to line up in the appropriate columns of
22405 @samp{configure --help} just like the standard Autoconf @samp{help
22406 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
22408 @anchor{AS_HELP_STRING}
22409 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
22410   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
22411 @asindex{HELP_STRING}
22413 Expands into a help string that looks pretty when the user executes
22414 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
22415 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
22416 Options}).  The following example makes this clearer.
22418 @example
22419 AC_ARG_WITH([foo],
22420   [AS_HELP_STRING([--with-foo],
22421      [use foo (default is no)])],
22422   [use_foo=$withval],
22423   [use_foo=no])
22424 @end example
22426 Then the last few lines of @samp{configure --help} appear like
22427 this:
22429 @example
22430 --enable and --with options recognized:
22431   --with-foo              use foo (default is no)
22432 @end example
22434 Macro expansion is performed on the first argument.  However, the second
22435 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
22436 list of text to be reformatted, and is not subject to macro expansion.
22437 Since it is not expanded, it should not be double quoted.
22438 @xref{Autoconf Language}, for a more detailed explanation.
22440 The @code{AS_HELP_STRING} macro is particularly helpful when the
22441 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
22442 arguments, as shown in the following example.  Be aware that
22443 @var{left-hand-side} may not expand to unbalanced quotes,
22444 although quadrigraphs can be used.
22446 @example
22447 AC_DEFUN([MY_ARG_WITH],
22448   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
22449      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
22450                      [use $1 (default is $2)])],
22451      [use_[]$1=$withval],
22452      [use_[]$1=$2])])
22453 MY_ARG_WITH([a_b], [no])
22454 @end example
22455 @noindent
22456 Here, the last few lines of @samp{configure --help} will include:
22458 @example
22459 --enable and --with options recognized:
22460   --with-a-b              use a_b (default is no)
22461 @end example
22463 The parameters @var{indent-column} and @var{wrap-column} were introduced
22464 in Autoconf 2.62.  Generally, they should not be specified; they exist
22465 for fine-tuning of the wrapping.
22466 @example
22467 AS_HELP_STRING([--option], [description of option])
22468 @result{}  --option                description of option
22469 AS_HELP_STRING([--option], [description of option], [15], [30])
22470 @result{}  --option     description of
22471 @result{}               option
22472 @end example
22473 @end defmac
22476 @node Option Checking
22477 @section Controlling Checking of @command{configure} Options
22478 @cindex Options, Package
22480 The @command{configure} script checks its command-line options against a
22481 list of known options, like @option{--help} or @option{--config-cache}.
22482 An unknown option ordinarily indicates a mistake by the user and
22483 @command{configure} halts with an error.  However, by default unknown
22484 @option{--with-@var{package}} and @option{--enable-@var{feature}}
22485 options elicit only a warning, to support configuring entire source
22486 trees.
22488 Source trees often contain multiple packages with a top-level
22489 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
22490 (@pxref{Subdirectories}).  Because the packages generally support
22491 different @option{--with-@var{package}} and
22492 @option{--enable-@var{feature}} options, the GNU Coding
22493 Standards say they must accept unrecognized options without halting.
22494 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
22495 automatically disables the warnings.
22497 This default behavior may be modified in two ways.  First, the installer
22498 can invoke @code{configure --disable-option-checking} to disable
22499 these warnings, or invoke @code{configure --enable-option-checking=fatal}
22500 options to turn them into fatal errors, respectively.  Second, the
22501 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
22503 @defmac AC_DISABLE_OPTION_CHECKING
22504 @acindex{DISABLE_OPTION_CHECKING}
22506 By default, disable warnings related to any unrecognized
22507 @option{--with-@var{package}} or @option{--enable-@var{feature}}
22508 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
22510 The installer can override this behavior by passing
22511 @option{--enable-option-checking} (enable warnings) or
22512 @option{--enable-option-checking=fatal} (enable errors) to
22513 @command{configure}.
22514 @end defmac
22517 @node Site Details
22518 @section Configuring Site Details
22519 @cindex Site details
22521 Some software packages require complex site-specific information.  Some
22522 examples are host names to use for certain services, company names, and
22523 email addresses to contact.  Since some configuration scripts generated
22524 by Metaconfig ask for such information interactively, people sometimes
22525 wonder how to get that information in Autoconf-generated configuration
22526 scripts, which aren't interactive.
22528 Such site configuration information should be put in a file that is
22529 edited @emph{only by users}, not by programs.  The location of the file
22530 can either be based on the @code{prefix} variable, or be a standard
22531 location such as the user's home directory.  It could even be specified
22532 by an environment variable.  The programs should examine that file at
22533 runtime, rather than at compile time.  Runtime configuration is more
22534 convenient for users and makes the configuration process simpler than
22535 getting the information while configuring.  @xref{Directory Variables, ,
22536 Variables for Installation Directories, standards, The GNU Coding
22537 Standards}, for more information on where to put data files.
22539 @node Transforming Names
22540 @section Transforming Program Names When Installing
22541 @cindex Transforming program names
22542 @cindex Program names, transforming
22544 Autoconf supports changing the names of programs when installing them.
22545 In order to use these transformations, @file{configure.ac} must call the
22546 macro @code{AC_ARG_PROGRAM}.
22548 @defmac AC_ARG_PROGRAM
22549 @acindex{ARG_PROGRAM}
22550 @ovindex program_transform_name
22551 Place in output variable @code{program_transform_name} a sequence of
22552 @code{sed} commands for changing the names of installed programs.
22554 If any of the options described below are given to @command{configure},
22555 program names are transformed accordingly.  Otherwise, if
22556 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
22557 is given, the target type followed by a dash is used as a prefix.
22558 Otherwise, no program name transformation is done.
22559 @end defmac
22561 @menu
22562 * Transformation Options::      @command{configure} options to transform names
22563 * Transformation Examples::     Sample uses of transforming names
22564 * Transformation Rules::        Makefile uses of transforming names
22565 @end menu
22567 @node Transformation Options
22568 @subsection Transformation Options
22570 You can specify name transformations by giving @command{configure} these
22571 command line options:
22573 @table @option
22574 @item --program-prefix=@var{prefix}
22575 prepend @var{prefix} to the names;
22577 @item --program-suffix=@var{suffix}
22578 append @var{suffix} to the names;
22580 @item --program-transform-name=@var{expression}
22581 perform @code{sed} substitution @var{expression} on the names.
22582 @end table
22584 @node Transformation Examples
22585 @subsection Transformation Examples
22587 These transformations are useful with programs that can be part of a
22588 cross-compilation development environment.  For example, a
22589 cross-assembler running on a Sun 4 configured with
22590 @option{--target=i960-vxworks} is normally installed as
22591 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
22592 with a native Sun 4 assembler.
22594 You can force a program name to begin with @file{g}, if you don't want
22595 GNU programs installed on your system to shadow other programs with
22596 the same name.  For example, if you configure GNU @code{diff} with
22597 @option{--program-prefix=g}, then when you run @samp{make install} it is
22598 installed as @file{/usr/local/bin/gdiff}.
22600 As a more sophisticated example, you could use
22602 @example
22603 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
22604 @end example
22605 @noindent
22607 to prepend @samp{g} to most of the program names in a source tree,
22608 excepting those like @code{gdb} that already have one and those like
22609 @code{less} and @code{lesskey} that aren't GNU programs.  (That is
22610 assuming that you have a source tree containing those programs that is
22611 set up to use this feature.)
22613 One way to install multiple versions of some programs simultaneously is
22614 to append a version number to the name of one or both.  For example, if
22615 you want to keep Autoconf version 1 around for awhile, you can configure
22616 Autoconf version 2 using @option{--program-suffix=2} to install the
22617 programs as @file{/usr/local/bin/autoconf2},
22618 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
22619 that only the binaries are renamed, therefore you'd have problems with
22620 the library files which might overlap.
22622 @node Transformation Rules
22623 @subsection Transformation Rules
22625 Here is how to use the variable @code{program_transform_name} in a
22626 @file{Makefile.in}:
22628 @example
22629 PROGRAMS = cp ls rm
22630 transform = @@program_transform_name@@
22631 install:
22632         for p in $(PROGRAMS); do \
22633           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
22634                                               sed '$(transform)'`; \
22635         done
22637 uninstall:
22638         for p in $(PROGRAMS); do \
22639           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
22640 @c $$ restore font-lock
22641         done
22642 @end example
22644 It is guaranteed that @code{program_transform_name} is never empty, and
22645 that there are no useless separators.  Therefore you may safely embed
22646 @code{program_transform_name} within a sed program using @samp{;}:
22648 @example
22649 transform = @@program_transform_name@@
22650 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
22651 @end example
22653 Whether to do the transformations on documentation files (Texinfo or
22654 @code{man}) is a tricky question; there seems to be no perfect answer,
22655 due to the several reasons for name transforming.  Documentation is not
22656 usually particular to a specific architecture, and Texinfo files do not
22657 conflict with system documentation.  But they might conflict with
22658 earlier versions of the same files, and @code{man} pages sometimes do
22659 conflict with system documentation.  As a compromise, it is probably
22660 best to do name transformations on @code{man} pages but not on Texinfo
22661 manuals.
22663 @node Site Defaults
22664 @section Setting Site Defaults
22665 @cindex Site defaults
22666 @cindex config.site
22668 Autoconf-generated @command{configure} scripts allow your site to provide
22669 default values for some configuration values.  You do this by creating
22670 site- and system-wide initialization files.
22672 @evindex CONFIG_SITE
22673 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
22674 uses its value as the name of a shell script to read; it is recommended
22675 that this be an absolute file name.  Otherwise, it
22676 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
22677 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
22678 settings in machine-specific files override those in machine-independent
22679 ones in case of conflict.
22681 Site files can be arbitrary shell scripts, but only certain kinds of
22682 code are really appropriate to be in them.  Because @command{configure}
22683 reads any cache file after it has read any site files, a site file can
22684 define a default cache file to be shared between all Autoconf-generated
22685 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
22686 you set a default cache file in a site file, it is a good idea to also
22687 set the output variable @code{CC} in that site file, because the cache
22688 file is only valid for a particular compiler, but many systems have
22689 several available.
22691 You can examine or override the value set by a command line option to
22692 @command{configure} in a site file; options set shell variables that have
22693 the same names as the options, with any dashes turned into underscores.
22694 The exceptions are that @option{--without-} and @option{--disable-} options
22695 are like giving the corresponding @option{--with-} or @option{--enable-}
22696 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
22697 sets the variable @code{cache_file} to the value @samp{localcache};
22698 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
22699 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
22700 variable @code{prefix} to the value @samp{/usr}; etc.
22702 Site files are also good places to set default values for other output
22703 variables, such as @code{CFLAGS}, if you need to give them non-default
22704 values: anything you would normally do, repetitively, on the command
22705 line.  If you use non-default values for @var{prefix} or
22706 @var{exec_prefix} (wherever you locate the site file), you can set them
22707 in the site file if you specify it with the @code{CONFIG_SITE}
22708 environment variable.
22710 You can set some cache values in the site file itself.  Doing this is
22711 useful if you are cross-compiling, where it is impossible to check features
22712 that require running a test program.  You could ``prime the cache'' by
22713 setting those values correctly for that system in
22714 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
22715 variables you need to set, see the documentation of the respective
22716 Autoconf macro.  If the variables or their semantics are undocumented,
22717 you may need to look for shell variables with @samp{_cv_} in their names
22718 in the affected @command{configure} scripts, or in the Autoconf M4
22719 source code for those macros; but in that case, their name or semantics
22720 may change in a future Autoconf version.
22722 The cache file is careful to not override any variables set in the site
22723 files.  Similarly, you should not override command-line options in the
22724 site files.  Your code should check that variables such as @code{prefix}
22725 and @code{cache_file} have their default values (as set near the top of
22726 @command{configure}) before changing them.
22728 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
22729 command @samp{configure --prefix=/usr/share/local/gnu} would read this
22730 file (if @code{CONFIG_SITE} is not set to a different file).
22732 @example
22733 # /usr/share/local/gnu/share/config.site for configure
22735 # Change some defaults.
22736 test "$prefix" = NONE && prefix=/usr/share/local/gnu
22737 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
22738 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22739 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22740 test "$runstatedir" = '$@{localstatedir@}/run' && runstatedir=/run
22742 # Give Autoconf 2.x generated configure scripts a shared default
22743 # cache file for feature test results, architecture-specific.
22744 if test "$cache_file" = /dev/null; then
22745   cache_file="$prefix/var/config.cache"
22746   # A cache file is only valid for one C compiler.
22747   CC=gcc
22749 @end example
22751 @c Leave this use of "File system" rendered as one word, but
22752 @c slightly obfuscated so as not to trigger the syntax-check prohibition.
22753 @cindex File@/system Hierarchy Standard
22754 @cindex FHS
22756 Another use of @file{config.site} is for priming the directory variables
22757 @c "File system", but slightly obfuscated, as above.
22758 in a manner consistent with the File@/system Hierarchy Standard
22759 (FHS).  Once the following file is installed at
22760 @file{/usr/share/config.site}, a user can execute simply
22761 @code{./configure --prefix=/usr} to get all the directories chosen in
22762 the locations recommended by FHS.
22764 @example
22765 # /usr/share/config.site for FHS defaults when installing below /usr,
22766 # and the respective settings were not changed on the command line.
22767 if test "$prefix" = /usr; then
22768   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
22769   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22770   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22772 @end example
22774 @cindex @file{lib64}
22775 @cindex 64-bit libraries
22776 Likewise, on platforms where 64-bit libraries are built by default, then
22777 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
22778 it is appropriate to install @file{/usr/local/@/share/config.site}:
22780 @example
22781 # /usr/local/share/config.site for platforms that prefer
22782 # the directory /usr/local/lib64 over /usr/local/lib.
22783 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
22784 @end example
22787 @c ============================================== Running configure Scripts.
22789 @node Running configure Scripts
22790 @chapter Running @command{configure} Scripts
22791 @cindex @command{configure}
22793 Below are instructions on how to configure a package that uses a
22794 @command{configure} script, suitable for inclusion as an @file{INSTALL}
22795 file in the package.  A plain-text version of @file{INSTALL} which you
22796 may use comes with Autoconf.
22798 @menu
22799 * Basic Installation::          Instructions for typical cases
22800 * Compilers and Options::       Selecting compilers and optimization
22801 * Multiple Architectures::      Compiling for multiple architectures at once
22802 * Installation Names::          Installing in different directories
22803 * Optional Features::           Selecting optional features
22804 * Particular Systems::          Particular systems
22805 * System Type::                 Specifying the system type
22806 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
22807 * Defining Variables::          Specifying the compiler etc.
22808 * configure Invocation::        Changing how @command{configure} runs
22809 @end menu
22811 @set autoconf
22812 @include install.texi
22815 @c ============================================== config.status Invocation
22817 @node config.status Invocation
22818 @chapter config.status Invocation
22819 @cindex @command{config.status}
22821 The @command{configure} script creates a file named @file{config.status},
22822 which actually configures, @dfn{instantiates}, the template files.  It
22823 also records the configuration options that were specified when the
22824 package was last configured in case reconfiguring is needed.
22826 Synopsis:
22827 @example
22828 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
22829 @end example
22831 It configures each @var{tag}; if none are specified, all the templates
22832 are instantiated.  A @var{tag} refers to a file or other tag associated
22833 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
22834 macro (@pxref{Configuration Actions}).  The files must be specified
22835 without their dependencies, as in
22837 @example
22838 ./config.status foobar
22839 @end example
22841 @noindent
22844 @example
22845 ./config.status foobar:foo.in:bar.in
22846 @end example
22848 The supported options are:
22850 @table @option
22851 @item --help
22852 @itemx -h
22853 Print a summary of the command line options, the list of the template
22854 files, and exit.
22856 @item --version
22857 @itemx -V
22858 Print the version number of Autoconf and the configuration settings,
22859 and exit.
22861 @item --config
22862 Print the configuration settings in reusable way, quoted for the shell,
22863 and exit.  For example, for a debugging build that otherwise reuses the
22864 configuration from a different build directory @var{build-dir} of a
22865 package in @var{src-dir}, you could use the following:
22867 @example
22868 args=`@var{build-dir}/config.status --config`
22869 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
22870 @end example
22872 @noindent
22873 Note that it may be necessary to override a @option{--srcdir} setting
22874 that was saved in the configuration, if the arguments are used in a
22875 different build directory.
22877 @item --silent
22878 @itemx --quiet
22879 @itemx -q
22880 Do not print progress messages.
22882 @item --debug
22883 @itemx -d
22884 Don't remove the temporary files.
22886 @item --file=@var{file}[:@var{template}]
22887 Require that @var{file} be instantiated as if
22888 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
22889 @var{file} and @var{template} may be @samp{-} in which case the standard
22890 output and/or standard input, respectively, is used.  If a
22891 @var{template} file name is relative, it is first looked for in the build
22892 tree, and then in the source tree.  @xref{Configuration Actions}, for
22893 more details.
22895 This option and the following ones provide one way for separately
22896 distributed packages to share the values computed by @command{configure}.
22897 Doing so can be useful if some of the packages need a superset of the
22898 features that one of them, perhaps a common library, does.  These
22899 options allow a @file{config.status} file to create files other than the
22900 ones that its @file{configure.ac} specifies, so it can be used for a
22901 different package, or for extracting a subset of values.  For example,
22903 @example
22904 echo '@@CC@@' | ./config.status --file=-
22905 @end example
22907 @noindent
22908 provides the value of @code{@@CC@@} on standard output.
22910 @item --header=@var{file}[:@var{template}]
22911 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
22913 @item --recheck
22914 Ask @file{config.status} to update itself and exit (no instantiation).
22915 This option is useful if you change @command{configure}, so that the
22916 results of some tests might be different from the previous run.  The
22917 @option{--recheck} option reruns @command{configure} with the same arguments
22918 you used before, plus the @option{--no-create} option, which prevents
22919 @command{configure} from running @file{config.status} and creating
22920 @file{Makefile} and other files, and the @option{--no-recursion} option,
22921 which prevents @command{configure} from running other @command{configure}
22922 scripts in subdirectories.  (This is so other Make rules can
22923 run @file{config.status} when it changes; @pxref{Automatic Remaking},
22924 for an example).
22925 @end table
22927 @file{config.status} checks several optional environment variables that
22928 can alter its behavior:
22930 @anchor{CONFIG_SHELL}
22931 @defvar CONFIG_SHELL
22932 @evindex CONFIG_SHELL
22933 The shell with which to run @command{configure}.  It must be
22934 Bourne-compatible, and the absolute name of the shell should be passed.
22935 The default is a shell that supports @code{LINENO} if available, and
22936 @file{/bin/sh} otherwise.
22937 @end defvar
22939 @defvar CONFIG_STATUS
22940 @evindex CONFIG_STATUS
22941 The file name to use for the shell script that records the
22942 configuration.  The default is @file{./config.status}.  This variable is
22943 useful when one package uses parts of another and the @command{configure}
22944 scripts shouldn't be merged because they are maintained separately.
22945 @end defvar
22947 You can use @file{./config.status} in your makefiles.  For example, in
22948 the dependencies given above (@pxref{Automatic Remaking}),
22949 @file{config.status} is run twice when @file{configure.ac} has changed.
22950 If that bothers you, you can make each run only regenerate the files for
22951 that rule:
22952 @example
22953 @group
22954 config.h: stamp-h
22955 stamp-h: config.h.in config.status
22956         ./config.status config.h
22957         echo > stamp-h
22959 Makefile: Makefile.in config.status
22960         ./config.status Makefile
22961 @end group
22962 @end example
22964 The calling convention of @file{config.status} has changed; see
22965 @ref{Obsolete config.status Use}, for details.
22968 @c =================================================== Obsolete Constructs
22970 @node Obsolete Constructs
22971 @chapter Obsolete Constructs
22972 @cindex Obsolete constructs
22974 Autoconf changes, and throughout the years some constructs have been
22975 obsoleted.  Most of the changes involve the macros, but in some cases
22976 the tools themselves, or even some concepts, are now considered
22977 obsolete.
22979 You may completely skip this chapter if you are new to Autoconf.  Its
22980 intention is mainly to help maintainers updating their packages by
22981 understanding how to move to more modern constructs.
22983 @menu
22984 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
22985 * acconfig Header::             Additional entries in @file{config.h.in}
22986 * autoupdate Invocation::       Automatic update of @file{configure.ac}
22987 * Obsolete Macros::             Backward compatibility macros
22988 * Autoconf 1::                  Tips for upgrading your files
22989 * Autoconf 2.13::               Some fresher tips
22990 @end menu
22992 @node Obsolete config.status Use
22993 @section Obsolete @file{config.status} Invocation
22995 @file{config.status} now supports arguments to specify the files to
22996 instantiate; see @ref{config.status Invocation}, for more details.
22997 Before, environment variables had to be used.
22999 @defvar CONFIG_COMMANDS
23000 @evindex CONFIG_COMMANDS
23001 The tags of the commands to execute.  The default is the arguments given
23002 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
23003 @file{configure.ac}.
23004 @end defvar
23006 @defvar CONFIG_FILES
23007 @evindex CONFIG_FILES
23008 The files in which to perform @samp{@@@var{variable}@@} substitutions.
23009 The default is the arguments given to @code{AC_OUTPUT} and
23010 @code{AC_CONFIG_FILES} in @file{configure.ac}.
23011 @end defvar
23013 @defvar CONFIG_HEADERS
23014 @evindex CONFIG_HEADERS
23015 The files in which to substitute C @code{#define} statements.  The
23016 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
23017 macro was not called, @file{config.status} ignores this variable.
23018 @end defvar
23020 @defvar CONFIG_LINKS
23021 @evindex CONFIG_LINKS
23022 The symbolic links to establish.  The default is the arguments given to
23023 @code{AC_CONFIG_LINKS}; if that macro was not called,
23024 @file{config.status} ignores this variable.
23025 @end defvar
23027 In @ref{config.status Invocation}, using this old interface, the example
23028 would be:
23030 @example
23031 @group
23032 config.h: stamp-h
23033 stamp-h: config.h.in config.status
23034         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
23035           CONFIG_HEADERS=config.h ./config.status
23036         echo > stamp-h
23038 Makefile: Makefile.in config.status
23039         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
23040           CONFIG_FILES=Makefile ./config.status
23041 @end group
23042 @end example
23044 @noindent
23045 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
23046 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
23047 for @code{CONFIG_COMMANDS}, etc.)
23050 @node acconfig Header
23051 @section @file{acconfig.h}
23053 @cindex @file{acconfig.h}
23054 @cindex @file{config.h.top}
23055 @cindex @file{config.h.bot}
23057 In order to produce @file{config.h.in}, @command{autoheader} needs to
23058 build or to find templates for each symbol.  Modern releases of Autoconf
23059 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
23060 Macros}), but in older releases a file, @file{acconfig.h}, contained the
23061 list of needed templates.  @command{autoheader} copied comments and
23062 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
23063 the current directory, if present.  This file used to be mandatory if
23064 you @code{AC_DEFINE} any additional symbols.
23066 Modern releases of Autoconf also provide @code{AH_TOP} and
23067 @code{AH_BOTTOM} if you need to prepend/append some information to
23068 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
23069 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
23070 @command{autoheader} copies the lines before the line containing
23071 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
23072 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
23073 @command{autoheader} copies the lines after that line to the end of the
23074 file it generates.  Either or both of those strings may be omitted.  An
23075 even older alternate way to produce the same effect in ancient versions
23076 of Autoconf is to create the files @file{@var{file}.top} (typically
23077 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
23078 directory.  If they exist, @command{autoheader} copies them to the
23079 beginning and end, respectively, of its output.
23081 In former versions of Autoconf, the files used in preparing a software
23082 package for distribution were:
23083 @example
23084 @group
23085 configure.ac --.   .------> autoconf* -----> configure
23086                +---+
23087 [aclocal.m4] --+   `---.
23088 [acsite.m4] ---'       |
23089                        +--> [autoheader*] -> [config.h.in]
23090 [acconfig.h] ----.     |
23091                  +-----'
23092 [config.h.top] --+
23093 [config.h.bot] --'
23094 @end group
23095 @end example
23097 Using only the @code{AH_} macros, @file{configure.ac} should be
23098 self-contained, and should not depend upon @file{acconfig.h} etc.
23101 @node autoupdate Invocation
23102 @section Using @command{autoupdate} to Modernize @file{configure.ac}
23103 @cindex @command{autoupdate}
23105 The @command{autoupdate} program updates a @file{configure.ac} file that
23106 calls Autoconf macros by their old names to use the current macro names.
23107 In version 2 of Autoconf, most of the macros were renamed to use a more
23108 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
23109 description of the new scheme.  Although the old names still work
23110 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
23111 new names), you can make your @file{configure.ac} files more readable
23112 and make it easier to use the current Autoconf documentation if you
23113 update them to use the new macro names.
23115 @evindex SIMPLE_BACKUP_SUFFIX
23116 If given no arguments, @command{autoupdate} updates @file{configure.ac},
23117 backing up the original version with the suffix @file{~} (or the value
23118 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
23119 set).  If you give @command{autoupdate} an argument, it reads that file
23120 instead of @file{configure.ac} and writes the updated file to the
23121 standard output.
23123 @noindent
23124 @command{autoupdate} accepts the following options:
23126 @table @option
23127 @item --help
23128 @itemx -h
23129 Print a summary of the command line options and exit.
23131 @item --version
23132 @itemx -V
23133 Print the version number of Autoconf and exit.
23135 @item --verbose
23136 @itemx -v
23137 Report processing steps.
23139 @item --debug
23140 @itemx -d
23141 Don't remove the temporary files.
23143 @item --force
23144 @itemx -f
23145 Force the update even if the file has not changed.  Disregard the cache.
23147 @item --include=@var{dir}
23148 @itemx -I @var{dir}
23149 Also look for input files in @var{dir}.  Multiple invocations accumulate.
23150 Directories are browsed from last to first.
23152 @item --prepend-include=@var{dir}
23153 @itemx -B @var{dir}
23154 Prepend directory @var{dir} to the search path.  This is used to include
23155 the language-specific files before any third-party macros.
23156 @end table
23158 @node Obsolete Macros
23159 @section Obsolete Macros
23161 Several macros are obsoleted in Autoconf, for various reasons (typically
23162 they failed to quote properly, couldn't be extended for more recent
23163 issues, etc.).  They are still supported, but deprecated: their use
23164 should be avoided.
23166 During the jump from Autoconf version 1 to version 2, most of the
23167 macros were renamed to use a more uniform and descriptive naming scheme,
23168 but their signature did not change.  @xref{Macro Names}, for a
23169 description of the new naming scheme.  Below, if there is just the mapping
23170 from old names to new names for these macros, the reader is invited to
23171 refer to the definition of the new macro for the signature and the
23172 description.
23174 @defmac AC_AIX
23175 @acindex{AIX}
23176 @cvindex _ALL_SOURCE
23177 This macro is a platform-specific subset of
23178 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23179 @end defmac
23181 @defmac AC_ALLOCA
23182 @acindex{ALLOCA}
23183 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
23184 @end defmac
23186 @defmac AC_ARG_ARRAY
23187 @acindex{ARG_ARRAY}
23188 Removed because of limited usefulness.
23189 @end defmac
23191 @defmac AC_C_CROSS
23192 @acindex{C_CROSS}
23193 This macro is obsolete; it does nothing.
23194 @end defmac
23196 @defmac AC_C_LONG_DOUBLE
23197 @acindex{C_LONG_DOUBLE}
23198 @cvindex HAVE_LONG_DOUBLE
23199 If the C compiler supports a working @code{long double} type with more
23200 range or precision than the @code{double} type, define
23201 @code{HAVE_LONG_DOUBLE}.
23203 You should use @code{AC_TYPE_LONG_DOUBLE} or
23204 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23205 @end defmac
23207 @defmac AC_CANONICAL_SYSTEM
23208 @acindex{CANONICAL_SYSTEM}
23209 Determine the system type and set output variables to the names of the
23210 canonical system types.  @xref{Canonicalizing}, for details about the
23211 variables this macro sets.
23213 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
23214 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
23215 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
23216 other macros (@pxref{Canonicalizing}).
23217 @end defmac
23219 @defmac AC_CHAR_UNSIGNED
23220 @acindex{CHAR_UNSIGNED}
23221 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
23222 @end defmac
23224 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
23225 @acindex{CHECK_TYPE}
23226 Autoconf, up to 2.13, used to provide this version of
23227 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
23228 it is a member of the @code{CHECK} clan, it does
23229 more than just checking.  Secondly, missing types are defined
23230 using @code{#define}, not @code{typedef}, and this can lead to
23231 problems in the case of pointer types.
23233 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
23234 @ref{Generic Types}, for the description of the current macro.
23236 If the type @var{type} is not defined, define it to be the C (or C++)
23237 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
23239 This macro is equivalent to:
23241 @example
23242 AC_CHECK_TYPE([@var{type}], [],
23243   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
23244      [Define to `@var{default}'
23245       if <sys/types.h> does not define.])])
23246 @end example
23248 In order to keep backward compatibility, the two versions of
23249 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
23251 @enumerate
23252 @item
23253 If there are three or four arguments, the modern version is used.
23255 @item
23256 If the second argument appears to be a C or C++ type, then the
23257 obsolete version is used.  This happens if the argument is a C or C++
23258 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
23259 followed by one of @samp{[(* } and then by a string of zero or more
23260 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
23262 @item
23263 If the second argument is spelled with the alphabet of valid C and C++
23264 types, the user is warned and the modern version is used.
23266 @item
23267 Otherwise, the modern version is used.
23268 @end enumerate
23270 @noindent
23271 You are encouraged either to use a valid builtin type, or to use the
23272 equivalent modern code (see above), or better yet, to use
23273 @code{AC_CHECK_TYPES} together with
23275 @example
23276 #ifndef HAVE_LOFF_T
23277 typedef loff_t off_t;
23278 #endif
23279 @end example
23280 @end defmac
23281 @c end of AC_CHECK_TYPE
23283 @defmac AC_CHECKING (@var{feature-description})
23284 @acindex{CHECKING}
23285 Same as
23287 @example
23288 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
23289 @end example
23291 @noindent
23292 @xref{AC_MSG_NOTICE}.
23293 @end defmac
23295 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
23296   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
23297 @acindex{COMPILE_CHECK}
23298 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
23299 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
23300 addition that it prints @samp{checking for @var{echo-text}} to the
23301 standard output first, if @var{echo-text} is non-empty.  Use
23302 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
23303 messages (@pxref{Printing Messages}).
23304 @end defmac
23306 @defmac AC_CONST
23307 @acindex{CONST}
23308 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
23309 @end defmac
23311 @defmac AC_CROSS_CHECK
23312 @acindex{CROSS_CHECK}
23313 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
23314 @code{:-)}.
23315 @end defmac
23317 @defmac AC_CYGWIN
23318 @acindex{CYGWIN}
23319 @evindex CYGWIN
23320 Check for the Cygwin environment in which case the shell variable
23321 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
23322 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
23323 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
23325 @example
23326 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
23327 case $host_os in
23328   *cygwin* ) CYGWIN=yes;;
23329          * ) CYGWIN=no;;
23330 esac
23331 @end example
23333 Beware that the variable @env{CYGWIN} has a special meaning when
23334 running Cygwin, and should not be changed.  That's yet another reason
23335 not to use this macro.
23336 @end defmac
23338 @defmac AC_DECL_SYS_SIGLIST
23339 @acindex{DECL_SYS_SIGLIST}
23340 @cvindex SYS_SIGLIST_DECLARED
23341 Same as:
23343 @example
23344 AC_CHECK_DECLS([sys_siglist], [], [],
23345 [#include <signal.h>
23346 /* NetBSD declares sys_siglist in unistd.h.  */
23347 #ifdef HAVE_UNISTD_H
23348 # include <unistd.h>
23349 #endif
23351 @end example
23353 @noindent
23354 @xref{AC_CHECK_DECLS}.
23355 @end defmac
23357 @defmac AC_DECL_YYTEXT
23358 @acindex{DECL_YYTEXT}
23359 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23360 @end defmac
23362 @defmac AC_DIR_HEADER
23363 @acindex{DIR_HEADER}
23364 @cvindex DIRENT
23365 @cvindex SYSNDIR
23366 @cvindex SYSDIR
23367 @cvindex NDIR
23368 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
23369 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
23370 (@pxref{AC_HEADER_DIRENT}),
23371 but defines a different set of C preprocessor macros to indicate which
23372 header file is found:
23374 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
23375 @item Header            @tab Old Symbol     @tab New Symbol
23376 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
23377 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
23378 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
23379 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
23380 @end multitable
23381 @end defmac
23383 @defmac AC_DYNIX_SEQ
23384 @acindex{DYNIX_SEQ}
23385 If on DYNIX/ptx, add @option{-lseq} to output variable
23386 @code{LIBS}.  This macro used to be defined as
23388 @example
23389 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
23390 @end example
23392 @noindent
23393 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
23394 @end defmac
23396 @defmac AC_EXEEXT
23397 @acindex{EXEEXT}
23398 @ovindex EXEEXT
23399 Defined the output variable @code{EXEEXT} based on the output of the
23400 compiler, which is now done automatically.  Typically set to empty
23401 string if Posix and @samp{.exe} if a DOS variant.
23402 @end defmac
23404 @defmac AC_EMXOS2
23405 @acindex{EMXOS2}
23406 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
23407 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
23408 check the nature of the host is using @code{AC_CANONICAL_HOST}
23409 (@pxref{Canonicalizing}).
23410 @end defmac
23412 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
23413   @ovar{action-if-not-given})
23414 @acindex{ENABLE}
23415 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
23416 support providing a help string (@pxref{AC_ARG_ENABLE}).
23417 @end defmac
23419 @defmac AC_ERROR
23420 @acindex{ERROR}
23421 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
23422 @end defmac
23424 @defmac AC_FIND_X
23425 @acindex{FIND_X}
23426 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
23427 @end defmac
23429 @defmac AC_FIND_XTRA
23430 @acindex{FIND_XTRA}
23431 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
23432 @end defmac
23434 @defmac AC_FOREACH
23435 @acindex{FOREACH}
23436 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
23437 @end defmac
23439 @defmac AC_FUNC_CHECK
23440 @acindex{FUNC_CHECK}
23441 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
23442 @end defmac
23444 @anchor{AC_FUNC_SETVBUF_REVERSED}
23445 @defmac AC_FUNC_SETVBUF_REVERSED
23446 @acindex{FUNC_SETVBUF_REVERSED}
23447 @cvindex SETVBUF_REVERSED
23448 @c @fuindex setvbuf
23449 @prindex @code{setvbuf}
23450 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
23451 the buffering type as its second argument and the buffer pointer as the
23452 third, instead of the other way around, and defined
23453 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
23454 were those based on SVR2, which became obsolete in 1987, and the macro
23455 is no longer needed.
23456 @end defmac
23458 @defmac AC_FUNC_WAIT3
23459 @acindex{FUNC_WAIT3}
23460 @cvindex HAVE_WAIT3
23461 @c @fuindex wait3
23462 @prindex @code{wait3}
23463 If @code{wait3} is found and fills in the contents of its third argument
23464 (a @samp{struct rusage *}), which HP-UX does not do, define
23465 @code{HAVE_WAIT3}.
23467 These days portable programs should use @code{waitpid}, not
23468 @code{wait3}, as @code{wait3} has been removed from Posix.
23469 @end defmac
23471 @defmac AC_GCC_TRADITIONAL
23472 @acindex{GCC_TRADITIONAL}
23473 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
23474 @end defmac
23476 @defmac AC_GETGROUPS_T
23477 @acindex{GETGROUPS_T}
23478 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
23479 @end defmac
23481 @defmac AC_GETLOADAVG
23482 @acindex{GETLOADAVG}
23483 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
23484 @end defmac
23486 @defmac AC_GNU_SOURCE
23487 @acindex{GNU_SOURCE}
23488 @cvindex _GNU_SOURCE
23489 This macro is a platform-specific subset of
23490 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23491 @end defmac
23493 @defmac AC_HAVE_FUNCS
23494 @acindex{HAVE_FUNCS}
23495 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
23496 @end defmac
23498 @defmac AC_HAVE_HEADERS
23499 @acindex{HAVE_HEADERS}
23500 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
23501 @end defmac
23503 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
23504   @ovar{action-if-not-found}, @ovar{other-libraries})
23505 @acindex{HAVE_LIBRARY}
23506 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
23507 @var{function} argument of @code{main}.  In addition, @var{library} can
23508 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
23509 all of those cases, the compiler is passed @option{-lfoo}.  However,
23510 @var{library} cannot be a shell variable; it must be a literal name.
23511 @xref{AC_CHECK_LIB}.
23512 @end defmac
23514 @defmac AC_HAVE_POUNDBANG
23515 @acindex{HAVE_POUNDBANG}
23516 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
23517 @end defmac
23519 @defmac AC_HEADER_CHECK
23520 @acindex{HEADER_CHECK}
23521 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
23522 @end defmac
23524 @defmac AC_HEADER_EGREP
23525 @acindex{HEADER_EGREP}
23526 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
23527 @end defmac
23529 @anchor{AC_HEADER_TIME}
23530 @defmac AC_HEADER_TIME
23531 @acindex{HEADER_TIME}
23532 @cvindex TIME_WITH_SYS_TIME
23533 @hdrindex{time.h}
23534 @hdrindex{sys/time.h}
23535 @caindex header_time
23536 This macro used to check whether it was possible to include
23537 @file{time.h} and @file{sys/time.h} in the same source file,
23538 defining @code{TIME_WITH_SYS_TIME} if so.
23540 Nowadays, it is equivalent to @samp{AC_CHECK_HEADERS([sys/time.h])},
23541 although it does still define @code{TIME_WITH_SYS_TIME} for
23542 compatibility's sake.  @file{time.h} is universally present, and the
23543 systems on which @file{sys/time.h} conflicted with @file{time.h} are
23544 obsolete.
23545 @end defmac
23547 @defmac AC_HELP_STRING
23548 @acindex{HELP_STRING}
23549 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
23550 @end defmac
23552 @defmac AC_INIT (@var{unique-file-in-source-dir})
23553 @acindex{INIT}
23554 Formerly @code{AC_INIT} used to have a single argument, and was
23555 equivalent to:
23557 @example
23558 AC_INIT
23559 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
23560 @end example
23561 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
23562 @end defmac
23564 @defmac AC_INLINE
23565 @acindex{INLINE}
23566 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
23567 @end defmac
23569 @defmac AC_INT_16_BITS
23570 @acindex{INT_16_BITS}
23571 @cvindex INT_16_BITS
23572 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
23573 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
23574 @end defmac
23576 @defmac AC_IRIX_SUN
23577 @acindex{IRIX_SUN}
23578 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
23579 @code{LIBS}.  If you were using it to get @code{getmntent}, use
23580 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
23581 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
23582 getpwnam)}.  Up to Autoconf 2.13, it used to be
23584 @example
23585 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
23586 @end example
23588 @noindent
23589 now it is defined as
23591 @example
23592 AC_FUNC_GETMNTENT
23593 AC_CHECK_LIB([sun], [getpwnam])
23594 @end example
23596 @noindent
23597 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
23598 @end defmac
23600 @defmac AC_ISC_POSIX
23601 @acindex{ISC_POSIX}
23602 @ovindex LIBS
23603 This macro adds @option{-lcposix} to output variable @code{LIBS} if
23604 necessary for Posix facilities.  Sun dropped support for the obsolete
23605 INTERACTIVE Systems Corporation Unix on 2006-07-23.  New programs
23606 need not use this macro.  It is implemented as
23607 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
23608 @end defmac
23610 @defmac AC_LANG_C
23611 @acindex{LANG_C}
23612 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
23613 @end defmac
23615 @defmac AC_LANG_CPLUSPLUS
23616 @acindex{LANG_CPLUSPLUS}
23617 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
23618 @end defmac
23620 @defmac AC_LANG_FORTRAN77
23621 @acindex{LANG_FORTRAN77}
23622 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
23623 @end defmac
23625 @defmac AC_LANG_RESTORE
23626 @acindex{LANG_RESTORE}
23627 Select the @var{language} that is saved on the top of the stack, as set
23628 by @code{AC_LANG_SAVE}, remove it from the stack, and call
23629 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
23630 preferred way to change languages.
23631 @end defmac
23633 @defmac AC_LANG_SAVE
23634 @acindex{LANG_SAVE}
23635 Remember the current language (as set by @code{AC_LANG}) on a stack.
23636 The current language does not change.  @code{AC_LANG_PUSH} is preferred
23637 (@pxref{AC_LANG_PUSH}).
23638 @end defmac
23640 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
23641 @acindex{LINK_FILES}
23642 This is an obsolete version of @code{AC_CONFIG_LINKS}
23643 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
23645 @example
23646 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
23647               host.h            object.h)
23648 @end example
23650 @noindent
23653 @example
23654 AC_CONFIG_LINKS([host.h:config/$machine.h
23655                 object.h:config/$obj_format.h])
23656 @end example
23657 @end defmac
23659 @defmac AC_LN_S
23660 @acindex{LN_S}
23661 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
23662 @end defmac
23664 @defmac AC_LONG_64_BITS
23665 @acindex{LONG_64_BITS}
23666 @cvindex LONG_64_BITS
23667 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
23668 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
23669 (@pxref{AC_CHECK_SIZEOF}).
23670 @end defmac
23672 @defmac AC_LONG_DOUBLE
23673 @acindex{LONG_DOUBLE}
23674 If the C compiler supports a working @code{long double} type with more
23675 range or precision than the @code{double} type, define
23676 @code{HAVE_LONG_DOUBLE}.
23678 You should use @code{AC_TYPE_LONG_DOUBLE} or
23679 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23680 @end defmac
23682 @defmac AC_LONG_FILE_NAMES
23683 @acindex{LONG_FILE_NAMES}
23684 Replaced by
23685 @example
23686 AC_SYS_LONG_FILE_NAMES
23687 @end example
23688 @noindent
23689 @xref{AC_SYS_LONG_FILE_NAMES}.
23690 @end defmac
23692 @defmac AC_MAJOR_HEADER
23693 @acindex{MAJOR_HEADER}
23694 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
23695 @end defmac
23697 @defmac AC_MEMORY_H
23698 @acindex{MEMORY_H}
23699 @cvindex NEED_MEMORY_H
23700 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
23701 defined in @file{memory.h}.  Today it is equivalent to
23702 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
23703 your code to get the @code{mem} functions from @file{string.h} instead.
23704 @end defmac
23706 @defmac AC_MINGW32
23707 @acindex{MINGW32}
23708 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
23709 environment and sets @code{MINGW32}.  Don't use this macro, the
23710 dignified means to check the nature of the host is using
23711 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23712 @end defmac
23714 @defmac AC_MINIX
23715 @acindex{MINIX}
23716 @cvindex _MINIX
23717 @cvindex _POSIX_SOURCE
23718 @cvindex _POSIX_1_SOURCE
23719 This macro is a platform-specific subset of
23720 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23721 @end defmac
23723 @defmac AC_MINUS_C_MINUS_O
23724 @acindex{MINUS_C_MINUS_O}
23725 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
23726 @end defmac
23728 @defmac AC_MMAP
23729 @acindex{MMAP}
23730 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
23731 @end defmac
23733 @defmac AC_MODE_T
23734 @acindex{MODE_T}
23735 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
23736 @end defmac
23738 @defmac AC_OBJEXT
23739 @acindex{OBJEXT}
23740 @ovindex OBJEXT
23741 Defined the output variable @code{OBJEXT} based on the output of the
23742 compiler, after .c files have been excluded.  Typically set to @samp{o}
23743 if Posix, @samp{obj} if a DOS variant.
23744 Now the compiler checking macros handle
23745 this automatically.
23746 @end defmac
23748 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
23749 @acindex{OBSOLETE}
23750 Make M4 print a message to the standard error output warning that
23751 @var{this-macro-name} is obsolete, and giving the file and line number
23752 where it was called.  @var{this-macro-name} should be the name of the
23753 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
23754 it is printed at the end of the warning message; for example, it can be
23755 a suggestion for what to use instead of @var{this-macro-name}.
23757 For instance
23759 @example
23760 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
23761 @end example
23763 @noindent
23764 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
23765 services to the user (@pxref{AU_DEFUN}).
23766 @end defmac
23768 @defmac AC_OFF_T
23769 @acindex{OFF_T}
23770 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
23771 @end defmac
23773 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
23774 @acindex{OUTPUT}
23775 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
23776 interface is equivalent to:
23778 @example
23779 @group
23780 AC_CONFIG_FILES(@var{file}@dots{})
23781 AC_CONFIG_COMMANDS([default],
23782                    @var{extra-cmds}, @var{init-cmds})
23783 AC_OUTPUT
23784 @end group
23785 @end example
23787 @noindent
23788 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
23789 @end defmac
23791 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
23792 @acindex{OUTPUT_COMMANDS}
23793 Specify additional shell commands to run at the end of
23794 @file{config.status}, and shell commands to initialize any variables
23795 from @command{configure}.  This macro may be called multiple times.  It is
23796 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
23798 Here is an unrealistic example:
23800 @example
23801 fubar=27
23802 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
23803                    [fubar=$fubar])
23804 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
23805                    [echo init bit])
23806 @end example
23808 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
23809 additional key, an important difference is that
23810 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
23811 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
23812 can safely be given macro calls as arguments:
23814 @example
23815 AC_CONFIG_COMMANDS(foo, [my_FOO()])
23816 @end example
23818 @noindent
23819 Conversely, where one level of quoting was enough for literal strings
23820 with @code{AC_OUTPUT_COMMANDS}, you need two with
23821 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
23823 @example
23824 @group
23825 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
23826 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
23827 @end group
23828 @end example
23829 @end defmac
23831 @defmac AC_PID_T
23832 @acindex{PID_T}
23833 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
23834 @end defmac
23836 @defmac AC_PREFIX
23837 @acindex{PREFIX}
23838 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
23839 @end defmac
23841 @defmac AC_PROG_CC_C89
23842 @acindex{PROG_CC_C89}
23843 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23844 @end defmac
23846 @defmac AC_PROG_CC_C99
23847 @acindex{PROG_CC_C99}
23848 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23849 @end defmac
23851 @defmac AC_PROG_CC_STDC
23852 @acindex{PROG_CC_STDC}
23853 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23854 @end defmac
23856 @defmac AC_PROGRAMS_CHECK
23857 @acindex{PROGRAMS_CHECK}
23858 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
23859 @end defmac
23861 @defmac AC_PROGRAMS_PATH
23862 @acindex{PROGRAMS_PATH}
23863 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
23864 @end defmac
23866 @defmac AC_PROGRAM_CHECK
23867 @acindex{PROGRAM_CHECK}
23868 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
23869 @end defmac
23871 @defmac AC_PROGRAM_EGREP
23872 @acindex{PROGRAM_EGREP}
23873 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
23874 @end defmac
23876 @defmac AC_PROGRAM_PATH
23877 @acindex{PROGRAM_PATH}
23878 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
23879 @end defmac
23881 @defmac AC_REMOTE_TAPE
23882 @acindex{REMOTE_TAPE}
23883 Removed because of limited usefulness.
23884 @end defmac
23886 @defmac AC_RESTARTABLE_SYSCALLS
23887 @acindex{RESTARTABLE_SYSCALLS}
23888 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
23889 these days portable programs should use @code{sigaction} with
23890 @code{SA_RESTART} if they want restartable system calls.  They should
23891 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23892 system call is restartable is a dynamic issue, not a configuration-time
23893 issue.
23894 @end defmac
23896 @defmac AC_RETSIGTYPE
23897 @acindex{RETSIGTYPE}
23898 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
23899 is obsolete when assuming C89 or better.
23900 @end defmac
23902 @defmac AC_RSH
23903 @acindex{RSH}
23904 Removed because of limited usefulness.
23905 @end defmac
23907 @defmac AC_SCO_INTL
23908 @acindex{SCO_INTL}
23909 @ovindex LIBS
23910 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
23911 macro used to do this:
23913 @example
23914 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
23915 @end example
23917 @noindent
23918 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
23919 @end defmac
23921 @defmac AC_SETVBUF_REVERSED
23922 @acindex{SETVBUF_REVERSED}
23923 Replaced by
23924 @example
23925 AC_FUNC_SETVBUF_REVERSED
23926 @end example
23927 @noindent
23928 @xref{AC_FUNC_SETVBUF_REVERSED}.
23929 @end defmac
23931 @defmac AC_SET_MAKE
23932 @acindex{SET_MAKE}
23933 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
23934 @end defmac
23936 @defmac AC_SIZEOF_TYPE
23937 @acindex{SIZEOF_TYPE}
23938 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
23939 @end defmac
23941 @defmac AC_SIZE_T
23942 @acindex{SIZE_T}
23943 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
23944 @end defmac
23946 @defmac AC_STAT_MACROS_BROKEN
23947 @acindex{STAT_MACROS_BROKEN}
23948 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
23949 @end defmac
23951 @defmac AC_STDC_HEADERS
23952 @acindex{STDC_HEADERS}
23953 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}), which
23954 is itself obsolete.  Nowadays it is safe to assume the facilities of C90
23955 exist.
23956 @end defmac
23958 @defmac AC_STRCOLL
23959 @acindex{STRCOLL}
23960 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
23961 @end defmac
23963 @defmac AC_STRUCT_ST_BLKSIZE
23964 @acindex{STRUCT_ST_BLKSIZE}
23965 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
23966 @cvindex HAVE_ST_BLKSIZE
23967 If @code{struct stat} contains an @code{st_blksize} member, define
23968 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
23969 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
23970 the future.  This macro is obsoleted, and should be replaced by
23972 @example
23973 AC_CHECK_MEMBERS([struct stat.st_blksize])
23974 @end example
23975 @noindent
23976 @xref{AC_CHECK_MEMBERS}.
23977 @end defmac
23979 @defmac AC_STRUCT_ST_RDEV
23980 @acindex{STRUCT_ST_RDEV}
23981 @cvindex HAVE_ST_RDEV
23982 @cvindex HAVE_STRUCT_STAT_ST_RDEV
23983 If @code{struct stat} contains an @code{st_rdev} member, define
23984 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
23985 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
23986 in the future.  Actually, even the new macro is obsolete and should be
23987 replaced by:
23988 @example
23989 AC_CHECK_MEMBERS([struct stat.st_rdev])
23990 @end example
23991 @noindent
23992 @xref{AC_CHECK_MEMBERS}.
23993 @end defmac
23995 @defmac AC_ST_BLKSIZE
23996 @acindex{ST_BLKSIZE}
23997 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
23998 @end defmac
24000 @defmac AC_ST_BLOCKS
24001 @acindex{ST_BLOCKS}
24002 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
24003 @end defmac
24005 @defmac AC_ST_RDEV
24006 @acindex{ST_RDEV}
24007 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24008 @end defmac
24010 @defmac AC_SYS_RESTARTABLE_SYSCALLS
24011 @acindex{SYS_RESTARTABLE_SYSCALLS}
24012 @cvindex HAVE_RESTARTABLE_SYSCALLS
24013 If the system automatically restarts a system call that is interrupted
24014 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
24015 not check whether system calls are restarted in general---it checks whether a
24016 signal handler installed with @code{signal} (but not @code{sigaction})
24017 causes system calls to be restarted.  It does not check whether system calls
24018 can be restarted when interrupted by signals that have no handler.
24020 These days portable programs should use @code{sigaction} with
24021 @code{SA_RESTART} if they want restartable system calls.  They should
24022 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
24023 system call is restartable is a dynamic issue, not a configuration-time
24024 issue.
24025 @end defmac
24027 @defmac AC_SYS_SIGLIST_DECLARED
24028 @acindex{SYS_SIGLIST_DECLARED}
24029 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
24030 name is obsolete, as the same functionality is now achieved via
24031 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
24032 @end defmac
24034 @defmac AC_TEST_CPP
24035 @acindex{TEST_CPP}
24036 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
24037 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
24038 @end defmac
24040 @defmac AC_TEST_PROGRAM
24041 @acindex{TEST_PROGRAM}
24042 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
24043 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
24044 @end defmac
24046 @defmac AC_TIMEZONE
24047 @acindex{TIMEZONE}
24048 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
24049 @end defmac
24051 @defmac AC_TIME_WITH_SYS_TIME
24052 @acindex{TIME_WITH_SYS_TIME}
24053 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}), which is
24054 itself obsolete; nowadays one need only do
24055 @samp{AC_CHECK_HEADERS([sys/time.h])}.
24056 @end defmac
24058 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
24059   @ovar{action-if-true}, @ovar{action-if-false})
24060 @acindex{TRY_COMPILE}
24061 Same as:
24063 @example
24064 AC_COMPILE_IFELSE(
24065   [AC_LANG_PROGRAM([[@var{includes}]],
24066      [[@var{function-body}]])],
24067   [@var{action-if-true}],
24068   [@var{action-if-false}])
24069 @end example
24071 @noindent
24072 @xref{Running the Compiler}.
24074 This macro double quotes both @var{includes} and @var{function-body}.
24076 For C and C++, @var{includes} is any @code{#include} statements needed
24077 by the code in @var{function-body} (@var{includes} is ignored if
24078 the currently selected language is Fortran or Fortran 77).  The compiler
24079 and compilation flags are determined by the current language
24080 (@pxref{Language Choice}).
24081 @end defmac
24083 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
24084 @acindex{TRY_CPP}
24085 Same as:
24087 @example
24088 AC_PREPROC_IFELSE(
24089   [AC_LANG_SOURCE([[@var{input}]])],
24090   [@var{action-if-true}],
24091   [@var{action-if-false}])
24092 @end example
24094 @noindent
24095 @xref{Running the Preprocessor}.
24097 This macro double quotes the @var{input}.
24098 @end defmac
24100 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
24101   @ovar{action-if-true}, @ovar{action-if-false})
24102 @acindex{TRY_LINK}
24103 Same as:
24105 @example
24106 AC_LINK_IFELSE(
24107   [AC_LANG_PROGRAM([[@var{includes}]],
24108      [[@var{function-body}]])],
24109   [@var{action-if-true}],
24110   [@var{action-if-false}])
24111 @end example
24113 @noindent
24114 @xref{Running the Compiler}.
24116 This macro double quotes both @var{includes} and @var{function-body}.
24118 Depending on the current language (@pxref{Language Choice}), create a
24119 test program to see whether a function whose body consists of
24120 @var{function-body} can be compiled and linked.  If the file compiles
24121 and links successfully, run shell commands @var{action-if-found},
24122 otherwise run @var{action-if-not-found}.
24124 This macro double quotes both @var{includes} and @var{function-body}.
24126 For C and C++, @var{includes} is any @code{#include} statements needed
24127 by the code in @var{function-body} (@var{includes} is ignored if
24128 the currently selected language is Fortran or Fortran 77).  The compiler
24129 and compilation flags are determined by the current language
24130 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
24131 @code{LIBS} are used for linking.
24132 @end defmac
24134 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
24135   @ovar{action-if-not-found})
24136 @acindex{TRY_LINK_FUNC}
24137 This macro is equivalent to
24138 @example
24139 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
24140   [@var{action-if-found}], [@var{action-if-not-found}])
24141 @end example
24142 @noindent
24143 @xref{AC_LINK_IFELSE}.
24144 @end defmac
24146 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
24147   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
24148 @acindex{TRY_RUN}
24149 Same as:
24151 @example
24152 AC_RUN_IFELSE(
24153   [AC_LANG_SOURCE([[@var{program}]])],
24154   [@var{action-if-true}],
24155   [@var{action-if-false}],
24156   [@var{action-if-cross-compiling}])
24157 @end example
24159 @noindent
24160 @xref{Runtime}.
24161 @end defmac
24163 @anchor{AC_TYPE_SIGNAL}
24164 @defmac AC_TYPE_SIGNAL
24165 @acindex{TYPE_SIGNAL}
24166 @cvindex RETSIGTYPE
24167 @hdrindex{signal.h}
24168 If @file{signal.h} declares @code{signal} as returning a pointer to a
24169 function returning @code{void}, define @code{RETSIGTYPE} to be
24170 @code{void}; otherwise, define it to be @code{int}.  These days, it is
24171 portable to assume C89, and that signal handlers return @code{void},
24172 without needing to use this macro or @code{RETSIGTYPE}.
24174 When targeting older K&R C, it is possible to define signal handlers as
24175 returning type @code{RETSIGTYPE}, and omit a return statement:
24177 @example
24178 @group
24179 RETSIGTYPE
24180 hup_handler ()
24182 @dots{}
24184 @end group
24185 @end example
24186 @end defmac
24188 @defmac AC_UID_T
24189 @acindex{UID_T}
24190 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
24191 @end defmac
24193 @defmac AC_UNISTD_H
24194 @acindex{UNISTD_H}
24195 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}),
24196 which is one of the tests done as a side effect by
24197 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), so usually
24198 unnecessary to write explicitly.
24199 @end defmac
24201 @defmac AC_USG
24202 @acindex{USG}
24203 @cvindex USG
24204 Define @code{USG} if the BSD string functions (@code{bcopy},
24205 @code{bzero}, @code{index}, @code{rindex}, etc) are @emph{not} defined
24206 in @file{strings.h}.  Modern code should assume @file{string.h} exists
24207 and should use the ISO C string functions (@code{memmove}, @code{memset},
24208 @code{strchr}, @code{strrchr}, etc) unconditionally.
24210 @file{strings.h} may be the only header that declares @code{strcasecmp},
24211 @code{strncasecmp}, and @code{ffs}.  @code{AC_INCLUDES_DEFAULT} checks
24212 for it (@pxref{Default Includes}); test @code{HAVE_STRINGS_H}.
24213 @end defmac
24215 @defmac AC_UTIME_NULL
24216 @acindex{UTIME_NULL}
24217 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
24218 @end defmac
24220 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
24221 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
24222 If the cache file is inconsistent with the current host, target and
24223 build system types, it used to execute @var{cmd} or print a default
24224 error message.  This is now handled by default.
24225 @end defmac
24227 @defmac AC_VERBOSE (@var{result-description})
24228 @acindex{VERBOSE}
24229 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
24230 @end defmac
24232 @defmac AC_VFORK
24233 @acindex{VFORK}
24234 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
24235 @end defmac
24237 @defmac AC_VPRINTF
24238 @acindex{VPRINTF}
24239 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
24240 @end defmac
24242 @defmac AC_WAIT3
24243 @acindex{WAIT3}
24244 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
24245 portable programs should use @code{waitpid}, not @code{wait3}, as
24246 @code{wait3} has been removed from Posix.
24247 @end defmac
24249 @defmac AC_WARN
24250 @acindex{WARN}
24251 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
24252 @end defmac
24254 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
24255   @ovar{action-if-not-given})
24256 @acindex{WITH}
24257 This is an obsolete version of @code{AC_ARG_WITH} that does not
24258 support providing a help string (@pxref{AC_ARG_WITH}).
24259 @end defmac
24261 @defmac AC_WORDS_BIGENDIAN
24262 @acindex{WORDS_BIGENDIAN}
24263 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
24264 @end defmac
24266 @defmac AC_XENIX_DIR
24267 @acindex{XENIX_DIR}
24268 @ovindex LIBS
24269 This macro used to add @option{-lx} to output variable @code{LIBS} if on
24270 Xenix.  Also, if @file{dirent.h} is being checked for, added
24271 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
24272 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
24273 running XENIX on which you should not depend:
24275 @example
24276 AC_MSG_CHECKING([for Xenix])
24277 AC_EGREP_CPP([yes],
24278 [#if defined M_XENIX && !defined M_UNIX
24279   yes
24280 #endif],
24281              [AC_MSG_RESULT([yes]); XENIX=yes],
24282              [AC_MSG_RESULT([no]); XENIX=])
24283 @end example
24284 @noindent
24285 Don't use this macro, the dignified means to check the nature of the
24286 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24287 @end defmac
24289 @defmac AC_YYTEXT_POINTER
24290 @acindex{YYTEXT_POINTER}
24291 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
24292 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
24293 @end defmac
24295 @node Autoconf 1
24296 @section Upgrading From Version 1
24297 @cindex Upgrading autoconf
24298 @cindex Autoconf upgrading
24300 Autoconf version 2 is mostly backward compatible with version 1.
24301 However, it introduces better ways to do some things, and doesn't
24302 support some of the ugly things in version 1.  So, depending on how
24303 sophisticated your @file{configure.ac} files are, you might have to do
24304 some manual work in order to upgrade to version 2.  This chapter points
24305 out some problems to watch for when upgrading.  Also, perhaps your
24306 @command{configure} scripts could benefit from some of the new features in
24307 version 2; the changes are summarized in the file @file{NEWS} in the
24308 Autoconf distribution.
24310 @menu
24311 * Changed File Names::          Files you might rename
24312 * Changed Makefiles::           New things to put in @file{Makefile.in}
24313 * Changed Macros::              Macro calls you might replace
24314 * Changed Results::             Changes in how to check test results
24315 * Changed Macro Writing::       Better ways to write your own macros
24316 @end menu
24318 @node Changed File Names
24319 @subsection Changed File Names
24321 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
24322 in a particular package's source directory), you must rename it to
24323 @file{acsite.m4}.  @xref{autoconf Invocation}.
24325 If you distribute @file{install.sh} with your package, rename it to
24326 @file{install-sh} so @command{make} builtin rules don't inadvertently
24327 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
24328 looks for the script under both names, but it is best to use the new name.
24330 If you were using @file{config.h.top}, @file{config.h.bot}, or
24331 @file{acconfig.h}, you still can, but you have less clutter if you
24332 use the @code{AH_} macros.  @xref{Autoheader Macros}.
24334 @node Changed Makefiles
24335 @subsection Changed Makefiles
24337 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
24338 your @file{Makefile.in} files, so they can take advantage of the values
24339 of those variables in the environment when @command{configure} is run.
24340 Doing this isn't necessary, but it's a convenience for users.
24342 Also add @samp{@@configure_input@@} in a comment to each input file for
24343 @code{AC_OUTPUT}, so that the output files contain a comment saying
24344 they were produced by @command{configure}.  Automatically selecting the
24345 right comment syntax for all the kinds of files that people call
24346 @code{AC_OUTPUT} on became too much work.
24348 Add @file{config.log} and @file{config.cache} to the list of files you
24349 remove in @code{distclean} targets.
24351 If you have the following in @file{Makefile.in}:
24353 @example
24354 prefix = /usr/local
24355 exec_prefix = $(prefix)
24356 @end example
24358 @noindent
24359 you must change it to:
24361 @example
24362 prefix = @@prefix@@
24363 exec_prefix = @@exec_prefix@@
24364 @end example
24366 @noindent
24367 The old behavior of replacing those variables without @samp{@@}
24368 characters around them has been removed.
24370 @node Changed Macros
24371 @subsection Changed Macros
24373 Many of the macros were renamed in Autoconf version 2.  You can still
24374 use the old names, but the new ones are clearer, and it's easier to find
24375 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
24376 new names for the old macros.  Use the @command{autoupdate} program to
24377 convert your @file{configure.ac} to using the new macro names.
24378 @xref{autoupdate Invocation}.
24380 Some macros have been superseded by similar ones that do the job better,
24381 but are not call-compatible.  If you get warnings about calling obsolete
24382 macros while running @command{autoconf}, you may safely ignore them, but
24383 your @command{configure} script generally works better if you follow
24384 the advice that is printed about what to replace the obsolete macros with.  In
24385 particular, the mechanism for reporting the results of tests has
24386 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
24387 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
24388 looks better if you switch to @code{AC_MSG_CHECKING} and
24389 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
24390 in conjunction with cache variables.  @xref{Caching Results}.
24394 @node Changed Results
24395 @subsection Changed Results
24397 If you were checking the results of previous tests by examining the
24398 shell variable @code{DEFS}, you need to switch to checking the values of
24399 the cache variables for those tests.  @code{DEFS} no longer exists while
24400 @command{configure} is running; it is only created when generating output
24401 files.  This difference from version 1 is because properly quoting the
24402 contents of that variable turned out to be too cumbersome and
24403 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
24404 Variable Names}.
24406 For example, here is a @file{configure.ac} fragment written for Autoconf
24407 version 1:
24409 @example
24410 AC_HAVE_FUNCS(syslog)
24411 case "$DEFS" in
24412 *-DHAVE_SYSLOG*) ;;
24413 *) # syslog is not in the default libraries.  See if it's in some other.
24414   saved_LIBS="$LIBS"
24415   for lib in bsd socket inet; do
24416     AC_CHECKING(for syslog in -l$lib)
24417     LIBS="-l$lib $saved_LIBS"
24418     AC_HAVE_FUNCS(syslog)
24419     case "$DEFS" in
24420     *-DHAVE_SYSLOG*) break ;;
24421     *) ;;
24422     esac
24423     LIBS="$saved_LIBS"
24424   done ;;
24425 esac
24426 @end example
24428 Here is a way to write it for version 2:
24430 @example
24431 AC_CHECK_FUNCS([syslog])
24432 if test "x$ac_cv_func_syslog" = xno; then
24433   # syslog is not in the default libraries.  See if it's in some other.
24434   for lib in bsd socket inet; do
24435     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
24436       LIBS="-l$lib $LIBS"; break])
24437   done
24439 @end example
24441 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
24442 backslashes before quotes, you need to remove them.  It now works
24443 predictably, and does not treat quotes (except back quotes) specially.
24444 @xref{Setting Output Variables}.
24446 All of the Boolean shell variables set by Autoconf macros now use
24447 @samp{yes} for the true value.  Most of them use @samp{no} for false,
24448 though for backward compatibility some use the empty string instead.  If
24449 you were relying on a shell variable being set to something like 1 or
24450 @samp{t} for true, you need to change your tests.
24452 @node Changed Macro Writing
24453 @subsection Changed Macro Writing
24455 When defining your own macros, you should now use @code{AC_DEFUN}
24456 instead of @code{define}.  @code{AC_DEFUN} automatically calls
24457 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
24458 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
24459 messages on the screen.  There's no actual harm in continuing to use the
24460 older way, but it's less convenient and attractive.  @xref{Macro
24461 Definitions}.
24463 You probably looked at the macros that came with Autoconf as a guide for
24464 how to do things.  It would be a good idea to take a look at the new
24465 versions of them, as the style is somewhat improved and they take
24466 advantage of some new features.
24468 If you were doing tricky things with undocumented Autoconf internals
24469 (macros, variables, diversions), check whether you need to change
24470 anything to account for changes that have been made.  Perhaps you can
24471 even use an officially supported technique in version 2 instead of
24472 kludging.  Or perhaps not.
24474 To speed up your locally written feature tests, add caching to them.
24475 See whether any of your tests are of general enough usefulness to
24476 encapsulate them into macros that you can share.
24479 @node Autoconf 2.13
24480 @section Upgrading From Version 2.13
24481 @cindex Upgrading autoconf
24482 @cindex Autoconf upgrading
24484 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
24485 suits this section@enddots{}
24487 @quotation
24488 Autoconf version 2.50 is mostly backward compatible with version 2.13.
24489 However, it introduces better ways to do some things, and doesn't
24490 support some of the ugly things in version 2.13.  So, depending on how
24491 sophisticated your @file{configure.ac} files are, you might have to do
24492 some manual work in order to upgrade to version 2.50.  This chapter
24493 points out some problems to watch for when upgrading.  Also, perhaps
24494 your @command{configure} scripts could benefit from some of the new
24495 features in version 2.50; the changes are summarized in the file
24496 @file{NEWS} in the Autoconf distribution.
24497 @end quotation
24499 @menu
24500 * Changed Quotation::           Broken code which used to work
24501 * New Macros::                  Interaction with foreign macros
24502 * Hosts and Cross-Compilation::  Bugward compatibility kludges
24503 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
24504 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
24505 @end menu
24507 @node Changed Quotation
24508 @subsection Changed Quotation
24510 The most important changes are invisible to you: the implementation of
24511 most macros have completely changed.  This allowed more factorization of
24512 the code, better error messages, a higher uniformity of the user's
24513 interface etc.  Unfortunately, as a side effect, some construct which
24514 used to (miraculously) work might break starting with Autoconf 2.50.
24515 The most common culprit is bad quotation.
24517 For instance, in the following example, the message is not properly
24518 quoted:
24520 @example
24521 AC_INIT
24522 AC_CHECK_HEADERS(foo.h, ,
24523   AC_MSG_ERROR(cannot find foo.h, bailing out))
24524 AC_OUTPUT
24525 @end example
24527 @noindent
24528 Autoconf 2.13 simply ignores it:
24530 @example
24531 $ @kbd{autoconf-2.13; ./configure --silent}
24532 creating cache ./config.cache
24533 configure: error: cannot find foo.h
24535 @end example
24537 @noindent
24538 while Autoconf 2.50 produces a broken @file{configure}:
24540 @example
24541 $ @kbd{autoconf-2.50; ./configure --silent}
24542 configure: error: cannot find foo.h
24543 ./configure: exit: bad non-numeric arg `bailing'
24544 ./configure: exit: bad non-numeric arg `bailing'
24546 @end example
24548 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
24549 too!
24551 @example
24552 AC_INIT([Example], [1.0], [bug-example@@example.org])
24553 AC_CHECK_HEADERS([foo.h], [],
24554   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
24555 AC_OUTPUT
24556 @end example
24558 Many many (and many more) Autoconf macros were lacking proper quotation,
24559 including no less than@dots{} @code{AC_DEFUN} itself!
24561 @example
24562 $ @kbd{cat configure.in}
24563 AC_DEFUN([AC_PROG_INSTALL],
24564 [# My own much better version
24566 AC_INIT
24567 AC_PROG_INSTALL
24568 AC_OUTPUT
24569 $ @kbd{autoconf-2.13}
24570 autoconf: Undefined macros:
24571 ***BUG in Autoconf--please report*** AC_FD_MSG
24572 ***BUG in Autoconf--please report*** AC_EPI
24573 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
24574 configure.in:5:AC_PROG_INSTALL
24575 $ @kbd{autoconf-2.50}
24577 @end example
24580 @node New Macros
24581 @subsection New Macros
24583 @cindex undefined macro
24584 @cindex @code{_m4_divert_diversion}
24586 While Autoconf was relatively dormant in the late 1990s, Automake
24587 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
24588 in 2001, Autoconf provided
24589 versions of these macros, integrated in the @code{AC_} namespace,
24590 instead of @code{AM_}.  But in order to ease the upgrading via
24591 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
24593 Unfortunately older versions of Automake (e.g., Automake 1.4)
24594 did not quote the names of these macros.
24595 Therefore, when @command{m4} finds something like
24596 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
24597 @code{AM_TYPE_PTRDIFF_T} is
24598 expanded, replaced with its Autoconf definition.
24600 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
24601 complains, in its own words:
24603 @example
24604 $ @kbd{cat configure.ac}
24605 AC_INIT([Example], [1.0], [bug-example@@example.org])
24606 AM_TYPE_PTRDIFF_T
24607 $ @kbd{aclocal-1.4}
24608 $ @kbd{autoconf}
24609 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
24610 aclocal.m4:17: the top level
24611 autom4te: m4 failed with exit status: 1
24613 @end example
24615 Modern versions of Automake no longer define most of these
24616 macros, and properly quote the names of the remaining macros.
24617 If you must use an old Automake, do not depend upon macros from Automake
24618 as it is simply not its job
24619 to provide macros (but the one it requires itself):
24621 @example
24622 $ @kbd{cat configure.ac}
24623 AC_INIT([Example], [1.0], [bug-example@@example.org])
24624 AM_TYPE_PTRDIFF_T
24625 $ @kbd{rm aclocal.m4}
24626 $ @kbd{autoupdate}
24627 autoupdate: `configure.ac' is updated
24628 $ @kbd{cat configure.ac}
24629 AC_INIT([Example], [1.0], [bug-example@@example.org])
24630 AC_CHECK_TYPES([ptrdiff_t])
24631 $ @kbd{aclocal-1.4}
24632 $ @kbd{autoconf}
24634 @end example
24637 @node Hosts and Cross-Compilation
24638 @subsection Hosts and Cross-Compilation
24639 @cindex Cross compilation
24641 Based on the experience of compiler writers, and after long public
24642 debates, many aspects of the cross-compilation chain have changed:
24644 @itemize @minus
24645 @item
24646 the relationship between the build, host, and target architecture types,
24648 @item
24649 the command line interface for specifying them to @command{configure},
24651 @item
24652 the variables defined in @command{configure},
24654 @item
24655 the enabling of cross-compilation mode.
24656 @end itemize
24658 @sp 1
24660 The relationship between build, host, and target have been cleaned up:
24661 the chain of default is now simply: target defaults to host, host to
24662 build, and build to the result of @command{config.guess}.  Nevertheless,
24663 in order to ease the transition from 2.13 to 2.50, the following
24664 transition scheme is implemented.  @emph{Do not rely on it}, as it will
24665 be completely disabled in a couple of releases (we cannot keep it, as it
24666 proves to cause more problems than it cures).
24668 They all default to the result of running @command{config.guess}, unless
24669 you specify either @option{--build} or @option{--host}.  In this case,
24670 the default becomes the system type you specified.  If you specify both,
24671 and they're different, @command{configure} enters cross compilation
24672 mode, so it doesn't run any tests that require execution.
24674 Hint: if you mean to override the result of @command{config.guess},
24675 prefer @option{--build} over @option{--host}.
24677 @sp 1
24679 For backward compatibility, @command{configure} accepts a system
24680 type as an option by itself.  Such an option overrides the
24681 defaults for build, host, and target system types.  The following
24682 configure statement configures a cross toolchain that runs on
24683 NetBSD/alpha but generates code for GNU Hurd/sparc,
24684 which is also the build platform.
24686 @example
24687 ./configure --host=alpha-netbsd sparc-gnu
24688 @end example
24690 @sp 1
24692 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
24693 and @code{target} had a different semantics before and after the
24694 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
24695 @option{--build} is strictly copied into @code{build_alias}, and is left
24696 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
24697 set to the canonicalized build type.  To ease the transition, before,
24698 its contents is the same as that of @code{build_alias}.  Do @emph{not}
24699 rely on this broken feature.
24701 For consistency with the backward compatibility scheme exposed above,
24702 when @option{--host} is specified but @option{--build} isn't, the build
24703 system is assumed to be the same as @option{--host}, and
24704 @samp{build_alias} is set to that value.  Eventually, this
24705 historically incorrect behavior will go away.
24707 @sp 1
24709 The former scheme to enable cross-compilation proved to cause more harm
24710 than good, in particular, it used to be triggered too easily, leaving
24711 regular end users puzzled in front of cryptic error messages.
24712 @command{configure} could even enter cross-compilation mode only
24713 because the compiler was not functional.  This is mainly because
24714 @command{configure} used to try to detect cross-compilation, instead of
24715 waiting for an explicit flag from the user.
24717 Now, @command{configure} enters cross-compilation mode if and only if
24718 @option{--host} is passed.
24720 That's the short documentation.  To ease the transition between 2.13 and
24721 its successors, a more complicated scheme is implemented.  @emph{Do not
24722 rely on the following}, as it will be removed in the near future.
24724 If you specify @option{--host}, but not @option{--build}, when
24725 @command{configure} performs the first compiler test it tries to run
24726 an executable produced by the compiler.  If the execution fails, it
24727 enters cross-compilation mode.  This is fragile.  Moreover, by the time
24728 the compiler test is performed, it may be too late to modify the
24729 build-system type: other tests may have already been performed.
24730 Therefore, whenever you specify @option{--host}, be sure to specify
24731 @option{--build} too.
24733 @example
24734 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
24735 @end example
24737 @noindent
24738 enters cross-compilation mode.  The former interface, which
24739 consisted in setting the compiler to a cross-compiler without informing
24740 @command{configure} is obsolete.  For instance, @command{configure}
24741 fails if it can't run the code generated by the specified compiler if you
24742 configure as follows:
24744 @example
24745 ./configure CC=m68k-coff-gcc
24746 @end example
24749 @node AC_LIBOBJ vs LIBOBJS
24750 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
24752 Up to Autoconf 2.13, the replacement of functions was triggered via the
24753 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
24754 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
24755 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
24757 This change is mandated by the unification of the GNU Build System
24758 components.  In particular, the various fragile techniques used to parse
24759 a @file{configure.ac} are all replaced with the use of traces.  As a
24760 consequence, any action must be traceable, which obsoletes critical
24761 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
24762 and it can even be handled gracefully (read, ``without your having to
24763 change something'').
24765 There were two typical uses of @code{LIBOBJS}: asking for a replacement
24766 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
24768 @sp 1
24770 As for function replacement, the fix is immediate: use
24771 @code{AC_LIBOBJ}.  For instance:
24773 @example
24774 LIBOBJS="$LIBOBJS fnmatch.o"
24775 LIBOBJS="$LIBOBJS malloc.$ac_objext"
24776 @end example
24778 @noindent
24779 should be replaced with:
24781 @example
24782 AC_LIBOBJ([fnmatch])
24783 AC_LIBOBJ([malloc])
24784 @end example
24786 @sp 1
24788 @ovindex LIBOBJDIR
24789 When used with Automake 1.10 or newer, a suitable value for
24790 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
24791 can be referenced from any @file{Makefile.am}.  Even without Automake,
24792 arranging for @code{LIBOBJDIR} to be set correctly enables
24793 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
24794 The @code{LIBOBJDIR} feature is experimental.
24797 @node AC_ACT_IFELSE vs AC_TRY_ACT
24798 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
24799 @c the anchor keeps the old node name, to try to avoid breaking links
24800 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
24802 @acindex{@var{ACT}_IFELSE}
24803 @acindex{TRY_@var{ACT}}
24804 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
24805 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
24806 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
24807 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
24808 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
24809 @code{AC_TRY_RUN}.  The motivations where:
24810 @itemize @minus
24811 @item
24812 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
24813 quoting their arguments;
24815 @item
24816 the combinatoric explosion is solved by decomposing on the one hand the
24817 generation of sources, and on the other hand executing the program;
24819 @item
24820 this scheme helps supporting more languages than plain C and C++.
24821 @end itemize
24823 In addition to the change of syntax, the philosophy has changed too:
24824 while emphasis was put on speed at the expense of accuracy, today's
24825 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
24826 expense of speed.
24829 As a perfect example of what is @emph{not} to be done, here is how to
24830 find out whether a header file contains a particular declaration, such
24831 as a typedef, a structure, a structure member, or a function.  Use
24832 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
24833 header file; on some systems the symbol might be defined in another
24834 header file that the file you are checking includes.
24836 As a (bad) example, here is how you should not check for C preprocessor
24837 symbols, either defined by header files or predefined by the C
24838 preprocessor: using @code{AC_EGREP_CPP}:
24840 @example
24841 @group
24842 AC_EGREP_CPP(yes,
24843 [#ifdef _AIX
24844   yes
24845 #endif
24846 ], is_aix=yes, is_aix=no)
24847 @end group
24848 @end example
24850 The above example, properly written would (i) use
24851 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
24853 @example
24854 @group
24855 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
24856 [[#ifndef _AIX
24857  error: This isn't AIX!
24858 #endif
24859 ]])],
24860                    [is_aix=yes],
24861                    [is_aix=no])
24862 @end group
24863 @end example
24866 @c ============================= Generating Test Suites with Autotest
24868 @node Using Autotest
24869 @chapter Generating Test Suites with Autotest
24871 @cindex Autotest
24873 @display
24874 @strong{N.B.: This section describes a feature which is still
24875 stabilizing.  Although we believe that Autotest is useful as-is, this
24876 documentation describes an interface which might change in the future:
24877 do not depend upon Autotest without subscribing to the Autoconf mailing
24878 lists.}
24879 @end display
24881 It is paradoxical that portable projects depend on nonportable tools
24882 to run their test suite.  Autoconf by itself is the paragon of this
24883 problem: although it aims at perfectly portability, up to 2.13 its
24884 test suite was using DejaGNU, a rich and complex testing
24885 framework, but which is far from being standard on Posix systems.
24886 Worse yet, it was likely to be missing on the most fragile platforms,
24887 the very platforms that are most likely to torture Autoconf and
24888 exhibit deficiencies.
24890 To circumvent this problem, many package maintainers have developed their
24891 own testing framework, based on simple shell scripts whose sole outputs
24892 are exit status values describing whether the test succeeded.  Most of
24893 these tests share common patterns, and this can result in lots of
24894 duplicated code and tedious maintenance.
24896 Following exactly the same reasoning that yielded to the inception of
24897 Autoconf, Autotest provides a test suite generation framework, based on
24898 M4 macros building a portable shell script.  The suite itself is
24899 equipped with automatic logging and tracing facilities which greatly
24900 diminish the interaction with bug reporters, and simple timing reports.
24902 Autoconf itself has been using Autotest for years, and we do attest that
24903 it has considerably improved the strength of the test suite and the
24904 quality of bug reports.  Other projects are known to use some generation
24905 of Autotest, such as Bison, GNU Wdiff, GNU Tar, each of
24906 them with different needs, and this usage has validated Autotest as a general
24907 testing framework.
24909 Nonetheless, compared to DejaGNU, Autotest is inadequate for
24910 interactive tool testing, which is probably its main limitation.
24912 @menu
24913 * Using an Autotest Test Suite::  Autotest and the user
24914 * Writing Testsuites::          Autotest macros
24915 * testsuite Invocation::        Running @command{testsuite} scripts
24916 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
24917 @end menu
24919 @node Using an Autotest Test Suite
24920 @section Using an Autotest Test Suite
24922 @menu
24923 * testsuite Scripts::           The concepts of Autotest
24924 * Autotest Logs::               Their contents
24925 @end menu
24927 @node testsuite Scripts
24928 @subsection @command{testsuite} Scripts
24930 @cindex @command{testsuite}
24932 Generating testing or validation suites using Autotest is rather easy.
24933 The whole validation suite is held in a file to be processed through
24934 @command{autom4te}, itself using GNU M4 under the hood, to
24935 produce a stand-alone Bourne shell script which then gets distributed.
24936 Neither @command{autom4te} nor GNU M4 are needed at
24937 the installer's end.
24939 @cindex test group
24940 Each test of the validation suite should be part of some test group.  A
24941 @dfn{test group} is a sequence of interwoven tests that ought to be
24942 executed together, usually because one test in the group creates data
24943 files that a later test in the same group needs to read.  Complex test
24944 groups make later debugging more tedious.  It is much better to
24945 keep only a few tests per test group.  Ideally there is only one test
24946 per test group.
24948 For all but the simplest packages, some file such as @file{testsuite.at}
24949 does not fully hold all test sources, as these are often easier to
24950 maintain in separate files.  Each of these separate files holds a single
24951 test group, or a sequence of test groups all addressing some common
24952 functionality in the package.  In such cases, @file{testsuite.at}
24953 merely initializes the validation suite, and sometimes does elementary
24954 health checking, before listing include statements for all other test
24955 files.  The special file @file{package.m4}, containing the
24956 identification of the package, is automatically included if found.
24958 A convenient alternative consists in moving all the global issues
24959 (local Autotest macros, elementary health checking, and @code{AT_INIT}
24960 invocation) into the file @code{local.at}, and making
24961 @file{testsuite.at} be a simple list of @code{m4_include}s of sub test
24962 suites.  In such case, generating the whole test suite or pieces of it
24963 is only a matter of choosing the @command{autom4te} command line
24964 arguments.
24966 The validation scripts that Autotest produces are by convention called
24967 @command{testsuite}.  When run, @command{testsuite} executes each test
24968 group in turn, producing only one summary line per test to say if that
24969 particular test succeeded or failed.  At end of all tests, summarizing
24970 counters get printed.  One debugging directory is left for each test
24971 group which failed, if any: such directories are named
24972 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
24973 the test group, and they include:
24975 @itemize @bullet
24976 @item a debugging script named @file{run} which reruns the test in
24977 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
24978 of debugging scripts has the purpose of easing the chase for bugs.
24980 @item all the files created with @code{AT_DATA}
24982 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
24984 @item a log of the run, named @file{testsuite.log}
24985 @end itemize
24987 In the ideal situation, none of the tests fail, and consequently no
24988 debugging directory is left behind for validation.
24990 It often happens in practice that individual tests in the validation
24991 suite need to get information coming out of the configuration process.
24992 Some of this information, common for all validation suites, is provided
24993 through the file @file{atconfig}, automatically created by
24994 @code{AC_CONFIG_TESTDIR}.  For configuration information which your
24995 testing environment specifically needs, you might prepare an optional
24996 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
24997 The configuration process produces @file{atconfig} and @file{atlocal}
24998 out of these two input files, and these two produced files are
24999 automatically read by the @file{testsuite} script.
25001 Here is a diagram showing the relationship between files.
25003 @noindent
25004 Files used in preparing a software package for distribution:
25006 @example
25007                 [package.m4] -->.
25008                                  \
25009 subfile-1.at ->.  [local.at] ---->+
25010     ...         \                  \
25011 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
25012     ...         /
25013 subfile-n.at ->'
25014 @end example
25016 @noindent
25017 Files used in configuring a software package:
25019 @example
25020                                      .--> atconfig
25021                                     /
25022 [atlocal.in] -->  config.status* --<
25023                                     \
25024                                      `--> [atlocal]
25025 @end example
25027 @noindent
25028 Files created during test suite execution:
25030 @example
25031 atconfig -->.                    .--> testsuite.log
25032              \                  /
25033               >-- testsuite* --<
25034              /                  \
25035 [atlocal] ->'                    `--> [testsuite.dir]
25036 @end example
25039 @node Autotest Logs
25040 @subsection Autotest Logs
25042 When run, the test suite creates a log file named after itself, e.g., a
25043 test suite named @command{testsuite} creates @file{testsuite.log}.  It
25044 contains a lot of information, usually more than maintainers actually
25045 need, but therefore most of the time it contains all that is needed:
25047 @table @asis
25048 @item command line arguments
25049 A bad but unfortunately widespread habit consists of
25050 setting environment variables before the command, such as in
25051 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
25052 know this change, hence (i) it cannot report it to you, and (ii)
25053 it cannot preserve the value of @code{CC} for subsequent runs.
25054 Autoconf faced exactly the same problem, and solved it by asking
25055 users to pass the variable definitions as command line arguments.
25056 Autotest requires this rule, too, but has no means to enforce it; the log
25057 then contains a trace of the variables that were changed by the user.
25059 @item @file{ChangeLog} excerpts
25060 The topmost lines of all the @file{ChangeLog} files found in the source
25061 hierarchy.  This is especially useful when bugs are reported against
25062 development versions of the package, since the version string does not
25063 provide sufficient information to know the exact state of the sources
25064 the user compiled.  Of course, this relies on the use of a
25065 @file{ChangeLog}.
25067 @item build machine
25068 Running a test suite in a cross-compile environment is not an easy task,
25069 since it would mean having the test suite run on a machine @var{build},
25070 while running programs on a machine @var{host}.  It is much simpler to
25071 run both the test suite and the programs on @var{host}, but then, from
25072 the point of view of the test suite, there remains a single environment,
25073 @var{host} = @var{build}.  The log contains relevant information on the
25074 state of the @var{build} machine, including some important environment
25075 variables.
25076 @c FIXME: How about having an M4sh macro to say `hey, log the value
25077 @c of `@dots{}'?  This would help both Autoconf and Autotest.
25079 @item tested programs
25080 The absolute file name and answers to @option{--version} of the tested
25081 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
25083 @item configuration log
25084 The contents of @file{config.log}, as created by @command{configure},
25085 are appended.  It contains the configuration flags and a detailed report
25086 on the configuration itself.
25087 @end table
25090 @node Writing Testsuites
25091 @section Writing @file{testsuite.at}
25093 The @file{testsuite.at} is a Bourne shell script making use of special
25094 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
25095 its beginning followed by one call to @code{m4_include} per source file
25096 for tests.  Each such included file, or the remainder of
25097 @file{testsuite.at} if include files are not used, contain a sequence of
25098 test groups.  Each test group begins with a call to @code{AT_SETUP},
25099 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
25100 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
25101 groups can be categorized by a call to @code{AT_BANNER}.
25103 All of the public Autotest macros have all-uppercase names in the
25104 namespace @samp{^AT_} to prevent them from accidentally conflicting with
25105 other text; Autoconf also reserves the namespace @samp{^_AT_} for
25106 internal macros.  All shell variables used in the testsuite for internal
25107 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
25108 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
25109 makes use of the file system namespace @samp{^at-}.
25111 Since Autoconf is built on top of M4sugar (@pxref{Programming in
25112 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
25113 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
25114 @emph{should not use} the namespace of a package that does not own the
25115 macro or shell code you are writing.
25117 @defmac AT_INIT (@ovar{name})
25118 @atindex{INIT}
25119 @c FIXME: Not clear, plus duplication of the information.
25120 Initialize Autotest.  Giving a @var{name} to the test suite is
25121 encouraged if your package includes several test suites.  Before this
25122 macro is called, @code{AT_PACKAGE_STRING} and
25123 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
25124 information about the testsuite to the user.  Typically, these macros
25125 are provided by a file @file{package.m4} built by @command{make}
25126 (@pxref{Making testsuite Scripts}), in order to inherit the package
25127 name, version, and bug reporting address from @file{configure.ac}.
25128 @end defmac
25130 @defmac AT_COPYRIGHT (@var{copyright-notice})
25131 @atindex{COPYRIGHT}
25132 @cindex Copyright Notice
25133 State that, in addition to the Free Software Foundation's copyright on
25134 the Autotest macros, parts of your test suite are covered by
25135 @var{copyright-notice}.
25137 The @var{copyright-notice} shows up in both the head of
25138 @command{testsuite} and in @samp{testsuite --version}.
25139 @end defmac
25141 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
25142   @ovar{action-if-given}, @ovar{action-if-not-given})
25143 @atindex{ARG_OPTION}
25144 @vrindex at_arg_@var{option}
25145 Accept options from the space-separated list @var{options}, a list that
25146 has leading dashes removed from the options.  Long options will be
25147 prefixed with @samp{--}, single-character options with @samp{-}.  The
25148 first word in this list is the primary @var{option}, any others are
25149 assumed to be short-hand aliases.  The variable associated with it
25150 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
25151 with underscores.
25153 If the user passes @option{--@var{option}} to the @command{testsuite},
25154 the variable will be set to @samp{:}.  If the user does not pass the
25155 option, or passes @option{--no-@var{option}}, then the variable will be
25156 set to @samp{false}.
25158 @vrindex at_optarg
25159 @vrindex at_optarg_@var{option}
25160 @var{action-if-given} is run each time the option is encountered; here,
25161 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
25162 appropriate.  @code{at_optarg} is actually just a copy of
25163 @code{at_arg_@var{option}}.
25165 @var{action-if-not-given} will be run once after option parsing is
25166 complete and if no option from @var{options} was used.
25168 @var{help-text} is added to the end of the list of options shown in
25169 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25171 It is recommended that you use a package-specific prefix to @var{options}
25172 names in order to avoid clashes with future Autotest built-in options.
25173 @end defmac
25175 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
25176   @ovar{action-if-given}, @ovar{action-if-not-given})
25177 @atindex{ARG_OPTION_ARG}
25178 @vrindex at_arg_@var{option}
25179 Accept options with arguments from the space-separated list
25180 @var{options}, a list that has leading dashes removed from the options.
25181 Long options will be prefixed with @samp{--}, single-character options
25182 with @samp{-}.  The first word in this list is the primary @var{option},
25183 any others are assumed to be short-hand aliases.  The variable associated
25184 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
25185 replaced with underscores.
25187 If the user passes @option{--@var{option}=@var{arg}} or
25188 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
25189 variable will be set to @samp{@var{arg}}.
25191 @vrindex at_optarg
25192 @var{action-if-given} is run each time the option is encountered; here,
25193 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
25194 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
25196 @var{action-if-not-given} will be run once after option parsing is
25197 complete and if no option from @var{options} was used.
25199 @var{help-text} is added to the end of the list of options shown in
25200 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25202 It is recommended that you use a package-specific prefix to @var{options}
25203 names in order to avoid clashes with future Autotest built-in options.
25204 @end defmac
25206 @defmac AT_COLOR_TESTS
25207 @atindex{COLOR_TESTS}
25208 Enable colored test results by default when the output is connected to
25209 a terminal.
25210 @end defmac
25212 @defmac AT_TESTED (@var{executables})
25213 @atindex{TESTED}
25214 Log the file name and answer to @option{--version} of each program in
25215 space-separated list @var{executables}.  Several invocations register
25216 new executables, in other words, don't fear registering one program
25217 several times.
25219 Autotest test suites rely on @env{PATH} to find the tested program.
25220 This avoids the need to generate absolute names of the various tools, and
25221 makes it possible to test installed programs.  Therefore, knowing which
25222 programs are being exercised is crucial to understanding problems in
25223 the test suite itself, or its occasional misuses.  It is a good idea to
25224 also subscribe foreign programs you depend upon, to avoid incompatible
25225 diagnostics.
25227 @var{executables} is implicitly wrapped in shell double quotes, but it
25228 will still use shell variable expansion (@samp{$}), command substitution
25229 (@samp{`}), and backslash escaping (@samp{\}).  In particular, the
25230 @env{EXEEXT} variable is available if it is passed to the testsuite
25231 via @file{atlocal} or @file{atconfig}.
25232 @end defmac
25234 @sp 1
25236 @defmac AT_BANNER (@var{test-category-name})
25237 @atindex{BANNER}
25238 This macro identifies the start of a category of related test groups.
25239 When the resulting @file{testsuite} is invoked with more than one test
25240 group to run, its output will include a banner containing
25241 @var{test-category-name} prior to any tests run from that category.  The
25242 banner should be no more than about 40 or 50 characters.  A blank banner
25243 indicates uncategorized tests; an empty line will be inserted after
25244 tests from an earlier category, effectively ending that category.
25245 @end defmac
25247 @defmac AT_SETUP (@var{test-group-name})
25248 @atindex{SETUP}
25249 This macro starts a group of related tests, all to be executed in the
25250 same subshell.  It accepts a single argument, which holds a few words
25251 (no more than about 30 or 40 characters) quickly describing the purpose
25252 of the test group being started.  @var{test-group-name} must not expand
25253 to unbalanced quotes, although quadrigraphs can be used.
25254 @end defmac
25256 @defmac AT_KEYWORDS (@var{keywords})
25257 @atindex{KEYWORDS}
25258 Associate the space-separated list of @var{keywords} to the enclosing
25259 test group.  This makes it possible to run ``slices'' of the test suite.
25260 For instance, if some of your test groups exercise some @samp{foo}
25261 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
25262 @samp{./testsuite -k foo} to run exclusively these test groups.  The
25263 @var{test-group-name} of the test group is automatically recorded to
25264 @code{AT_KEYWORDS}.
25266 Several invocations within a test group accumulate new keywords.  In
25267 other words, don't fear registering the same keyword several times in a
25268 test group.
25269 @end defmac
25271 @defmac AT_CAPTURE_FILE (@var{file})
25272 @atindex{CAPTURE_FILE}
25273 If the current test group fails, log the contents of @var{file}.
25274 Several identical calls within one test group have no additional effect.
25275 @end defmac
25277 @defmac AT_FAIL_IF (@var{shell-condition})
25278 @atindex{FAIL_IF}
25279 Make the test group fail and skip the rest of its execution, if
25280 @var{shell-condition} is true.  @var{shell-condition} is a shell expression
25281 such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
25282 will be executed and may still cause the test group to be skipped.
25283 You can instantiate this macro many times from within the same test group.
25285 You should use this macro only for very simple failure conditions.  If the
25286 @var{shell-condition} could emit any kind of output you should instead
25287 use @command{AT_CHECK} like
25288 @example
25289 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
25290 @end example
25291 @noindent
25292 so that such output is properly recorded in the @file{testsuite.log}
25293 file.
25294 @end defmac
25296 @defmac AT_SKIP_IF (@var{shell-condition})
25297 @atindex{SKIP_IF}
25298 Determine whether the test should be skipped because it requires
25299 features that are unsupported on the machine under test.
25300 @var{shell-condition} is a shell expression such as a @code{test}
25301 command.  Tests before @command{AT_SKIP_IF} will be executed
25302 and may still cause the test group to fail.  You can instantiate this
25303 macro many times from within the same test group.
25305 You should use this macro only for very simple skip conditions.  If the
25306 @var{shell-condition} could emit any kind of output you should instead
25307 use @command{AT_CHECK} like
25308 @example
25309 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
25310 @end example
25311 @noindent
25312 so that such output is properly recorded in the @file{testsuite.log}
25313 file.
25314 @end defmac
25316 @defmac AT_XFAIL_IF (@var{shell-condition})
25317 @atindex{XFAIL_IF}
25318 Determine whether the test is expected to fail because it is a known
25319 bug (for unsupported features, you should skip the test).
25320 @var{shell-condition} is a shell expression such as a @code{test}
25321 command; you can instantiate this macro many times from within the
25322 same test group, and one of the conditions is enough to turn
25323 the test into an expected failure.
25324 @end defmac
25326 @defmac AT_CLEANUP
25327 @atindex{CLEANUP}
25328 End the current test group.
25329 @end defmac
25331 @sp 1
25333 @defmac AT_DATA (@var{file}, @var{contents})
25334 @defmacx AT_DATA_UNQUOTED (@var{file}, @var{contents})
25335 @atindex{DATA}
25336 Initialize an input data @var{file} with given @var{contents}.  Of
25337 course, the @var{contents} have to be properly quoted between square
25338 brackets to protect against included commas or spurious M4
25339 expansion.  @var{contents} must be empty or end with a newline.
25340 @var{file} must
25341 be a single shell word that expands into a single file name.
25343 The difference between @code{AT_DATA} and @code{AT_DATA_UNQUOTED} is
25344 that only the latter performs shell variable expansion (@samp{$}),
25345 command substitution (@samp{`}), and backslash escaping (@samp{\})
25346 on @var{contents}.
25347 @end defmac
25349 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25350   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25351 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25352   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25353 @atindex{CHECK}
25354 @atindex{CHECK_UNQUOTED}
25355 @vrindex at_status
25356 Execute a test by performing given shell @var{commands} in a subshell.
25357 @var{commands} is output as-is, so shell expansions are honored.  These
25358 commands should normally exit with @var{status}, while producing expected
25359 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
25360 unexpected status 77, then the rest of the test group is skipped.  If
25361 @var{commands} exit with unexpected status 99, then the test group is
25362 immediately failed.  Otherwise, if this test fails, run shell commands
25363 @var{run-if-fail} or, if this test passes, run shell commands
25364 @var{run-if-pass}, both inside the current shell execution environment.
25365 At the beginning of @var{run-if-fail} and @var{run-if-pass}, the status of
25366 @var{commands} is available in the @code{at_status} shell variable.
25368 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25370 If @var{status} is the literal @samp{ignore}, then the corresponding
25371 exit status is not checked, except for the special cases of 77 (skip)
25372 and 99 (hard failure).  The existence of hard failures allows one to
25373 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
25374 feature has not yet been implemented, but to still distinguish between
25375 gracefully handling the missing feature and dumping core.  A hard
25376 failure also inhibits post-test actions in @var{run-if-fail}.
25378 If the value of the @var{stdout} or @var{stderr} parameter is one of the
25379 literals in the following table, then the test treats the output
25380 according to the rules of that literal.  Otherwise, the value of the
25381 parameter is treated as text that must exactly match the output given by
25382 @var{commands} on standard output and standard error (including an empty
25383 parameter for no output); any differences are captured in the testsuite
25384 log and the test is failed (unless an unexpected exit status of 77
25385 skipped the test instead).  The difference between @code{AT_CHECK} and
25386 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
25387 expansion (@samp{$}), command substitution (@samp{`}), and backslash
25388 escaping (@samp{\}) on comparison text given in the @var{stdout} and
25389 @var{stderr} arguments; if the text includes a trailing newline, this
25390 would be the same as if it were specified via an unquoted
25391 here-document.  (However, there is no difference in the interpretation
25392 of @var{commands}).
25394 @table @samp
25395 @item ignore
25396 The content of the output is ignored, but still captured in the test
25397 group log (if the testsuite is run with option @option{-v}, the test
25398 group log is displayed as the test is run; if the test group later
25399 fails, the test group log is also copied into the overall testsuite
25400 log).  This action is valid for both @var{stdout} and @var{stderr}.
25402 @item ignore-nolog
25403 The content of the output is ignored, and nothing is captured in the log
25404 files.  If @var{commands} are likely to produce binary output (including
25405 long lines) or large amounts of output, then logging the output can make
25406 it harder to locate details related to subsequent tests within the
25407 group, and could potentially corrupt terminal display of a user running
25408 @command{testsuite -v}.
25410 @item stdout
25411 For the @var{stdout} parameter, capture the content of standard output
25412 to both the file @file{stdout} and the test group log.  Subsequent
25413 commands in the test group can then post-process the file.  This action
25414 is often used when it is desired to use @command{grep} to look for a
25415 substring in the output, or when the output must be post-processed to
25416 normalize error messages into a common form.
25418 @item stderr
25419 Like @samp{stdout}, except that it only works for the @var{stderr}
25420 parameter, and the standard error capture file will be named
25421 @file{stderr}.
25423 @item stdout-nolog
25424 @itemx stderr-nolog
25425 Like @samp{stdout} or @samp{stderr}, except that the captured output is
25426 not duplicated into the test group log.  This action is particularly
25427 useful for an intermediate check that produces large amounts of data,
25428 which will be followed by another check that filters down to the
25429 relevant data, as it makes it easier to locate details in the log.
25431 @item expout
25432 For the @var{stdout} parameter, compare standard output contents with
25433 the previously created file @file{expout}, and list any differences in
25434 the testsuite log.
25436 @item experr
25437 Like @samp{expout}, except that it only works for the @var{stderr}
25438 parameter, and the standard error contents are compared with
25439 @file{experr}.
25440 @end table
25441 @end defmac
25443 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
25444   @ovar{run-if-fail}, @ovar{run-if-pass})
25445 @atindex{CHECK_EUNIT}
25446 Initialize and execute an Erlang module named @var{module} that performs
25447 tests following the @var{test-spec} EUnit test specification.
25448 @var{test-spec} must be a valid EUnit test specification, as defined in
25449 the @uref{http://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
25450 Reference Manual}.  @var{erlflags} are optional command-line options
25451 passed to the Erlang interpreter to execute the test Erlang module.
25452 Typically, @var{erlflags} defines at least the paths to directories
25453 containing the compiled Erlang modules under test, as @samp{-pa path1
25454 path2 ...}.
25456 For example, the unit tests associated with Erlang module @samp{testme},
25457 which compiled code is in subdirectory @file{src}, can be performed
25458 with:
25460 @example
25461 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
25462                [-pa "$@{abs_top_builddir@}/src"])
25463 @end example
25465 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25467 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
25468 must be defined as the path of the Erlang interpreter, the path of the
25469 Erlang compiler, and the command-line flags to pass to the compiler,
25470 respectively.  Those variables should be configured in
25471 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
25472 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
25473 variables are automatically defined in the testsuite.  If @code{ERL} or
25474 @code{ERLC} is not defined, the test group is skipped.
25476 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
25477 be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
25478 an invalid EUnit test specification, the test group fails.  Otherwise,
25479 if the EUnit test passes, shell commands @var{run-if-pass} are executed
25480 or, if the EUnit test fails, shell commands @var{run-if-fail} are
25481 executed and the test group fails.
25483 Only the generated test Erlang module is automatically compiled and
25484 executed.  If @var{test-spec} involves testing other Erlang modules,
25485 e.g. module @samp{testme} in the example above, those modules must be
25486 already compiled.
25488 If the testsuite is run in verbose mode, with option @option{--verbose},
25489 EUnit is also run in verbose mode to output more details about
25490 individual unit tests.
25491 @end defmac
25494 @node testsuite Invocation
25495 @section Running @command{testsuite} Scripts
25496 @cindex @command{testsuite}
25498 Autotest test suites support the following options:
25500 @table @option
25501 @item --help
25502 @itemx -h
25503 Display the list of options and exit successfully.
25505 @item --version
25506 @itemx -V
25507 Display the version of the test suite and exit successfully.
25509 @item --directory=@var{dir}
25510 @itemx -C @var{dir}
25511 Change the current directory to @var{dir} before creating any files.
25512 Useful for running the testsuite in a subdirectory from a top-level
25513 Makefile.
25515 @item --jobs@r{[}=@var{n}@r{]}
25516 @itemx -j@ovar{n}
25517 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
25518 run all given tests in parallel.  Note that there should be no space
25519 before the argument to @option{-j}, as @option{-j @var{number}} denotes
25520 the separate arguments @option{-j} and @option{@var{number}}, see below.
25522 In parallel mode, the standard input device of the testsuite script is
25523 not available to commands inside a test group.  Furthermore, banner
25524 lines are not printed, and the summary line for each test group is
25525 output after the test group completes.  Summary lines may appear
25526 unordered.  If verbose and trace output are enabled (see below), they
25527 may appear intermixed from concurrently running tests.
25529 Parallel mode requires the @command{mkfifo} command to work, and will be
25530 silently disabled otherwise.
25532 @item --clean
25533 @itemx -c
25534 Remove all the files the test suite might have created and exit.  Meant
25535 for @code{clean} Make targets.
25537 @item --list
25538 @itemx -l
25539 List all the tests (or only the selection), including their possible
25540 keywords.
25541 @end table
25543 @sp 1
25545 By default all tests are performed (or described with @option{--list})
25546 silently in the default environment, but the environment, set of tests,
25547 and verbosity level can be tuned:
25549 @table @samp
25550 @item @var{variable}=@var{value}
25551 Set the environment @var{variable} to @var{value}.  Use this rather
25552 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
25553 different environment.
25555 @cindex @code{AUTOTEST_PATH}
25556 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
25557 to @env{PATH}.  Relative directory names (not starting with
25558 @samp{/}) are considered to be relative to the top level of the
25559 package being built.  All directories are made absolute, first
25560 starting from the top level @emph{build} tree, then from the
25561 @emph{source} tree.  For instance @samp{./testsuite
25562 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
25563 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
25564 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
25565 @env{PATH}.
25567 @item @var{number}
25568 @itemx @var{number}-@var{number}
25569 @itemx @var{number}-
25570 @itemx -@var{number}
25571 Add the corresponding test groups, with obvious semantics, to the
25572 selection.
25574 @item --keywords=@var{keywords}
25575 @itemx -k @var{keywords}
25576 Add to the selection the test groups with title or keywords (arguments
25577 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
25578 of the comma separated list @var{keywords}, case-insensitively.  Use
25579 @samp{!} immediately before the keyword to invert the selection for this
25580 keyword.  By default, the keywords match whole words; enclose them in
25581 @samp{.*} to also match parts of words.
25583 For example, running
25585 @example
25586 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
25587 @end example
25589 @noindent
25590 selects all tests tagged @samp{autoupdate} @emph{and} with tags
25591 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
25592 etc.), while
25594 @example
25595 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
25596 @end example
25598 @noindent
25599 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
25600 containing @samp{FUNC}.
25602 @item --errexit
25603 @itemx -e
25604 If any test fails, immediately abort testing.  This implies
25605 @option{--debug}: post test group clean up, and top-level logging
25606 are inhibited.  This option is meant for the full test
25607 suite, it is not really useful for generated debugging scripts.
25608 If the testsuite is run in parallel mode using @option{--jobs},
25609 then concurrently running tests will finish before exiting.
25611 @item --verbose
25612 @itemx -v
25613 Force more verbosity in the detailed output of what is being done.  This
25614 is the default for debugging scripts.
25616 @item --color
25617 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
25618 Enable colored test results.  Without an argument, or with @samp{always},
25619 test results will be colored.  With @samp{never}, color mode is turned
25620 off.  Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
25621 the testsuite author, or the argument @samp{auto} is given, then test
25622 results are colored if standard output is connected to a terminal.
25624 @item --debug
25625 @itemx -d
25626 Do not remove the files after a test group was performed---but they are
25627 still removed @emph{before}, therefore using this option is sane when
25628 running several test groups.  Create debugging scripts.  Do not
25629 overwrite the top-level
25630 log (in order to preserve a supposedly existing full log file).  This is
25631 the default for debugging scripts, but it can also be useful to debug
25632 the testsuite itself.
25634 @item --recheck
25635 Add to the selection all test groups that failed or passed unexpectedly
25636 during the last non-debugging test run.
25638 @item --trace
25639 @itemx -x
25640 Trigger shell tracing of the test groups.
25641 @end table
25643 Besides these options accepted by every Autotest testsuite, the
25644 testsuite author might have added package-specific options
25645 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
25646 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
25647 the package documentation for details.
25650 @node Making testsuite Scripts
25651 @section Making @command{testsuite} Scripts
25653 For putting Autotest into movement, you need some configuration and
25654 makefile machinery.  We recommend, at least if your package uses deep or
25655 shallow hierarchies, that you use @file{tests/} as the name of the
25656 directory holding all your tests and their makefile.  Here is a
25657 check list of things to do, followed by an example, taking into
25658 consideration whether you are also using Automake.
25660 @itemize @minus
25662 @item
25663 @cindex @file{package.m4}
25664 @atindex{PACKAGE_STRING}
25665 @atindex{PACKAGE_BUGREPORT}
25666 @atindex{PACKAGE_NAME}
25667 @atindex{PACKAGE_TARNAME}
25668 @atindex{PACKAGE_VERSION}
25669 @atindex{PACKAGE_URL}
25670 Make sure to create the file @file{package.m4}, which defines the
25671 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
25672 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
25673 address to which bug reports should be sent.  For sake of completeness,
25674 we suggest that you also define @code{AT_PACKAGE_NAME},
25675 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
25676 @code{AT_PACKAGE_URL}.
25677 @xref{Initializing configure}, for a description of these variables.
25678 Be sure to distribute @file{package.m4} and to put it into the source
25679 hierarchy: the test suite ought to be shipped!  See below for an example.
25681 @item
25682 Invoke @code{AC_CONFIG_TESTDIR} in your @file{configure.ac}.
25684 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvarv{test-path, directory})
25685 @acindex{CONFIG_TESTDIR}
25686 An Autotest test suite is to be configured in @var{directory}.  This
25687 macro causes @file{@var{directory}/atconfig} to be created by
25688 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
25689 @var{test-path} (@pxref{testsuite Invocation}).
25690 @end defmac
25692 @item
25693 Still within @file{configure.ac}, as appropriate, ensure that some
25694 @code{AC_CONFIG_FILES} command includes substitution for
25695 @file{tests/atlocal}.
25697 @item
25698 Also within your @file{configure.ac}, arrange for the @code{AUTOM4TE}
25699 variable to be set.
25701 @item
25702 The appropriate @file{Makefile} should be modified so the validation in
25703 your package is triggered by @samp{make check}.
25704 @end itemize
25706 The following example demonstrates the above checklist, first by
25707 assuming that you are using Automake (see below for tweaks to make to
25708 get the same results without Automake).  Begin by adding the following
25709 lines to your @file{configure.ac}:
25711 @example
25712 # Initialize the test suite.
25713 AC_CONFIG_TESTDIR([tests])
25714 AC_CONFIG_FILES([tests/Makefile tests/atlocal])
25715 AM_MISSING_PROG([AUTOM4TE], [autom4te])
25716 @end example
25718 Next, add the following lines to your @file{tests/Makefile.am}, in order
25719 to link @samp{make check} with a validation suite.
25721 @example
25722 # The `:;' works around a Bash 3.2 bug when the output is not writable.
25723 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
25724         :;@{ \
25725           echo '# Signature of the current package.' && \
25726           echo 'm4_define([AT_PACKAGE_NAME],' && \
25727           echo '  [$(PACKAGE_NAME)])' && \
25728           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
25729           echo '  [$(PACKAGE_TARNAME)])' && \
25730           echo 'm4_define([AT_PACKAGE_VERSION],' && \
25731           echo '  [$(PACKAGE_VERSION)])' && \
25732           echo 'm4_define([AT_PACKAGE_STRING],' && \
25733           echo '  [$(PACKAGE_STRING)])' && \
25734           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
25735           echo '  [$(PACKAGE_BUGREPORT)])'; \
25736           echo 'm4_define([AT_PACKAGE_URL],' && \
25737           echo '  [$(PACKAGE_URL)])'; \
25738         @} >'$(srcdir)/package.m4'
25740 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
25741 TESTSUITE = $(srcdir)/testsuite
25743 check-local: atconfig atlocal $(TESTSUITE)
25744         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
25746 installcheck-local: atconfig atlocal $(TESTSUITE)
25747         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
25748           $(TESTSUITEFLAGS)
25750 clean-local:
25751         test ! -f '$(TESTSUITE)' || \
25752          $(SHELL) '$(TESTSUITE)' --clean
25754 AUTOTEST = $(AUTOM4TE) --language=autotest
25755 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
25756         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
25757         mv $@@.tmp $@@
25758 @end example
25760 Note that the built testsuite is distributed; this is necessary because
25761 users might not have Autoconf installed, and thus would not be able to
25762 rebuild it.  Likewise, the use of Automake's @code{AM_MISSING_PROG} will
25763 arrange for the definition of @code{$AUTOM4TE} within the Makefile to
25764 provide the user with
25765 a nicer error message if they modify a source file to the testsuite, and
25766 accidentally trigger the rebuild rules.
25768 You might want to list explicitly the dependencies, i.e., the list of
25769 the files @file{testsuite.at} includes.
25771 If you don't use Automake, you should make the following tweaks.  In
25772 your @file{configure.ac}, replace the @code{AM_MISSING_PROG} line above
25773 with @code{AC_PATH_PROG([AUTOM4TE], [autom4te], [false])}.  You are
25774 welcome to also try using the @command{missing} script from the Automake
25775 project instead of @command{false}, to try to get a nicer error message
25776 when the user modifies prerequisites but did not have Autoconf
25777 installed, but at that point you may be better off using Automake.
25778 Then, take the code suggested above for @file{tests/@/Makefile.am} and
25779 place it in your @file{tests/@/Makefile.in} instead.  Add code to your
25780 @file{tests/@/Makefile.in} to ensure that @code{$(EXTRA_DIST)} files are
25781 distributed, as well as adding the following additional lines to prepare
25782 the set of needed Makefile variables:
25784 @example
25785 subdir = tests
25786 PACKAGE_NAME = @@PACKAGE_NAME@@
25787 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
25788 PACKAGE_VERSION = @@PACKAGE_VERSION@@
25789 PACKAGE_STRING = @@PACKAGE_STRING@@
25790 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
25791 PACKAGE_URL = @@PACKAGE_URL@@
25792 AUTOM4TE = @@AUTOM4TE@@
25794 atconfig: $(top_builddir)/config.status
25795         cd $(top_builddir) && \
25796            $(SHELL) ./config.status $(subdir)/$@@
25798 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
25799         cd $(top_builddir) && \
25800            $(SHELL) ./config.status $(subdir)/$@@
25801 @end example
25803 Using the above example (with or without Automake), and assuming you
25804 were careful to not initialize @samp{TESTSUITEFLAGS} within your
25805 makefile, you can now fine-tune test suite execution at runtime by
25806 altering this variable, for example:
25808 @example
25809 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
25810 @end example
25814 @c =============================== Frequent Autoconf Questions, with answers
25816 @node FAQ
25817 @chapter Frequent Autoconf Questions, with answers
25819 Several questions about Autoconf come up occasionally.  Here some of them
25820 are addressed.
25822 @menu
25823 * Distributing::                Distributing @command{configure} scripts
25824 * Why GNU M4::                  Why not use the standard M4?
25825 * Bootstrapping::               Autoconf and GNU M4 require each other?
25826 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
25827 * Defining Directories::        Passing @code{datadir} to program
25828 * Autom4te Cache::              What is it?  Can I remove it?
25829 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
25830 * Expanded Before Required::    Expanded Before Required
25831 * Debugging::                   Debugging @command{configure} scripts
25832 @end menu
25834 @node Distributing
25835 @section Distributing @command{configure} Scripts
25836 @cindex License
25838 @display
25839 What are the restrictions on distributing @command{configure}
25840 scripts that Autoconf generates?  How does that affect my
25841 programs that use them?
25842 @end display
25844 There are no restrictions on how the configuration scripts that Autoconf
25845 produces may be distributed or used.  In Autoconf version 1, they were
25846 covered by the GNU General Public License.  We still encourage
25847 software authors to distribute their work under terms like those of the
25848 GPL, but doing so is not required to use Autoconf.
25850 Of the other files that might be used with @command{configure},
25851 @file{config.h.in} is under whatever copyright you use for your
25852 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
25853 exception to the GPL when they are used with an Autoconf-generated
25854 @command{configure} script, which permits you to distribute them under the
25855 same terms as the rest of your package.  @file{install-sh} is from the X
25856 Consortium and is not copyrighted.
25858 @node Why GNU M4
25859 @section Why Require GNU M4?
25861 @display
25862 Why does Autoconf require GNU M4?
25863 @end display
25865 Many M4 implementations have hard-coded limitations on the size and
25866 number of macros that Autoconf exceeds.  They also lack several
25867 builtin macros that it would be difficult to get along without in a
25868 sophisticated application like Autoconf, including:
25870 @example
25871 m4_builtin
25872 m4_indir
25873 m4_bpatsubst
25874 __file__
25875 __line__
25876 @end example
25878 Autoconf requires version 1.4.6 or later of GNU M4.
25880 Since only software maintainers need to use Autoconf, and since GNU
25881 M4 is simple to configure and install, it seems reasonable to require
25882 GNU M4 to be installed also.  Many maintainers of GNU and
25883 other free software already have most of the GNU utilities
25884 installed, since they prefer them.
25886 @node Bootstrapping
25887 @section How Can I Bootstrap?
25888 @cindex Bootstrap
25890 @display
25891 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
25892 @command{configure} script, how do I bootstrap?  It seems like a chicken
25893 and egg problem!
25894 @end display
25896 This is a misunderstanding.  Although GNU M4 does come with a
25897 @command{configure} script produced by Autoconf, Autoconf is not required
25898 in order to run the script and install GNU M4.  Autoconf is only
25899 required if you want to change the M4 @command{configure} script, which few
25900 people have to do (mainly its maintainer).
25902 @node Why Not Imake
25903 @section Why Not Imake?
25904 @cindex Imake
25906 @display
25907 Why not use Imake instead of @command{configure} scripts?
25908 @end display
25910 Several people have written addressing this question, so
25911 adaptations of their explanations are included here.
25913 The following answer is based on one written by Richard Pixley:
25915 @quotation
25916 Autoconf generated scripts frequently work on machines that it has
25917 never been set up to handle before.  That is, it does a good job of
25918 inferring a configuration for a new system.  Imake cannot do this.
25920 Imake uses a common database of host specific data.  For X11, this makes
25921 sense because the distribution is made as a collection of tools, by one
25922 central authority who has control over the database.
25924 GNU tools are not released this way.  Each GNU tool has a
25925 maintainer; these maintainers are scattered across the world.  Using a
25926 common database would be a maintenance nightmare.  Autoconf may appear
25927 to be this kind of database, but in fact it is not.  Instead of listing
25928 host dependencies, it lists program requirements.
25930 If you view the GNU suite as a collection of native tools, then the
25931 problems are similar.  But the GNU development tools can be
25932 configured as cross tools in almost any host+target permutation.  All of
25933 these configurations can be installed concurrently.  They can even be
25934 configured to share host independent files across hosts.  Imake doesn't
25935 address these issues.
25937 Imake templates are a form of standardization.  The GNU coding
25938 standards address the same issues without necessarily imposing the same
25939 restrictions.
25940 @end quotation
25943 Here is some further explanation, written by Per Bothner:
25945 @quotation
25946 One of the advantages of Imake is that it is easy to generate large
25947 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
25948 However, @code{cpp} is not programmable: it has limited conditional
25949 facilities, and no looping.  And @code{cpp} cannot inspect its
25950 environment.
25952 All of these problems are solved by using @code{sh} instead of
25953 @code{cpp}.  The shell is fully programmable, has macro substitution,
25954 can execute (or source) other shell scripts, and can inspect its
25955 environment.
25956 @end quotation
25959 Paul Eggert elaborates more:
25961 @quotation
25962 With Autoconf, installers need not assume that Imake itself is already
25963 installed and working well.  This may not seem like much of an advantage
25964 to people who are accustomed to Imake.  But on many hosts Imake is not
25965 installed or the default installation is not working well, and requiring
25966 Imake to install a package hinders the acceptance of that package on
25967 those hosts.  For example, the Imake template and configuration files
25968 might not be installed properly on a host, or the Imake build procedure
25969 might wrongly assume that all source files are in one big directory
25970 tree, or the Imake configuration might assume one compiler whereas the
25971 package or the installer needs to use another, or there might be a
25972 version mismatch between the Imake expected by the package and the Imake
25973 supported by the host.  These problems are much rarer with Autoconf,
25974 where each package comes with its own independent configuration
25975 processor.
25977 Also, Imake often suffers from unexpected interactions between
25978 @command{make} and the installer's C preprocessor.  The fundamental problem
25979 here is that the C preprocessor was designed to preprocess C programs,
25980 not makefiles.  This is much less of a problem with Autoconf,
25981 which uses the general-purpose preprocessor M4, and where the
25982 package's author (rather than the installer) does the preprocessing in a
25983 standard way.
25984 @end quotation
25987 Finally, Mark Eichin notes:
25989 @quotation
25990 Imake isn't all that extensible, either.  In order to add new features to
25991 Imake, you need to provide your own project template, and duplicate most
25992 of the features of the existing one.  This means that for a sophisticated
25993 project, using the vendor-provided Imake templates fails to provide any
25994 leverage---since they don't cover anything that your own project needs
25995 (unless it is an X11 program).
25997 On the other side, though:
25999 The one advantage that Imake has over @command{configure}:
26000 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
26001 than @file{Makefile.in} files.  There is a fix to this, however---at least
26002 for the Kerberos V5 tree, we've modified things to call in common
26003 @file{post.in} and @file{pre.in} makefile fragments for the
26004 entire tree.  This means that a lot of common things don't have to be
26005 duplicated, even though they normally are in @command{configure} setups.
26006 @end quotation
26009 @node Defining Directories
26010 @section How Do I @code{#define} Installation Directories?
26012 @display
26013 My program needs library files, installed in @code{datadir} and
26014 similar.  If I use
26016 @example
26017 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
26018   [Define to the read-only architecture-independent
26019    data directory.])
26020 @end example
26022 @noindent
26023 I get
26025 @example
26026 #define DATADIR "$@{prefix@}/share"
26027 @end example
26028 @end display
26030 As already explained, this behavior is on purpose, mandated by the
26031 GNU Coding Standards, see @ref{Installation Directory
26032 Variables}.  There are several means to achieve a similar goal:
26034 @itemize @minus
26035 @item
26036 Do not use @code{AC_DEFINE} but use your makefile to pass the
26037 actual value of @code{datadir} via compilation flags.
26038 @xref{Installation Directory Variables}, for the details.
26040 @item
26041 This solution can be simplified when compiling a program: you may either
26042 extend the @code{CPPFLAGS}:
26044 @example
26045 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
26046 @end example
26048 @noindent
26049 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
26051 @example
26052 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
26053 @end example
26055 @noindent
26056 Alternatively, create a dedicated header file:
26058 @example
26059 DISTCLEANFILES = myprog-paths.h
26060 myprog-paths.h: Makefile
26061         echo '#define DATADIR "$(datadir)"' >$@@
26062 @end example
26064 @noindent
26065 The gnulib module @samp{configmake} provides such a header with all the
26066 standard directory variables defined, @pxref{configmake,,, gnulib, GNU
26067 Gnulib}.
26069 @item
26070 Use @code{AC_DEFINE} but have @command{configure} compute the literal
26071 value of @code{datadir} and others.  Many people have wrapped macros to
26072 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
26073 the @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
26074 Archive}.
26076 This solution does not conform to the GNU Coding Standards.
26078 @item
26079 Note that all the previous solutions hard wire the absolute name of
26080 these directories in the executables, which is not a good property.  You
26081 may try to compute the names relative to @code{prefix}, and try to
26082 find @code{prefix} at runtime, this way your package is relocatable.
26083 @end itemize
26086 @node Autom4te Cache
26087 @section What is @file{autom4te.cache}?
26089 @display
26090 What is this directory @file{autom4te.cache}?  Can I safely remove it?
26091 @end display
26093 In the GNU Build System, @file{configure.ac} plays a central
26094 role and is read by many tools: @command{autoconf} to create
26095 @file{configure}, @command{autoheader} to create @file{config.h.in},
26096 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
26097 check the completeness of @file{configure.ac}, @command{autoreconf} to
26098 check the GNU Build System components that are used.  To
26099 ``read @file{configure.ac}'' actually means to compile it with M4,
26100 which can be a long process for complex @file{configure.ac}.
26102 This is why all these tools, instead of running directly M4, invoke
26103 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
26104 a specific demand, stores additional information in
26105 @file{autom4te.cache} for future runs.  For instance, if you run
26106 @command{autoconf}, behind the scenes, @command{autom4te} also
26107 stores information for the other tools, so that when you invoke
26108 @command{autoheader} or @command{automake} etc., reprocessing
26109 @file{configure.ac} is not needed.  The speed up is frequently 30%,
26110 and is increasing with the size of @file{configure.ac}.
26112 But it is and remains being simply a cache: you can safely remove it.
26114 @sp 1
26116 @display
26117 Can I permanently get rid of it?
26118 @end display
26120 The creation of this cache can be disabled from
26121 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
26122 details.  You should be aware that disabling the cache slows down the
26123 Autoconf test suite by 40%.  The more GNU Build System
26124 components are used, the more the cache is useful; for instance
26125 running @samp{autoreconf -f} on the Core Utilities is twice slower without
26126 the cache @emph{although @option{--force} implies that the cache is
26127 not fully exploited}, and eight times slower than without
26128 @option{--force}.
26131 @node Present But Cannot Be Compiled
26132 @section Header Present But Cannot Be Compiled
26134 The most important guideline to bear in mind when checking for
26135 features is to mimic as much as possible the intended use.
26136 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
26137 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
26138 the preprocessor, instead of the compiler, to check for headers.  As a
26139 result, incompatibilities between headers went unnoticed during
26140 configuration, and maintainers finally had to deal with this issue
26141 elsewhere.
26143 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
26144 checks are performed, and @command{configure} complains loudly if the
26145 compiler and the preprocessor do not agree.  However, only the compiler
26146 result is considered.  As of Autoconf 2.70, only the compiler check is
26147 performed.
26149 Consider the following example:
26151 @smallexample
26152 $ @kbd{cat number.h}
26153 typedef int number;
26154 $ @kbd{cat pi.h}
26155 const number pi = 3;
26156 $ @kbd{cat configure.ac}
26157 AC_INIT([Example], [1.0], [bug-example@@example.org])
26158 AC_CHECK_HEADERS([pi.h])
26159 $ @kbd{autoconf -Wall}
26160 $ @kbd{./configure CPPFLAGS='-I.'}
26161 checking for gcc... gcc
26162 checking whether the C compiler works... yes
26163 checking for C compiler default output file name... a.out
26164 checking for suffix of executables...
26165 checking whether we are cross compiling... no
26166 checking for suffix of object files... o
26167 checking whether the compiler supports GNU C... yes
26168 checking whether gcc accepts -g... yes
26169 checking for gcc option to enable C11 features... -std=gnu11
26170 checking for sys/types.h... yes
26171 checking for sys/stat.h... yes
26172 checking for strings.h... yes
26173 checking for inttypes.h... yes
26174 checking for stdint.h... yes
26175 checking for unistd.h... yes
26176 checking for pi.h... no
26177 @end smallexample
26179 @noindent
26180 The proper way to handle this case is using the fourth argument
26181 (@pxref{Generic Headers}):
26183 @example
26184 $ @kbd{cat configure.ac}
26185 AC_INIT([Example], [1.0], [bug-example@@example.org])
26186 AC_CHECK_HEADERS([number.h pi.h], [], [],
26187 [[#ifdef HAVE_NUMBER_H
26188 # include <number.h>
26189 #endif
26191 $ @kbd{autoconf -Wall}
26192 $ @kbd{./configure CPPFLAGS='-I.'}
26193 checking for gcc... gcc
26194 checking whether the C compiler works... yes
26195 checking for C compiler default output file name... a.out
26196 checking for suffix of executables...
26197 checking whether we are cross compiling... no
26198 checking for suffix of object files... o
26199 checking whether the compiler supports GNU C... yes
26200 checking whether gcc accepts -g... yes
26201 checking for gcc option to enable C11 features... -std=gnu11
26202 checking for number.h... yes
26203 checking for pi.h... yes
26204 @end example
26206 See @ref{Particular Headers}, for a list of headers with their
26207 prerequisites.
26209 @node Expanded Before Required
26210 @section Expanded Before Required
26212 @cindex expanded before required
26213 Older versions of Autoconf silently built files with incorrect ordering
26214 between dependent macros if an outer macro first expanded, then later
26215 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
26216 situation no longer generates out-of-order code, but results in
26217 duplicate output and a syntax warning:
26219 @example
26220 $ @kbd{cat configure.ac}
26221 @result{}AC_DEFUN([TESTA], [[echo in A
26222 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
26223 @result{}SEEN_A=:]])
26224 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
26225 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
26226 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
26227 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
26228 @result{}TESTA
26229 @result{}TESTC])
26230 @result{}AC_INIT
26231 @result{}OUTER
26232 @result{}AC_OUTPUT
26233 $ @kbd{autoconf}
26234 @result{}configure.ac:11: warning: AC_REQUIRE:
26235 @result{} `TESTA' was expanded before it was required
26236 @result{}configure.ac:4: TESTB is expanded from...
26237 @result{}configure.ac:6: TESTC is expanded from...
26238 @result{}configure.ac:7: OUTER is expanded from...
26239 @result{}configure.ac:11: the top level
26240 @end example
26242 @noindent
26243 To avoid this warning, decide what purpose the macro in question serves.
26244 If it only needs to be expanded once (for example, if it provides
26245 initialization text used by later macros), then the simplest fix is to
26246 change the macro to be declared with @code{AC_DEFUN_ONCE}
26247 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
26248 newer.  A more portable fix is to change all
26249 instances of direct calls to instead go through @code{AC_REQUIRE}
26250 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
26251 by arguments or by the current definition of other macros in the m4
26252 environment, then the macro should always be directly expanded instead
26253 of required.
26255 For another case study, consider this example trimmed down from an
26256 actual package.  Originally, the package contained shell code and
26257 multiple macro invocations at the top level of @file{configure.ac}:
26259 @example
26260 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26261 foobar=
26262 AC_PROG_CC
26264 @end example
26266 @noindent
26267 but that was getting complex, so the author wanted to offload some of
26268 the text into a new macro in another file included via
26269 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
26270 macro:
26272 @example
26273 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26274 AC_DEFUN([BAR], [
26275 foobar=
26276 AC_PROG_CC
26280 @end example
26282 @noindent
26283 With older versions of Autoconf, the setting of @samp{foobar=} occurs
26284 before the single compiler check, as the author intended.  But with
26285 Autoconf 2.64, this issues the ``expanded before it was required''
26286 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
26287 check, one before @samp{foobar=}, and one after.  To understand why this
26288 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
26289 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
26290 the documented semantics of @code{AC_REQUIRE}, this means that
26291 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
26292 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceding the
26293 use of @samp{foobar=}.  The older versions of Autoconf were broken with
26294 regards to the rules of @code{AC_REQUIRE}, which explains why the code
26295 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
26296 autoconf.  In other words, the author was unknowingly relying on a bug
26297 exploit to get the desired results, and that exploit broke once the bug
26298 was fixed.
26300 So, what recourse does the author have, to restore their intended
26301 semantics of setting @samp{foobar=} prior to a single compiler check,
26302 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
26303 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
26304 there is always the possibility of using the lower-level
26305 @code{m4_define}:
26307 @example
26308 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26309 m4_define([BAR], [
26310 foobar=
26311 AC_PROG_CC
26315 @end example
26317 @noindent
26318 This works great if everything is in the same file.  However, it does
26319 not help in the case where the author wants to have @command{aclocal}
26320 find the definition of @code{BAR} from its own file, since
26321 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
26322 better fix is to recognize that if @code{BAR} also uses
26323 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
26324 to a subsequent require.  Then, by creating yet another helper macro,
26325 the author can once again guarantee a single invocation of
26326 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
26327 author can also use @code{AC_BEFORE} to make sure no other macro
26328 appearing before @code{BAR} has triggered an unwanted expansion of
26329 @code{AC_PROG_CC}.
26331 @example
26332 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26333 AC_DEFUN([BEFORE_CC], [
26334 foobar=
26336 AC_DEFUN([BAR], [
26337 AC_BEFORE([$0], [AC_PROG_CC])dnl
26338 AC_REQUIRE([BEFORE_CC])dnl
26339 AC_REQUIRE([AC_PROG_CC])dnl
26343 @end example
26346 @node Debugging
26347 @section Debugging @command{configure} scripts
26349 While in general, @command{configure} scripts generated by Autoconf
26350 strive to be fairly portable to various systems, compilers, shells, and
26351 other tools, it may still be necessary to debug a failing test, broken
26352 script or makefile, or fix or override an incomplete, faulty, or erroneous
26353 test, especially during macro development.  Failures can occur at all levels,
26354 in M4 syntax or semantics, shell script issues, or due to bugs in the
26355 test or the tools invoked by @command{configure}.  Together with the
26356 rather arcane error message that @command{m4} and @command{make} may
26357 produce when their input contains syntax errors, this can make debugging
26358 rather painful.
26360 Nevertheless, here is a list of hints and strategies that may help:
26362 @itemize
26363 @item
26364 When @command{autoconf} fails, common causes for error include:
26366 @itemize
26367 @item
26368 mismatched or unbalanced parentheses or braces (@pxref{Balancing
26369 Parentheses}),
26371 @item under- or overquoted macro arguments (@pxref{Autoconf
26372 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
26373 Macros}),
26375 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
26376 Language}).
26377 @end itemize
26379 Typically, it helps to go back to the last working version of the input
26380 and compare the differences for each of these errors.  Another
26381 possibility is to sprinkle pairs of @code{m4_traceon} and
26382 @code{m4_traceoff} judiciously in the code, either without a parameter
26383 or listing some macro names and watch @command{m4} expand its input
26384 verbosely (@pxref{Debugging via autom4te}).
26386 @item
26387 Sometimes @command{autoconf} succeeds but the generated
26388 @command{configure} script has invalid shell syntax.  You can detect this
26389 case by running @samp{bash -n configure} or @samp{sh -n configure}.
26390 If this command fails, the same tips apply, as if @command{autoconf} had
26391 failed.
26393 @item
26394 Debugging @command{configure} script execution may be done by sprinkling
26395 pairs of @code{set -x} and @code{set +x} into the shell script before
26396 and after the region that contains a bug.  Running the whole script with
26397 @samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
26398 @var{shell} may work, but produces lots of output.  Here, it can help to
26399 search for markers like @samp{checking for} a particular test in the
26400 @var{log-file}.
26402 @item
26403 Alternatively, you might use a shell with debugging capabilities like
26404 @uref{http://bashdb.sourceforge.net/, bashdb}.
26406 @item
26407 When @command{configure} tests produce invalid results for your system,
26408 it may be necessary to override them:
26410 @itemize
26411 @item
26412 For programs, tools or libraries variables, preprocessor, compiler, or
26413 linker flags, it is often sufficient to override them at @command{make}
26414 run time with some care (@pxref{Macros and Submakes}).  Since this
26415 normally won't cause @command{configure} to be run again with these
26416 changed settings, it may fail if the changed variable would have caused
26417 different test results from @command{configure}, so this may work only
26418 for simple differences.
26420 @item
26421 Most tests which produce their result in a substituted variable allow to
26422 override the test by setting the variable on the @command{configure}
26423 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
26424 @pxref{Particular Systems}).
26426 @item
26427 Many tests store their result in a cache variable (@pxref{Caching
26428 Results}).  This lets you override them either on the
26429 @command{configure} command line as above, or through a primed cache or
26430 site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
26431 cache variable is documented with a test macro or may be inferred from
26432 @ref{Cache Variable Names}; the precise semantics of undocumented
26433 variables are often internal details, subject to change.
26434 @end itemize
26436 @item
26437 Alternatively, @command{configure} may produce invalid results because
26438 of uncaught programming errors, in your package or in an upstream
26439 library package.  For example, when @code{AC_CHECK_LIB} fails to find a
26440 library with a specified function, always check @file{config.log}.  This
26441 will reveal the exact error that produced the failing result: the
26442 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
26443 @end itemize
26445 Conversely, as macro author, you can make it easier for users of your
26446 macro:
26448 @itemize
26449 @item
26450 by minimizing dependencies between tests and between test results as far
26451 as possible,
26453 @item
26454 by using @command{make} variables to factorize and allow
26455 override of settings at @command{make} run time,
26457 @item
26458 by honoring the GNU Coding Standards and not overriding flags
26459 reserved for the user except temporarily during @command{configure}
26460 tests,
26462 @item
26463 by not requiring users of your macro to use the cache variables.
26464 Instead, expose the result of the test via @var{run-if-true} and
26465 @var{run-if-false} parameters.  If the result is not a boolean,
26466 then provide it through documented shell variables.
26467 @end itemize
26470 @c ===================================================== History of Autoconf.
26472 @node History
26473 @chapter History of Autoconf
26474 @cindex History of autoconf
26476 @emph{This chapter was written by the original author, David MacKenzie.}
26478 You may be wondering, Why was Autoconf originally written?  How did it
26479 get into its present form?  (Why does it look like gorilla spit?)  If
26480 you're not wondering, then this chapter contains no information useful
26481 to you, and you might as well skip it.  If you @emph{are} wondering,
26482 then let there be light@enddots{}
26484 @menu
26485 * Genesis::                     Prehistory and naming of @command{configure}
26486 * Exodus::                      The plagues of M4 and Perl
26487 * Leviticus::                   The priestly code of portability arrives
26488 * Numbers::                     Growth and contributors
26489 * Deuteronomy::                 Approaching the promises of easy configuration
26490 @end menu
26492 @node Genesis
26493 @section Genesis
26495 In June 1991 I was maintaining many of the GNU utilities for the
26496 Free Software Foundation.  As they were ported to more platforms and
26497 more programs were added, the number of @option{-D} options that users
26498 had to select in the makefile (around 20) became burdensome.
26499 Especially for me---I had to test each new release on a bunch of
26500 different systems.  So I wrote a little shell script to guess some of
26501 the correct settings for the fileutils package, and released it as part
26502 of fileutils 2.0.  That @command{configure} script worked well enough that
26503 the next month I adapted it (by hand) to create similar @command{configure}
26504 scripts for several other GNU utilities packages.  Brian Berliner
26505 also adapted one of my scripts for his CVS revision control system.
26507 Later that summer, I learned that Richard Stallman and Richard Pixley
26508 were developing similar scripts to use in the GNU compiler tools;
26509 so I adapted my @command{configure} scripts to support their evolving
26510 interface: using the file name @file{Makefile.in} as the templates;
26511 adding @samp{+srcdir}, the first option (of many); and creating
26512 @file{config.status} files.
26514 @node Exodus
26515 @section Exodus
26517 As I got feedback from users, I incorporated many improvements, using
26518 Emacs to search and replace, cut and paste, similar changes in each of
26519 the scripts.  As I adapted more GNU utilities packages to use
26520 @command{configure} scripts, updating them all by hand became impractical.
26521 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
26522 mail saying that the @command{configure} scripts were great, and asking if
26523 I had a tool for generating them that I could send him.  No, I thought,
26524 but I should!  So I started to work out how to generate them.  And the
26525 journey from the slavery of hand-written @command{configure} scripts to the
26526 abundance and ease of Autoconf began.
26528 Cygnus @command{configure}, which was being developed at around that time,
26529 is table driven; it is meant to deal mainly with a discrete number of
26530 system types with a small number of mainly unguessable features (such as
26531 details of the object file format).  The automatic configuration system
26532 that Brian Fox had developed for Bash takes a similar approach.  For
26533 general use, it seems to me a hopeless cause to try to maintain an
26534 up-to-date database of which features each variant of each operating
26535 system has.  It's easier and more reliable to check for most features on
26536 the fly---especially on hybrid systems that people have hacked on
26537 locally or that have patches from vendors installed.
26539 I considered using an architecture similar to that of Cygnus
26540 @command{configure}, where there is a single @command{configure} script that
26541 reads pieces of @file{configure.in} when run.  But I didn't want to have
26542 to distribute all of the feature tests with every package, so I settled
26543 on having a different @command{configure} made from each
26544 @file{configure.in} by a preprocessor.  That approach also offered more
26545 control and flexibility.
26547 I looked briefly into using the Metaconfig package, by Larry Wall,
26548 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
26549 reasons.  The @command{Configure} scripts it produces are interactive,
26550 which I find quite inconvenient; I didn't like the ways it checked for
26551 some features (such as library functions); I didn't know that it was
26552 still being maintained, and the @command{Configure} scripts I had
26553 seen didn't work on many modern systems (such as System V R4 and NeXT);
26554 it wasn't flexible in what it could do in response to a feature's
26555 presence or absence; I found it confusing to learn; and it was too big
26556 and complex for my needs (I didn't realize then how much Autoconf would
26557 eventually have to grow).
26559 I considered using Perl to generate my style of @command{configure}
26560 scripts, but decided that M4 was better suited to the job of simple
26561 textual substitutions: it gets in the way less, because output is
26562 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
26563 the GNU extensions to M4.)  Also, some of my friends at the
26564 University of Maryland had recently been putting M4 front ends on
26565 several programs, including @code{tvtwm}, and I was interested in trying
26566 out a new language.
26568 @node Leviticus
26569 @section Leviticus
26571 Since my @command{configure} scripts determine the system's capabilities
26572 automatically, with no interactive user intervention, I decided to call
26573 the program that generates them Autoconfig.  But with a version number
26574 tacked on, that name would be too long for old Unix file systems,
26575 so I shortened it to Autoconf.
26577 In the fall of 1991 I called together a group of fellow questers after
26578 the Holy Grail of portability (er, that is, alpha testers) to give me
26579 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
26580 and continued to add features and improve the techniques used in the
26581 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
26582 with the idea of making an Autoconf shell script to run M4
26583 and check for unresolved macro calls; Richard Pixley, who suggested
26584 running the compiler instead of searching the file system to find
26585 include files and symbols, for more accurate results; Karl Berry, who
26586 got Autoconf to configure @TeX{} and added the macro index to the
26587 documentation; and Ian Lance Taylor, who added support for creating a C
26588 header file as an alternative to putting @option{-D} options in a
26589 makefile, so he could use Autoconf for his UUCP package.
26590 The alpha testers cheerfully adjusted their files again and again as the
26591 names and calling conventions of the Autoconf macros changed from
26592 release to release.  They all contributed many specific checks, great
26593 ideas, and bug fixes.
26595 @node Numbers
26596 @section Numbers
26598 In July 1992, after months of alpha testing, I released Autoconf 1.0,
26599 and converted many GNU packages to use it.  I was surprised by how
26600 positive the reaction to it was.  More people started using it than I
26601 could keep track of, including people working on software that wasn't
26602 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
26603 Autoconf continued to improve rapidly, as many people using the
26604 @command{configure} scripts reported problems they encountered.
26606 Autoconf turned out to be a good torture test for M4 implementations.
26607 Unix M4 started to dump core because of the length of the
26608 macros that Autoconf defined, and several bugs showed up in GNU
26609 M4 as well.  Eventually, we realized that we needed to use some
26610 features that only GNU M4 has.  4.3BSD M4, in
26611 particular, has an impoverished set of builtin macros; the System V
26612 version is better, but still doesn't provide everything we need.
26614 More development occurred as people put Autoconf under more stresses
26615 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
26616 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
26617 invalid arguments.  Jim Blandy bravely coerced it into configuring
26618 GNU Emacs, laying the groundwork for several later improvements.
26619 Roland McGrath got it to configure the GNU C Library, wrote the
26620 @command{autoheader} script to automate the creation of C header file
26621 templates, and added a @option{--verbose} option to @command{configure}.
26622 Noah Friedman added the @option{--autoconf-dir} option and
26623 @code{AC_MACRODIR} environment variable.  (He also coined the term
26624 @dfn{autoconfiscate} to mean ``adapt a software package to use
26625 Autoconf''.)  Roland and Noah improved the quoting protection in
26626 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
26627 dealing with portability problems from February through June, 1993.
26629 @node Deuteronomy
26630 @section Deuteronomy
26632 A long wish list for major features had accumulated, and the effect of
26633 several years of patching by various people had left some residual
26634 cruft.  In April 1994, while working for Cygnus Support, I began a major
26635 revision of Autoconf.  I added most of the features of the Cygnus
26636 @command{configure} that Autoconf had lacked, largely by adapting the
26637 relevant parts of Cygnus @command{configure} with the help of david zuhn
26638 and Ken Raeburn.  These features include support for using
26639 @file{config.sub}, @file{config.guess}, @option{--host}, and
26640 @option{--target}; making links to files; and running @command{configure}
26641 scripts in subdirectories.  Adding these features enabled Ken to convert
26642 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
26643 Autoconf.
26645 I added more features in response to other peoples' requests.  Many
26646 people had asked for @command{configure} scripts to share the results of
26647 the checks between runs, because (particularly when configuring a large
26648 source tree, like Cygnus does) they were frustratingly slow.  Mike
26649 Haertel suggested adding site-specific initialization scripts.  People
26650 distributing software that had to unpack on MS-DOS asked for a way to
26651 override the @file{.in} extension on the file names, which produced file
26652 names like @file{config.h.in} containing two dots.  Jim Avera did an
26653 extensive examination of the problems with quoting in @code{AC_DEFINE}
26654 and @code{AC_SUBST}; his insights led to significant improvements.
26655 Richard Stallman asked that compiler output be sent to @file{config.log}
26656 instead of @file{/dev/null}, to help people debug the Emacs
26657 @command{configure} script.
26659 I made some other changes because of my dissatisfaction with the quality
26660 of the program.  I made the messages showing results of the checks less
26661 ambiguous, always printing a result.  I regularized the names of the
26662 macros and cleaned up coding style inconsistencies.  I added some
26663 auxiliary utilities that I had developed to help convert source code
26664 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
26665 the macros not interrupt each others' messages.  (That feature revealed
26666 some performance bottlenecks in GNU M4, which he hastily
26667 corrected!)  I reorganized the documentation around problems people want
26668 to solve.  And I began a test suite, because experience had shown that
26669 Autoconf has a pronounced tendency to regress when we change it.
26671 Again, several alpha testers gave invaluable feedback, especially
26672 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
26673 and Mark Eichin.
26675 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
26676 have free time again.  I think.  Yeah, right.)
26679 @c ========================================================== Appendices
26682 @node GNU Free Documentation License
26683 @appendix GNU Free Documentation License
26685 @include fdl.texi
26687 @node Indices
26688 @appendix Indices
26690 @menu
26691 * Environment Variable Index::  Index of environment variables used
26692 * Output Variable Index::       Index of variables set in output files
26693 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
26694 * Cache Variable Index::        Index of documented cache variables
26695 * Autoconf Macro Index::        Index of Autoconf macros
26696 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
26697 * Autotest Macro Index::        Index of Autotest macros
26698 * Program & Function Index::    Index of those with portability problems
26699 * Concept Index::               General index
26700 @end menu
26702 @node Environment Variable Index
26703 @appendixsec Environment Variable Index
26705 This is an alphabetical list of the environment variables that might
26706 influence Autoconf checks.
26708 @printindex ev
26710 @node Output Variable Index
26711 @appendixsec Output Variable Index
26713 This is an alphabetical list of the variables that Autoconf can
26714 substitute into files that it creates, typically one or more
26715 makefiles.  @xref{Setting Output Variables}, for more information
26716 on how this is done.
26718 @printindex ov
26720 @node Preprocessor Symbol Index
26721 @appendixsec Preprocessor Symbol Index
26723 This is an alphabetical list of the C preprocessor symbols that the
26724 Autoconf macros define.  To work with Autoconf, C source code needs to
26725 use these names in @code{#if} or @code{#ifdef} directives.
26727 @printindex cv
26729 @node Cache Variable Index
26730 @appendixsec Cache Variable Index
26732 This is an alphabetical list of documented cache variables used
26733 by macros defined in Autoconf.  Autoconf macros may use additional cache
26734 variables internally.
26735 @ifset shortindexflag
26736 To make the list easier to use, the variables are listed without their
26737 preceding @samp{ac_cv_}.
26738 @end ifset
26740 @printindex CA
26742 @node Autoconf Macro Index
26743 @appendixsec Autoconf Macro Index
26745 This is an alphabetical list of the Autoconf macros.
26746 @ifset shortindexflag
26747 To make the list easier to use, the macros are listed without their
26748 preceding @samp{AC_}.
26749 @end ifset
26751 @printindex AC
26753 @node M4 Macro Index
26754 @appendixsec M4 Macro Index
26756 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
26757 @ifset shortindexflag
26758 To make the list easier to use, the macros are listed without their
26759 preceding @samp{m4_} or @samp{AS_}.  The prefix is @samp{m4_} for
26760 all-lowercase macro names and @samp{AS_} for all-uppercase macro
26761 names.
26762 @end ifset
26764 @printindex MS
26766 @node Autotest Macro Index
26767 @appendixsec Autotest Macro Index
26769 This is an alphabetical list of the Autotest macros.
26770 @ifset shortindexflag
26771 To make the list easier to use, the macros are listed without their
26772 preceding @samp{AT_}.
26773 @end ifset
26775 @printindex AT
26777 @node Program & Function Index
26778 @appendixsec Program and Function Index
26780 This is an alphabetical list of the programs and functions whose
26781 portability is discussed in this document.
26783 @printindex pr
26785 @node Concept Index
26786 @appendixsec Concept Index
26788 This is an alphabetical list of the files, tools, and concepts
26789 introduced in this document.
26791 @printindex cp
26793 @bye
26795 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
26796 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
26797 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
26798 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
26799 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
26800 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
26801 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
26802 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
26803 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
26804 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
26805 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
26806 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
26807 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
26808 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
26809 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
26810 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
26811 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
26812 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
26813 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
26814 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
26815 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
26816 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
26817 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
26818 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
26819 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
26820 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
26821 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
26822 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
26823 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
26824 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
26825 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
26826 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
26827 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
26828 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
26829 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
26830 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
26831 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
26832 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
26833 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
26834 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
26835 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
26836 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
26837 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
26838 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
26839 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
26840 @c  LocalWords:  STDBOOL BOOL stdbool cplusplus bool Bool stdarg tm
26841 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
26842 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
26843 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
26844 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
26845 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
26846 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
26847 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
26848 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
26849 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
26850 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
26851 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
26852 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
26853 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
26854 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
26855 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
26856 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
26857 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
26858 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
26859 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
26860 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
26861 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
26862 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
26863 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
26864 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
26865 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
26866 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
26867 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
26868 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
26869 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
26870 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
26871 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
26872 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
26873 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
26874 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
26875 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
26876 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
26877 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
26878 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
26879 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
26880 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
26881 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
26882 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
26883 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
26884 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
26885 @c  LocalWords:  Dynix basename aname cname macroexpands xno xcheck
26886 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
26888 @c Local Variables:
26889 @c fill-column: 72
26890 @c ispell-local-dictionary: "american"
26891 @c indent-tabs-mode: nil
26892 @c whitespace-check-buffer-indent: nil
26893 @c End: