Improve release automation.
[autoconf.git] / doc / autoconf.texi
blobcc192841cf4032e5941bd8cb5092e292a6dd7b35
1 \input texinfo @c -*-texinfo-*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename autoconf.info
5 @include version.texi
6 @settitle Autoconf
7 @setchapternewpage odd
8 @ifnothtml
9 @setcontentsaftertitlepage
10 @end ifnothtml
11 @finalout
13 @c @ovar(ARG)
14 @c ----------
15 @c The ARG is an optional argument.  To be used for macro arguments in
16 @c their documentation (@defmac).
17 @macro ovar{varname}
18 @r{[}@var{\varname\}@r{]}@c
19 @end macro
21 @c @dvar(ARG, DEFAULT)
22 @c -------------------
23 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
24 @c for macro arguments in their documentation (@defmac).
25 @macro dvar{varname, default}
26 @r{[}@var{\varname\} = @samp{\default\}@r{]}@c
27 @end macro
29 @c Handling the indexes with Texinfo yields several different problems.
31 @c Because we want to drop out the AC_ part of the macro names in the
32 @c printed manual, but not in the other outputs, we need a layer above
33 @c the usual @acindex{} etc.  That's why we first define indexes such as
34 @c acx meant to become the macro @acindex.  First of all, using ``ac_''
35 @c does not work with makeinfo, and using ``ac1'' doesn't work with TeX.
36 @c So use something more regular ``acx''.  Then you finish with a printed
37 @c index saying ``index is not existent''.  Of course: you ought to use
38 @c two letters :(  So you use capitals.
40 @c Second, when defining a macro in the TeX world, following spaces are
41 @c eaten.  But then, since we embed @acxindex commands that use the end
42 @c of line as an end marker, the whole things wrecks itself.  So make
43 @c sure you do *force* an additional end of line, add a ``@c''.
45 @c Finally, you might want to get rid of TeX expansion, using --expand
46 @c with texi2dvi.  But then you wake up an old problem: we use macros
47 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
49 @c Define an environment variable index.
50 @defcodeindex ev
51 @c Define an output variable index.
52 @defcodeindex ov
53 @c Define a CPP variable index.
54 @defcodeindex cv
55 @c Define a cache variable index.
56 @defcodeindex CA
57 @c Define an Autoconf macro index that @defmac doesn't write to.
58 @defcodeindex AC
59 @c Define an Autotest macro index that @defmac doesn't write to.
60 @defcodeindex AT
61 @c Define an M4sugar macro index that @defmac doesn't write to.
62 @defcodeindex MS
63 @c Define an index for *foreign* programs: `mv' etc.  Used for the
64 @c portability sections and so on.
65 @defindex pr
67 @c shortindexflag
68 @c --------------
69 @c Shall we factor AC_ out of the Autoconf macro index etc.?
70 @iftex
71 @set shortindexflag
72 @end iftex
74 @c @acindex{MACRO}
75 @c ---------------
76 @c Registering an AC_\MACRO\.
77 @ifset shortindexflag
78 @macro acindex{macro}
79 @ACindex \macro\
81 @end macro
82 @end ifset
83 @ifclear shortindexflag
84 @macro acindex{macro}
85 @ACindex AC_\macro\
86 @end macro
87 @end ifclear
89 @c @ahindex{MACRO}
90 @c ---------------
91 @c Registering an AH_\MACRO\.
92 @macro ahindex{macro}
93 @ACindex AH_\macro\
95 @end macro
97 @c @asindex{MACRO}
98 @c ---------------
99 @c Registering an AS_\MACRO\.
100 @ifset shortindexflag
101 @macro asindex{macro}
102 @MSindex \macro\
104 @end macro
105 @end ifset
106 @ifclear shortindexflag
107 @macro asindex{macro}
108 @MSindex AS_\macro\
109 @end macro
110 @end ifclear
112 @c @atindex{MACRO}
113 @c ---------------
114 @c Registering an AT_\MACRO\.
115 @ifset shortindexflag
116 @macro atindex{macro}
117 @ATindex \macro\
119 @end macro
120 @end ifset
121 @ifclear shortindexflag
122 @macro atindex{macro}
123 @ATindex AT_\macro\
124 @end macro
125 @end ifclear
127 @c @auindex{MACRO}
128 @c ---------------
129 @c Registering an AU_\MACRO\.
130 @macro auindex{macro}
131 @ACindex AU_\macro\
133 @end macro
135 @c @hdrindex{MACRO}
136 @c ----------------
137 @c Indexing a header.
138 @macro hdrindex{macro}
139 @prindex @file{\macro\}
141 @end macro
143 @c @msindex{MACRO}
144 @c ---------------
145 @c Registering an m4_\MACRO\.
146 @ifset shortindexflag
147 @macro msindex{macro}
148 @MSindex \macro\
150 @end macro
151 @end ifset
152 @ifclear shortindexflag
153 @macro msindex{macro}
154 @MSindex m4_\macro\
155 @end macro
156 @end ifclear
159 @c @caindex{VARIABLE}
160 @c ------------------
161 @c Registering an ac_cv_\VARIABLE\ cache variable.
162 @ifset shortindexflag
163 @macro caindex{macro}
164 @CAindex \macro\
165 @end macro
166 @end ifset
167 @ifclear shortindexflag
168 @macro caindex{macro}
169 @CAindex ac_cv_\macro\
170 @end macro
171 @end ifclear
173 @c Define an index for functions: `alloca' etc.  Used for the
174 @c portability sections and so on.  We can't use `fn' (aka `fnindex),
175 @c since `@defmac' goes into it => we'd get all the macros too.
177 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
179 @c   ! No room for a new @write .
180 @c   l.112 @defcodeindex fu
182 @c   so don't define yet another one :(  Just put some tags before each
183 @c   @prindex which is actually a @funindex.
185 @c   @defcodeindex fu
188 @c   @c Put the programs and functions into their own index.
189 @c   @syncodeindex fu pr
191 @comment %**end of header
192 @comment ========================================================
194 @copying
196 This manual (@value{UPDATED}) is for @acronym{GNU} Autoconf
197 (version @value{VERSION}),
198 a package for creating scripts to configure source code packages using
199 templates and an M4 macro package.
201 Copyright @copyright{} 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000,
202 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
203 Foundation, Inc.
205 @quotation
206 Permission is granted to copy, distribute and/or modify this document
207 under the terms of the @acronym{GNU} Free Documentation License,
208 Version 1.3 or any later version published by the Free Software
209 Foundation; with no Invariant Sections, with the Front-Cover texts
210 being ``A @acronym{GNU} Manual,'' and with the Back-Cover Texts as in
211 (a) below.  A copy of the license is included in the section entitled
212 ``@acronym{GNU} Free Documentation License.''
214 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
215 modify this @acronym{GNU} manual.  Buying copies from the @acronym{FSF}
216 supports it in developing @acronym{GNU} and promoting software
217 freedom.''
218 @end quotation
219 @end copying
223 @dircategory Software development
224 @direntry
225 * Autoconf: (autoconf).         Create source code configuration scripts.
226 @end direntry
228 @dircategory Individual utilities
229 @direntry
230 * autoscan: (autoconf)autoscan Invocation.
231                                 Semi-automatic @file{configure.ac} writing
232 * ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
233 * autoconf-invocation: (autoconf)autoconf Invocation.
234                                 How to create configuration scripts
235 * autoreconf: (autoconf)autoreconf Invocation.
236                                 Remaking multiple @command{configure} scripts
237 * autoheader: (autoconf)autoheader Invocation.
238                                 How to create configuration templates
239 * autom4te: (autoconf)autom4te Invocation.
240                                 The Autoconf executables backbone
241 * configure: (autoconf)configure Invocation.    Configuring a package.
242 * autoupdate: (autoconf)autoupdate Invocation.
243                                 Automatic update of @file{configure.ac}
244 * config.status: (autoconf)config.status Invocation. Recreating configurations.
245 * testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
246 @end direntry
248 @titlepage
249 @title Autoconf
250 @subtitle Creating Automatic Configuration Scripts
251 @subtitle for version @value{VERSION}, @value{UPDATED}
252 @author David MacKenzie
253 @author Ben Elliston
254 @author Akim Demaille
255 @page
256 @vskip 0pt plus 1filll
257 @insertcopying
258 @end titlepage
260 @contents
263 @ifnottex
264 @node Top
265 @top Autoconf
266 @insertcopying
267 @end ifnottex
269 @c The master menu, created with texinfo-master-menu, goes here.
271 @menu
272 * Introduction::                Autoconf's purpose, strengths, and weaknesses
273 * The GNU Build System::        A set of tools for portable software packages
274 * Making configure Scripts::    How to organize and produce Autoconf scripts
275 * Setup::                       Initialization and output
276 * Existing Tests::              Macros that check for particular features
277 * Writing Tests::               How to write new feature checks
278 * Results::                     What to do with results from feature checks
279 * Programming in M4::           Layers on top of which Autoconf is written
280 * Programming in M4sh::         Shell portability layer
281 * Writing Autoconf Macros::     Adding new macros to Autoconf
282 * Portable Shell::              Shell script portability pitfalls
283 * Portable Make::               Makefile portability pitfalls
284 * Portable C and C++::          C and C++ portability pitfalls
285 * Manual Configuration::        Selecting features that can't be guessed
286 * Site Configuration::          Local defaults for @command{configure}
287 * Running configure Scripts::   How to use the Autoconf output
288 * config.status Invocation::    Recreating a configuration
289 * Obsolete Constructs::         Kept for backward compatibility
290 * Using Autotest::              Creating portable test suites
291 * FAQ::                         Frequent Autoconf Questions, with answers
292 * History::                     History of Autoconf
293 * GNU Free Documentation License::  License for copying this manual
294 * Indices::                     Indices of symbols, concepts, etc.
296 @detailmenu
297  --- The Detailed Node Listing ---
299 The @acronym{GNU} Build System
301 * Automake::                    Escaping makefile hell
302 * Gnulib::                      The @acronym{GNU} portability library
303 * Libtool::                     Building libraries portably
304 * Pointers::                    More info on the @acronym{GNU} build system
306 Making @command{configure} Scripts
308 * Writing Autoconf Input::      What to put in an Autoconf input file
309 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
310 * ifnames Invocation::          Listing the conditionals in source code
311 * autoconf Invocation::         How to create configuration scripts
312 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
314 Writing @file{configure.ac}
316 * Shell Script Compiler::       Autoconf as solution of a problem
317 * Autoconf Language::           Programming in Autoconf
318 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
320 Initialization and Output Files
322 * Initializing configure::      Option processing etc.
323 * Versioning::                  Dealing with Autoconf versions
324 * Notices::                     Copyright, version numbers in @command{configure}
325 * Input::                       Where Autoconf should find files
326 * Output::                      Outputting results from the configuration
327 * Configuration Actions::       Preparing the output based on results
328 * Configuration Files::         Creating output files
329 * Makefile Substitutions::      Using output variables in makefiles
330 * Configuration Headers::       Creating a configuration header file
331 * Configuration Commands::      Running arbitrary instantiation commands
332 * Configuration Links::         Links depending on the configuration
333 * Subdirectories::              Configuring independent packages together
334 * Default Prefix::              Changing the default installation prefix
336 Substitutions in Makefiles
338 * Preset Output Variables::     Output variables that are always set
339 * Installation Directory Variables::  Other preset output variables
340 * Changed Directory Variables:: Warnings about @file{datarootdir}
341 * Build Directories::           Supporting multiple concurrent compiles
342 * Automatic Remaking::          Makefile rules for configuring
344 Configuration Header Files
346 * Header Templates::            Input for the configuration headers
347 * autoheader Invocation::       How to create configuration templates
348 * Autoheader Macros::           How to specify CPP templates
350 Existing Tests
352 * Common Behavior::             Macros' standard schemes
353 * Alternative Programs::        Selecting between alternative programs
354 * Files::                       Checking for the existence of files
355 * Libraries::                   Library archives that might be missing
356 * Library Functions::           C library functions that might be missing
357 * Header Files::                Header files that might be missing
358 * Declarations::                Declarations that may be missing
359 * Structures::                  Structures or members that might be missing
360 * Types::                       Types that might be missing
361 * Compilers and Preprocessors::  Checking for compiling programs
362 * System Services::             Operating system services
363 * Posix Variants::              Special kludges for specific Posix variants
364 * Erlang Libraries::            Checking for the existence of Erlang libraries
366 Common Behavior
368 * Standard Symbols::            Symbols defined by the macros
369 * Default Includes::            Includes used by the generic macros
371 Alternative Programs
373 * Particular Programs::         Special handling to find certain programs
374 * Generic Programs::            How to find other programs
376 Library Functions
378 * Function Portability::        Pitfalls with usual functions
379 * Particular Functions::        Special handling to find certain functions
380 * Generic Functions::           How to find other functions
382 Header Files
384 * Header Portability::          Collected knowledge on common headers
385 * Particular Headers::          Special handling to find certain headers
386 * Generic Headers::             How to find other headers
388 Declarations
390 * Particular Declarations::     Macros to check for certain declarations
391 * Generic Declarations::        How to find other declarations
393 Structures
395 * Particular Structures::       Macros to check for certain structure members
396 * Generic Structures::          How to find other structure members
398 Types
400 * Particular Types::            Special handling to find certain types
401 * Generic Types::               How to find other types
403 Compilers and Preprocessors
405 * Specific Compiler Characteristics::  Some portability issues
406 * Generic Compiler Characteristics::  Language independent tests and features
407 * C Compiler::                  Checking its characteristics
408 * C++ Compiler::                Likewise
409 * Objective C Compiler::        Likewise
410 * Objective C++ Compiler::      Likewise
411 * Erlang Compiler and Interpreter::  Likewise
412 * Fortran Compiler::            Likewise
414 Writing Tests
416 * Language Choice::             Selecting which language to use for testing
417 * Writing Test Programs::       Forging source files for compilers
418 * Running the Preprocessor::    Detecting preprocessor symbols
419 * Running the Compiler::        Detecting language or header features
420 * Running the Linker::          Detecting library features
421 * Runtime::                     Testing for runtime features
422 * Systemology::                 A zoology of operating systems
423 * Multiple Cases::              Tests for several possible values
425 Writing Test Programs
427 * Guidelines::                  General rules for writing test programs
428 * Test Functions::              Avoiding pitfalls in test programs
429 * Generating Sources::          Source program boilerplate
431 Results of Tests
433 * Defining Symbols::            Defining C preprocessor symbols
434 * Setting Output Variables::    Replacing variables in output files
435 * Special Chars in Variables::  Characters to beware of in variables
436 * Caching Results::             Speeding up subsequent @command{configure} runs
437 * Printing Messages::           Notifying @command{configure} users
439 Caching Results
441 * Cache Variable Names::        Shell variables used in caches
442 * Cache Files::                 Files @command{configure} uses for caching
443 * Cache Checkpointing::         Loading and saving the cache file
445 Programming in M4
447 * M4 Quotation::                Protecting macros from unwanted expansion
448 * Using autom4te::              The Autoconf executables backbone
449 * Programming in M4sugar::      Convenient pure M4 macros
450 * Debugging via autom4te::      Figuring out what M4 was doing
452 Programming in M4sh
454 * Common Shell Constructs::     Portability layer for common shell constructs
455 * Polymorphic Variables::       Support for indirect variable names
456 * Initialization Macros::       Macros to establish a sane shell environment
457 * File Descriptor Macros::      File descriptor macros for input and output
459 M4 Quotation
461 * Active Characters::           Characters that change the behavior of M4
462 * One Macro Call::              Quotation and one macro call
463 * Quoting and Parameters::      M4 vs. shell parameters
464 * Quotation and Nested Macros::  Macros calling macros
465 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
466 * Quadrigraphs::                Another way to escape special characters
467 * Balancing Parentheses::       Dealing with unbalanced parentheses
468 * Quotation Rule Of Thumb::     One parenthesis, one quote
470 Using @command{autom4te}
472 * autom4te Invocation::         A @acronym{GNU} M4 wrapper
473 * Customizing autom4te::        Customizing the Autoconf package
475 Programming in M4sugar
477 * Redefined M4 Macros::         M4 builtins changed in M4sugar
478 * Diagnostic Macros::           Diagnostic messages from M4sugar
479 * Diversion support::           Diversions in M4sugar
480 * Conditional constructs::      Conditions in M4
481 * Looping constructs::          Iteration in M4
482 * Evaluation Macros::           More quotation and evaluation control
483 * Text processing Macros::      String manipulation in M4
484 * Number processing Macros::    Arithmetic computation in M4
485 * Set manipulation Macros::     Set manipulation in M4
486 * Forbidden Patterns::          Catching unexpanded macros
488 Writing Autoconf Macros
490 * Macro Definitions::           Basic format of an Autoconf macro
491 * Macro Names::                 What to call your new macros
492 * Reporting Messages::          Notifying @command{autoconf} users
493 * Dependencies Between Macros::  What to do when macros depend on other macros
494 * Obsoleting Macros::           Warning about old ways of doing things
495 * Coding Style::                Writing Autoconf macros @`a la Autoconf
497 Dependencies Between Macros
499 * Prerequisite Macros::         Ensuring required information
500 * Suggested Ordering::          Warning about possible ordering problems
501 * One-Shot Macros::             Ensuring a macro is called only once
503 Portable Shell Programming
505 * Shellology::                  A zoology of shells
506 * Here-Documents::              Quirks and tricks
507 * File Descriptors::            FDs and redirections
508 * File System Conventions::     File names
509 * Shell Pattern Matching::      Pattern matching
510 * Shell Substitutions::         Variable and command expansions
511 * Assignments::                 Varying side effects of assignments
512 * Parentheses::                 Parentheses in shell scripts
513 * Slashes::                     Slashes in shell scripts
514 * Special Shell Variables::     Variables you should not change
515 * Shell Functions::             What to look out for if you use them
516 * Limitations of Builtins::     Portable use of not so portable /bin/sh
517 * Limitations of Usual Tools::  Portable use of portable tools
519 Portable Make Programming
521 * $< in Ordinary Make Rules::   $< in ordinary rules
522 * Failure in Make Rules::       Failing portably in rules
523 * Special Chars in Names::      Special Characters in Macro Names
524 * Backslash-Newline-Newline::   Empty last lines in macro definitions
525 * Backslash-Newline Comments::  Spanning comments across line boundaries
526 * Long Lines in Makefiles::     Line length limitations
527 * Macros and Submakes::         @code{make macro=value} and submakes
528 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
529 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
530 * Parallel Make::               Parallel @command{make} quirks
531 * Comments in Make Rules::      Other problems with Make comments
532 * obj/ and Make::               Don't name a subdirectory @file{obj}
533 * make -k Status::              Exit status of @samp{make -k}
534 * VPATH and Make::              @code{VPATH} woes
535 * Single Suffix Rules::         Single suffix rules and separated dependencies
536 * Timestamps and Make::         Subsecond timestamp resolution
538 @code{VPATH} and Make
540 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
541 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
542 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
543 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
544 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
545 * Make Target Lookup::          More details about @code{VPATH} lookup
547 Portable C and C++ Programming
549 * Varieties of Unportability::  How to make your programs unportable
550 * Integer Overflow::            When integers get too large
551 * Preprocessor Arithmetic::     @code{#if} expression problems
552 * Null Pointers::               Properties of null pointers
553 * Buffer Overruns::             Subscript errors and the like
554 * Volatile Objects::            @code{volatile} and signals
555 * Floating Point Portability::  Portable floating-point arithmetic
556 * Exiting Portably::            Exiting and the exit status
558 Manual Configuration
560 * Specifying Target Triplets::  Specifying target triplets
561 * Canonicalizing::              Getting the canonical system type
562 * Using System Type::           What to do with the system type
564 Site Configuration
566 * Help Formatting::             Customizing @samp{configure --help}
567 * External Software::           Working with other optional software
568 * Package Options::             Selecting optional features
569 * Pretty Help Strings::         Formatting help string
570 * Option Checking::             Controlling checking of @command{configure} options
571 * Site Details::                Configuring site details
572 * Transforming Names::          Changing program names when installing
573 * Site Defaults::               Giving @command{configure} local defaults
575 Transforming Program Names When Installing
577 * Transformation Options::      @command{configure} options to transform names
578 * Transformation Examples::     Sample uses of transforming names
579 * Transformation Rules::        Makefile uses of transforming names
581 Running @command{configure} Scripts
583 * Basic Installation::          Instructions for typical cases
584 * Compilers and Options::       Selecting compilers and optimization
585 * Multiple Architectures::      Compiling for multiple architectures at once
586 * Installation Names::          Installing in different directories
587 * Optional Features::           Selecting optional features
588 * Particular Systems::          Particular systems
589 * System Type::                 Specifying the system type
590 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
591 * Defining Variables::          Specifying the compiler etc.
592 * configure Invocation::        Changing how @command{configure} runs
594 Obsolete Constructs
596 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
597 * acconfig Header::             Additional entries in @file{config.h.in}
598 * autoupdate Invocation::       Automatic update of @file{configure.ac}
599 * Obsolete Macros::             Backward compatibility macros
600 * Autoconf 1::                  Tips for upgrading your files
601 * Autoconf 2.13::               Some fresher tips
603 Upgrading From Version 1
605 * Changed File Names::          Files you might rename
606 * Changed Makefiles::           New things to put in @file{Makefile.in}
607 * Changed Macros::              Macro calls you might replace
608 * Changed Results::             Changes in how to check test results
609 * Changed Macro Writing::       Better ways to write your own macros
611 Upgrading From Version 2.13
613 * Changed Quotation::           Broken code which used to work
614 * New Macros::                  Interaction with foreign macros
615 * Hosts and Cross-Compilation::  Bugward compatibility kludges
616 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
617 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
619 Generating Test Suites with Autotest
621 * Using an Autotest Test Suite::  Autotest and the user
622 * Writing Testsuites::          Autotest macros
623 * testsuite Invocation::        Running @command{testsuite} scripts
624 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
626 Using an Autotest Test Suite
628 * testsuite Scripts::           The concepts of Autotest
629 * Autotest Logs::               Their contents
631 Frequent Autoconf Questions, with answers
633 * Distributing::                Distributing @command{configure} scripts
634 * Why GNU M4::                  Why not use the standard M4?
635 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
636 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
637 * Defining Directories::        Passing @code{datadir} to program
638 * Autom4te Cache::              What is it?  Can I remove it?
639 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
640 * Expanded Before Required::    Expanded Before Required
641 * Debugging::                   Debugging @command{configure} scripts
643 History of Autoconf
645 * Genesis::                     Prehistory and naming of @command{configure}
646 * Exodus::                      The plagues of M4 and Perl
647 * Leviticus::                   The priestly code of portability arrives
648 * Numbers::                     Growth and contributors
649 * Deuteronomy::                 Approaching the promises of easy configuration
651 Indices
653 * Environment Variable Index::  Index of environment variables used
654 * Output Variable Index::       Index of variables set in output files
655 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
656 * Cache Variable Index::        Index of documented cache variables
657 * Autoconf Macro Index::        Index of Autoconf macros
658 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
659 * Autotest Macro Index::        Index of Autotest macros
660 * Program & Function Index::    Index of those with portability problems
661 * Concept Index::               General index
663 @end detailmenu
664 @end menu
666 @c ============================================================= Introduction.
668 @node Introduction
669 @chapter Introduction
670 @cindex Introduction
672 @flushright
673 A physicist, an engineer, and a computer scientist were discussing the
674 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
675 early in the Creation, God made Light; and you know, Maxwell's
676 equations, the dual nature of electromagnetic waves, the relativistic
677 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
678 before making Light, God split the Chaos into Land and Water; it takes a
679 hell of an engineer to handle that big amount of mud, and orderly
680 separation of solids from liquids@enddots{}'' The computer scientist
681 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
683 ---Anonymous
684 @end flushright
685 @c (via Franc,ois Pinard)
687 Autoconf is a tool for producing shell scripts that automatically
688 configure software source code packages to adapt to many kinds of
689 Posix-like systems.  The configuration scripts produced by Autoconf
690 are independent of Autoconf when they are run, so their users do not
691 need to have Autoconf.
693 The configuration scripts produced by Autoconf require no manual user
694 intervention when run; they do not normally even need an argument
695 specifying the system type.  Instead, they individually test for the
696 presence of each feature that the software package they are for might need.
697 (Before each check, they print a one-line message stating what they are
698 checking for, so the user doesn't get too bored while waiting for the
699 script to finish.)  As a result, they deal well with systems that are
700 hybrids or customized from the more common Posix variants.  There is
701 no need to maintain files that list the features supported by each
702 release of each variant of Posix.
704 For each software package that Autoconf is used with, it creates a
705 configuration script from a template file that lists the system features
706 that the package needs or can use.  After the shell code to recognize
707 and respond to a system feature has been written, Autoconf allows it to
708 be shared by many software packages that can use (or need) that feature.
709 If it later turns out that the shell code needs adjustment for some
710 reason, it needs to be changed in only one place; all of the
711 configuration scripts can be regenerated automatically to take advantage
712 of the updated code.
714 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
715 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
716 Those who do not understand Autoconf are condemned to reinvent it, poorly.
717 The primary goal of Autoconf is making the @emph{user's} life easier;
718 making the @emph{maintainer's} life easier is only a secondary goal.
719 Put another way, the primary goal is not to make the generation of
720 @file{configure} automatic for package maintainers (although patches
721 along that front are welcome, since package maintainers form the user
722 base of Autoconf); rather, the goal is to make @file{configure}
723 painless, portable, and predictable for the end user of each
724 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
725 successful at its goal --- most complaints to the Autoconf list are
726 about difficulties in writing Autoconf input, and not in the behavior of
727 the resulting @file{configure}.  Even packages that don't use Autoconf
728 will generally provide a @file{configure} script, and the most common
729 complaint about these alternative home-grown scripts is that they fail
730 to meet one or more of the @acronym{GNU} Coding Standards that users
731 have come to expect from Autoconf-generated @file{configure} scripts.
733 The Metaconfig package is similar in purpose to Autoconf, but the
734 scripts it produces require manual user intervention, which is quite
735 inconvenient when configuring large source trees.  Unlike Metaconfig
736 scripts, Autoconf scripts can support cross-compiling, if some care is
737 taken in writing them.
739 Autoconf does not solve all problems related to making portable
740 software packages---for a more complete solution, it should be used in
741 concert with other @acronym{GNU} build tools like Automake and
742 Libtool.  These other tools take on jobs like the creation of a
743 portable, recursive makefile with all of the standard targets,
744 linking of shared libraries, and so on.  @xref{The GNU Build System},
745 for more information.
747 Autoconf imposes some restrictions on the names of macros used with
748 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
750 Autoconf requires @acronym{GNU} M4 version 1.4.6 or later in order to
751 generate the scripts.  It uses features that some versions of M4,
752 including @acronym{GNU} M4 1.3, do not have.  Autoconf works better
753 with @acronym{GNU} M4 version 1.4.13 or later, though this is not
754 required.
756 @xref{Autoconf 1}, for information about upgrading from version 1.
757 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
758 for answers to some common questions about Autoconf.
760 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
761 Autoconf web page} for up-to-date information, details on the mailing
762 lists, pointers to a list of known bugs, etc.
764 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
765 list}.  Past suggestions are
766 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
768 Mail bug reports to @email{bug-autoconf@@gnu.org, the
769 Autoconf Bugs mailing list}.  Past bug reports are
770 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
772 If possible, first check that your bug is
773 not already solved in current development versions, and that it has not
774 been reported yet.  Be sure to include all the needed information and a
775 short @file{configure.ac} that demonstrates the problem.
777 Autoconf's development tree is accessible via @command{git}; see the
778 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
779 Summary} for details, or view
780 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
781 repository}.  Anonymous @acronym{CVS} access is also available, see
782 @file{README} for more details.  Patches relative to the
783 current @command{git} version can be sent for review to the
784 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
785 discussion on prior patches
786 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
787 archived}; and all commits are posted in the read-only
788 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
789 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
790 archived}.
792 Because of its mission, the Autoconf package itself
793 includes only a set of often-used
794 macros that have already demonstrated their usefulness.  Nevertheless,
795 if you wish to share your macros, or find existing ones, see the
796 @uref{http://@/autoconf-archive.cryp.to/, Autoconf Macro
797 Archive}, which is kindly run by @email{simons@@cryp.to,
798 Peter Simons}.
801 @c ================================================= The GNU Build System
803 @node The GNU Build System
804 @chapter The @acronym{GNU} Build System
805 @cindex @acronym{GNU} build system
807 Autoconf solves an important problem---reliable discovery of
808 system-specific build and runtime information---but this is only one
809 piece of the puzzle for the development of portable software.  To this
810 end, the @acronym{GNU} project has developed a suite of integrated
811 utilities to finish the job Autoconf started: the @acronym{GNU} build
812 system, whose most important components are Autoconf, Automake, and
813 Libtool.  In this chapter, we introduce you to those tools, point you
814 to sources of more information, and try to convince you to use the
815 entire @acronym{GNU} build system for your software.
817 @menu
818 * Automake::                    Escaping makefile hell
819 * Gnulib::                      The @acronym{GNU} portability library
820 * Libtool::                     Building libraries portably
821 * Pointers::                    More info on the @acronym{GNU} build system
822 @end menu
824 @node Automake
825 @section Automake
827 The ubiquity of @command{make} means that a makefile is almost the
828 only viable way to distribute automatic build rules for software, but
829 one quickly runs into its numerous limitations.  Its lack of
830 support for automatic dependency tracking, recursive builds in
831 subdirectories, reliable timestamps (e.g., for network file systems), and
832 so on, mean that developers must painfully (and often incorrectly)
833 reinvent the wheel for each project.  Portability is non-trivial, thanks
834 to the quirks of @command{make} on many systems.  On top of all this is the
835 manual labor required to implement the many standard targets that users
836 have come to expect (@code{make install}, @code{make distclean},
837 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
838 you also have to insert repetitive code in your @file{Makefile.in} to
839 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
840 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
841 @cindex Automake
843 Automake allows you to specify your build needs in a @file{Makefile.am}
844 file with a vastly simpler and more powerful syntax than that of a plain
845 makefile, and then generates a portable @file{Makefile.in} for
846 use with Autoconf.  For example, the @file{Makefile.am} to build and
847 install a simple ``Hello world'' program might look like:
849 @example
850 bin_PROGRAMS = hello
851 hello_SOURCES = hello.c
852 @end example
854 @noindent
855 The resulting @file{Makefile.in} (~400 lines) automatically supports all
856 the standard targets, the substitutions provided by Autoconf, automatic
857 dependency tracking, @code{VPATH} building, and so on.  @command{make}
858 builds the @code{hello} program, and @code{make install} installs it
859 in @file{/usr/local/bin} (or whatever prefix was given to
860 @command{configure}, if not @file{/usr/local}).
862 The benefits of Automake increase for larger packages (especially ones
863 with subdirectories), but even for small programs the added convenience
864 and portability can be substantial.  And that's not all@enddots{}
866 @node Gnulib
867 @section Gnulib
869 @acronym{GNU} software has a well-deserved reputation for running on
870 many different types of systems.  While our primary goal is to write
871 software for the @acronym{GNU} system, many users and developers have
872 been introduced to us through the systems that they were already using.
874 @cindex Gnulib
875 Gnulib is a central location for common @acronym{GNU} code, intended to
876 be shared among free software packages.  Its components are typically
877 shared at the source level, rather than being a library that gets built,
878 installed, and linked against.  The idea is to copy files from Gnulib
879 into your own source tree.  There is no distribution tarball; developers
880 should just grab source modules from the repository.  The source files
881 are available online, under various licenses, mostly @acronym{GNU}
882 @acronym{GPL} or @acronym{GNU} @acronym{LGPL}.
884 Gnulib modules typically contain C source code along with Autoconf
885 macros used to configure the source code.  For example, the Gnulib
886 @code{stdbool} module implements a @file{stdbool.h} header that nearly
887 conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
888 This module contains a source file for the replacement header, along
889 with an Autoconf macro that arranges to use the replacement header on
890 old-fashioned systems.
892 @node Libtool
893 @section Libtool
895 Often, one wants to build not only programs, but libraries, so that
896 other programs can benefit from the fruits of your labor.  Ideally, one
897 would like to produce @emph{shared} (dynamically linked) libraries,
898 which can be used by multiple programs without duplication on disk or in
899 memory and can be updated independently of the linked programs.
900 Producing shared libraries portably, however, is the stuff of
901 nightmares---each system has its own incompatible tools, compiler flags,
902 and magic incantations.  Fortunately, @acronym{GNU} provides a solution:
903 @dfn{Libtool}.
904 @cindex Libtool
906 Libtool handles all the requirements of building shared libraries for
907 you, and at this time seems to be the @emph{only} way to do so with any
908 portability.  It also handles many other headaches, such as: the
909 interaction of Make rules with the variable suffixes of
910 shared libraries, linking reliably with shared libraries before they are
911 installed by the superuser, and supplying a consistent versioning system
912 (so that different versions of a library can be installed or upgraded
913 without breaking binary compatibility).  Although Libtool, like
914 Autoconf, can be used without Automake, it is most simply utilized in
915 conjunction with Automake---there, Libtool is used automatically
916 whenever shared libraries are needed, and you need not know its syntax.
918 @node Pointers
919 @section Pointers
921 Developers who are used to the simplicity of @command{make} for small
922 projects on a single system might be daunted at the prospect of
923 learning to use Automake and Autoconf.  As your software is
924 distributed to more and more users, however, you otherwise
925 quickly find yourself putting lots of effort into reinventing the
926 services that the @acronym{GNU} build tools provide, and making the
927 same mistakes that they once made and overcame.  (Besides, since
928 you're already learning Autoconf, Automake is a piece of cake.)
930 There are a number of places that you can go to for more information on
931 the @acronym{GNU} build tools.
933 @itemize @minus
935 @item Web
937 The project home pages for
938 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
939 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
940 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
941 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
943 @item Automake Manual
945 @xref{Top, , Automake, automake, @acronym{GNU} Automake}, for more
946 information on Automake.
948 @item Books
950 The book @cite{@acronym{GNU} Autoconf, Automake and
951 Libtool}@footnote{@cite{@acronym{GNU} Autoconf, Automake and Libtool},
952 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
953 New Riders), 2000, ISBN 1578701902.} describes the complete @acronym{GNU}
954 build environment.  You can also find
955 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
957 @end itemize
959 @c ================================================= Making configure Scripts.
961 @node Making configure Scripts
962 @chapter Making @command{configure} Scripts
963 @cindex @file{aclocal.m4}
964 @cindex @command{configure}
966 The configuration scripts that Autoconf produces are by convention
967 called @command{configure}.  When run, @command{configure} creates several
968 files, replacing configuration parameters in them with appropriate
969 values.  The files that @command{configure} creates are:
971 @itemize @minus
972 @item
973 one or more @file{Makefile} files, usually one in each subdirectory of the
974 package (@pxref{Makefile Substitutions});
976 @item
977 optionally, a C header file, the name of which is configurable,
978 containing @code{#define} directives (@pxref{Configuration Headers});
980 @item
981 a shell script called @file{config.status} that, when run, recreates
982 the files listed above (@pxref{config.status Invocation});
984 @item
985 an optional shell script normally called @file{config.cache}
986 (created when using @samp{configure --config-cache}) that
987 saves the results of running many of the tests (@pxref{Cache Files});
989 @item
990 a file called @file{config.log} containing any messages produced by
991 compilers, to help debugging if @command{configure} makes a mistake.
992 @end itemize
994 @cindex @file{configure.in}
995 @cindex @file{configure.ac}
996 To create a @command{configure} script with Autoconf, you need to write an
997 Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
998 @command{autoconf} on it.  If you write your own feature tests to
999 supplement those that come with Autoconf, you might also write files
1000 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
1001 file to contain @code{#define} directives, you might also run
1002 @command{autoheader}, and you can distribute the generated file
1003 @file{config.h.in} with the package.
1005 Here is a diagram showing how the files that can be used in
1006 configuration are produced.  Programs that are executed are suffixed by
1007 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
1008 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1009 macro files (by reading @file{autoconf.m4}).
1011 @noindent
1012 Files used in preparing a software package for distribution:
1013 @example
1014 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1016 @group
1017 configure.ac --.
1018                |   .------> autoconf* -----> configure
1019 [aclocal.m4] --+---+
1020                |   `-----> [autoheader*] --> [config.h.in]
1021 [acsite.m4] ---'
1022 @end group
1024 Makefile.in -------------------------------> Makefile.in
1025 @end example
1027 @noindent
1028 Files used in configuring a software package:
1029 @example
1030 @group
1031                        .-------------> [config.cache]
1032 configure* ------------+-------------> config.log
1033                        |
1034 [config.h.in] -.       v            .-> [config.h] -.
1035                +--> config.status* -+               +--> make*
1036 Makefile.in ---'                    `-> Makefile ---'
1037 @end group
1038 @end example
1040 @menu
1041 * Writing Autoconf Input::      What to put in an Autoconf input file
1042 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1043 * ifnames Invocation::          Listing the conditionals in source code
1044 * autoconf Invocation::         How to create configuration scripts
1045 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1046 @end menu
1048 @node Writing Autoconf Input
1049 @section Writing @file{configure.ac}
1051 To produce a @command{configure} script for a software package, create a
1052 file called @file{configure.ac} that contains invocations of the
1053 Autoconf macros that test the system features your package needs or can
1054 use.  Autoconf macros already exist to check for many features; see
1055 @ref{Existing Tests}, for their descriptions.  For most other features,
1056 you can use Autoconf template macros to produce custom checks; see
1057 @ref{Writing Tests}, for information about them.  For especially tricky
1058 or specialized features, @file{configure.ac} might need to contain some
1059 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1060 Programming}.  The @command{autoscan} program can give you a good start
1061 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1062 information).
1064 Previous versions of Autoconf promoted the name @file{configure.in},
1065 which is somewhat ambiguous (the tool needed to process this file is not
1066 described by its extension), and introduces a slight confusion with
1067 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1068 processed by @command{configure}'').  Using @file{configure.ac} is now
1069 preferred.
1071 @menu
1072 * Shell Script Compiler::       Autoconf as solution of a problem
1073 * Autoconf Language::           Programming in Autoconf
1074 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1075 @end menu
1077 @node Shell Script Compiler
1078 @subsection A Shell Script Compiler
1080 Just as for any other computer language, in order to properly program
1081 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1082 the language tries to address and @emph{how} it does so.
1084 The problem Autoconf addresses is that the world is a mess.  After all,
1085 you are using Autoconf in order to have your package compile easily on
1086 all sorts of different systems, some of them being extremely hostile.
1087 Autoconf itself bears the price for these differences: @command{configure}
1088 must run on all those systems, and thus @command{configure} must limit itself
1089 to their lowest common denominator of features.
1091 Naturally, you might then think of shell scripts; who needs
1092 @command{autoconf}?  A set of properly written shell functions is enough to
1093 make it easy to write @command{configure} scripts by hand.  Sigh!
1094 Unfortunately, even in 2008, where shells without any function support are
1095 far and few between, there are pitfalls to avoid when making use of them.
1096 Also, finding a Bourne shell that accepts shell functions is not trivial,
1097 even though there is almost always one on interesting porting targets.
1099 So, what is really needed is some kind of compiler, @command{autoconf},
1100 that takes an Autoconf program, @file{configure.ac}, and transforms it
1101 into a portable shell script, @command{configure}.
1103 How does @command{autoconf} perform this task?
1105 There are two obvious possibilities: creating a brand new language or
1106 extending an existing one.  The former option is attractive: all
1107 sorts of optimizations could easily be implemented in the compiler and
1108 many rigorous checks could be performed on the Autoconf program
1109 (e.g., rejecting any non-portable construct).  Alternatively, you can
1110 extend an existing language, such as the @code{sh} (Bourne shell)
1111 language.
1113 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1114 therefore most convenient to implement @command{autoconf} as a macro
1115 expander: a program that repeatedly performs @dfn{macro expansions} on
1116 text input, replacing macro calls with macro bodies and producing a pure
1117 @code{sh} script in the end.  Instead of implementing a dedicated
1118 Autoconf macro expander, it is natural to use an existing
1119 general-purpose macro language, such as M4, and implement the extensions
1120 as a set of M4 macros.
1123 @node Autoconf Language
1124 @subsection The Autoconf Language
1125 @cindex quotation
1127 The Autoconf language differs from many other computer
1128 languages because it treats actual code the same as plain text.  Whereas
1129 in C, for instance, data and instructions have different syntactic
1130 status, in Autoconf their status is rigorously the same.  Therefore, we
1131 need a means to distinguish literal strings from text to be expanded:
1132 quotation.
1134 When calling macros that take arguments, there must not be any white
1135 space between the macro name and the open parenthesis.  Arguments should
1136 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1137 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1138 unless they are quoted.  You should always quote an argument that
1139 might contain a macro name, comma, parenthesis, or a leading blank or
1140 newline.  This rule applies recursively for every macro
1141 call, including macros called from other macros.  For more details on
1142 quoting rules, see @ref{Programming in M4}.
1144 For instance:
1146 @example
1147 AC_CHECK_HEADER([stdio.h],
1148                 [AC_DEFINE([HAVE_STDIO_H], [1],
1149                    [Define to 1 if you have <stdio.h>.])],
1150                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1151 @end example
1153 @noindent
1154 is quoted properly.  You may safely simplify its quotation to:
1156 @example
1157 AC_CHECK_HEADER([stdio.h],
1158                 [AC_DEFINE([HAVE_STDIO_H], 1,
1159                    [Define to 1 if you have <stdio.h>.])],
1160                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1161 @end example
1163 @noindent
1164 because @samp{1} cannot contain a macro call.  Here, the argument of
1165 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1166 interpreted as an argument separator.  Also, the second and third arguments
1167 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1168 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1169 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1170 if you unwisely defined a macro with a name like @samp{Define} or
1171 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1172 would keep the quotes, but many Autoconf users find such precautions
1173 annoying, and would rewrite the example as follows:
1175 @example
1176 AC_CHECK_HEADER(stdio.h,
1177                 [AC_DEFINE(HAVE_STDIO_H, 1,
1178                    [Define to 1 if you have <stdio.h>.])],
1179                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1180 @end example
1182 @noindent
1183 This is safe, so long as you adopt good naming conventions and do not
1184 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1185 @samp{h}.  Though it is also safe here to omit the quotes around
1186 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1187 message strings are more likely to inadvertently contain commas.
1189 The following example is wrong and dangerous, as it is underquoted:
1191 @example
1192 AC_CHECK_HEADER(stdio.h,
1193                 AC_DEFINE(HAVE_STDIO_H, 1,
1194                    Define to 1 if you have <stdio.h>.),
1195                 AC_MSG_ERROR([Sorry, can't do anything for you]))
1196 @end example
1198 In other cases, you may have to use text that also resembles a macro
1199 call.  You must quote that text even when it is not passed as a macro
1200 argument.  For example, these two approaches in @file{configure.ac}
1201 (quoting just the potential problems, or quoting the entire line) will
1202 protect your script in case autoconf ever adds a macro @code{AC_DC}:
1204 @example
1205 echo "Hard rock was here!  --[AC_DC]"
1206 [echo "Hard rock was here!  --AC_DC"]
1207 @end example
1209 @noindent
1210 which results in this text in @file{configure}:
1212 @example
1213 echo "Hard rock was here!  --AC_DC"
1214 echo "Hard rock was here!  --AC_DC"
1215 @end example
1217 @noindent
1218 When you use the same text in a macro argument, you must therefore have
1219 an extra quotation level (since one is stripped away by the macro
1220 substitution).  In general, then, it is a good idea to @emph{use double
1221 quoting for all literal string arguments}, either around just the
1222 problematic portions, or over the entire argument:
1224 @example
1225 AC_MSG_WARN([[AC_DC] stinks  --Iron Maiden])
1226 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1227 @end example
1229 However, the above example triggers a warning about a possibly
1230 unexpanded macro when running @command{autoconf}, because it collides
1231 with the namespace of macros reserved for the Autoconf language.  To be
1232 really safe, you can use additional escaping (either a quadrigraph, or
1233 creative shell constructs) to silence that particular warning:
1235 @example
1236 echo "Hard rock was here!  --AC""_DC"
1237 AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1238 @end example
1240 You are now able to understand one of the constructs of Autoconf that
1241 has been continually misunderstood@enddots{}  The rule of thumb is that
1242 @emph{whenever you expect macro expansion, expect quote expansion};
1243 i.e., expect one level of quotes to be lost.  For instance:
1245 @example
1246 AC_COMPILE_IFELSE([char b[10];], [], [AC_MSG_ERROR([you lose])])
1247 @end example
1249 @noindent
1250 is incorrect: here, the first argument of @code{AC_COMPILE_IFELSE} is
1251 @samp{char b[10];} and is expanded once, which results in
1252 @samp{char b10;}.  (There was an idiom common in Autoconf's past to
1253 address this issue via the M4 @code{changequote} primitive, but do not
1254 use it!)  Let's take a closer look: the author meant the first argument
1255 to be understood as a literal, and therefore it must be quoted twice:
1257 @example
1258 AC_COMPILE_IFELSE([[char b[10];]], [], [AC_MSG_ERROR([you lose])])
1259 @end example
1261 @noindent
1262 Voil@`a, you actually produce @samp{char b[10];} this time!
1264 On the other hand, descriptions (e.g., the last parameter of
1265 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1266 are subject to line breaking, for example---and should not be double quoted.
1267 Even if these descriptions are short and are not actually broken, double
1268 quoting them yields weird results.
1270 Some macros take optional arguments, which this documentation represents
1271 as @ovar{arg} (not to be confused with the quote characters).  You may
1272 just leave them empty, or use @samp{[]} to make the emptiness of the
1273 argument explicit, or you may simply omit the trailing commas.  The
1274 three lines below are equivalent:
1276 @example
1277 AC_CHECK_HEADERS([stdio.h], [], [], [])
1278 AC_CHECK_HEADERS([stdio.h],,,)
1279 AC_CHECK_HEADERS([stdio.h])
1280 @end example
1282 It is best to put each macro call on its own line in
1283 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1284 rely on the newline after the macro call to terminate the commands.
1285 This approach makes the generated @command{configure} script a little
1286 easier to read by not inserting lots of blank lines.  It is generally
1287 safe to set shell variables on the same line as a macro call, because
1288 the shell allows assignments without intervening newlines.
1290 You can include comments in @file{configure.ac} files by starting them
1291 with the @samp{#}.  For example, it is helpful to begin
1292 @file{configure.ac} files with a line like this:
1294 @example
1295 # Process this file with autoconf to produce a configure script.
1296 @end example
1298 @node Autoconf Input Layout
1299 @subsection Standard @file{configure.ac} Layout
1301 The order in which @file{configure.ac} calls the Autoconf macros is not
1302 important, with a few exceptions.  Every @file{configure.ac} must
1303 contain a call to @code{AC_INIT} before the checks, and a call to
1304 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1305 rely on other macros having been called first, because they check
1306 previously set values of some variables to decide what to do.  These
1307 macros are noted in the individual descriptions (@pxref{Existing
1308 Tests}), and they also warn you when @command{configure} is created if they
1309 are called out of order.
1311 To encourage consistency, here is a suggested order for calling the
1312 Autoconf macros.  Generally speaking, the things near the end of this
1313 list are those that could depend on things earlier in it.  For example,
1314 library functions could be affected by types and libraries.
1316 @display
1317 @group
1318 Autoconf requirements
1319 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1320 information on the package
1321 checks for programs
1322 checks for libraries
1323 checks for header files
1324 checks for types
1325 checks for structures
1326 checks for compiler characteristics
1327 checks for library functions
1328 checks for system services
1329 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1330 @code{AC_OUTPUT}
1331 @end group
1332 @end display
1335 @node autoscan Invocation
1336 @section Using @command{autoscan} to Create @file{configure.ac}
1337 @cindex @command{autoscan}
1339 The @command{autoscan} program can help you create and/or maintain a
1340 @file{configure.ac} file for a software package.  @command{autoscan}
1341 examines source files in the directory tree rooted at a directory given
1342 as a command line argument, or the current directory if none is given.
1343 It searches the source files for common portability problems and creates
1344 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1345 for that package, and checks a possibly existing @file{configure.ac} for
1346 completeness.
1348 When using @command{autoscan} to create a @file{configure.ac}, you
1349 should manually examine @file{configure.scan} before renaming it to
1350 @file{configure.ac}; it probably needs some adjustments.
1351 Occasionally, @command{autoscan} outputs a macro in the wrong order
1352 relative to another macro, so that @command{autoconf} produces a warning;
1353 you need to move such macros manually.  Also, if you want the package to
1354 use a configuration header file, you must add a call to
1355 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1356 also have to change or add some @code{#if} directives to your program in
1357 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1358 information about a program that can help with that job).
1360 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1361 consider adding its suggestions.  The file @file{autoscan.log}
1362 contains detailed information on why a macro is requested.
1364 @command{autoscan} uses several data files (installed along with Autoconf)
1365 to determine which macros to output when it finds particular symbols in
1366 a package's source files.  These data files all have the same format:
1367 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1368 output if that symbol is encountered.  Lines starting with @samp{#} are
1369 comments.
1371 @command{autoscan} accepts the following options:
1373 @table @option
1374 @item --help
1375 @itemx -h
1376 Print a summary of the command line options and exit.
1378 @item --version
1379 @itemx -V
1380 Print the version number of Autoconf and exit.
1382 @item --verbose
1383 @itemx -v
1384 Print the names of the files it examines and the potentially interesting
1385 symbols it finds in them.  This output can be voluminous.
1387 @item --debug
1388 @itemx -d
1389 Don't remove temporary files.
1391 @item --include=@var{dir}
1392 @itemx -I @var{dir}
1393 Append @var{dir} to the include path.  Multiple invocations accumulate.
1395 @item --prepend-include=@var{dir}
1396 @itemx -B @var{dir}
1397 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1398 @end table
1400 @node ifnames Invocation
1401 @section Using @command{ifnames} to List Conditionals
1402 @cindex @command{ifnames}
1404 @command{ifnames} can help you write @file{configure.ac} for a software
1405 package.  It prints the identifiers that the package already uses in C
1406 preprocessor conditionals.  If a package has already been set up to have
1407 some portability, @command{ifnames} can thus help you figure out what its
1408 @command{configure} needs to check for.  It may help fill in some gaps in a
1409 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1410 Invocation}).
1412 @command{ifnames} scans all of the C source files named on the command line
1413 (or the standard input, if none are given) and writes to the standard
1414 output a sorted list of all the identifiers that appear in those files
1415 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1416 directives.  It prints each identifier on a line, followed by a
1417 space-separated list of the files in which that identifier occurs.
1419 @noindent
1420 @command{ifnames} accepts the following options:
1422 @table @option
1423 @item --help
1424 @itemx -h
1425 Print a summary of the command line options and exit.
1427 @item --version
1428 @itemx -V
1429 Print the version number of Autoconf and exit.
1430 @end table
1432 @node autoconf Invocation
1433 @section Using @command{autoconf} to Create @command{configure}
1434 @cindex @command{autoconf}
1436 To create @command{configure} from @file{configure.ac}, run the
1437 @command{autoconf} program with no arguments.  @command{autoconf} processes
1438 @file{configure.ac} with the M4 macro processor, using the
1439 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1440 file instead of @file{configure.ac} and writes the configuration script
1441 to the standard output instead of to @command{configure}.  If you give
1442 @command{autoconf} the argument @option{-}, it reads from the standard
1443 input instead of @file{configure.ac} and writes the configuration script
1444 to the standard output.
1446 The Autoconf macros are defined in several files.  Some of the files are
1447 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1448 looks for the optional file @file{acsite.m4} in the directory that
1449 contains the distributed Autoconf macro files, and for the optional file
1450 @file{aclocal.m4} in the current directory.  Those files can contain
1451 your site's or the package's own Autoconf macro definitions
1452 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1453 defined in more than one of the files that @command{autoconf} reads, the
1454 last definition it reads overrides the earlier ones.
1456 @command{autoconf} accepts the following options:
1458 @table @option
1459 @item --help
1460 @itemx -h
1461 Print a summary of the command line options and exit.
1463 @item --version
1464 @itemx -V
1465 Print the version number of Autoconf and exit.
1467 @item --verbose
1468 @itemx -v
1469 Report processing steps.
1471 @item --debug
1472 @itemx -d
1473 Don't remove the temporary files.
1475 @item --force
1476 @itemx -f
1477 Remake @file{configure} even if newer than its input files.
1479 @item --include=@var{dir}
1480 @itemx -I @var{dir}
1481 Append @var{dir} to the include path.  Multiple invocations accumulate.
1483 @item --prepend-include=@var{dir}
1484 @itemx -B @var{dir}
1485 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1487 @item --output=@var{file}
1488 @itemx -o @var{file}
1489 Save output (script or trace) to @var{file}.  The file @option{-} stands
1490 for the standard output.
1492 @item --warnings=@var{category}
1493 @itemx -W @var{category}
1494 @evindex WARNINGS
1495 Report the warnings related to @var{category} (which can actually be a
1496 comma separated list).  @xref{Reporting Messages}, macro
1497 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1498 values include:
1500 @table @samp
1501 @item all
1502 report all the warnings
1504 @item none
1505 report none
1507 @item error
1508 treats warnings as errors
1510 @item no-@var{category}
1511 disable warnings falling into @var{category}
1512 @end table
1514 Warnings about @samp{syntax} are enabled by default, and the environment
1515 variable @env{WARNINGS}, a comma separated list of categories, is
1516 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1517 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1518 disable the defaults and @env{WARNINGS}, and then
1519 enable warnings about obsolete constructs, use @option{-W
1520 none,obsolete}.
1522 @cindex Back trace
1523 @cindex Macro invocation stack
1524 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1525 displays a back trace for errors, but not for warnings; if you want
1526 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1527 examples.
1529 @item --trace=@var{macro}[:@var{format}]
1530 @itemx -t @var{macro}[:@var{format}]
1531 Do not create the @command{configure} script, but list the calls to
1532 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1533 arguments can be used to list several macros.  Multiple @option{--trace}
1534 arguments for a single macro are not cumulative; instead, you should
1535 just make @var{format} as long as needed.
1537 The @var{format} is a regular string, with newlines if desired, and
1538 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1539 @ref{autom4te Invocation}, for details on the @var{format}.
1541 @item --initialization
1542 @itemx -i
1543 By default, @option{--trace} does not trace the initialization of the
1544 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1545 results in a noticeable speedup, but can be disabled by this option.
1546 @end table
1549 It is often necessary to check the content of a @file{configure.ac}
1550 file, but parsing it yourself is extremely fragile and error-prone.  It
1551 is suggested that you rely upon @option{--trace} to scan
1552 @file{configure.ac}.  For instance, to find the list of variables that
1553 are substituted, use:
1555 @example
1556 @group
1557 $ @kbd{autoconf -t AC_SUBST}
1558 configure.ac:2:AC_SUBST:ECHO_C
1559 configure.ac:2:AC_SUBST:ECHO_N
1560 configure.ac:2:AC_SUBST:ECHO_T
1561 @i{More traces deleted}
1562 @end group
1563 @end example
1565 @noindent
1566 The example below highlights the difference between @samp{$@@},
1567 @samp{$*}, and @samp{$%}.
1569 @example
1570 @group
1571 $ @kbd{cat configure.ac}
1572 AC_DEFINE(This, is, [an
1573 [example]])
1574 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1575 *: $*
1576 %: $%'
1577 @@: [This],[is],[an
1578 [example]]
1579 *: This,is,an
1580 [example]
1581 %: This:is:an [example]
1582 @end group
1583 @end example
1585 @noindent
1586 The @var{format} gives you a lot of freedom:
1588 @example
1589 @group
1590 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1591 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1592 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1593 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1594 @i{More traces deleted}
1595 @end group
1596 @end example
1598 @noindent
1599 A long @var{separator} can be used to improve the readability of complex
1600 structures, and to ease their parsing (for instance when no single
1601 character is suitable as a separator):
1603 @example
1604 @group
1605 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1606 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1607 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1608 AUTOMAKE|:::::|automake|:::::|$missing_dir
1609 @i{More traces deleted}
1610 @end group
1611 @end example
1613 @node autoreconf Invocation
1614 @section Using @command{autoreconf} to Update @command{configure} Scripts
1615 @cindex @command{autoreconf}
1617 Installing the various components of the @acronym{GNU} Build System can be
1618 tedious: running @command{autopoint} for Gettext, @command{automake} for
1619 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1620 because some tools such as @command{automake} have been updated on your
1621 system, or because some of the sources such as @file{configure.ac} have
1622 been updated, or finally, simply in order to install the @acronym{GNU} Build
1623 System in a fresh tree.
1625 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1626 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1627 @command{autopoint} (when appropriate) repeatedly to update the
1628 @acronym{GNU} Build System in the specified directories and their
1629 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1630 those files that are older than their sources.  The environment variables
1631 @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL},
1632 @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE} may be used
1633 to override the invocation of the respective tools.
1635 If you install a new version of some tool, you can make
1636 @command{autoreconf} remake @emph{all} of the files by giving it the
1637 @option{--force} option.
1639 @xref{Automatic Remaking}, for Make rules to automatically
1640 rebuild @command{configure} scripts when their source files change.  That
1641 method handles the timestamps of configuration header templates
1642 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1643 @option{--localdir=@var{dir}}.
1645 @cindex Gettext
1646 @cindex @command{autopoint}
1647 Gettext supplies the @command{autopoint} command to add translation
1648 infrastructure to a source package.  If you use @command{autopoint},
1649 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1650 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1651 Invocation, , Invoking the @code{autopoint} Program, gettext,
1652 @acronym{GNU} @code{gettext} utilities}, for further details.
1654 @noindent
1655 @command{autoreconf} accepts the following options:
1657 @table @option
1658 @item --help
1659 @itemx -h
1660 Print a summary of the command line options and exit.
1662 @item --version
1663 @itemx -V
1664 Print the version number of Autoconf and exit.
1666 @item --verbose
1667 @itemx -V
1668 Print the name of each directory @command{autoreconf} examines and the
1669 commands it runs.  If given two or more times, pass @option{--verbose}
1670 to subordinate tools that support it.
1672 @item --debug
1673 @itemx -d
1674 Don't remove the temporary files.
1676 @item --force
1677 @itemx -f
1678 Remake even @file{configure} scripts and configuration headers that are
1679 newer than their input files (@file{configure.ac} and, if present,
1680 @file{aclocal.m4}).
1682 @item --install
1683 @itemx -i
1684 Install the missing auxiliary files in the package.  By default, files
1685 are copied; this can be changed with @option{--symlink}.
1687 If deemed appropriate, this option triggers calls to
1688 @samp{automake --add-missing},
1689 @samp{libtoolize}, @samp{autopoint}, etc.
1691 @item --no-recursive
1692 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1693 macro @code{AC_CONFIG_SUBDIRS}).
1695 @item --symlink
1696 @itemx -s
1697 When used with @option{--install}, install symbolic links to the missing
1698 auxiliary files instead of copying them.
1700 @item --make
1701 @itemx -m
1702 When the directories were configured, update the configuration by
1703 running @samp{./config.status --recheck && ./config.status}, and then
1704 run @samp{make}.
1706 @item --include=@var{dir}
1707 @itemx -I @var{dir}
1708 Append @var{dir} to the include path.  Multiple invocations accumulate.
1709 Passed on to @command{aclocal}, @command{autoconf} and
1710 @command{autoheader} internally.
1712 @item --prepend-include=@var{dir}
1713 @itemx -B @var{dir}
1714 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1715 Passed on to @command{autoconf} and @command{autoheader} internally.
1717 @item --warnings=@var{category}
1718 @itemx -W @var{category}
1719 @evindex WARNINGS
1720 Report the warnings related to @var{category} (which can actually be a
1721 comma separated list).
1723 @table @samp
1724 @item cross
1725 related to cross compilation issues.
1727 @item obsolete
1728 report the uses of obsolete constructs.
1730 @item portability
1731 portability issues
1733 @item syntax
1734 dubious syntactic constructs.
1736 @item all
1737 report all the warnings
1739 @item none
1740 report none
1742 @item error
1743 treats warnings as errors
1745 @item no-@var{category}
1746 disable warnings falling into @var{category}
1747 @end table
1749 Warnings about @samp{syntax} are enabled by default, and the environment
1750 variable @env{WARNINGS}, a comma separated list of categories, is
1751 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1752 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1753 disable the defaults and @env{WARNINGS}, and then
1754 enable warnings about obsolete constructs, use @option{-W
1755 none,obsolete}.
1756 @end table
1758 If you want @command{autoreconf} to pass flags that are not listed here
1759 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1760 Due to a limitation in the Autoconf implementation these flags currently
1761 must be set on a single line in @file{Makefile.am}, without any
1762 backslash-newlines.
1764 @c ========================================= Initialization and Output Files.
1766 @node Setup
1767 @chapter Initialization and Output Files
1769 Autoconf-generated @command{configure} scripts need some information about
1770 how to initialize, such as how to find the package's source files and
1771 about the output files to produce.  The following sections describe the
1772 initialization and the creation of output files.
1774 @menu
1775 * Initializing configure::      Option processing etc.
1776 * Versioning::                  Dealing with Autoconf versions
1777 * Notices::                     Copyright, version numbers in @command{configure}
1778 * Input::                       Where Autoconf should find files
1779 * Output::                      Outputting results from the configuration
1780 * Configuration Actions::       Preparing the output based on results
1781 * Configuration Files::         Creating output files
1782 * Makefile Substitutions::      Using output variables in makefiles
1783 * Configuration Headers::       Creating a configuration header file
1784 * Configuration Commands::      Running arbitrary instantiation commands
1785 * Configuration Links::         Links depending on the configuration
1786 * Subdirectories::              Configuring independent packages together
1787 * Default Prefix::              Changing the default installation prefix
1788 @end menu
1790 @node Initializing configure
1791 @section Initializing @command{configure}
1793 Every @command{configure} script must call @code{AC_INIT} before doing
1794 anything else that produces output.  Calls to silent macros, such as
1795 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1796 are generally used via @file{aclocal.m4}, since that is implicitly
1797 included before the start of @file{configure.ac}.  The only other
1798 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1800 @anchor{AC_INIT}
1801 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1802   @ovar{tarname}, @ovar{url})
1803 @acindex{INIT}
1804 Process any command-line arguments and perform various initializations
1805 and verifications.
1807 Set the name of the @var{package} and its @var{version}.  These are
1808 typically used in @option{--version} support, including that of
1809 @command{configure}.  The optional argument @var{bug-report} should be
1810 the email to which users should send bug reports.  The package
1811 @var{tarname} differs from @var{package}: the latter designates the full
1812 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1813 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1814 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1815 other than alphanumerics and underscores are changed to @samp{-}.  If
1816 provided, @var{url} should be the home page for the package.
1818 It is preferable that the arguments of @code{AC_INIT} be static, i.e.,
1819 there should not be any shell computation, but they can be computed by
1822 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1823 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1824 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1826 @table @asis
1827 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1828 @acindex{PACKAGE_NAME}
1829 @ovindex PACKAGE_NAME
1830 @cvindex PACKAGE_NAME
1831 Exactly @var{package}.
1833 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1834 @acindex{PACKAGE_TARNAME}
1835 @ovindex PACKAGE_TARNAME
1836 @cvindex PACKAGE_TARNAME
1837 Exactly @var{tarname}, possibly generated from @var{package}.
1839 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1840 @acindex{PACKAGE_VERSION}
1841 @ovindex PACKAGE_VERSION
1842 @cvindex PACKAGE_VERSION
1843 Exactly @var{version}.
1845 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1846 @acindex{PACKAGE_STRING}
1847 @ovindex PACKAGE_STRING
1848 @cvindex PACKAGE_STRING
1849 Exactly @samp{@var{package} @var{version}}.
1851 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1852 @acindex{PACKAGE_BUGREPORT}
1853 @ovindex PACKAGE_BUGREPORT
1854 @cvindex PACKAGE_BUGREPORT
1855 Exactly @var{bug-report}, if one was provided.
1857 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1858 @acindex{PACKAGE_URL}
1859 @ovindex PACKAGE_URL
1860 @cvindex PACKAGE_URL
1861 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1862 @var{package} begins with @samp{GNU }, then this defaults to
1863 @samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1864 assumed.
1865 @end table
1866 @end defmac
1868 If your @command{configure} script does its own option processing, it
1869 should inspect @samp{$@@} or @samp{$*} immediately after calling
1870 @code{AC_INIT}, because other Autoconf macros liberally use the
1871 @command{set} command to process strings, and this has the side effect
1872 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1873 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1874 implement your own option processing.  @xref{Site Configuration}.
1876 @node Versioning
1877 @section Dealing with Autoconf versions
1878 @cindex Autoconf version
1879 @cindex version, Autoconf
1881 The following optional macros can be used to help choose the minimum
1882 version of Autoconf that can successfully compile a given
1883 @file{configure.ac}.
1885 @defmac AC_PREREQ (@var{version})
1886 @acindex{PREREQ}
1887 @cindex Version
1888 Ensure that a recent enough version of Autoconf is being used.  If the
1889 version of Autoconf being used to create @command{configure} is
1890 earlier than @var{version}, print an error message to the standard
1891 error output and exit with failure (exit status is 63).  For example:
1893 @example
1894 AC_PREREQ([@value{VERSION}])
1895 @end example
1897 This macro may be used before @code{AC_INIT}.
1898 @end defmac
1900 @defmac AC_AUTOCONF_VERSION
1901 @acindex{AUTOCONF_VERSION}
1902 This macro was introduced in Autoconf 2.62.  It identifies the version
1903 of Autoconf that is currently parsing the input file, in a format
1904 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1905 other words, for this release of Autoconf, its value is
1906 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1907 conditional fallbacks based on when a feature was added to Autoconf,
1908 rather than using @code{AC_PREREQ} to require the newer version of
1909 Autoconf.  However, remember that the Autoconf philosophy favors feature
1910 checks over version checks.
1912 You should not expand this macro directly; use
1913 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1914 users might
1915 have a beta version of Autoconf installed, with arbitrary letters
1916 included in its version string.  This means it is possible for the
1917 version string to contain the name of a defined macro, such that
1918 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1919 macro during rescanning, and change the version string to be different
1920 than what you intended to check.
1921 @end defmac
1923 @node Notices
1924 @section Notices in @command{configure}
1925 @cindex Notices in @command{configure}
1927 The following macros manage version numbers for @command{configure}
1928 scripts.  Using them is optional.
1930 @defmac AC_COPYRIGHT (@var{copyright-notice})
1931 @acindex{COPYRIGHT}
1932 @cindex Copyright Notice
1933 State that, in addition to the Free Software Foundation's copyright on
1934 the Autoconf macros, parts of your @command{configure} are covered by the
1935 @var{copyright-notice}.
1937 The @var{copyright-notice} shows up in both the head of
1938 @command{configure} and in @samp{configure --version}.
1939 @end defmac
1942 @defmac AC_REVISION (@var{revision-info})
1943 @acindex{REVISION}
1944 @cindex Revision
1945 Copy revision stamp @var{revision-info} into the @command{configure}
1946 script, with any dollar signs or double-quotes removed.  This macro lets
1947 you put a revision stamp from @file{configure.ac} into @command{configure}
1948 without @acronym{RCS} or @acronym{CVS} changing it when you check in
1949 @command{configure}.  That way, you can determine easily which revision of
1950 @file{configure.ac} a particular @command{configure} corresponds to.
1952 For example, this line in @file{configure.ac}:
1954 @c The @w prevents RCS from changing the example in the manual.
1955 @example
1956 AC_REVISION([@w{$}Revision: 1.30 $])
1957 @end example
1959 @noindent
1960 produces this in @command{configure}:
1962 @example
1963 #!/bin/sh
1964 # From configure.ac Revision: 1.30
1965 @end example
1966 @end defmac
1969 @node Input
1970 @section Finding @command{configure} Input
1972 @anchor{AC_CONFIG_SRCDIR}
1973 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
1974 @acindex{CONFIG_SRCDIR}
1975 @var{unique-file-in-source-dir} is some file that is in the package's
1976 source directory; @command{configure} checks for this file's existence to
1977 make sure that the directory that it is told contains the source code in
1978 fact does.  Occasionally people accidentally specify the wrong directory
1979 with @option{--srcdir}; this is a safety check.  @xref{configure
1980 Invocation}, for more information.
1981 @end defmac
1984 @c FIXME: Remove definitively once --install explained.
1986 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
1987 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
1988 @c to split the macros in several files.  In this case, Autoconf must be
1989 @c told which files to load, and in which order.
1991 @c @defmac AC_INCLUDE (@var{file}@dots{})
1992 @c @acindex{INCLUDE}
1993 @c @c FIXME: There is no longer shell globbing.
1994 @c Read the macro definitions that appear in the listed files.  A list of
1995 @c space-separated file names or shell globbing patterns is expected.  The
1996 @c files are read in the order they're listed.
1998 @c Because the order of definition of macros is important (only the last
1999 @c definition of a macro is used), beware that it is @code{AC_INIT} that
2000 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
2001 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
2002 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
2003 @c the latter case, non-macro lines from included files may end up in the
2004 @c @file{configure} script, whereas in the former case, they'd be discarded
2005 @c just like any text that appear before @code{AC_INIT}.
2006 @c @end defmac
2008 Packages that do manual configuration or use the @command{install} program
2009 might need to tell @command{configure} where to find some other shell
2010 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
2011 it looks are correct for most cases.
2013 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2014 @acindex{CONFIG_AUX_DIR}
2015 Use the auxiliary build tools (e.g., @file{install-sh},
2016 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
2017 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
2018 These are auxiliary files used in configuration.  @var{dir} can be
2019 either absolute or relative to @file{@var{srcdir}}.  The default is
2020 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
2021 @file{@var{srcdir}/../..}, whichever is the first that contains
2022 @file{install-sh}.  The other files are not checked for, so that using
2023 @code{AC_PROG_INSTALL} does not automatically require distributing the
2024 other auxiliary files.  It checks for @file{install.sh} also, but that
2025 name is obsolete because some @command{make} have a rule that creates
2026 @file{install} from it if there is no makefile.
2028 The auxiliary directory is commonly named @file{build-aux}.
2029 If you need portability to @acronym{DOS} variants, do not name the
2030 auxiliary directory @file{aux}.  @xref{File System Conventions}.
2031 @end defmac
2033 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2034 @acindex{REQUIRE_AUX_FILE}
2035 Declares that @var{file} is expected in the directory defined above.  In
2036 Autoconf proper, this macro does nothing: its sole purpose is to be
2037 traced by third-party tools to produce a list of expected auxiliary
2038 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
2039 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2040 (@pxref{Canonicalizing}) to register the auxiliary files they need.
2041 @end defmac
2043 Similarly, packages that use @command{aclocal} should declare where
2044 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
2046 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
2047 @acindex{CONFIG_MACRO_DIR}
2048 Specify @var{dir} as the location of additional local Autoconf macros.
2049 This macro is intended for use by future versions of commands like
2050 @command{autoreconf} that trace macro calls.  It should be called
2051 directly from @file{configure.ac} so that tools that install macros for
2052 @command{aclocal} can find the macros' declarations.
2054 Note that if you use @command{aclocal} from Automake to generate
2055 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
2056 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
2057 the Autoconf implementation of @command{autoreconf}, these include
2058 directives currently must be set on a single line in @file{Makefile.am},
2059 without any backslash-newlines.
2060 @end defmac
2063 @node Output
2064 @section Outputting Files
2065 @cindex Outputting files
2067 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2068 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2069 @file{config.status}, which in turn creates the makefiles and any
2070 other files resulting from configuration.  This is the only required
2071 macro besides @code{AC_INIT} (@pxref{Input}).
2073 @anchor{AC_OUTPUT}
2074 @defmac AC_OUTPUT
2075 @acindex{OUTPUT}
2076 @cindex Instantiation
2077 Generate @file{config.status} and launch it.  Call this macro once, at
2078 the end of @file{configure.ac}.
2080 @file{config.status} performs all the configuration actions: all the
2081 output files (see @ref{Configuration Files}, macro
2082 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2083 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2084 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2085 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2086 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2087 are honored.
2089 The location of your @code{AC_OUTPUT} invocation is the exact point
2090 where configuration actions are taken: any code afterwards is
2091 executed by @command{configure} once @command{config.status} was run.  If
2092 you want to bind actions to @command{config.status} itself
2093 (independently of whether @command{configure} is being run), see
2094 @ref{Configuration Commands, , Running Arbitrary Configuration
2095 Commands}.
2096 @end defmac
2098 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2099 @xref{Obsolete Macros}, for a description of the arguments that
2100 @code{AC_OUTPUT} used to support.
2103 If you run @command{make} in subdirectories, you should run it using the
2104 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2105 @code{MAKE} to the name of the @command{make} program plus any options it
2106 was given.  (But many do not include in it the values of any variables
2107 set on the command line, so those are not passed on automatically.)
2108 Some old versions of @command{make} do not set this variable.  The
2109 following macro allows you to use it even with those versions.
2111 @anchor{AC_PROG_MAKE_SET}
2112 @defmac AC_PROG_MAKE_SET
2113 @acindex{PROG_MAKE_SET}
2114 @ovindex SET_MAKE
2115 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2116 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2117 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2118 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2119 @code{SET_MAKE}.
2120 @end defmac
2122 If you use this macro, place a line like this in each @file{Makefile.in}
2123 that runs @command{MAKE} on other directories:
2125 @example
2126 @@SET_MAKE@@
2127 @end example
2131 @node Configuration Actions
2132 @section Performing Configuration Actions
2133 @cindex Configuration actions
2135 @file{configure} is designed so that it appears to do everything itself,
2136 but there is actually a hidden slave: @file{config.status}.
2137 @file{configure} is in charge of examining your system, but it is
2138 @file{config.status} that actually takes the proper actions based on the
2139 results of @file{configure}.  The most typical task of
2140 @file{config.status} is to @emph{instantiate} files.
2142 @acindex{CONFIG_@var{ITEMS}}
2143 This section describes the common behavior of the four standard
2144 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2145 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2146 have this prototype:
2148 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2149 @c awful.
2150 @example
2151 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, [@var{commands}], [@var{init-cmds}])
2152 @end example
2154 @noindent
2155 where the arguments are:
2157 @table @var
2158 @item tag@dots{}
2159 A blank-or-newline-separated list of tags, which are typically the names of
2160 the files to instantiate.
2162 You are encouraged to use literals as @var{tags}.  In particular, you
2163 should avoid
2165 @example
2166 @dots{} && my_foos="$my_foos fooo"
2167 @dots{} && my_foos="$my_foos foooo"
2168 AC_CONFIG_@var{ITEMS}([$my_foos])
2169 @end example
2171 @noindent
2172 and use this instead:
2174 @example
2175 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2176 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2177 @end example
2179 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2180 special @var{tag} values: they may have the form @samp{@var{output}} or
2181 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2182 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2184 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk)]},
2185 for example, asks for
2186 the creation of the file @file{Makefile} that contains the expansion of the
2187 output variables in the concatenation of @file{boiler/top.mk} and
2188 @file{boiler/bot.mk}.
2190 The special value @samp{-} might be used to denote the standard output
2191 when used in @var{output}, or the standard input when used in the
2192 @var{inputs}.  You most probably don't need to use this in
2193 @file{configure.ac}, but it is convenient when using the command line
2194 interface of @file{./config.status}, see @ref{config.status Invocation},
2195 for more details.
2197 The @var{inputs} may be absolute or relative file names.  In the latter
2198 case they are first looked for in the build tree, and then in the source
2199 tree.  Input files should be text files, and a line length below 2000
2200 bytes should be safe.
2202 @item commands
2203 Shell commands output literally into @file{config.status}, and
2204 associated with a tag that the user can use to tell @file{config.status}
2205 which commands to run.  The commands are run each time a @var{tag}
2206 request is given to @file{config.status}, typically each time the file
2207 @file{@var{tag}} is created.
2209 The variables set during the execution of @command{configure} are
2210 @emph{not} available here: you first need to set them via the
2211 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2213 @table @code
2214 @item srcdir
2215 The name of the top source directory, assuming that the working
2216 directory is the top build directory.  This
2217 is what the @command{configure} option @option{--srcdir} sets.
2219 @item ac_top_srcdir
2220 The name of the top source directory, assuming that the working
2221 directory is the current build directory.
2223 @item ac_top_build_prefix
2224 The name of the top build directory, assuming that the working
2225 directory is the current build directory.
2226 It can be empty, or else ends with a slash, so that you may concatenate
2229 @item ac_srcdir
2230 The name of the corresponding source directory, assuming that the
2231 working directory is the current build directory.
2233 @item tmp
2234 The name of a temporary directory within the build tree, which you
2235 can use if you need to create additional temporary files.  The
2236 directory is cleaned up when @command{config.status} is done or
2237 interrupted.  Please use package-specific file name prefixes to
2238 avoid clashing with files that @command{config.status} may use
2239 internally.
2240 @end table
2242 @noindent
2243 The @dfn{current} directory refers to the directory (or
2244 pseudo-directory) containing the input part of @var{tags}.  For
2245 instance, running
2247 @example
2248 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2249 @end example
2251 @noindent
2252  with @option{--srcdir=../package} produces the following values:
2254 @example
2255 # Argument of --srcdir
2256 srcdir='../package'
2257 # Reversing deep/dir
2258 ac_top_build_prefix='../../'
2259 # Concatenation of $ac_top_build_prefix and srcdir
2260 ac_top_srcdir='../../../package'
2261 # Concatenation of $ac_top_srcdir and deep/dir
2262 ac_srcdir='../../../package/deep/dir'
2263 @end example
2265 @noindent
2266 independently of @samp{in/in.in}.
2268 @item init-cmds
2269 Shell commands output @emph{unquoted} near the beginning of
2270 @file{config.status}, and executed each time @file{config.status} runs
2271 (regardless of the tag).  Because they are unquoted, for example,
2272 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2273 is typically used by @file{configure} to give @file{config.status} some
2274 variables it needs to run the @var{commands}.
2276 You should be extremely cautious in your variable names: all the
2277 @var{init-cmds} share the same name space and may overwrite each other
2278 in unpredictable ways.  Sorry@enddots{}
2279 @end table
2281 All these macros can be called multiple times, with different
2282 @var{tag} values, of course!
2285 @node Configuration Files
2286 @section Creating Configuration Files
2287 @cindex Creating configuration files
2288 @cindex Configuration file creation
2290 Be sure to read the previous section, @ref{Configuration Actions}.
2292 @anchor{AC_CONFIG_FILES}
2293 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2294 @acindex{CONFIG_FILES}
2295 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2296 file (by default @file{@var{file}.in}), substituting the output variable
2297 values.
2298 @c Before we used to have this feature, which was later rejected
2299 @c because it complicates the writing of makefiles:
2300 @c If the file would be unchanged, it is left untouched, to preserve
2301 @c timestamp.
2302 This macro is one of the instantiating macros; see @ref{Configuration
2303 Actions}.  @xref{Makefile Substitutions}, for more information on using
2304 output variables.  @xref{Setting Output Variables}, for more information
2305 on creating them.  This macro creates the directory that the file is in
2306 if it doesn't exist.  Usually, makefiles are created this way,
2307 but other files, such as @file{.gdbinit}, can be specified as well.
2309 Typical calls to @code{AC_CONFIG_FILES} look like this:
2311 @example
2312 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2313 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2314 @end example
2316 You can override an input file name by appending to @var{file} a
2317 colon-separated list of input files.  Examples:
2319 @example
2320 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2321                 [lib/Makefile:boiler/lib.mk])
2322 @end example
2324 @noindent
2325 Doing this allows you to keep your file names acceptable to
2326 @acronym{DOS} variants, or
2327 to prepend and/or append boilerplate to the file.
2328 @end defmac
2332 @node Makefile Substitutions
2333 @section Substitutions in Makefiles
2334 @cindex Substitutions in makefiles
2335 @cindex Makefile substitutions
2337 Each subdirectory in a distribution that contains something to be
2338 compiled or installed should come with a file @file{Makefile.in}, from
2339 which @command{configure} creates a file @file{Makefile} in that directory.
2340 To create @file{Makefile}, @command{configure} performs a simple variable
2341 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2342 @file{Makefile.in} with the value that @command{configure} has determined
2343 for that variable.  Variables that are substituted into output files in
2344 this way are called @dfn{output variables}.  They are ordinary shell
2345 variables that are set in @command{configure}.  To make @command{configure}
2346 substitute a particular variable into the output files, the macro
2347 @code{AC_SUBST} must be called with that variable name as an argument.
2348 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2349 left unchanged.  @xref{Setting Output Variables}, for more information
2350 on creating output variables with @code{AC_SUBST}.
2352 A software package that uses a @command{configure} script should be
2353 distributed with a file @file{Makefile.in}, but no makefile; that
2354 way, the user has to properly configure the package for the local system
2355 before compiling it.
2357 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2358 @acronym{GNU} Coding Standards}, for more information on what to put in
2359 makefiles.
2361 @menu
2362 * Preset Output Variables::     Output variables that are always set
2363 * Installation Directory Variables::  Other preset output variables
2364 * Changed Directory Variables:: Warnings about @file{datarootdir}
2365 * Build Directories::           Supporting multiple concurrent compiles
2366 * Automatic Remaking::          Makefile rules for configuring
2367 @end menu
2369 @node Preset Output Variables
2370 @subsection Preset Output Variables
2371 @cindex Output variables
2373 Some output variables are preset by the Autoconf macros.  Some of the
2374 Autoconf macros set additional output variables, which are mentioned in
2375 the descriptions for those macros.  @xref{Output Variable Index}, for a
2376 complete list of output variables.  @xref{Installation Directory
2377 Variables}, for the list of the preset ones related to installation
2378 directories.  Below are listed the other preset ones, many of which are
2379 precious variables (@pxref{Setting Output Variables},
2380 @code{AC_ARG_VAR}).
2382 The preset variables which are available during @file{config.status}
2383 (@pxref{Configuration Actions}) may also be used during
2384 @command{configure} tests.  For example, it is permissible to reference
2385 @samp{$srcdir} when constructing a list of directories to pass via
2386 option @option{-I} during a compiler feature check.  When used in this
2387 manner, coupled with the fact that @command{configure} is always run
2388 from the top build directory, it is sufficient to use just
2389 @samp{$srcdir} instead of @samp{$top_srcdir}.
2391 @c Just say no to ASCII sorting!  We're humans, not computers.
2392 @c These variables are listed as they would be in a dictionary:
2393 @c actor
2394 @c Actress
2395 @c actress
2397 @defvar CFLAGS
2398 @evindex CFLAGS
2399 @ovindex CFLAGS
2400 Debugging and optimization options for the C compiler.  If it is not set
2401 in the environment when @command{configure} runs, the default value is set
2402 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2403 uses this variable when compiling or linking programs to test for C features.
2405 If a compiler option affects only the behavior of the preprocessor
2406 (e.g., @option{-D @var{name}}), it should be put into @code{CPPFLAGS}
2407 instead.  If it affects only the linker (e.g., @option{-L
2408 @var{directory}}), it should be put into @code{LDFLAGS} instead.  If it
2409 affects only the compiler proper, @code{CFLAGS} is the natural home for
2410 it.  If an option affects multiple phases of the compiler, though,
2411 matters get tricky.  One approach to put such options directly into
2412 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2413 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2415 However, remember that some @file{Makefile} variables are reserved by
2416 the @acronym{GNU} Coding Standards for the use of the ``user''---the person
2417 building the package.  For instance, @code{CFLAGS} is one such variable.
2419 Sometimes package developers are tempted to set user variables such as
2420 @code{CFLAGS} because it appears to make their job easier.  However, the
2421 package itself should never set a user variable, particularly not to
2422 include switches that are required for proper compilation of the
2423 package.  Since these variables are documented as being for the package
2424 builder, that person rightfully expects to be able to override any of
2425 these variables at build time.  If the package developer needs to add
2426 switches without interfering with the user, the proper way to do that is
2427 to introduce an additional variable.  Automake makes this easy by
2428 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2429 automake, @acronym{GNU} Automake}), but the concept is the same even if
2430 Automake is not used.
2431 @end defvar
2433 @defvar configure_input
2434 @ovindex configure_input
2435 A comment saying that the file was generated automatically by
2436 @command{configure} and giving the name of the input file.
2437 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2438 of every makefile it creates.  For other files, you should
2439 reference this variable in a comment at the top of each input file.  For
2440 example, an input shell script should begin like this:
2442 @example
2443 #!/bin/sh
2444 # @@configure_input@@
2445 @end example
2447 @noindent
2448 The presence of that line also reminds people editing the file that it
2449 needs to be processed by @command{configure} in order to be used.
2450 @end defvar
2452 @defvar CPPFLAGS
2453 @evindex CPPFLAGS
2454 @ovindex CPPFLAGS
2455 Preprocessor options for the C, C++, Objective C, and Objective C++
2456 preprocessors and compilers.  If
2457 it is not set in the environment when @command{configure} runs, the default
2458 value is empty.  @command{configure} uses this variable when preprocessing
2459 or compiling programs to test for C, C++, Objective C, and Objective C++
2460 features.
2462 This variable's contents should contain options like @option{-I},
2463 @option{-D}, and @option{-U} that affect only the behavior of the
2464 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2465 can do if an option affects other phases of the compiler as well.
2467 Currently, @command{configure} always links as part of a single
2468 invocation of the compiler that also preprocesses and compiles, so it
2469 uses this variable also when linking programs.  However, it is unwise to
2470 depend on this behavior because the @acronym{GNU} Coding Standards do
2471 not require it and many packages do not use @code{CPPFLAGS} when linking
2472 programs.
2474 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2475 might run into.
2476 @end defvar
2478 @defvar CXXFLAGS
2479 @evindex CXXFLAGS
2480 @ovindex CXXFLAGS
2481 Debugging and optimization options for the C++ compiler.  It acts like
2482 @code{CFLAGS}, but for C++ instead of C.
2483 @end defvar
2485 @defvar DEFS
2486 @ovindex DEFS
2487 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2488 is called, @command{configure} replaces @samp{@@DEFS@@} with
2489 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2490 variable is not defined while @command{configure} is performing its tests,
2491 only when creating the output files.  @xref{Setting Output Variables}, for
2492 how to check the results of previous tests.
2493 @end defvar
2495 @defvar ECHO_C
2496 @defvarx ECHO_N
2497 @defvarx ECHO_T
2498 @ovindex ECHO_C
2499 @ovindex ECHO_N
2500 @ovindex ECHO_T
2501 How does one suppress the trailing newline from @command{echo} for
2502 question-answer message pairs?  These variables provide a way:
2504 @example
2505 echo $ECHO_N "And the winner is... $ECHO_C"
2506 sleep 100000000000
2507 echo "$@{ECHO_T@}dead."
2508 @end example
2510 @noindent
2511 Some old and uncommon @command{echo} implementations offer no means to
2512 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2513 want to use it.
2514 @end defvar
2516 @defvar ERLCFLAGS
2517 @evindex ERLCFLAGS
2518 @ovindex ERLCFLAGS
2519 Debugging and optimization options for the Erlang compiler.  If it is not set
2520 in the environment when @command{configure} runs, the default value is empty.
2521 @command{configure} uses this variable when compiling
2522 programs to test for Erlang features.
2523 @end defvar
2525 @defvar FCFLAGS
2526 @evindex FCFLAGS
2527 @ovindex FCFLAGS
2528 Debugging and optimization options for the Fortran compiler.  If it
2529 is not set in the environment when @command{configure} runs, the default
2530 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2531 @command{configure} uses this variable when compiling or linking
2532 programs to test for Fortran features.
2533 @end defvar
2535 @defvar FFLAGS
2536 @evindex FFLAGS
2537 @ovindex FFLAGS
2538 Debugging and optimization options for the Fortran 77 compiler.  If it
2539 is not set in the environment when @command{configure} runs, the default
2540 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2541 @command{configure} uses this variable when compiling or linking
2542 programs to test for Fortran 77 features.
2543 @end defvar
2545 @defvar LDFLAGS
2546 @evindex LDFLAGS
2547 @ovindex LDFLAGS
2548 Options for the linker.  If it is not set
2549 in the environment when @command{configure} runs, the default value is empty.
2550 @command{configure} uses this variable when linking programs to test for
2551 C, C++, Objective C, Objective C++, and Fortran features.
2553 This variable's contents should contain options like @option{-s} and
2554 @option{-L} that affect only the behavior of the linker.  Please see the
2555 explanation of @code{CFLAGS} for what you can do if an option also
2556 affects other phases of the compiler.
2558 Don't use this variable to pass library names
2559 (@option{-l}) to the linker; use @code{LIBS} instead.
2560 @end defvar
2562 @defvar LIBS
2563 @evindex LIBS
2564 @ovindex LIBS
2565 @option{-l} options to pass to the linker.  The default value is empty,
2566 but some Autoconf macros may prepend extra libraries to this variable if
2567 those libraries are found and provide necessary functions, see
2568 @ref{Libraries}.  @command{configure} uses this variable when linking
2569 programs to test for C, C++, Objective C, Objective C++, and Fortran
2570 features.
2571 @end defvar
2573 @defvar OBJCFLAGS
2574 @evindex OBJCFLAGS
2575 @ovindex OBJCFLAGS
2576 Debugging and optimization options for the Objective C compiler.  It
2577 acts like @code{CFLAGS}, but for Objective C instead of C.
2578 @end defvar
2580 @defvar OBJCXXFLAGS
2581 @evindex OBJCXXFLAGS
2582 @ovindex OBJCXXFLAGS
2583 Debugging and optimization options for the Objective C++ compiler.  It
2584 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2585 @end defvar
2587 @defvar builddir
2588 @ovindex builddir
2589 Rigorously equal to @samp{.}.  Added for symmetry only.
2590 @end defvar
2592 @defvar abs_builddir
2593 @ovindex abs_builddir
2594 Absolute name of @code{builddir}.
2595 @end defvar
2597 @defvar top_builddir
2598 @ovindex top_builddir
2599 The relative name of the top level of the current build tree.  In the
2600 top-level directory, this is the same as @code{builddir}.
2601 @end defvar
2603 @defvar top_build_prefix
2604 @ovindex top_build_prefix
2605 The relative name of the top level of the current build tree with final
2606 slash if nonemtpy.  This is the same as @code{top_builddir}, except that
2607 it contains zero or more runs of @code{../}, so it should not be
2608 appended with a slash for concatenation.  This helps for @command{make}
2609 implementations that otherwise do not treat @file{./file} and @file{file}
2610 as equal in the toplevel build directory.
2611 @end defvar
2613 @defvar abs_top_builddir
2614 @ovindex abs_top_builddir
2615 Absolute name of @code{top_builddir}.
2616 @end defvar
2618 @defvar srcdir
2619 @ovindex srcdir
2620 The name of the directory that contains the source code for
2621 that makefile.
2622 @end defvar
2624 @defvar abs_srcdir
2625 @ovindex abs_srcdir
2626 Absolute name of @code{srcdir}.
2627 @end defvar
2629 @defvar top_srcdir
2630 @ovindex top_srcdir
2631 The name of the top-level source code directory for the
2632 package.  In the top-level directory, this is the same as @code{srcdir}.
2633 @end defvar
2635 @defvar abs_top_srcdir
2636 @ovindex abs_top_srcdir
2637 Absolute name of @code{top_srcdir}.
2638 @end defvar
2640 @node Installation Directory Variables
2641 @subsection Installation Directory Variables
2642 @cindex Installation directories
2643 @cindex Directories, installation
2645 The following variables specify the directories for
2646 package installation, see @ref{Directory Variables, , Variables for
2647 Installation Directories, standards, The @acronym{GNU} Coding
2648 Standards}, for more information.  Each variable corresponds to an
2649 argument of @command{configure}; trailing slashes are stripped so that
2650 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2651 between directory names.  See the end of this section for
2652 details on when and how to use these variables.
2654 @defvar bindir
2655 @ovindex bindir
2656 The directory for installing executables that users run.
2657 @end defvar
2659 @defvar datadir
2660 @ovindex datadir
2661 The directory for installing idiosyncratic read-only
2662 architecture-independent data.
2663 @end defvar
2665 @defvar datarootdir
2666 @ovindex datarootdir
2667 The root of the directory tree for read-only architecture-independent
2668 data files.
2669 @end defvar
2671 @defvar docdir
2672 @ovindex docdir
2673 The directory for installing documentation files (other than Info and
2674 man).
2675 @end defvar
2677 @defvar dvidir
2678 @ovindex dvidir
2679 The directory for installing documentation files in DVI format.
2680 @end defvar
2682 @defvar exec_prefix
2683 @ovindex exec_prefix
2684 The installation prefix for architecture-dependent files.  By default
2685 it's the same as @var{prefix}.  You should avoid installing anything
2686 directly to @var{exec_prefix}.  However, the default value for
2687 directories containing architecture-dependent files should be relative
2688 to @var{exec_prefix}.
2689 @end defvar
2691 @defvar htmldir
2692 @ovindex htmldir
2693 The directory for installing HTML documentation.
2694 @end defvar
2696 @defvar includedir
2697 @ovindex includedir
2698 The directory for installing C header files.
2699 @end defvar
2701 @defvar infodir
2702 @ovindex infodir
2703 The directory for installing documentation in Info format.
2704 @end defvar
2706 @defvar libdir
2707 @ovindex libdir
2708 The directory for installing object code libraries.
2709 @end defvar
2711 @defvar libexecdir
2712 @ovindex libexecdir
2713 The directory for installing executables that other programs run.
2714 @end defvar
2716 @defvar localedir
2717 @ovindex localedir
2718 The directory for installing locale-dependent but
2719 architecture-independent data, such as message catalogs.  This directory
2720 usually has a subdirectory per locale.
2721 @end defvar
2723 @defvar localstatedir
2724 @ovindex localstatedir
2725 The directory for installing modifiable single-machine data.
2726 @end defvar
2728 @defvar mandir
2729 @ovindex mandir
2730 The top-level directory for installing documentation in man format.
2731 @end defvar
2733 @defvar oldincludedir
2734 @ovindex oldincludedir
2735 The directory for installing C header files for non-@acronym{GCC} compilers.
2736 @end defvar
2738 @defvar pdfdir
2739 @ovindex pdfdir
2740 The directory for installing PDF documentation.
2741 @end defvar
2743 @defvar prefix
2744 @ovindex prefix
2745 The common installation prefix for all files.  If @var{exec_prefix}
2746 is defined to a different value, @var{prefix} is used only for
2747 architecture-independent files.
2748 @end defvar
2750 @defvar psdir
2751 @ovindex psdir
2752 The directory for installing PostScript documentation.
2753 @end defvar
2755 @defvar sbindir
2756 @ovindex sbindir
2757 The directory for installing executables that system
2758 administrators run.
2759 @end defvar
2761 @defvar sharedstatedir
2762 @ovindex sharedstatedir
2763 The directory for installing modifiable architecture-independent data.
2764 @end defvar
2766 @defvar sysconfdir
2767 @ovindex sysconfdir
2768 The directory for installing read-only single-machine data.
2769 @end defvar
2772 Most of these variables have values that rely on @code{prefix} or
2773 @code{exec_prefix}.  It is deliberate that the directory output
2774 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2775 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2776 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2778 This behavior is mandated by the @acronym{GNU} Coding Standards, so that when
2779 the user runs:
2781 @table @samp
2782 @item make
2783 she can still specify a different prefix from the one specified to
2784 @command{configure}, in which case, if needed, the package should hard
2785 code dependencies corresponding to the make-specified prefix.
2787 @item make install
2788 she can specify a different installation location, in which case the
2789 package @emph{must} still depend on the location which was compiled in
2790 (i.e., never recompile when @samp{make install} is run).  This is an
2791 extremely important feature, as many people may decide to install all
2792 the files of a package grouped together, and then install links from
2793 the final locations to there.
2794 @end table
2796 In order to support these features, it is essential that
2797 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2798 so that its value can be expanded based
2799 on the current value of @code{prefix}.
2801 A corollary is that you should not use these variables except in
2802 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2803 in @file{configure} and hard-coding it in makefiles using
2804 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2805 you should add
2806 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2807 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2809 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2810 @code{bindir} and friends in your shell scripts and other files; instead,
2811 let @command{make} manage their replacement.  For instance Autoconf
2812 ships templates of its shell scripts ending with @samp{.in}, and uses a
2813 makefile snippet similar to the following to build scripts like
2814 @command{autoheader} and @command{autom4te}:
2816 @example
2817 @group
2818 edit = sed \
2819         -e 's|@@bindir[@@]|$(bindir)|g' \
2820         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2821         -e 's|@@prefix[@@]|$(prefix)|g'
2822 @end group
2824 @group
2825 autoheader autom4te: Makefile
2826         rm -f $@@ $@@.tmp
2827         srcdir=''; \
2828           test -f ./$@@.in || srcdir=$(srcdir)/; \
2829           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2830         chmod +x $@@.tmp
2831         chmod a-w $@@.tmp
2832         mv $@@.tmp $@@
2833 @end group
2835 @group
2836 autoheader: $(srcdir)/autoheader.in
2837 autom4te: $(srcdir)/autom4te.in
2838 @end group
2839 @end example
2841 Some details are noteworthy:
2843 @table @asis
2844 @item @samp{@@bindir[@@]}
2845 The brackets prevent @command{configure} from replacing
2846 @samp{@@bindir@@} in the Sed expression itself.
2847 Brackets are preferable to a backslash here, since
2848 Posix says @samp{\@@} is not portable.
2850 @item @samp{$(bindir)}
2851 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2852 instead.
2854 @item @samp{$(pkgdatadir)}
2855 The example takes advantage of the variable @samp{$(pkgdatadir)}
2856 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2858 @item @samp{/}
2859 Don't use @samp{/} in the Sed expressions that replace file names since
2860 most likely the
2861 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2862 Use a shell metacharacter instead, such as @samp{|}.
2864 @item special characters
2865 File names, file name components, and the value of @code{VPATH} should
2866 not contain shell metacharacters or white
2867 space.  @xref{Special Chars in Variables}.
2869 @item dependency on @file{Makefile}
2870 Since @code{edit} uses values that depend on the configuration specific
2871 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2872 the output depends on @file{Makefile}, not @file{configure.ac}.
2874 @item @samp{$@@}
2875 The main rule is generic, and uses @samp{$@@} extensively to
2876 avoid the need for multiple copies of the rule.
2878 @item Separated dependencies and single suffix rules
2879 You can't use them!  The above snippet cannot be (portably) rewritten
2882 @example
2883 autoconf autoheader: Makefile
2884 @group
2885 .in:
2886         rm -f $@@ $@@.tmp
2887         $(edit) $< >$@@.tmp
2888         chmod +x $@@.tmp
2889         mv $@@.tmp $@@
2890 @end group
2891 @end example
2893 @xref{Single Suffix Rules}, for details.
2895 @item @samp{$(srcdir)}
2896 Be sure to specify the name of the source directory,
2897 otherwise the package won't support separated builds.
2898 @end table
2900 For the more specific installation of Erlang libraries, the following variables
2901 are defined:
2903 @defvar ERLANG_INSTALL_LIB_DIR
2904 @ovindex ERLANG_INSTALL_LIB_DIR
2905 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2906 The common parent directory of Erlang library installation directories.
2907 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2908 macro in @file{configure.ac}.
2909 @end defvar
2911 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2912 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2913 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2914 The installation directory for Erlang library @var{library}.
2915 This variable is set by using the
2916 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2917 macro in @file{configure.ac}.
2918 @end defvar
2920 @xref{Erlang Libraries}, for details.
2923 @node Changed Directory Variables
2924 @subsection Changed Directory Variables
2925 @cindex @file{datarootdir}
2927 In Autoconf 2.60, the set of directory variables has changed, and the
2928 defaults of some variables have been adjusted
2929 (@pxref{Installation Directory Variables}) to changes in the
2930 @acronym{GNU} Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
2931 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
2932 upgrading from an earlier Autoconf version, you may need to adjust your files
2933 to ensure that the directory variables are substituted correctly
2934 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
2935 in place.  For example, in a @file{Makefile.in}, adding
2937 @example
2938 datarootdir = @@datarootdir@@
2939 @end example
2941 @noindent
2942 is usually sufficient.  If you use Automake to create @file{Makefile.in},
2943 it will add this for you.
2945 To help with the transition, Autoconf warns about files that seem to use
2946 @code{datarootdir} without defining it.  In some cases, it then expands
2947 the value of @code{$datarootdir} in substitutions of the directory
2948 variables.  The following example shows such a warning:
2950 @example
2951 $ @kbd{cat configure.ac}
2952 AC_INIT
2953 AC_CONFIG_FILES([Makefile])
2954 AC_OUTPUT
2955 $ @kbd{cat Makefile.in}
2956 prefix = @@prefix@@
2957 datadir = @@datadir@@
2958 $ @kbd{autoconf}
2959 $ @kbd{configure}
2960 configure: creating ./config.status
2961 config.status: creating Makefile
2962 config.status: WARNING:
2963                Makefile.in seems to ignore the --datarootdir setting
2964 $ @kbd{cat Makefile}
2965 prefix = /usr/local
2966 datadir = $@{prefix@}/share
2967 @end example
2969 Usually one can easily change the file to accommodate both older and newer
2970 Autoconf releases:
2972 @example
2973 $ @kbd{cat Makefile.in}
2974 prefix = @@prefix@@
2975 datarootdir = @@datarootdir@@
2976 datadir = @@datadir@@
2977 $ @kbd{configure}
2978 configure: creating ./config.status
2979 config.status: creating Makefile
2980 $ @kbd{cat Makefile}
2981 prefix = /usr/local
2982 datarootdir = $@{prefix@}/share
2983 datadir = $@{datarootdir@}
2984 @end example
2986 @acindex{DATAROOTDIR_CHECKED}
2987 In some cases, however, the checks may not be able to detect that a suitable
2988 initialization of @code{datarootdir} is in place, or they may fail to detect
2989 that such an initialization is necessary in the output file.  If, after
2990 auditing your package, there are still spurious @file{configure} warnings about
2991 @code{datarootdir}, you may add the line
2993 @example
2994 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
2995 @end example
2997 @noindent
2998 to your @file{configure.ac} to disable the warnings.  This is an exception
2999 to the usual rule that you should not define a macro whose name begins with
3000 @code{AC_} (@pxref{Macro Names}).
3004 @node Build Directories
3005 @subsection Build Directories
3006 @cindex Build directories
3007 @cindex Directories, build
3009 You can support compiling a software package for several architectures
3010 simultaneously from the same copy of the source code.  The object files
3011 for each architecture are kept in their own directory.
3013 To support doing this, @command{make} uses the @code{VPATH} variable to
3014 find the files that are in the source directory.  @acronym{GNU} Make
3015 can do this.  Most other recent @command{make} programs can do this as
3016 well, though they may have difficulties and it is often simpler to
3017 recommend @acronym{GNU} @command{make} (@pxref{VPATH and Make}).  Older
3018 @command{make} programs do not support @code{VPATH}; when using them, the
3019 source code must be in the same directory as the object files.
3021 If you are using @acronym{GNU} Automake, the remaining details in this
3022 section are already covered for you, based on the contents of your
3023 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
3024 supporting @code{VPATH} requires the following in your
3025 @file{Makefile.in}:
3027 @example
3028 srcdir = @@srcdir@@
3029 VPATH = @@srcdir@@
3030 @end example
3032 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3033 listed in VPATH}.
3035 @command{configure} substitutes the correct value for @code{srcdir} when
3036 it produces @file{Makefile}.
3038 Do not use the @command{make} variable @code{$<}, which expands to the
3039 file name of the file in the source directory (found with @code{VPATH}),
3040 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3041 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3042 versions of @command{make} do not set @code{$<} in explicit rules; they
3043 expand it to an empty value.
3045 Instead, Make command lines should always refer to source
3046 files by prefixing them with @samp{$(srcdir)/}.  For example:
3048 @example
3049 time.info: time.texinfo
3050         $(MAKEINFO) '$(srcdir)/time.texinfo'
3051 @end example
3053 @node Automatic Remaking
3054 @subsection Automatic Remaking
3055 @cindex Automatic remaking
3056 @cindex Remaking automatically
3058 You can put rules like the following in the top-level @file{Makefile.in}
3059 for a package to automatically update the configuration information when
3060 you change the configuration files.  This example includes all of the
3061 optional files, such as @file{aclocal.m4} and those related to
3062 configuration header files.  Omit from the @file{Makefile.in} rules for
3063 any of these files that your package does not use.
3065 The @samp{$(srcdir)/} prefix is included because of limitations in the
3066 @code{VPATH} mechanism.
3068 The @file{stamp-} files are necessary because the timestamps of
3069 @file{config.h.in} and @file{config.h} are not changed if remaking
3070 them does not change their contents.  This feature avoids unnecessary
3071 recompilation.  You should include the file @file{stamp-h.in} in your
3072 package's distribution, so that @command{make} considers
3073 @file{config.h.in} up to date.  Don't use @command{touch}
3074 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3075 @command{echo} (using
3076 @command{date} would cause needless differences, hence @acronym{CVS}
3077 conflicts, etc.).
3079 @example
3080 @group
3081 $(srcdir)/configure: configure.ac aclocal.m4
3082         cd '$(srcdir)' && autoconf
3084 # autoheader might not change config.h.in, so touch a stamp file.
3085 $(srcdir)/config.h.in: stamp-h.in
3086 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3087         cd '$(srcdir)' && autoheader
3088         echo timestamp > '$(srcdir)/stamp-h.in'
3090 config.h: stamp-h
3091 stamp-h: config.h.in config.status
3092         ./config.status
3094 Makefile: Makefile.in config.status
3095         ./config.status
3097 config.status: configure
3098         ./config.status --recheck
3099 @end group
3100 @end example
3102 @noindent
3103 (Be careful if you copy these lines directly into your makefile, as you
3104 need to convert the indented lines to start with the tab character.)
3106 In addition, you should use
3108 @example
3109 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3110 @end example
3112 @noindent
3113 so @file{config.status} ensures that @file{config.h} is considered up to
3114 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3116 @xref{config.status Invocation}, for more examples of handling
3117 configuration-related dependencies.
3119 @node Configuration Headers
3120 @section Configuration Header Files
3121 @cindex Configuration Header
3122 @cindex @file{config.h}
3124 When a package contains more than a few tests that define C preprocessor
3125 symbols, the command lines to pass @option{-D} options to the compiler
3126 can get quite long.  This causes two problems.  One is that the
3127 @command{make} output is hard to visually scan for errors.  More
3128 seriously, the command lines can exceed the length limits of some
3129 operating systems.  As an alternative to passing @option{-D} options to
3130 the compiler, @command{configure} scripts can create a C header file
3131 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3132 macro selects this kind of output.  Though it can be called anywhere
3133 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3134 it right after @code{AC_INIT}.
3136 The package should @samp{#include} the configuration header file before
3137 any other header files, to prevent inconsistencies in declarations (for
3138 example, if it redefines @code{const}).
3140 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3141 option (or @option{-I..}; whichever directory contains @file{config.h}).
3142 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3143 the directory of the currently read file, i.e., the source directory, not
3144 the build directory.
3146 With the appropriate @option{-I} option, you can use
3147 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3148 because in the rare case when the source directory contains another
3149 @file{config.h}, the build directory should be searched first.
3152 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3153 @acindex{CONFIG_HEADERS}
3154 @cvindex HAVE_CONFIG_H
3155 This macro is one of the instantiating macros; see @ref{Configuration
3156 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3157 blank-or-newline-separated list @var{header} containing C preprocessor
3158 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3159 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3160 The usual name for @var{header} is @file{config.h}.
3162 If @var{header} already exists and its contents are identical to what
3163 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3164 making some changes in the configuration without needlessly causing
3165 object files that depend on the header file to be recompiled.
3167 Usually the input file is named @file{@var{header}.in}; however, you can
3168 override the input file name by appending to @var{header} a
3169 colon-separated list of input files.  For example, you might need to make
3170 the input file name acceptable to @acronym{DOS} variants:
3172 @example
3173 AC_CONFIG_HEADERS([config.h:config.hin])
3174 @end example
3176 @end defmac
3178 @defmac AH_HEADER
3179 @ahindex{HEADER}
3180 This macro is defined as the name of the first declared config header
3181 and undefined if no config headers have been declared up to this point.
3182 A third-party macro may, for example, require use of a config header
3183 without invoking AC_CONFIG_HEADERS twice, like this:
3185 @example
3186 AC_CONFIG_COMMANDS_PRE(
3187         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3188 @end example
3190 @end defmac
3192 @xref{Configuration Actions}, for more details on @var{header}.
3194 @menu
3195 * Header Templates::            Input for the configuration headers
3196 * autoheader Invocation::       How to create configuration templates
3197 * Autoheader Macros::           How to specify CPP templates
3198 @end menu
3200 @node Header Templates
3201 @subsection Configuration Header Templates
3202 @cindex Configuration Header Template
3203 @cindex Header templates
3204 @cindex @file{config.h.in}
3206 Your distribution should contain a template file that looks as you want
3207 the final header file to look, including comments, with @code{#undef}
3208 statements which are used as hooks.  For example, suppose your
3209 @file{configure.ac} makes these calls:
3211 @example
3212 AC_CONFIG_HEADERS([conf.h])
3213 AC_CHECK_HEADERS([unistd.h])
3214 @end example
3216 @noindent
3217 Then you could have code like the following in @file{conf.h.in}.
3218 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3219 to 1, if and only if the system has @file{unistd.h}.
3221 @example
3222 @group
3223 /* Define as 1 if you have unistd.h.  */
3224 #undef HAVE_UNISTD_H
3225 @end group
3226 @end example
3228 The format of the template file is stricter than what the C preprocessor
3229 is required to accept.  A directive line should contain only whitespace,
3230 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3231 instead of @samp{#undef}, or of comments on the same line as
3232 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3233 once.  Other preprocessor lines, such as @samp{#ifdef} or
3234 @samp{#include}, are copied verbatim from the template into the
3235 generated header.
3237 Since it is a tedious task to keep a template header up to date, you may
3238 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3240 During the instantiation of the header, each @samp{#undef} line in the
3241 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3242 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3243 been executed during the @command{configure} run, the @samp{#undef} line is
3244 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3245 on many systems, it can be implicitly defined by the compiler, and
3246 undefining it in the header would then break compilation of subsequent
3247 headers.)
3249 Currently, @emph{all} remaining @samp{#undef} lines in the header
3250 template are commented out, whether or not there was a corresponding
3251 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3252 for future releases of Autoconf.
3254 Generally speaking, since you should not use @samp{#define}, and you
3255 cannot guarantee whether a @samp{#undef} directive in the header
3256 template will be converted to a @samp{#define} or commented out in the
3257 generated header file, the template file cannot be used for conditional
3258 definition effects.  Consequently, if you need to use the construct
3260 @example
3261 @group
3262 #ifdef THIS
3263 # define THAT
3264 #endif
3265 @end group
3266 @end example
3268 @noindent
3269 you must place it outside of the template.
3270 If you absolutely need to hook it to the config header itself, please put
3271 the directives to a separate file, and @samp{#include} that file from the
3272 config header template.  If you are using @command{autoheader}, you would
3273 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3276 @node autoheader Invocation
3277 @subsection Using @command{autoheader} to Create @file{config.h.in}
3278 @cindex @command{autoheader}
3280 The @command{autoheader} program can create a template file of C
3281 @samp{#define} statements for @command{configure} to use.
3282 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3283 @file{configure} sources to determine the name of the template.
3284 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3285 input file name, @command{autoheader} uses the first one.)
3287 It is recommended that only one input file is used.  If you want to append
3288 a boilerplate code, it is preferable to use
3289 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3290 File @file{conf_post.h} is not processed during the configuration then,
3291 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3292 prepend a boilerplate code.
3294 In order to do its job, @command{autoheader} needs you to document all
3295 of the symbols that you might use.  Typically this is done via an
3296 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3297 is a literal symbol and whose third argument describes the symbol
3298 (@pxref{Defining Symbols}).  Alternatively, you can use
3299 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3300 suitable input file for a subsequent configuration header file.
3301 Symbols defined by Autoconf's builtin tests are already documented properly;
3302 you need to document only those that you
3303 define yourself.
3305 You might wonder why @command{autoheader} is needed: after all, why
3306 would @command{configure} need to ``patch'' a @file{config.h.in} to
3307 produce a @file{config.h} instead of just creating @file{config.h} from
3308 scratch?  Well, when everything rocks, the answer is just that we are
3309 wasting our time maintaining @command{autoheader}: generating
3310 @file{config.h} directly is all that is needed.  When things go wrong,
3311 however, you'll be thankful for the existence of @command{autoheader}.
3313 The fact that the symbols are documented is important in order to
3314 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3315 well-defined list of symbols that should be defined (or not) is
3316 also important for people who are porting packages to environments where
3317 @command{configure} cannot be run: they just have to @emph{fill in the
3318 blanks}.
3320 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3322 If you give @command{autoheader} an argument, it uses that file instead
3323 of @file{configure.ac} and writes the header file to the standard output
3324 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3325 argument of @option{-}, it reads the standard input instead of
3326 @file{configure.ac} and writes the header file to the standard output.
3328 @command{autoheader} accepts the following options:
3330 @table @option
3331 @item --help
3332 @itemx -h
3333 Print a summary of the command line options and exit.
3335 @item --version
3336 @itemx -V
3337 Print the version number of Autoconf and exit.
3339 @item --verbose
3340 @itemx -v
3341 Report processing steps.
3343 @item --debug
3344 @itemx -d
3345 Don't remove the temporary files.
3347 @item --force
3348 @itemx -f
3349 Remake the template file even if newer than its input files.
3351 @item --include=@var{dir}
3352 @itemx -I @var{dir}
3353 Append @var{dir} to the include path.  Multiple invocations accumulate.
3355 @item --prepend-include=@var{dir}
3356 @itemx -B @var{dir}
3357 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3359 @item --warnings=@var{category}
3360 @itemx -W @var{category}
3361 @evindex WARNINGS
3362 Report the warnings related to @var{category} (which can actually be a
3363 comma separated list).  Current categories include:
3365 @table @samp
3366 @item obsolete
3367 report the uses of obsolete constructs
3369 @item all
3370 report all the warnings
3372 @item none
3373 report none
3375 @item error
3376 treats warnings as errors
3378 @item no-@var{category}
3379 disable warnings falling into @var{category}
3380 @end table
3382 @end table
3386 @node Autoheader Macros
3387 @subsection Autoheader Macros
3388 @cindex Autoheader macros
3390 @command{autoheader} scans @file{configure.ac} and figures out which C
3391 preprocessor symbols it might define.  It knows how to generate
3392 templates for symbols defined by @code{AC_CHECK_HEADERS},
3393 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3394 symbol, you must define a template for it.  If there are missing
3395 templates, @command{autoheader} fails with an error message.
3397 The template for a @var{symbol} is created
3398 by @command{autoheader} from
3399 the @var{description} argument to an @code{AC_DEFINE};
3400 see @ref{Defining Symbols}.
3402 For special needs, you can use the following macros.
3405 @defmac AH_TEMPLATE (@var{key}, @var{description})
3406 @ahindex{TEMPLATE}
3407 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3408 generates standard templates just like @code{AC_DEFINE} when a
3409 @var{description} is given.
3411 For example:
3413 @example
3414 AH_TEMPLATE([CRAY_STACKSEG_END],
3415             [Define to one of _getb67, GETB67, getb67
3416              for Cray-2 and Cray-YMP systems.  This
3417              function is required for alloca.c support
3418              on those systems.])
3419 @end example
3421 @noindent
3422 generates the following template, with the description properly
3423 justified.
3425 @example
3426 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3427    Cray-YMP systems.  This function is required for alloca.c
3428    support on those systems.  */
3429 #undef CRAY_STACKSEG_END
3430 @end example
3431 @end defmac
3434 @defmac AH_VERBATIM (@var{key}, @var{template})
3435 @ahindex{VERBATIM}
3436 Tell @command{autoheader} to include the @var{template} as-is in the header
3437 template file.  This @var{template} is associated with the @var{key},
3438 which is used to sort all the different templates and guarantee their
3439 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3440 @end defmac
3443 @defmac AH_TOP (@var{text})
3444 @ahindex{TOP}
3445 Include @var{text} at the top of the header template file.
3446 @end defmac
3449 @defmac AH_BOTTOM (@var{text})
3450 @ahindex{BOTTOM}
3451 Include @var{text} at the bottom of the header template file.
3452 @end defmac
3455 Please note that @var{text} gets included ``verbatim'' to the template file,
3456 not to the resulting config header, so it can easily get mangled when the
3457 template is processed.  There is rarely a need for something other than
3459 @example
3460 AH_BOTTOM([#include <custom.h>])
3461 @end example
3465 @node Configuration Commands
3466 @section Running Arbitrary Configuration Commands
3467 @cindex Configuration commands
3468 @cindex Commands for configuration
3470 You can execute arbitrary commands before, during, and after
3471 @file{config.status} is run.  The three following macros accumulate the
3472 commands to run when they are called multiple times.
3473 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3474 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3476 @anchor{AC_CONFIG_COMMANDS}
3477 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3478 @acindex{CONFIG_COMMANDS}
3479 Specify additional shell commands to run at the end of
3480 @file{config.status}, and shell commands to initialize any variables
3481 from @command{configure}.  Associate the commands with @var{tag}.
3482 Since typically the @var{cmds} create a file, @var{tag} should
3483 naturally be the name of that file.  If needed, the directory hosting
3484 @var{tag} is created.  This macro is one of the instantiating macros;
3485 see @ref{Configuration Actions}.
3487 Here is an unrealistic example:
3488 @example
3489 fubar=42
3490 AC_CONFIG_COMMANDS([fubar],
3491                    [echo this is extra $fubar, and so on.],
3492                    [fubar=$fubar])
3493 @end example
3495 Here is a better one:
3496 @example
3497 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3498 @end example
3499 @end defmac
3501 The following two macros look similar, but in fact they are not of the same
3502 breed: they are executed directly by @file{configure}, so you cannot use
3503 @file{config.status} to rerun them.
3505 @c Yet it is good to leave them here.  The user sees them together and
3506 @c decides which best fits their needs.
3508 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3509 @acindex{CONFIG_COMMANDS_PRE}
3510 Execute the @var{cmds} right before creating @file{config.status}.
3512 This macro presents the last opportunity to call @code{AC_SUBST},
3513 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3514 @end defmac
3516 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3517 @acindex{CONFIG_COMMANDS_POST}
3518 Execute the @var{cmds} right after creating @file{config.status}.
3519 @end defmac
3524 @node Configuration Links
3525 @section Creating Configuration Links
3526 @cindex Configuration links
3527 @cindex Links for configuration
3529 You may find it convenient to create links whose destinations depend upon
3530 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3531 creation of relative symbolic links can be delicate when the package is
3532 built in a directory different from the source directory.
3534 @anchor{AC_CONFIG_LINKS}
3535 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3536   @ovar{init-cmds})
3537 @acindex{CONFIG_LINKS}
3538 @cindex Links
3539 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3540 the corresponding link name @var{dest}.  Makes a symbolic link if
3541 possible, otherwise a hard link if possible, otherwise a copy.  The
3542 @var{dest} and @var{source} names should be relative to the top level
3543 source or build directory.  This macro is one of the instantiating
3544 macros; see @ref{Configuration Actions}.
3546 For example, this call:
3548 @example
3549 AC_CONFIG_LINKS([host.h:config/$machine.h
3550                 object.h:config/$obj_format.h])
3551 @end example
3553 @noindent
3554 creates in the current directory @file{host.h} as a link to
3555 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3556 link to @file{@var{srcdir}/config/$obj_format.h}.
3558 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3559 impossible for @samp{config.status} to guess the links to establish.
3561 One can then run:
3562 @example
3563 ./config.status host.h object.h
3564 @end example
3565 @noindent
3566 to create the links.
3567 @end defmac
3571 @node Subdirectories
3572 @section Configuring Other Packages in Subdirectories
3573 @cindex Configure subdirectories
3574 @cindex Subdirectory configure
3576 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3577 makefiles in subdirectories.  However, @command{configure} scripts
3578 that control more than one independent package can use
3579 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3580 packages in subdirectories.
3582 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3583 @acindex{CONFIG_SUBDIRS}
3584 @ovindex subdirs
3585 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3586 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3587 be a literal, i.e., please do not use:
3589 @example
3590 if test "x$package_foo_enabled" = xyes; then
3591   $my_subdirs="$my_subdirs foo"
3593 AC_CONFIG_SUBDIRS([$my_subdirs])
3594 @end example
3596 @noindent
3597 because this prevents @samp{./configure --help=recursive} from
3598 displaying the options of the package @code{foo}.  Instead, you should
3599 write:
3601 @example
3602 if test "x$package_foo_enabled" = xyes; then
3603   AC_CONFIG_SUBDIRS([foo])
3605 @end example
3607 If a given @var{dir} is not found, an error is reported: if the
3608 subdirectory is optional, write:
3610 @example
3611 if test -d "$srcdir/foo"; then
3612   AC_CONFIG_SUBDIRS([foo])
3614 @end example
3616 @c NB: Yes, below we mean configure.in, not configure.ac.
3617 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3618 of @command{configure}.  This is for packages that might use a
3619 non-Autoconf script @command{Configure}, which can't be called through a
3620 wrapper @command{configure} since it would be the same file on
3621 case-insensitive file systems.  Likewise, if a @var{dir} contains
3622 @file{configure.in} but no @command{configure}, the Cygnus
3623 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3625 The subdirectory @command{configure} scripts are given the same command
3626 line options that were given to this @command{configure} script, with minor
3627 changes if needed, which include:
3629 @itemize @minus
3630 @item
3631 adjusting a relative name for the cache file;
3633 @item
3634 adjusting a relative name for the source directory;
3636 @item
3637 propagating the current value of @code{$prefix}, including if it was
3638 defaulted, and if the default values of the top level and of the subdirectory
3639 @file{configure} differ.
3640 @end itemize
3642 This macro also sets the output variable @code{subdirs} to the list of
3643 directories @samp{@var{dir} @dots{}}.  Make rules can use
3644 this variable to determine which subdirectories to recurse into.
3646 This macro may be called multiple times.
3647 @end defmac
3649 @node Default Prefix
3650 @section Default Prefix
3651 @cindex Install prefix
3652 @cindex Prefix for install
3654 By default, @command{configure} sets the prefix for files it installs to
3655 @file{/usr/local}.  The user of @command{configure} can select a different
3656 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3657 There are two ways to change the default: when creating
3658 @command{configure}, and when running it.
3660 Some software packages might want to install in a directory other than
3661 @file{/usr/local} by default.  To accomplish that, use the
3662 @code{AC_PREFIX_DEFAULT} macro.
3664 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3665 @acindex{PREFIX_DEFAULT}
3666 Set the default installation prefix to @var{prefix} instead of
3667 @file{/usr/local}.
3668 @end defmac
3670 It may be convenient for users to have @command{configure} guess the
3671 installation prefix from the location of a related program that they
3672 have already installed.  If you wish to do that, you can call
3673 @code{AC_PREFIX_PROGRAM}.
3675 @anchor{AC_PREFIX_PROGRAM}
3676 @defmac AC_PREFIX_PROGRAM (@var{program})
3677 @acindex{PREFIX_PROGRAM}
3678 If the user did not specify an installation prefix (using the
3679 @option{--prefix} option), guess a value for it by looking for
3680 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3681 is found, set the prefix to the parent of the directory containing
3682 @var{program}, else default the prefix as described above
3683 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3684 @var{program} is @code{gcc} and the @env{PATH} contains
3685 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3686 @end defmac
3690 @c ======================================================== Existing tests
3692 @node Existing Tests
3693 @chapter Existing Tests
3695 These macros test for particular system features that packages might
3696 need or want to use.  If you need to test for a kind of feature that
3697 none of these macros check for, you can probably do it by calling
3698 primitive test macros with appropriate arguments (@pxref{Writing
3699 Tests}).
3701 These tests print messages telling the user which feature they're
3702 checking for, and what they find.  They cache their results for future
3703 @command{configure} runs (@pxref{Caching Results}).
3705 Some of these macros set output variables.  @xref{Makefile
3706 Substitutions}, for how to get their values.  The phrase ``define
3707 @var{name}'' is used below as a shorthand to mean ``define the C
3708 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3709 Symbols}, for how to get those symbol definitions into your program.
3711 @menu
3712 * Common Behavior::             Macros' standard schemes
3713 * Alternative Programs::        Selecting between alternative programs
3714 * Files::                       Checking for the existence of files
3715 * Libraries::                   Library archives that might be missing
3716 * Library Functions::           C library functions that might be missing
3717 * Header Files::                Header files that might be missing
3718 * Declarations::                Declarations that may be missing
3719 * Structures::                  Structures or members that might be missing
3720 * Types::                       Types that might be missing
3721 * Compilers and Preprocessors::  Checking for compiling programs
3722 * System Services::             Operating system services
3723 * Posix Variants::              Special kludges for specific Posix variants
3724 * Erlang Libraries::            Checking for the existence of Erlang libraries
3725 @end menu
3727 @node Common Behavior
3728 @section Common Behavior
3729 @cindex Common autoconf behavior
3731 Much effort has been expended to make Autoconf easy to learn.  The most
3732 obvious way to reach this goal is simply to enforce standard interfaces
3733 and behaviors, avoiding exceptions as much as possible.  Because of
3734 history and inertia, unfortunately, there are still too many exceptions
3735 in Autoconf; nevertheless, this section describes some of the common
3736 rules.
3738 @menu
3739 * Standard Symbols::            Symbols defined by the macros
3740 * Default Includes::            Includes used by the generic macros
3741 @end menu
3743 @node Standard Symbols
3744 @subsection Standard Symbols
3745 @cindex Standard symbols
3747 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3748 their test transform their @var{argument} values to a standard alphabet.
3749 First, @var{argument} is converted to upper case and any asterisks
3750 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3751 that are not alphanumeric are converted to underscores.
3753 For instance,
3755 @example
3756 AC_CHECK_TYPES([struct $Expensive*])
3757 @end example
3759 @noindent
3760 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3761 succeeds.
3764 @node Default Includes
3765 @subsection Default Includes
3766 @cindex Default includes
3767 @cindex Includes, default
3769 Several tests depend upon a set of header files.  Since these headers
3770 are not universally available, tests actually have to provide a set of
3771 protected includes, such as:
3773 @example
3774 @group
3775 #ifdef TIME_WITH_SYS_TIME
3776 # include <sys/time.h>
3777 # include <time.h>
3778 #else
3779 # ifdef HAVE_SYS_TIME_H
3780 #  include <sys/time.h>
3781 # else
3782 #  include <time.h>
3783 # endif
3784 #endif
3785 @end group
3786 @end example
3788 @noindent
3789 Unless you know exactly what you are doing, you should avoid using
3790 unconditional includes, and check the existence of the headers you
3791 include beforehand (@pxref{Header Files}).
3793 Most generic macros use the following macro to provide the default set
3794 of includes:
3796 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3797 @acindex{INCLUDES_DEFAULT}
3798 Expand to @var{include-directives} if defined, otherwise to:
3800 @example
3801 @group
3802 #include <stdio.h>
3803 #ifdef HAVE_SYS_TYPES_H
3804 # include <sys/types.h>
3805 #endif
3806 #ifdef HAVE_SYS_STAT_H
3807 # include <sys/stat.h>
3808 #endif
3809 #ifdef STDC_HEADERS
3810 # include <stdlib.h>
3811 # include <stddef.h>
3812 #else
3813 # ifdef HAVE_STDLIB_H
3814 #  include <stdlib.h>
3815 # endif
3816 #endif
3817 #ifdef HAVE_STRING_H
3818 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3819 #  include <memory.h>
3820 # endif
3821 # include <string.h>
3822 #endif
3823 #ifdef HAVE_STRINGS_H
3824 # include <strings.h>
3825 #endif
3826 #ifdef HAVE_INTTYPES_H
3827 # include <inttypes.h>
3828 #endif
3829 #ifdef HAVE_STDINT_H
3830 # include <stdint.h>
3831 #endif
3832 #ifdef HAVE_UNISTD_H
3833 # include <unistd.h>
3834 #endif
3835 @end group
3836 @end example
3838 If the default includes are used, then check for the presence of these
3839 headers and their compatibility, i.e., you don't need to run
3840 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3842 These headers are checked for in the same order as they are included.
3843 For instance, on some systems @file{string.h} and @file{strings.h} both
3844 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3845 @code{HAVE_STRINGS_H}.
3846 @end defmac
3848 @node Alternative Programs
3849 @section Alternative Programs
3850 @cindex Programs, checking
3852 These macros check for the presence or behavior of particular programs.
3853 They are used to choose between several alternative programs and to
3854 decide what to do once one has been chosen.  If there is no macro
3855 specifically defined to check for a program you need, and you don't need
3856 to check for any special properties of it, then you can use one of the
3857 general program-check macros.
3859 @menu
3860 * Particular Programs::         Special handling to find certain programs
3861 * Generic Programs::            How to find other programs
3862 @end menu
3864 @node Particular Programs
3865 @subsection Particular Program Checks
3867 These macros check for particular programs---whether they exist, and
3868 in some cases whether they support certain features.
3870 @defmac AC_PROG_AWK
3871 @acindex{PROG_AWK}
3872 @ovindex AWK
3873 @caindex prog_AWK
3874 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3875 order, and set output variable @code{AWK} to the first one that is found.
3876 It tries @code{gawk} first because that is reported to be the
3877 best implementation.  The result can be overridden by setting the
3878 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
3879 @end defmac
3881 @defmac AC_PROG_GREP
3882 @acindex{PROG_GREP}
3883 @ovindex GREP
3884 @caindex prog_GREP
3885 Look for the best available @code{grep} or @code{ggrep} that accepts the
3886 longest input lines possible, and that supports multiple @option{-e} options.
3887 Set the output variable @code{GREP} to whatever is chosen.
3888 @xref{grep, , Limitations of Usual Tools}, for more information about
3889 portability problems with the @command{grep} command family.  The result
3890 can be overridden by setting the @code{GREP} variable and is cached in the
3891 @code{ac_cv_path_GREP} variable.
3892 @end defmac
3894 @defmac AC_PROG_EGREP
3895 @acindex{PROG_EGREP}
3896 @ovindex EGREP
3897 @caindex prog_EGREP
3898 Check whether @code{$GREP -E} works, or else look for the best available
3899 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3900 Set the output variable @code{EGREP} to whatever is chosen.  The result
3901 can be overridden by setting the @code{EGREP} variable and is cached in the
3902 @code{ac_cv_path_EGREP} variable.
3903 @end defmac
3905 @defmac AC_PROG_FGREP
3906 @acindex{PROG_FGREP}
3907 @ovindex FGREP
3908 @caindex prog_FGREP
3909 Check whether @code{$GREP -F} works, or else look for the best available
3910 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3911 Set the output variable @code{FGREP} to whatever is chosen.  The result
3912 can be overridden by setting the @code{FGREP} variable and is cached in the
3913 @code{ac_cv_path_FGREP} variable.
3914 @end defmac
3916 @defmac AC_PROG_INSTALL
3917 @acindex{PROG_INSTALL}
3918 @ovindex INSTALL
3919 @ovindex INSTALL_PROGRAM
3920 @ovindex INSTALL_DATA
3921 @ovindex INSTALL_SCRIPT
3922 @caindex path_install
3923 Set output variable @code{INSTALL} to the name of a @acronym{BSD}-compatible
3924 @command{install} program, if one is found in the current @env{PATH}.
3925 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3926 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3927 default directories) to determine @var{dir} (@pxref{Output}).  Also set
3928 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
3929 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
3931 @samp{@@INSTALL@@} is special, as its value may vary for different
3932 configuration files.
3934 This macro screens out various instances of @command{install} known not to
3935 work.  It prefers to find a C program rather than a shell script, for
3936 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
3937 but that name is obsolete because some @command{make} programs have a rule
3938 that creates @file{install} from it if there is no makefile.  Further, this
3939 macro requires @command{install} to be able to install multiple files into a
3940 target directory in a single invocation.
3942 Autoconf comes with a copy of @file{install-sh} that you can use.  If
3943 you use @code{AC_PROG_INSTALL}, you must include either
3944 @file{install-sh} or @file{install.sh} in your distribution; otherwise
3945 @command{configure} produces an error message saying it can't find
3946 them---even if the system you're on has a good @command{install} program.
3947 This check is a safety measure to prevent you from accidentally leaving
3948 that file out, which would prevent your package from installing on
3949 systems that don't have a @acronym{BSD}-compatible @command{install} program.
3951 If you need to use your own installation program because it has features
3952 not found in standard @command{install} programs, there is no reason to use
3953 @code{AC_PROG_INSTALL}; just put the file name of your program into your
3954 @file{Makefile.in} files.
3956 The result of the test can be overridden by setting the variable
3957 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
3958 @end defmac
3960 @defmac AC_PROG_MKDIR_P
3961 @acindex{PROG_MKDIR_P}
3962 @ovindex MKDIR_P
3963 @caindex path_mkdir
3964 Set output variable @code{MKDIR_P} to a program that ensures that for
3965 each argument, a directory named by this argument exists, creating it
3966 and its parent directories if needed, and without race conditions when
3967 two instances of the program attempt to make the same directory at
3968 nearly the same time.
3970 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
3971 falls back on invoking @command{install-sh} with the @option{-d} option,
3972 so your package should
3973 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
3974 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
3975 is vulnerable to race conditions, so if you want to support parallel
3976 installs from
3977 different packages into the same directory you need to make sure you
3978 have an up-to-date @file{install-sh}.  In particular, be careful about
3979 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
3981 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
3982 in M4sh}), but it sets an output variable intended for use in other
3983 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
3984 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
3985 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
3986 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
3987 directory, and conversely a makefile should use @code{$(MKDIR_P) --
3988 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
3989 Finally, @code{AS_MKDIR_P} does not check for race condition
3990 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
3992 @samp{@@MKDIR_P@@} is special, as its value may vary for different
3993 configuration files.
3995 The result of the test can be overridden by setting the variable
3996 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
3997 @end defmac
3999 @anchor{AC_PROG_LEX}
4000 @defmac AC_PROG_LEX
4001 @acindex{PROG_LEX}
4002 @ovindex LEX
4003 @ovindex LEXLIB
4004 @cvindex YYTEXT_POINTER
4005 @ovindex LEX_OUTPUT_ROOT
4006 @caindex prog_LEX
4007 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
4008 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
4009 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
4010 @option{-ll}, if found.  If neither variant is available, set @code{LEX}
4011 to @samp{:}; for packages that ship the generated @file{file.yy.c}
4012 alongside the source @file{file.l}, this default allows users without a
4013 lexer generator to still build the package even if the timestamp for
4014 @file{file.l} is inadvertantly changed.
4016 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
4017 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
4018 the base of the file name that the lexer generates; usually
4019 @file{lex.yy}, but sometimes something else.  These results vary
4020 according to whether @code{lex} or @code{flex} is being used.
4022 You are encouraged to use Flex in your sources, since it is both more
4023 pleasant to use than plain Lex and the C source it produces is portable.
4024 In order to ensure portability, however, you must either provide a
4025 function @code{yywrap} or, if you don't use it (e.g., your scanner has
4026 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
4027 statement in the scanner's source.  Once this done, the scanner is
4028 portable (unless @emph{you} felt free to use nonportable constructs) and
4029 does not depend on any library.  In this case, and in this case only, it
4030 is suggested that you use this Autoconf snippet:
4032 @example
4033 AC_PROG_LEX
4034 if test "x$LEX" != xflex; then
4035   LEX="$SHELL $missing_dir/missing flex"
4036   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4037   AC_SUBST([LEXLIB], [''])
4039 @end example
4041 The shell script @command{missing} can be found in the Automake
4042 distribution.
4044 Remember that the user may have supplied an alternate location in
4045 @env{LEX}, so if Flex is required, it is better to check that the user
4046 provided something sufficient by parsing the output of @samp{$LEX
4047 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4049 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
4050 (indirectly) this macro twice, which causes an annoying but benign
4051 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
4052 of Automake will fix this issue; meanwhile, just ignore this message.
4054 As part of running the test, this macro may delete any file in the
4055 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
4057 The result of this test can be influenced by setting the variable
4058 @code{LEX} or the cache variable @code{ac_cv_prog_LEX}.
4059 @end defmac
4061 @anchor{AC_PROG_LN_S}
4062 @defmac AC_PROG_LN_S
4063 @acindex{PROG_LN_S}
4064 @ovindex LN_S
4065 If @samp{ln -s} works on the current file system (the operating system
4066 and file system support symbolic links), set the output variable
4067 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4068 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
4070 If you make a link in a directory other than the current directory, its
4071 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4072 create links using @samp{$(LN_S)}, either find out which form is used
4073 and adjust the arguments, or always invoke @code{ln} in the directory
4074 where the link is to be created.
4076 In other words, it does not work to do:
4077 @example
4078 $(LN_S) foo /x/bar
4079 @end example
4081 Instead, do:
4083 @example
4084 (cd /x && $(LN_S) foo bar)
4085 @end example
4086 @end defmac
4088 @defmac AC_PROG_RANLIB
4089 @acindex{PROG_RANLIB}
4090 @ovindex RANLIB
4091 @c @caindex prog_RANLIB
4092 @c @caindex prog_ac_ct_RANLIB
4093 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4094 is found, and otherwise to @samp{:} (do nothing).
4095 @end defmac
4097 @defmac AC_PROG_SED
4098 @acindex{PROG_SED}
4099 @ovindex SED
4100 @caindex path_SED
4101 Set output variable @code{SED} to a Sed implementation that conforms to
4102 Posix and does not have arbitrary length limits.  Report an error if no
4103 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4104 information about portability problems with Sed.
4106 The result of this test can be overridden by setting the @code{SED} variable
4107 and is cached in the @code{ac_cv_path_SED} variable.
4108 @end defmac
4110 @defmac AC_PROG_YACC
4111 @acindex{PROG_YACC}
4112 @evindex YACC
4113 @evindex YFLAGS
4114 @ovindex YACC
4115 @caindex prog_YACC
4116 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4117 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4118 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4119 The result of this test can be influenced by setting the variable
4120 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4121 @end defmac
4123 @node Generic Programs
4124 @subsection Generic Program and File Checks
4126 These macros are used to find programs not covered by the ``particular''
4127 test macros.  If you need to check the behavior of a program as well as
4128 find out whether it is present, you have to write your own test for it
4129 (@pxref{Writing Tests}).  By default, these macros use the environment
4130 variable @env{PATH}.  If you need to check for a program that might not
4131 be in the user's @env{PATH}, you can pass a modified path to use
4132 instead, like this:
4134 @example
4135 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4136              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4137 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4138 @end example
4140 You are strongly encouraged to declare the @var{variable} passed to
4141 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
4142 @code{AC_ARG_VAR}, for more details.
4144 @anchor{AC_CHECK_PROG}
4145 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4146   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4147   @ovar{reject})
4148 @acindex{CHECK_PROG}
4149 @caindex prog_@var{variable}
4150 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4151 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4152 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4153 absolute file name) even if it is the first found in the search path; in
4154 that case, set @var{variable} using the absolute file name of the
4155 @var{prog-to-check-for} found that is not @var{reject}.  If
4156 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4157 @var{variable}.  The result of this test can be overridden by setting the
4158 @var{variable} variable or the cache variable
4159 @code{ac_cv_prog_@var{variable}}.
4160 @end defmac
4162 @anchor{AC_CHECK_PROGS}
4163 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4164   @ovar{value-if-not-found}, @dvar{path, $PATH})
4165 @acindex{CHECK_PROGS}
4166 @caindex prog_@var{variable}
4167 Check for each program in the blank-separated list
4168 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4169 @var{variable} to the name of that program.  Otherwise, continue
4170 checking the next program in the list.  If none of the programs in the
4171 list are found, set @var{variable} to @var{value-if-not-found}; if
4172 @var{value-if-not-found} is not specified, the value of @var{variable}
4173 is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4174 this test can be overridden by setting the @var{variable} variable or the
4175 cache variable @code{ac_cv_prog_@var{variable}}.
4176 @end defmac
4178 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4179   @ovar{value-if-not-found}, @dvar{path, $PATH})
4180 @acindex{CHECK_TARGET_TOOL}
4181 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4182 with a prefix of the target type as determined by
4183 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4184 If the tool cannot be found with a prefix, and if the build and target
4185 types are equal, then it is also searched for without a prefix.
4187 As noted in @ref{Specifying Target Triplets}, the
4188 target is rarely specified, because most of the time it is the same
4189 as the host: it is the type of system for which any compiler tool in
4190 the package produces code.  What this macro looks for is,
4191 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4192 compiler driver @r{(@command{gcc} for the @acronym{GNU} C Compiler)}
4193 uses to produce objects, archives or executables}.
4194 @end defmac
4196 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4197   @ovar{value-if-not-found}, @dvar{path, $PATH})
4198 @acindex{CHECK_TOOL}
4199 @c @caindex prog_@var{VARIABLE}
4200 @c @caindex prog_ac_ct_@var{VARIABLE}
4201 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4202 with a prefix of the host type as specified by @option{--host}, followed by a
4203 dash.  For example, if the user runs
4204 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4205 @example
4206 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4207 @end example
4208 @noindent
4209 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4210 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4211 @var{path}, or to @samp{:} if neither program exists.
4213 When cross-compiling, this macro will issue a warning if no program
4214 prefixed with the host type could be found.
4215 For more information, see @ref{Specifying Target Triplets}.
4216 @end defmac
4218 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4219   @ovar{value-if-not-found}, @dvar{path, $PATH})
4220 @acindex{CHECK_TARGET_TOOLS}
4221 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4222 @var{progs-to-check-for} are checked with a prefix of the target type as
4223 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4224 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4225 prefix, and if the build and target types are equal, then the first one
4226 without a prefix is used.  If a tool is found, set @var{variable} to
4227 the name of that program.  If none of the tools in the list are found,
4228 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4229 is not specified, the value of @var{variable} is not changed.  Calls
4230 @code{AC_SUBST} for @var{variable}.
4231 @end defmac
4233 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4234   @ovar{value-if-not-found}, @dvar{path, $PATH})
4235 @acindex{CHECK_TOOLS}
4236 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4237 @var{progs-to-check-for} are checked with a prefix of the host type as
4238 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4239 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4240 prefix, then the first one without a prefix is used.  If a tool is found,
4241 set @var{variable} to the name of that program.  If none of the tools in
4242 the list are found, set @var{variable} to @var{value-if-not-found}; if
4243 @var{value-if-not-found} is not specified, the value of @var{variable}
4244 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4246 When cross-compiling, this macro will issue a warning if no program
4247 prefixed with the host type could be found.
4248 For more information, see @ref{Specifying Target Triplets}.
4249 @end defmac
4251 @anchor{AC_PATH_PROG}
4252 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4253   @ovar{value-if-not-found}, @dvar{path, $PATH})
4254 @acindex{PATH_PROG}
4255 @caindex path_@var{variable}
4256 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4257 name of @var{prog-to-check-for} if found.  The result of this test
4258 can be overridden by setting the @var{variable} variable.  A positive
4259 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4260 variable.
4261 @end defmac
4263 @anchor{AC_PATH_PROGS}
4264 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4265   @ovar{value-if-not-found}, @dvar{path, $PATH})
4266 @acindex{PATH_PROGS}
4267 @caindex path_@var{variable}
4268 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4269 are found, set @var{variable} to the absolute name of the program
4270 found.  The result of this test can be overridden by setting the
4271 @var{variable} variable.  A positive result of this test is cached in
4272 the @code{ac_cv_path_@var{variable}} variable.
4273 @end defmac
4275 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4276   @var{progs-to-check-for}, @var{feature-test}, @
4277   @ovar{action-if-not-found}, @dvar{path, $PATH})
4278 @acindex{PATH_PROGS_FEATURE_CHECK}
4279 @caindex path_@var{variable}
4280 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4281 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4282 its value.  Otherwise, check for each program in the blank-separated
4283 list @var{progs-to-check-for} existing in @var{path}.  For each program
4284 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4285 set to the absolute name of the candidate program.  If no invocation of
4286 @var{feature-test} sets the shell variable
4287 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4288 executed.  @var{feature-test} will be run even when
4289 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4290 choose a better candidate found later in @var{path}; to accept the
4291 current setting and bypass all futher checks, @var{feature-test} can
4292 execute @code{ac_path_@var{variable}_found=:}.
4294 Note that this macro has some subtle differences from
4295 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4296 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4297 particular, @var{variable} is not set to the final value of
4298 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4299 run.  Also, on failure, any action can be performed, whereas
4300 @code{AC_CHECK_PROGS} only performs
4301 @code{@var{variable}=@var{value-if-not-found}}.
4303 Here is an example, similar to what Autoconf uses in its own configure
4304 script.  It will search for an implementation of @command{m4} that
4305 supports the @code{indir} builtin, even if it goes by the name
4306 @command{gm4} or is not the first implementation on @env{PATH}.
4308 @example
4309 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4310   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4311     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4312       test "x$m4out" = x0 \
4313       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4314     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4315 AC_SUBST([M4], [$ac_cv_path_M4])
4316 @end example
4317 @end defmac
4319 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4320   @ovar{value-if-not-found}, @dvar{path, $PATH})
4321 @acindex{PATH_TARGET_TOOL}
4322 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4323 name of the program if it is found.
4324 @end defmac
4326 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4327   @ovar{value-if-not-found}, @dvar{path, $PATH})
4328 @acindex{PATH_TOOL}
4329 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4330 name of the program if it is found.
4332 When cross-compiling, this macro will issue a warning if no program
4333 prefixed with the host type could be found.
4334 For more information, see @ref{Specifying Target Triplets}.
4335 @end defmac
4338 @node Files
4339 @section Files
4340 @cindex File, checking
4342 You might also need to check for the existence of files.  Before using
4343 these macros, ask yourself whether a runtime test might not be a better
4344 solution.  Be aware that, like most Autoconf macros, they test a feature
4345 of the host machine, and therefore, they die when cross-compiling.
4347 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4348   @ovar{action-if-not-found})
4349 @acindex{CHECK_FILE}
4350 @caindex file_@var{file}
4351 Check whether file @var{file} exists on the native system.  If it is
4352 found, execute @var{action-if-found}, otherwise do
4353 @var{action-if-not-found}, if given.  The result of this test is cached
4354 in the @code{ac_cv_file_@var{file}} variable, with characters not
4355 suitable for a variable name mapped to underscores.
4356 @end defmac
4358 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4359   @ovar{action-if-not-found})
4360 @acindex{CHECK_FILES}
4361 @caindex file_@var{file}
4362 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4363 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4364 for each file found.  The results of each test are cached in the
4365 @code{ac_cv_file_@var{file}} variable, with characters not suitable for
4366 a variable name mapped to underscores.
4367 @end defmac
4370 @node Libraries
4371 @section Library Files
4372 @cindex Library, checking
4374 The following macros check for the presence of certain C, C++, or Fortran
4375 library archive files.
4377 @anchor{AC_CHECK_LIB}
4378 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4379   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4380 @acindex{CHECK_LIB}
4381 @caindex lib_@var{library}_@var{function}
4382 Test whether the library @var{library} is available by trying to link
4383 a test program that calls function @var{function} with the library.
4384 @var{function} should be a function provided by the library.
4385 Use the base
4386 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4387 the @var{library} argument.
4389 @var{action-if-found} is a list of shell commands to run if the link
4390 with the library succeeds; @var{action-if-not-found} is a list of shell
4391 commands to run if the link fails.  If @var{action-if-found} is not
4392 specified, the default action prepends @option{-l@var{library}} to
4393 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4394 capitals).  This macro is intended to support building @code{LIBS} in
4395 a right-to-left (least-dependent to most-dependent) fashion such that
4396 library dependencies are satisfied as a natural side effect of
4397 consecutive tests.  Linkers are sensitive to library ordering
4398 so the order in which @code{LIBS} is generated is important to reliable
4399 detection of libraries.
4401 If linking with @var{library} results in unresolved symbols that would
4402 be resolved by linking with additional libraries, give those libraries
4403 as the @var{other-libraries} argument, separated by spaces:
4404 e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4405 that @var{library} is present, because linking the test program can
4406 fail with unresolved symbols.  The @var{other-libraries} argument
4407 should be limited to cases where it is desirable to test for one library
4408 in the presence of another that is not already in @code{LIBS}.
4410 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4411 in some common cases.  Many standard functions like @code{gethostbyname}
4412 appear in the standard C library on some hosts, and in special libraries
4413 like @code{nsl} on other hosts.  On some hosts the special libraries
4414 contain variant implementations that you may not want to use.  These
4415 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4416 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4418 The result of this test is cached in the
4419 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4420 @end defmac
4422 @anchor{AC_SEARCH_LIBS}
4423 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4424   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4425 @acindex{SEARCH_LIBS}
4426 @caindex search_@var{function}
4427 Search for a library defining @var{function} if it's not already
4428 available.  This equates to calling
4429 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4430 no libraries, then for each library listed in @var{search-libs}.
4432 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4433 to contain @var{function}, and run @var{action-if-found}.  If the
4434 function is not found, run @var{action-if-not-found}.
4436 If linking with @var{library} results in unresolved symbols that would
4437 be resolved by linking with additional libraries, give those libraries
4438 as the @var{other-libraries} argument, separated by spaces:
4439 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4440 that @var{function} is present, because linking the test program
4441 always fails with unresolved symbols.
4443 The result of this test is cached in the
4444 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4445 @var{function} is already available, as @samp{no} if no library
4446 containing @var{function} was found, otherwise as the
4447 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4448 @end defmac
4452 @node Library Functions
4453 @section Library Functions
4455 The following macros check for particular C library functions.
4456 If there is no macro specifically defined to check for a function you need,
4457 and you don't need to check for any special properties of
4458 it, then you can use one of the general function-check macros.
4460 @menu
4461 * Function Portability::        Pitfalls with usual functions
4462 * Particular Functions::        Special handling to find certain functions
4463 * Generic Functions::           How to find other functions
4464 @end menu
4466 @node Function Portability
4467 @subsection Portability of C Functions
4468 @cindex Portability of C functions
4469 @cindex C function portability
4471 Most usual functions can either be missing, or be buggy, or be limited
4472 on some architectures.  This section tries to make an inventory of these
4473 portability issues.  By definition, this list always requires
4474 additions.  Please help us keeping it as complete as possible.
4476 @table @asis
4477 @item @code{exit}
4478 @c @fuindex exit
4479 @prindex @code{exit}
4480 On ancient hosts, @code{exit} returned @code{int}.
4481 This is because @code{exit} predates @code{void}, and there was a long
4482 tradition of it returning @code{int}.
4484 On current hosts, the problem more likely is that @code{exit} is not
4485 declared, due to C++ problems of some sort or another.  For this reason
4486 we suggest that test programs not invoke @code{exit}, but return from
4487 @code{main} instead.
4489 @item @code{free}
4490 @c @fuindex free
4491 @prindex @code{free}
4492 The C standard says a call @code{free (NULL)} does nothing, but
4493 some old systems don't support this (e.g., NextStep).
4495 @item @code{isinf}
4496 @itemx @code{isnan}
4497 @c @fuindex isinf
4498 @c @fuindex isnan
4499 @prindex @code{isinf}
4500 @prindex @code{isnan}
4501 The C99 standard says that @code{isinf} and @code{isnan} are
4502 macros.  On some systems just macros are available
4503 (e.g., @acronym{HP-UX} and Solaris 10), on
4504 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4505 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4506 these functions are declared in nonstandard headers like
4507 @code{<sunmath.h>} and defined in non-default libraries like
4508 @option{-lm} or @option{-lsunmath}.
4510 The C99 @code{isinf} and @code{isnan} macros work correctly with
4511 @code{long double} arguments, but pre-C99 systems that use functions
4512 typically assume @code{double} arguments.  On such a system,
4513 @code{isinf} incorrectly returns true for a finite @code{long double}
4514 argument that is outside the range of @code{double}.
4516 The best workaround for these issues is to use gnulib modules
4517 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4518 solution involves code like the following.
4520 @smallexample
4521 #include <math.h>
4523 #ifndef isnan
4524 # define isnan(x) \
4525     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4526      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4527      : isnan_f (x))
4528 static inline int isnan_f  (float       x) @{ return x != x; @}
4529 static inline int isnan_d  (double      x) @{ return x != x; @}
4530 static inline int isnan_ld (long double x) @{ return x != x; @}
4531 #endif
4533 #ifndef isinf
4534 # define isinf(x) \
4535     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4536      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4537      : isinf_f (x))
4538 static inline int isinf_f  (float       x)
4539 @{ return !isnan (x) && isnan (x - x); @}
4540 static inline int isinf_d  (double      x)
4541 @{ return !isnan (x) && isnan (x - x); @}
4542 static inline int isinf_ld (long double x)
4543 @{ return !isnan (x) && isnan (x - x); @}
4544 #endif
4545 @end smallexample
4547 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4548 compilers that lack the @code{inline} keyword.  Some optimizing
4549 compilers mishandle these definitions, but systems with that bug
4550 typically have many other floating point corner-case compliance problems
4551 anyway, so it's probably not worth worrying about.
4553 @item @code{malloc}
4554 @c @fuindex malloc
4555 @prindex @code{malloc}
4556 The C standard says a call @code{malloc (0)} is implementation
4557 dependent.  It can return either @code{NULL} or a new non-null pointer.
4558 The latter is more common (e.g., the @acronym{GNU} C Library) but is by
4559 no means universal.  @code{AC_FUNC_MALLOC}
4560 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4562 @item @code{putenv}
4563 @c @fuindex putenv
4564 @prindex @code{putenv}
4565 Posix prefers @code{setenv} to @code{putenv}; among other things,
4566 @code{putenv} is not required of all Posix implementations, but
4567 @code{setenv} is.
4569 Posix specifies that @code{putenv} puts the given string directly in
4570 @code{environ}, but some systems make a copy of it instead (e.g.,
4571 glibc 2.0, or @acronym{BSD}).  And when a copy is made, @code{unsetenv} might
4572 not free it, causing a memory leak (e.g., Free@acronym{BSD} 4).
4574 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4575 environment, but this is not standard usage and it dumps core
4576 on some systems (e.g., AIX).
4578 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4579 environment, rather than inserting it with an empty value.
4581 @item @code{realloc}
4582 @c @fuindex realloc
4583 @prindex @code{realloc}
4584 The C standard says a call @code{realloc (NULL, size)} is equivalent
4585 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4586 NextStep).
4588 @item @code{signal} handler
4589 @c @fuindex signal
4590 @prindex @code{signal}
4591 @prindex @code{sigaction}
4592 Normally @code{signal} takes a handler function with a return type of
4593 @code{void}, but some old systems required @code{int} instead.  Any
4594 actual @code{int} value returned is not used; this is only a
4595 difference in the function prototype demanded.
4597 All systems we know of in current use return @code{void}.  The
4598 @code{int} was to support K&R C, where of course @code{void} is not
4599 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4600 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4601 all cases.
4603 In most cases, it is more robust to use @code{sigaction} when it is
4604 available, rather than @code{signal}.
4606 @item @code{snprintf}
4607 @c @fuindex snprintf
4608 @prindex @code{snprintf}
4609 @c @fuindex vsnprintf
4610 @prindex @code{vsnprintf}
4611 The C99 standard says that if the output array isn't big enough
4612 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4613 truncate the output and return the number of bytes that ought to have
4614 been produced.  Some older systems return the truncated length (e.g.,
4615 @acronym{GNU} C Library 2.0.x or @sc{irix} 6.5), some a negative value
4616 (e.g., earlier @acronym{GNU} C Library versions), and some the buffer
4617 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4618 older systems ignore the length and overrun the buffer (e.g., 64-bit
4619 Solaris 7).
4621 @item @code{sprintf}
4622 @c @fuindex sprintf
4623 @prindex @code{sprintf}
4624 @c @fuindex vsprintf
4625 @prindex @code{vsprintf}
4626 The C standard says @code{sprintf} and @code{vsprintf} return the
4627 number of bytes written.  On some ancient systems (SunOS 4 for
4628 instance) they return the buffer pointer instead, but these no
4629 longer need to be worried about.
4631 @item @code{sscanf}
4632 @c @fuindex sscanf
4633 @prindex @code{sscanf}
4634 On various old systems, e.g., @acronym{HP-UX} 9, @code{sscanf} requires
4635 that its
4636 input string be writable (though it doesn't actually change it).  This
4637 can be a problem when using @command{gcc} since it normally puts
4638 constant strings in read-only memory (@pxref{Incompatibilities,
4639 Incompatibilities of @acronym{GCC}, , gcc, Using and
4640 Porting the @acronym{GNU} Compiler Collection}).  Apparently in some cases even
4641 having format strings read-only can be a problem.
4643 @item @code{strerror_r}
4644 @c @fuindex strerror_r
4645 @prindex @code{strerror_r}
4646 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4647 systems (e.g., @acronym{GNU} C Library version 2.2.4) provide a
4648 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4649 can detect which is in use (@pxref{Particular Functions}).
4651 @item @code{strnlen}
4652 @c @fuindex strnlen
4653 @prindex @code{strnlen}
4654 @acronym{AIX} 4.3 provides a broken version which produces the
4655 following results:
4657 @example
4658 strnlen ("foobar", 0) = 0
4659 strnlen ("foobar", 1) = 3
4660 strnlen ("foobar", 2) = 2
4661 strnlen ("foobar", 3) = 1
4662 strnlen ("foobar", 4) = 0
4663 strnlen ("foobar", 5) = 6
4664 strnlen ("foobar", 6) = 6
4665 strnlen ("foobar", 7) = 6
4666 strnlen ("foobar", 8) = 6
4667 strnlen ("foobar", 9) = 6
4668 @end example
4670 @item @code{sysconf}
4671 @c @fuindex sysconf
4672 @prindex @code{sysconf}
4673 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., @acronym{HP-UX}
4674 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4675 @code{#ifdef}.
4677 @item @code{unlink}
4678 @c @fuindex unlink
4679 @prindex @code{unlink}
4680 The Posix spec says that @code{unlink} causes the given file to be
4681 removed only after there are no more open file handles for it.  Some
4682 non-Posix hosts have trouble with this requirement, though,
4683 and some @acronym{DOS} variants even corrupt the file system.
4685 @item @code{unsetenv}
4686 @c @fuindex unsetenv
4687 @prindex @code{unsetenv}
4688 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4689 can be removed with a call @code{putenv ("FOO=")}, as described under
4690 @code{putenv} above.
4692 @item @code{va_copy}
4693 @c @fuindex va_copy
4694 @prindex @code{va_copy}
4695 The C99 standard provides @code{va_copy} for copying
4696 @code{va_list} variables.  It may be available in older environments
4697 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4698 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4699 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4700 portability.
4702 @item @code{va_list}
4703 @c @fuindex va_list
4704 @prindex @code{va_list}
4705 @code{va_list} is not necessarily just a pointer.  It can be a
4706 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4707 not portable.  Or it can be an array (e.g., @command{gcc} in some
4708 PowerPC configurations), which means as a function parameter it can be
4709 effectively call-by-reference and library routines might modify the
4710 value back in the caller (e.g., @code{vsnprintf} in the @acronym{GNU} C Library
4711 2.1).
4713 @item Signed @code{>>}
4714 Normally the C @code{>>} right shift of a signed type replicates the
4715 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4716 taken since Standard C doesn't require that behavior.  On those
4717 few processors without a native arithmetic shift (for instance Cray
4718 vector systems) zero bits may be shifted in, the same as a shift of an
4719 unsigned type.
4721 @item Integer @code{/}
4722 C divides signed integers by truncating their quotient toward zero,
4723 yielding the same result as Fortran.  However, before C99 the standard
4724 allowed C implementations to take the floor or ceiling of the quotient
4725 in some cases.  Hardly any implementations took advantage of this
4726 freedom, though, and it's probably not worth worrying about this issue
4727 nowadays.
4728 @end table
4731 @node Particular Functions
4732 @subsection Particular Function Checks
4733 @cindex Function, checking
4735 These macros check for particular C functions---whether they exist, and
4736 in some cases how they respond when given certain arguments.
4738 @anchor{AC_FUNC_ALLOCA}
4739 @defmac AC_FUNC_ALLOCA
4740 @acindex{FUNC_ALLOCA}
4741 @cvindex C_ALLOCA
4742 @cvindex HAVE_ALLOCA_H
4743 @ovindex ALLOCA
4744 @c @fuindex alloca
4745 @prindex @code{alloca}
4746 @hdrindex{alloca.h}
4747 @c @caindex working_alloca_h
4748 Check how to get @code{alloca}.  Tries to get a builtin version by
4749 checking for @file{alloca.h} or the predefined C preprocessor macros
4750 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4751 it defines @code{HAVE_ALLOCA_H}.
4753 If those attempts fail, it looks for the function in the standard C
4754 library.  If any of those methods succeed, it defines
4755 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4756 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4757 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4758 garbage collect).  This variable is separate from @code{LIBOBJS} so
4759 multiple programs can share the value of @code{ALLOCA} without needing
4760 to create an actual library, in case only some of them use the code in
4761 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4762 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4764 This macro does not try to get @code{alloca} from the System V R3
4765 @file{libPW} or the System V R4 @file{libucb} because those libraries
4766 contain some incompatible functions that cause trouble.  Some versions
4767 do not even contain @code{alloca} or contain a buggy version.  If you
4768 still want to use their @code{alloca}, use @code{ar} to extract
4769 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4771 Source files that use @code{alloca} should start with a piece of code
4772 like the following, to declare it properly.
4774 @example
4775 @group
4776 #ifdef HAVE_ALLOCA_H
4777 # include <alloca.h>
4778 #elif defined __GNUC__
4779 # define alloca __builtin_alloca
4780 #elif defined _AIX
4781 # define alloca __alloca
4782 #elif defined _MSC_VER
4783 # include <malloc.h>
4784 # define alloca _alloca
4785 #else
4786 # include <stddef.h>
4787 # ifdef  __cplusplus
4788 extern "C"
4789 # endif
4790 void *alloca (size_t);
4791 #endif
4792 @end group
4793 @end example
4794 @end defmac
4796 @defmac AC_FUNC_CHOWN
4797 @acindex{FUNC_CHOWN}
4798 @cvindex HAVE_CHOWN
4799 @c @fuindex chown
4800 @prindex @code{chown}
4801 @caindex func_chown_works
4802 If the @code{chown} function is available and works (in particular, it
4803 should accept @option{-1} for @code{uid} and @code{gid}), define
4804 @code{HAVE_CHOWN}.  The result of this macro is cached in the
4805 @code{ac_cv_func_chown_works} variable.
4806 @end defmac
4808 @anchor{AC_FUNC_CLOSEDIR_VOID}
4809 @defmac AC_FUNC_CLOSEDIR_VOID
4810 @acindex{FUNC_CLOSEDIR_VOID}
4811 @cvindex CLOSEDIR_VOID
4812 @c @fuindex closedir
4813 @prindex @code{closedir}
4814 @caindex func_closedir_void
4815 If the @code{closedir} function does not return a meaningful value,
4816 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4817 return value for an error indicator.
4819 Currently this test is implemented by running a test program.  When
4820 cross compiling the pessimistic assumption that @code{closedir} does not
4821 return a meaningful value is made.
4823 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
4824 variable.
4826 This macro is obsolescent, as @code{closedir} returns a meaningful value
4827 on current systems.  New programs need not use this macro.
4828 @end defmac
4830 @defmac AC_FUNC_ERROR_AT_LINE
4831 @acindex{FUNC_ERROR_AT_LINE}
4832 @c @fuindex error_at_line
4833 @prindex @code{error_at_line}
4834 @caindex lib_error_at_line
4835 If the @code{error_at_line} function is not found, require an
4836 @code{AC_LIBOBJ} replacement of @samp{error}.
4838 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
4839 variable.
4840 @end defmac
4842 @defmac AC_FUNC_FNMATCH
4843 @acindex{FUNC_FNMATCH}
4844 @c @fuindex fnmatch
4845 @prindex @code{fnmatch}
4846 @caindex func_fnmatch_works
4847 If the @code{fnmatch} function conforms to Posix, define
4848 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4849 the bugs in Solaris 2.4.
4851 Unlike the other specific
4852 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4853 broken/missing @code{fnmatch}.  This is for historical reasons.
4854 See @code{AC_REPLACE_FNMATCH} below.
4856 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
4857 variable.
4859 This macro is obsolescent.  New programs should use Gnulib's
4860 @code{fnmatch-posix} module.  @xref{Gnulib}.
4861 @end defmac
4863 @defmac AC_FUNC_FNMATCH_GNU
4864 @acindex{FUNC_FNMATCH_GNU}
4865 @c @fuindex fnmatch
4866 @prindex @code{fnmatch}
4867 @caindex func_fnmatch_gnu
4868 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4869 whether @code{fnmatch} supports @acronym{GNU} extensions.  Detect common
4870 implementation bugs, for example, the bugs in the @acronym{GNU} C
4871 Library 2.1.
4873 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
4874 variable.
4876 This macro is obsolescent.  New programs should use Gnulib's
4877 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4878 @end defmac
4880 @anchor{AC_FUNC_FORK}
4881 @defmac AC_FUNC_FORK
4882 @acindex{FUNC_FORK}
4883 @cvindex HAVE_VFORK_H
4884 @cvindex HAVE_WORKING_FORK
4885 @cvindex HAVE_WORKING_VFORK
4886 @cvindex vfork
4887 @c @fuindex fork
4888 @prindex @code{fork}
4889 @c @fuindex vfork
4890 @prindex @code{vfork}
4891 @hdrindex{vfork.h}
4892 @c @caindex func_fork
4893 @c @caindex func_fork_works
4894 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4895 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4896 checks whether @code{fork} is just a stub by trying to run it.
4898 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4899 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4900 define @code{vfork} to be @code{fork} for backward compatibility with
4901 previous versions of @command{autoconf}.  This macro checks for several known
4902 errors in implementations of @code{vfork} and considers the system to not
4903 have a working @code{vfork} if it detects any of them.  It is not considered
4904 to be an implementation error if a child's invocation of @code{signal}
4905 modifies the parent's signal handler, since child processes rarely change
4906 their signal handlers.
4908 Since this macro defines @code{vfork} only for backward compatibility with
4909 previous versions of @command{autoconf} you're encouraged to define it
4910 yourself in new code:
4911 @example
4912 @group
4913 #ifndef HAVE_WORKING_VFORK
4914 # define vfork fork
4915 #endif
4916 @end group
4917 @end example
4918 @end defmac
4920 @defmac AC_FUNC_FSEEKO
4921 @acindex{FUNC_FSEEKO}
4922 @cvindex _LARGEFILE_SOURCE
4923 @cvindex HAVE_FSEEKO
4924 @c @fuindex fseeko
4925 @prindex @code{fseeko}
4926 @c @fuindex ftello
4927 @prindex @code{ftello}
4928 @c @caindex sys_largefile_source
4929 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
4930 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
4931 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
4932 may occur when compiling with @code{AC_SYS_LARGEFILE} on
4933 largefile-sensitive systems where @code{off_t} does not default to a
4934 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
4935 @end defmac
4937 @defmac AC_FUNC_GETGROUPS
4938 @acindex{FUNC_GETGROUPS}
4939 @cvindex HAVE_GETGROUPS
4940 @ovindex GETGROUPS_LIBS
4941 @c @fuindex getgroups
4942 @prindex @code{getgroups}
4943 @caindex func_getgroups_works
4944 If the @code{getgroups} function is available and works (unlike on
4945 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
4946 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
4947 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
4948 @end defmac
4950 @anchor{AC_FUNC_GETLOADAVG}
4951 @defmac AC_FUNC_GETLOADAVG
4952 @acindex{FUNC_GETLOADAVG}
4953 @cvindex SVR4
4954 @cvindex DGUX
4955 @cvindex UMAX
4956 @cvindex UMAX4_3
4957 @cvindex HAVE_NLIST_H
4958 @cvindex NLIST_NAME_UNION
4959 @cvindex GETLOADAVG_PRIVILEGED
4960 @cvindex NEED_SETGID
4961 @cvindex C_GETLOADAVG
4962 @ovindex LIBOBJS
4963 @ovindex NEED_SETGID
4964 @ovindex KMEM_GROUP
4965 @ovindex GETLOADAVG_LIBS
4966 @c @fuindex getloadavg
4967 @prindex @code{getloadavg}
4968 Check how to get the system load averages.  To perform its tests
4969 properly, this macro needs the file @file{getloadavg.c}; therefore, be
4970 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
4971 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
4973 If the system has the @code{getloadavg} function, define
4974 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
4975 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
4976 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
4977 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
4978 possibly define several other C preprocessor macros and output
4979 variables:
4981 @enumerate
4982 @item
4983 Define @code{C_GETLOADAVG}.
4985 @item
4986 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
4987 those systems.
4989 @item
4990 @hdrindex{nlist.h}
4991 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
4993 @item
4994 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
4995 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
4996 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
4998 @item
4999 Programs may need to be installed set-group-ID (or set-user-ID) for
5000 @code{getloadavg} to work.  In this case, define
5001 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5002 to @samp{true} (and otherwise to @samp{false}), and set
5003 @code{KMEM_GROUP} to the name of the group that should own the installed
5004 program.
5005 @end enumerate
5007 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5008 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5009 @end defmac
5011 @anchor{AC_FUNC_GETMNTENT}
5012 @defmac AC_FUNC_GETMNTENT
5013 @acindex{FUNC_GETMNTENT}
5014 @cvindex HAVE_GETMNTENT
5015 @c @fuindex getmntent
5016 @prindex @code{getmntent}
5017 @caindex search_getmntent
5018 Check for @code{getmntent} in the standard C library, and then in the
5019 @file{sun}, @file{seq}, and @file{gen} libraries, for @sc{unicos},
5020 @sc{irix} 4, @sc{ptx}, and UnixWare, respectively.  Then, if
5021 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5022 @code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5023 @code{ac_cv_func_getmntent} to @code{no}.
5025 The result of this macro can be overridden by setting the cache variable
5026 @code{ac_cv_search_getmntent}.
5027 @end defmac
5029 @defmac AC_FUNC_GETPGRP
5030 @acindex{FUNC_GETPGRP}
5031 @cvindex GETPGRP_VOID
5032 @c @fuindex getpgid
5033 @c @fuindex getpgrp
5034 @prindex @code{getpgid}
5035 @prindex @code{getpgrp}
5036 @caindex func_getpgrp_void
5037 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5038 @code{getpgrp}; this is the Posix behavior.  On older @acronym{BSD}
5039 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5040 behaves like Posix's @code{getpgid}.
5042 @example
5043 #ifdef GETPGRP_VOID
5044   pid = getpgrp ();
5045 #else
5046   pid = getpgrp (0);
5047 #endif
5048 @end example
5050 This macro does not check whether
5051 @code{getpgrp} exists at all; if you need to work in that situation,
5052 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5054 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5055 variable.
5057 This macro is obsolescent, as current systems have a @code{getpgrp}
5058 whose signature conforms to Posix.  New programs need not use this macro.
5059 @end defmac
5061 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5062 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5063 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5064 @c @fuindex lstat
5065 @prindex @code{lstat}
5066 @caindex func_lstat_dereferences_slashed_symlink
5067 If @file{link} is a symbolic link, then @code{lstat} should treat
5068 @file{link/} the same as @file{link/.}.  However, many older
5069 @code{lstat} implementations incorrectly ignore trailing slashes.
5071 It is safe to assume that if @code{lstat} incorrectly ignores
5072 trailing slashes, then other symbolic-link-aware functions like
5073 @code{unlink} also incorrectly ignore trailing slashes.
5075 If @code{lstat} behaves properly, define
5076 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5077 @code{AC_LIBOBJ} replacement of @code{lstat}.
5079 The result of this macro is cached in the
5080 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5081 @end defmac
5083 @defmac AC_FUNC_MALLOC
5084 @acindex{FUNC_MALLOC}
5085 @cvindex HAVE_MALLOC
5086 @cvindex malloc
5087 @c @fuindex malloc
5088 @prindex @code{malloc}
5089 @caindex func_malloc_0_nonnull
5090 If the @code{malloc} function is compatible with the @acronym{GNU} C
5091 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5092 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5093 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5094 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5095 native @code{malloc} is not used in the main project.
5097 Typically, the replacement file @file{malloc.c} should look like (note
5098 the @samp{#undef malloc}):
5100 @verbatim
5101 #include <config.h>
5102 #undef malloc
5104 #include <sys/types.h>
5106 void *malloc ();
5108 /* Allocate an N-byte block of memory from the heap.
5109    If N is zero, allocate a 1-byte block.  */
5111 void *
5112 rpl_malloc (size_t n)
5114   if (n == 0)
5115     n = 1;
5116   return malloc (n);
5118 @end verbatim
5120 The result of this macro is cached in the
5121 @code{ac_cv_func_malloc_0_nonnull} variable.
5122 @end defmac
5124 @defmac AC_FUNC_MBRTOWC
5125 @acindex{FUNC_MBRTOWC}
5126 @cvindex HAVE_MBRTOWC
5127 @c @fuindex mbrtowc
5128 @prindex @code{mbrtowc}
5129 @caindex func_mbrtowc
5130 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5131 type @code{mbstate_t} are properly declared.
5133 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5134 variable.
5135 @end defmac
5137 @defmac AC_FUNC_MEMCMP
5138 @acindex{FUNC_MEMCMP}
5139 @ovindex LIBOBJS
5140 @c @fuindex memcmp
5141 @prindex @code{memcmp}
5142 @caindex func_memcmp_working
5143 If the @code{memcmp} function is not available, or does not work on
5144 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5145 bytes or more and with at least one buffer not starting on a 4-byte
5146 boundary (such as the one on NeXT x86 OpenStep), require an
5147 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5149 The result of this macro is cached in the
5150 @code{ac_cv_func_memcmp_working} variable.
5152 This macro is obsolescent, as current systems have a working
5153 @code{memcmp}.  New programs need not use this macro.
5154 @end defmac
5156 @defmac AC_FUNC_MKTIME
5157 @acindex{FUNC_MKTIME}
5158 @ovindex LIBOBJS
5159 @c @fuindex mktime
5160 @prindex @code{mktime}
5161 @caindex func_working_mktime
5162 If the @code{mktime} function is not available, or does not work
5163 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5164 For the purposes of this test, @code{mktime} should conform to the
5165 Posix standard and should be the inverse of
5166 @code{localtime}.
5168 The result of this macro is cached in the
5169 @code{ac_cv_func_working_mktime} variable.
5170 @end defmac
5172 @anchor{AC_FUNC_MMAP}
5173 @defmac AC_FUNC_MMAP
5174 @acindex{FUNC_MMAP}
5175 @cvindex HAVE_MMAP
5176 @c @fuindex mmap
5177 @prindex @code{mmap}
5178 @caindex func_mmap_fixed_mapped
5179 If the @code{mmap} function exists and works correctly, define
5180 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5181 memory.
5183 The result of this macro is cached in the
5184 @code{ac_cv_func_mmap_fixed_mapped} variable.
5185 @end defmac
5187 @defmac AC_FUNC_OBSTACK
5188 @acindex{FUNC_OBSTACK}
5189 @cvindex HAVE_OBSTACK
5190 @cindex obstack
5191 @caindex func_obstack
5192 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5193 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5195 The result of this macro is cached in the @code{ac_cv_func_obstack}
5196 variable.
5197 @end defmac
5199 @defmac AC_FUNC_REALLOC
5200 @acindex{FUNC_REALLOC}
5201 @cvindex HAVE_REALLOC
5202 @cvindex realloc
5203 @c @fuindex realloc
5204 @prindex @code{realloc}
5205 @caindex func_realloc_0_nonnull
5206 If the @code{realloc} function is compatible with the @acronym{GNU} C
5207 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5208 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5209 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5210 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5211 the native @code{realloc} is not used in the main project.  See
5212 @code{AC_FUNC_MALLOC} for details.
5214 The result of this macro is cached in the
5215 @code{ac_cv_func_realloc_0_nonnull} variable.
5216 @end defmac
5218 @defmac AC_FUNC_SELECT_ARGTYPES
5219 @acindex{FUNC_SELECT_ARGTYPES}
5220 @cvindex SELECT_TYPE_ARG1
5221 @cvindex SELECT_TYPE_ARG234
5222 @cvindex SELECT_TYPE_ARG5
5223 @c @fuindex select
5224 @prindex @code{select}
5225 @c @caindex func_select_args
5226 Determines the correct type to be passed for each of the
5227 @code{select} function's arguments, and defines those types
5228 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5229 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5230 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5231 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5233 This macro is obsolescent, as current systems have a @code{select} whose
5234 signature conforms to Posix.  New programs need not use this macro.
5235 @end defmac
5237 @defmac AC_FUNC_SETPGRP
5238 @acindex{FUNC_SETPGRP}
5239 @cvindex SETPGRP_VOID
5240 @c @fuindex setpgrp
5241 @prindex @code{setpgrp}
5242 @caindex func_setpgrp_void
5243 If @code{setpgrp} takes no argument (the Posix version), define
5244 @code{SETPGRP_VOID}.  Otherwise, it is the @acronym{BSD} version, which takes
5245 two process IDs as arguments.  This macro does not check whether
5246 @code{setpgrp} exists at all; if you need to work in that situation,
5247 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5249 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5250 variable.
5252 This macro is obsolescent, as current systems have a @code{setpgrp}
5253 whose signature conforms to Posix.  New programs need not use this macro.
5254 @end defmac
5256 @defmac AC_FUNC_STAT
5257 @defmacx AC_FUNC_LSTAT
5258 @acindex{FUNC_STAT}
5259 @acindex{FUNC_LSTAT}
5260 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5261 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5262 @c @fuindex stat
5263 @prindex @code{stat}
5264 @c @fuindex lstat
5265 @prindex @code{lstat}
5266 @caindex func_stat_empty_string_bug
5267 @caindex func_lstat_empty_string_bug
5268 Determine whether @code{stat} or @code{lstat} have the bug that it
5269 succeeds when given the zero-length file name as argument.  The @code{stat}
5270 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5271 this.
5273 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5274 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5275 replacement of it.
5277 The results of these macros are cached in the
5278 @code{ac_cv_func_stat_empty_string_bug} and the
5279 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5281 These macros are obsolescent, as no current systems have the bug.
5282 New programs need not use these macros.
5283 @end defmac
5285 @anchor{AC_FUNC_STRCOLL}
5286 @defmac AC_FUNC_STRCOLL
5287 @acindex{FUNC_STRCOLL}
5288 @cvindex HAVE_STRCOLL
5289 @c @fuindex strcoll
5290 @prindex @code{strcoll}
5291 @caindex func_strcoll_works
5292 If the @code{strcoll} function exists and works correctly, define
5293 @code{HAVE_STRCOLL}.  This does a bit more than
5294 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5295 definitions of @code{strcoll} that should not be used.
5297 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5298 variable.
5299 @end defmac
5301 @defmac AC_FUNC_STRERROR_R
5302 @acindex{FUNC_STRERROR_R}
5303 @cvindex HAVE_STRERROR_R
5304 @cvindex HAVE_DECL_STRERROR_R
5305 @cvindex STRERROR_R_CHAR_P
5306 @c @fuindex strerror_r
5307 @caindex func_strerror_r_char_p
5308 @prindex @code{strerror_r}
5309 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5310 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5311 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5312 returns an @code{int} error number.  The Thread-Safe Functions option of
5313 Posix requires @code{strerror_r} to return @code{int}, but
5314 many systems (including, for example, version 2.2.4 of the @acronym{GNU} C
5315 Library) return a @code{char *} value that is not necessarily equal to
5316 the buffer argument.
5318 The result of this macro is cached in the
5319 @code{ac_cv_func_strerror_r_char_p} variable.
5320 @end defmac
5322 @anchor{AC_FUNC_STRFTIME}
5323 @defmac AC_FUNC_STRFTIME
5324 @acindex{FUNC_STRFTIME}
5325 @cvindex HAVE_STRFTIME
5326 @c @fuindex strftime
5327 @prindex @code{strftime}
5328 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5329 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5331 This macro is obsolescent, as no current systems require the @file{intl}
5332 library for @code{strftime}.  New programs need not use this macro.
5333 @end defmac
5335 @defmac AC_FUNC_STRTOD
5336 @acindex{FUNC_STRTOD}
5337 @ovindex POW_LIB
5338 @c @fuindex strtod
5339 @prindex @code{strtod}
5340 @caindex func_strtod
5341 @caindex func_pow
5342 If the @code{strtod} function does not exist or doesn't work correctly,
5343 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5344 because @file{strtod.c} is likely to need @samp{pow}, set the output
5345 variable @code{POW_LIB} to the extra library needed.
5347 This macro caches its result in the @code{ac_cv_func_strtod} variable
5348 and depends upon the result in the @code{ac_cv_func_pow} variable.
5349 @end defmac
5351 @defmac AC_FUNC_STRTOLD
5352 @acindex{FUNC_STRTOLD}
5353 @cvindex HAVE_STRTOLD
5354 @prindex @code{strtold}
5355 @caindex func_strtold
5356 If the @code{strtold} function exists and conforms to C99, define
5357 @code{HAVE_STRTOLD}.
5359 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5360 @end defmac
5362 @defmac AC_FUNC_STRNLEN
5363 @acindex{FUNC_STRNLEN}
5364 @cvindex HAVE_STRNLEN
5365 @c @fuindex strnlen
5366 @prindex @code{strnlen}
5367 @caindex func_strnlen_working
5368 If the @code{strnlen} function is not available, or is buggy (like the one
5369 from @acronym{AIX} 4.3), require an @code{AC_LIBOBJ} replacement for it.
5371 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5372 variable.
5373 @end defmac
5375 @anchor{AC_FUNC_UTIME_NULL}
5376 @defmac AC_FUNC_UTIME_NULL
5377 @acindex{FUNC_UTIME_NULL}
5378 @cvindex HAVE_UTIME_NULL
5379 @c @fuindex utime
5380 @prindex @code{utime}
5381 @caindex func_utime_null
5382 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5383 the present, define @code{HAVE_UTIME_NULL}.
5385 This macro caches its result in the @code{ac_cv_func_utime_null}
5386 variable.
5388 This macro is obsolescent, as all current systems have a @code{utime}
5389 that behaves this way.  New programs need not use this macro.
5390 @end defmac
5392 @anchor{AC_FUNC_VPRINTF}
5393 @defmac AC_FUNC_VPRINTF
5394 @acindex{FUNC_VPRINTF}
5395 @cvindex HAVE_VPRINTF
5396 @cvindex HAVE_DOPRNT
5397 @c @fuindex vprintf
5398 @prindex @code{vprintf}
5399 @c @fuindex vsprintf
5400 @prindex @code{vsprintf}
5401 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5402 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5403 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5404 are also available.)
5406 This macro is obsolescent, as all current systems have @code{vprintf}.
5407 New programs need not use this macro.
5408 @end defmac
5410 @defmac AC_REPLACE_FNMATCH
5411 @acindex{REPLACE_FNMATCH}
5412 @c @fuindex fnmatch
5413 @prindex @code{fnmatch}
5414 @hdrindex{fnmatch.h}
5415 @caindex func_fnmatch_works
5416 If the @code{fnmatch} function does not conform to Posix (see
5417 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5419 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5420 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5421 copy of the source code of @acronym{GNU} @code{fnmatch}.  If necessary,
5422 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5423 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5424 included in place of the system @code{<fnmatch.h>}.
5426 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5427 variable.
5429 This macro is obsolescent, as it assumes the use of particular source
5430 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5431 which provides this macro along with the source files.  @xref{Gnulib}.
5432 @end defmac
5436 @node Generic Functions
5437 @subsection Generic Function Checks
5439 These macros are used to find functions not covered by the ``particular''
5440 test macros.  If the functions might be in libraries other than the
5441 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5442 If you need to check the behavior of a function as well as find out
5443 whether it is present, you have to write your own test for
5444 it (@pxref{Writing Tests}).
5446 @anchor{AC_CHECK_FUNC}
5447 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5448   @ovar{action-if-not-found})
5449 @acindex{CHECK_FUNC}
5450 @caindex func_@var{function}
5451 If C function @var{function} is available, run shell commands
5452 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5453 want to define a symbol if the function is available, consider using
5454 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5455 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5456 standardized than C++.  (@pxref{Language Choice}, for more information
5457 about selecting the language for checks.)
5459 This macro caches its result in the @code{ac_cv_func_@var{function}}
5460 variable.
5461 @end defmac
5463 @anchor{AC_CHECK_FUNCS}
5464 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5465   @ovar{action-if-not-found})
5466 @acindex{CHECK_FUNCS}
5467 @cvindex HAVE_@var{function}
5468 For each @var{function} enumerated in the blank-or-newline-separated argument
5469 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5470 If @var{action-if-found} is given, it is additional shell code to
5471 execute when one of the functions is found.  You can give it a value of
5472 @samp{break} to break out of the loop on the first match.  If
5473 @var{action-if-not-found} is given, it is executed when one of the
5474 functions is not found.
5476 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5477 @end defmac
5479 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5480 @acindex{CHECK_FUNCS_ONCE}
5481 @cvindex HAVE_@var{function}
5482 For each @var{function} enumerated in the blank-or-newline-separated argument
5483 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5484 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5485 checking code at most once, so that @command{configure} is smaller and
5486 faster; but the checks cannot be conditionalized and are always done once,
5487 early during the @command{configure} run.
5488 @end defmac
5490 @sp 1
5492 Autoconf follows a philosophy that was formed over the years by those
5493 who have struggled for portability: isolate the portability issues in
5494 specific files, and then program as if you were in a Posix
5495 environment.  Some functions may be missing or unfixable, and your
5496 package must be ready to replace them.
5498 Suitable replacements for many such problem functions are available from
5499 Gnulib (@pxref{Gnulib}).
5501 @defmac AC_LIBOBJ (@var{function})
5502 @acindex{LIBOBJ}
5503 @ovindex LIBOBJS
5504 Specify that @samp{@var{function}.c} must be included in the executables
5505 to replace a missing or broken implementation of @var{function}.
5507 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5508 variable @code{LIBOBJS} if it is not already in, and calls
5509 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5510 directly change @code{LIBOBJS}, since this is not traceable.
5511 @end defmac
5513 @defmac AC_LIBSOURCE (@var{file})
5514 @acindex{LIBSOURCE}
5515 Specify that @var{file} might be needed to compile the project.  If you
5516 need to know what files might be needed by a @file{configure.ac}, you
5517 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5519 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5520 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5521 that case, since shell variables cannot be traced statically, you must
5522 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5523 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5524 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5525 @code{"foo"} or @code{"bar"}, you should do:
5527 @example
5528 AC_LIBSOURCE([foo.c])
5529 AC_LIBSOURCE([bar.c])
5530 AC_LIBOBJ([$foo_or_bar])
5531 @end example
5533 @noindent
5534 There is usually a way to avoid this, however, and you are encouraged to
5535 simply call @code{AC_LIBOBJ} with literal arguments.
5537 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5538 slightly different semantics: the old macro took the function name,
5539 e.g., @code{foo}, as its argument rather than the file name.
5540 @end defmac
5542 @defmac AC_LIBSOURCES (@var{files})
5543 @acindex{LIBSOURCES}
5544 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5545 comma-separated M4 list.  Thus, the above example might be rewritten:
5547 @example
5548 AC_LIBSOURCES([foo.c, bar.c])
5549 AC_LIBOBJ([$foo_or_bar])
5550 @end example
5551 @end defmac
5553 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5554 @acindex{CONFIG_LIBOBJ_DIR}
5555 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5556 @var{directory}, a name relative to the top level of the
5557 source tree.  The replacement directory defaults to @file{.}, the top
5558 level directory, and the most typical value is @file{lib}, corresponding
5559 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5561 @command{configure} might need to know the replacement directory for the
5562 following reasons: (i) some checks use the replacement files, (ii) some
5563 macros bypass broken system headers by installing links to the
5564 replacement headers (iii) when used in conjunction with Automake,
5565 within each makefile, @var{directory} is used as a relative path
5566 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5567 @code{LTLIBOBJS}, etc.
5568 @end defmac
5570 @sp 1
5572 It is common to merely check for the existence of a function, and ask
5573 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5574 a convenient shorthand.
5576 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5577 @acindex{REPLACE_FUNCS}
5578 @cvindex HAVE_@var{function}
5579 @ovindex LIBOBJS
5580 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5581 @var{action-if-not-found}.  You can declare your replacement function by
5582 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5583 system has the function, it probably declares it in a header file you
5584 should be including, so you shouldn't redeclare it lest your declaration
5585 conflict.
5586 @end defmac
5588 @node Header Files
5589 @section Header Files
5590 @cindex Header, checking
5592 The following macros check for the presence of certain C header files.
5593 If there is no macro specifically defined to check for a header file you need,
5594 and you don't need to check for any special properties of
5595 it, then you can use one of the general header-file check macros.
5597 @menu
5598 * Header Portability::          Collected knowledge on common headers
5599 * Particular Headers::          Special handling to find certain headers
5600 * Generic Headers::             How to find other headers
5601 @end menu
5603 @node Header Portability
5604 @subsection Portability of Headers
5605 @cindex Portability of headers
5606 @cindex Header portability
5608 This section tries to collect knowledge about common headers, and the
5609 problems they cause.  By definition, this list always requires
5610 additions.  Please help us keeping it as complete as possible.
5612 @table @asis
5614 @item @file{limits.h}
5615 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5616 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5617 environments (e.g., default @acronym{GCC} 4.0.2 + glibc 2.4) do not
5618 define them.
5620 @item @file{inttypes.h} vs.@: @file{stdint.h}
5621 @hdrindex{inttypes.h}
5622 @hdrindex{stdint.h}
5623 The C99 standard says that @file{inttypes.h} includes
5624 @file{stdint.h}, so there's no need to include @file{stdint.h}
5625 separately in a standard environment.  Some implementations have
5626 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5627 know of any implementation that has @file{stdint.h} but not
5628 @file{inttypes.h}.
5630 @item @file{linux/irda.h}
5631 @hdrindex{linux/irda.h}
5632 It requires @file{linux/types.h} and @file{sys/socket.h}.
5634 @item @file{linux/random.h}
5635 @hdrindex{linux/random.h}
5636 It requires @file{linux/types.h}.
5638 @item @file{net/if.h}
5639 @hdrindex{net/if.h}
5640 On Darwin, this file requires that @file{sys/socket.h} be included
5641 beforehand.  One should run:
5643 @example
5644 AC_CHECK_HEADERS([sys/socket.h])
5645 AC_CHECK_HEADERS([net/if.h], [], [],
5646 [#include <stdio.h>
5647 #ifdef STDC_HEADERS
5648 # include <stdlib.h>
5649 # include <stddef.h>
5650 #else
5651 # ifdef HAVE_STDLIB_H
5652 #  include <stdlib.h>
5653 # endif
5654 #endif
5655 #ifdef HAVE_SYS_SOCKET_H
5656 # include <sys/socket.h>
5657 #endif
5659 @end example
5661 @item @file{netinet/if_ether.h}
5662 @hdrindex{netinet/if_ether.h}
5663 On Darwin, this file requires that @file{stdio.h} and
5664 @file{sys/socket.h} be included beforehand.  One should run:
5666 @example
5667 AC_CHECK_HEADERS([sys/socket.h])
5668 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5669 [#include <stdio.h>
5670 #ifdef STDC_HEADERS
5671 # include <stdlib.h>
5672 # include <stddef.h>
5673 #else
5674 # ifdef HAVE_STDLIB_H
5675 #  include <stdlib.h>
5676 # endif
5677 #endif
5678 #ifdef HAVE_SYS_SOCKET_H
5679 # include <sys/socket.h>
5680 #endif
5682 @end example
5684 @item @file{stdint.h}
5685 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5687 @item @file{stdlib.h}
5688 @hdrindex{stdlib.h}
5689 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5691 @item @file{sys/mount.h}
5692 @hdrindex{sys/mount.h}
5693 On Free@acronym{BSD} 4.8 on ia32 and using gcc version 2.95.4,
5694 @file{sys/params.h} is a prerequisite.
5696 @item @file{sys/ptem.h}
5697 @hdrindex{sys/ptem.h}
5698 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5700 @item @file{sys/socket.h}
5701 @hdrindex{sys/socket.h}
5702 On Darwin, @file{stdlib.h} is a prerequisite.
5704 @item @file{sys/ucred.h}
5705 @hdrindex{sys/ucred.h}
5706 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5708 @item @file{X11/extensions/scrnsaver.h}
5709 @hdrindex{X11/extensions/scrnsaver.h}
5710 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5711 so required that you might not even consider looking for it.
5713 @example
5714 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5715 [[#include <X11/Xlib.h>
5717 @end example
5718 @end table
5721 @node Particular Headers
5722 @subsection Particular Header Checks
5724 These macros check for particular system header files---whether they
5725 exist, and in some cases whether they declare certain symbols.
5727 @defmac AC_HEADER_ASSERT
5728 @acindex{HEADER_ASSERT}
5729 @cvindex NDEBUG
5730 @hdrindex{assert.h}
5731 Check whether to enable assertions in the style of @file{assert.h}.
5732 Assertions are enabled by default, but the user can override this by
5733 invoking @command{configure} with the @option{--disable-assert} option.
5734 @end defmac
5736 @anchor{AC_HEADER_DIRENT}
5737 @defmac AC_HEADER_DIRENT
5738 @acindex{HEADER_DIRENT}
5739 @cvindex HAVE_DIRENT_H
5740 @cvindex HAVE_NDIR_H
5741 @cvindex HAVE_SYS_DIR_H
5742 @cvindex HAVE_SYS_NDIR_H
5743 @hdrindex{dirent.h}
5744 @hdrindex{sys/ndir.h}
5745 @hdrindex{sys/dir.h}
5746 @hdrindex{ndir.h}
5747 Check for the following header files.  For the first one that is
5748 found and defines @samp{DIR}, define the listed C preprocessor macro:
5750 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5751 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5752 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5753 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5754 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5755 @end multitable
5757 The directory-library declarations in your source code should look
5758 something like the following:
5760 @example
5761 @group
5762 #include <sys/types.h>
5763 #ifdef HAVE_DIRENT_H
5764 # include <dirent.h>
5765 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5766 #else
5767 # define dirent direct
5768 # define NAMLEN(dirent) ((dirent)->d_namlen)
5769 # ifdef HAVE_SYS_NDIR_H
5770 #  include <sys/ndir.h>
5771 # endif
5772 # ifdef HAVE_SYS_DIR_H
5773 #  include <sys/dir.h>
5774 # endif
5775 # ifdef HAVE_NDIR_H
5776 #  include <ndir.h>
5777 # endif
5778 #endif
5779 @end group
5780 @end example
5782 Using the above declarations, the program would declare variables to be
5783 of type @code{struct dirent}, not @code{struct direct}, and would access
5784 the length of a directory entry name by passing a pointer to a
5785 @code{struct dirent} to the @code{NAMLEN} macro.
5787 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5789 This macro is obsolescent, as all current systems with directory
5790 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5792 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5793 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5794 @end defmac
5796 @anchor{AC_HEADER_MAJOR}
5797 @defmac AC_HEADER_MAJOR
5798 @acindex{HEADER_MAJOR}
5799 @cvindex MAJOR_IN_MKDEV
5800 @cvindex MAJOR_IN_SYSMACROS
5801 @hdrindex{sys/mkdev.h}
5802 @hdrindex{sys/sysmacros.h}
5803 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5804 @code{makedev}, but @file{sys/mkdev.h} does, define
5805 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5806 @code{MAJOR_IN_SYSMACROS}.
5807 @end defmac
5809 @defmac AC_HEADER_RESOLV
5810 @acindex{HEADER_RESOLV}
5811 @cvindex HAVE_RESOLV_H
5812 @hdrindex{resolv.h}
5813 Checks for header @file{resolv.h}, checking for prerequisites first.
5814 To properly use @file{resolv.h}, your code should contain something like
5815 the following:
5817 @verbatim
5818 #ifdef HAVE_SYS_TYPES_H
5819 #  include <sys/types.h>
5820 #endif
5821 #ifdef HAVE_NETINET_IN_H
5822 #  include <netinet/in.h>   /* inet_ functions / structs */
5823 #endif
5824 #ifdef HAVE_ARPA_NAMESER_H
5825 #  include <arpa/nameser.h> /* DNS HEADER struct */
5826 #endif
5827 #ifdef HAVE_NETDB_H
5828 #  include <netdb.h>
5829 #endif
5830 #include <resolv.h>
5831 @end verbatim
5832 @end defmac
5834 @anchor{AC_HEADER_STAT}
5835 @defmac AC_HEADER_STAT
5836 @acindex{HEADER_STAT}
5837 @cvindex STAT_MACROS_BROKEN
5838 @hdrindex{sys/stat.h}
5839 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5840 @file{sys/stat.h} do not work properly (returning false positives),
5841 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5842 Amdahl UTS and Motorola System V/88.
5844 This macro is obsolescent, as no current systems have the bug.
5845 New programs need not use this macro.
5846 @end defmac
5848 @defmac AC_HEADER_STDBOOL
5849 @acindex{HEADER_STDBOOL}
5850 @cvindex HAVE_STDBOOL_H
5851 @cvindex HAVE__BOOL
5852 @hdrindex{stdbool.h}
5853 @hdrindex{system.h}
5854 @caindex header_stdbool_h
5855 If @file{stdbool.h} exists and conforms to C99, define
5856 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5857 @code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5858 @file{system.h} could contain the following code:
5860 @verbatim
5861 #ifdef HAVE_STDBOOL_H
5862 # include <stdbool.h>
5863 #else
5864 # ifndef HAVE__BOOL
5865 #  ifdef __cplusplus
5866 typedef bool _Bool;
5867 #  else
5868 #   define _Bool signed char
5869 #  endif
5870 # endif
5871 # define bool _Bool
5872 # define false 0
5873 # define true 1
5874 # define __bool_true_false_are_defined 1
5875 #endif
5876 @end verbatim
5878 Alternatively you can use the @samp{stdbool} package of Gnulib
5879 (@pxref{Gnulib}); it packages the above code into a replacement header
5880 and contains a few other bells and whistles.
5882 This macro caches its result in the @code{ac_cv_header_stdbool_h}
5883 variable.
5884 @end defmac
5886 @anchor{AC_HEADER_STDC}
5887 @defmac AC_HEADER_STDC
5888 @acindex{HEADER_STDC}
5889 @cvindex STDC_HEADERS
5890 @hdrindex{stdlib.h}
5891 @hdrindex{stdarg.h}
5892 @hdrindex{string.h}
5893 @hdrindex{float.h}
5894 @hdrindex{ctype.h}
5895 @caindex header_stdc
5896 Define @code{STDC_HEADERS} if the system has C header files
5897 conforming to @acronym{ANSI} C89 (@acronym{ISO} C90).
5898 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
5899 @file{string.h}, and @file{float.h}; if the system has those, it
5900 probably has the rest of the C89 header files.  This macro also
5901 checks whether @file{string.h} declares @code{memchr} (and thus
5902 presumably the other @code{mem} functions), whether @file{stdlib.h}
5903 declare @code{free} (and thus presumably @code{malloc} and other related
5904 functions), and whether the @file{ctype.h} macros work on characters
5905 with the high bit set, as the C standard requires.
5907 If you use this macro, your code can refer to @code{STDC_HEADERS} to
5908 determine whether the system has conforming header files (and probably C
5909 library functions).
5911 This macro caches its result in the @code{ac_cv_header_stdc} variable.
5913 This macro is obsolescent, as current systems have conforming header
5914 files.  New programs need not use this macro.
5916 @hdrindex{string.h}
5917 @hdrindex{strings.h}
5918 Nowadays @file{string.h} is part of the C standard and declares functions like
5919 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
5920 @acronym{BSD} functions like @code{bcopy}; but
5921 historically, string functions were a major sticking point in this area.
5922 If you still want to worry about portability to ancient systems without
5923 standard headers, there is so much variation
5924 that it is probably easier to declare the functions you use than to
5925 figure out exactly what the system header files declare.  Some ancient systems
5926 contained a mix of functions from the C standard and from @acronym{BSD};
5927 some were mostly standard but lacked @samp{memmove}; some defined the
5928 @acronym{BSD} functions as macros in @file{string.h} or
5929 @file{strings.h}; some had only the @acronym{BSD} functions but
5930 @file{string.h}; some declared the memory functions in @file{memory.h},
5931 some in @file{string.h}; etc.  It is probably sufficient to check for
5932 one string function and one memory function; if the library had the
5933 standard versions of those then it probably had most of the others.
5934 If you put the following in @file{configure.ac}:
5936 @example
5937 # This example is obsolescent.
5938 # Nowadays you can omit these macro calls.
5939 AC_HEADER_STDC
5940 AC_CHECK_FUNCS([strchr memcpy])
5941 @end example
5943 @noindent
5944 then, in your code, you can use declarations like this:
5946 @example
5947 @group
5948 /* This example is obsolescent.
5949    Nowadays you can just #include <string.h>.  */
5950 #ifdef STDC_HEADERS
5951 # include <string.h>
5952 #else
5953 # ifndef HAVE_STRCHR
5954 #  define strchr index
5955 #  define strrchr rindex
5956 # endif
5957 char *strchr (), *strrchr ();
5958 # ifndef HAVE_MEMCPY
5959 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
5960 #  define memmove(d, s, n) bcopy ((s), (d), (n))
5961 # endif
5962 #endif
5963 @end group
5964 @end example
5966 @noindent
5967 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
5968 or @code{strspn}, which have no @acronym{BSD} equivalent, then macros don't
5969 suffice to port to ancient hosts; you must provide an implementation of
5970 each function.  An easy
5971 way to incorporate your implementations only when needed (since the ones
5972 in system C libraries may be hand optimized) is to, taking @code{memchr}
5973 for example, put it in @file{memchr.c} and use
5974 @samp{AC_REPLACE_FUNCS([memchr])}.
5975 @end defmac
5977 @defmac AC_HEADER_SYS_WAIT
5978 @acindex{HEADER_SYS_WAIT}
5979 @cvindex HAVE_SYS_WAIT_H
5980 @hdrindex{sys/wait.h}
5981 @caindex header_sys_wait_h
5982 If @file{sys/wait.h} exists and is compatible with Posix, define
5983 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
5984 does not exist, or if it uses the old @acronym{BSD} @code{union wait} instead
5985 of @code{int} to store a status value.  If @file{sys/wait.h} is not
5986 Posix compatible, then instead of including it, define the
5987 Posix macros with their usual interpretations.  Here is an
5988 example:
5990 @example
5991 @group
5992 #include <sys/types.h>
5993 #ifdef HAVE_SYS_WAIT_H
5994 # include <sys/wait.h>
5995 #endif
5996 #ifndef WEXITSTATUS
5997 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
5998 #endif
5999 #ifndef WIFEXITED
6000 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6001 #endif
6002 @end group
6003 @end example
6005 @noindent
6006 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6007 variable.
6009 This macro is obsolescent, as current systems are compatible with Posix.
6010 New programs need not use this macro.
6011 @end defmac
6013 @cvindex _POSIX_VERSION
6014 @hdrindex{unistd.h}
6015 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6016 Posix systems.  If there is no @file{unistd.h}, it is definitely
6017 not a Posix system.  However, some non-Posix systems do
6018 have @file{unistd.h}.
6020 The way to check whether the system supports Posix is:
6022 @example
6023 @group
6024 #ifdef HAVE_UNISTD_H
6025 # include <sys/types.h>
6026 # include <unistd.h>
6027 #endif
6029 #ifdef _POSIX_VERSION
6030 /* Code for Posix systems.  */
6031 #endif
6032 @end group
6033 @end example
6035 @anchor{AC_HEADER_TIME}
6036 @defmac AC_HEADER_TIME
6037 @acindex{HEADER_TIME}
6038 @cvindex TIME_WITH_SYS_TIME
6039 @hdrindex{time.h}
6040 @hdrindex{sys/time.h}
6041 @caindex header_time
6042 If a program may include both @file{time.h} and @file{sys/time.h},
6043 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
6044 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
6045 protected against multiple inclusion, so programs could not explicitly
6046 include both files.  This macro is useful in programs that use, for
6047 example, @code{struct timeval} as well as
6048 @code{struct tm}.  It is best used in conjunction with
6049 @code{HAVE_SYS_TIME_H}, which can be checked for using
6050 @code{AC_CHECK_HEADERS([sys/time.h])}.
6052 @example
6053 @group
6054 #ifdef TIME_WITH_SYS_TIME
6055 # include <sys/time.h>
6056 # include <time.h>
6057 #else
6058 # ifdef HAVE_SYS_TIME_H
6059 #  include <sys/time.h>
6060 # else
6061 #  include <time.h>
6062 # endif
6063 #endif
6064 @end group
6065 @end example
6067 @noindent
6068 This macro caches its result in the @code{ac_cv_header_time} variable.
6070 This macro is obsolescent, as current systems can include both files
6071 when they exist.  New programs need not use this macro.
6072 @end defmac
6075 @defmac AC_HEADER_TIOCGWINSZ
6076 @acindex{HEADER_TIOCGWINSZ}
6077 @cvindex GWINSZ_IN_SYS_IOCTL
6078 @hdrindex{sys/ioctl.h}
6079 @hdrindex{termios.h}
6080 @c FIXME: I need clarifications from Jim.
6081 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6082 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6083 found in @file{<termios.h>}.
6085 Use:
6087 @example
6088 @group
6089 #ifdef HAVE_TERMIOS_H
6090 # include <termios.h>
6091 #endif
6093 #ifdef GWINSZ_IN_SYS_IOCTL
6094 # include <sys/ioctl.h>
6095 #endif
6096 @end group
6097 @end example
6098 @end defmac
6100 @node Generic Headers
6101 @subsection Generic Header Checks
6103 These macros are used to find system header files not covered by the
6104 ``particular'' test macros.  If you need to check the contents of a header
6105 as well as find out whether it is present, you have to write your own
6106 test for it (@pxref{Writing Tests}).
6108 @anchor{AC_CHECK_HEADER}
6109 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6110   @ovar{action-if-not-found}, @ovar{includes})
6111 @acindex{CHECK_HEADER}
6112 @caindex header_@var{header-file}
6113 If the system header file @var{header-file} is compilable, execute shell
6114 commands @var{action-if-found}, otherwise execute
6115 @var{action-if-not-found}.  If you just want to define a symbol if the
6116 header file is available, consider using @code{AC_CHECK_HEADERS}
6117 instead.
6119 @var{includes} is decoded to determine the appropriate include
6120 directives.  If omitted or empty, @file{configure} will check for both header
6121 existence (with the preprocessor) and usability (with the compiler),
6122 using @code{AC_INCLUDES_DEFAULT} for the compile test.  If
6123 there is a discrepancy between the results, a warning is issued to the
6124 user, and the compiler results are favored (@pxref{Present But
6125 Cannot Be Compiled}).  In general, favoring the compiler results means
6126 that a header will be treated as not found even though the file exists,
6127 because you did not provide enough prerequisites.
6129 Providing a non-empty @var{includes} argument allows the code to provide
6130 any prerequisites prior to including the header under test; it is common
6131 to use the argument @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6132 Includes}).  With an explicit fourth argument, no preprocessor test is
6133 needed.  As a special case, an @var{includes} of exactly @samp{-}
6134 triggers the older preprocessor check, which merely determines existence
6135 of the file in the preprocessor search path; this should only be used as
6136 a last resort (it is safer to determine the actual prerequisites and
6137 perform a compiler check, or else use @code{AC_PREPROC_IFELSE} to make
6138 it obvious that only a preprocessor check is desired).
6140 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6141 variable, with characters not suitable for a variable name mapped to
6142 underscores.
6143 @end defmac
6145 @anchor{AC_CHECK_HEADERS}
6146 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6147   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6148   @ovar{includes})
6149 @acindex{CHECK_HEADERS}
6150 @cvindex HAVE_@var{header}
6151 @caindex header_@var{header-file}
6152 For each given system header file @var{header-file} in the
6153 blank-separated argument list that exists, define
6154 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6155 is given, it is additional shell code to execute when one of the header
6156 files is found.  You can give it a value of @samp{break} to break out of
6157 the loop on the first match.  If @var{action-if-not-found} is given, it
6158 is executed when one of the header files is not found.
6160 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6161 choose the set of preprocessor directives supplied before the header
6162 under test.
6164 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6165 variable, with characters not suitable for a variable name mapped to
6166 underscores.
6167 @end defmac
6169 Previous versions of Autoconf merely checked whether the header was
6170 accepted by the preprocessor.  This was changed because the old test was
6171 inappropriate for typical uses.  Headers are typically used to compile,
6172 not merely to preprocess, and the old behavior sometimes accepted
6173 headers that clashed at compile-time (@pxref{Present But Cannot Be
6174 Compiled}).  If you need to check whether a header is preprocessable,
6175 you can use @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}).
6177 Actually requiring a header to compile improves the robustness of the
6178 test, but it also requires
6179 that you make sure that headers that must be included before the
6180 @var{header-file} be part of the @var{includes}, (@pxref{Default
6181 Includes}).  If looking for @file{bar.h}, which requires that
6182 @file{foo.h} be included before if it exists, we suggest the following
6183 scheme:
6185 @verbatim
6186 AC_CHECK_HEADERS([foo.h])
6187 AC_CHECK_HEADERS([bar.h], [], [],
6188 [#ifdef HAVE_FOO_H
6189 # include <foo.h>
6190 #endif
6192 @end verbatim
6194 The following variant generates smaller, faster @command{configure}
6195 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
6197 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6198 @acindex{CHECK_HEADERS_ONCE}
6199 @cvindex HAVE_@var{header}
6200 For each given system header file @var{header-file} in the
6201 blank-separated argument list that exists, define
6202 @code{HAVE_@var{header-file}} (in all capitals).
6203 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
6204 checking code at most once, so that @command{configure} is smaller and
6205 faster; but the checks cannot be conditionalized and are always done once,
6206 early during the @command{configure} run.  Thus, this macro is only safe
6207 for checking headers that do not have prerequisites beyond what
6208 @code{AC_INCLUDES_DEFAULT} provides.
6209 @end defmac
6211 @node Declarations
6212 @section Declarations
6213 @cindex Declaration, checking
6215 The following macros check for the declaration of variables and
6216 functions.  If there is no macro specifically defined to check for a
6217 symbol you need, then you can use the general macros (@pxref{Generic
6218 Declarations}) or, for more complex tests, you may use
6219 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6221 @menu
6222 * Particular Declarations::     Macros to check for certain declarations
6223 * Generic Declarations::        How to find other declarations
6224 @end menu
6226 @node Particular Declarations
6227 @subsection Particular Declaration Checks
6229 There are no specific macros for declarations.
6231 @node Generic Declarations
6232 @subsection Generic Declaration Checks
6234 These macros are used to find declarations not covered by the ``particular''
6235 test macros.
6237 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6238   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6239 @acindex{CHECK_DECL}
6240 @caindex have_decl_@var{symbol}
6241 If @var{symbol} (a function, variable, or constant) is not declared in
6242 @var{includes} and a declaration is needed, run the shell commands
6243 @var{action-if-not-found}, otherwise @var{action-if-found}.
6244 @var{includes} is a series of include directives, defaulting to
6245 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6246 prior to the declaration under test.
6248 This macro actually tests whether @var{symbol} is defined as a macro or
6249 can be used as an r-value, not whether it is really declared, because it
6250 is much safer to avoid
6251 introducing extra declarations when they are not needed.
6253 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6254 variable, with characters not suitable for a variable name mapped to
6255 underscores.
6256 @end defmac
6258 @anchor{AC_CHECK_DECLS}
6259 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6260   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6261 @acindex{CHECK_DECLS}
6262 @cvindex HAVE_DECL_@var{symbol}
6263 @caindex have_decl_@var{symbol}
6264 For each of the @var{symbols} (@emph{comma}-separated list), define
6265 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6266 @var{symbol} is declared, otherwise to @samp{0}.  If
6267 @var{action-if-not-found} is given, it is additional shell code to
6268 execute when one of the function declarations is needed, otherwise
6269 @var{action-if-found} is executed.
6271 @var{includes} is a series of include directives, defaulting to
6272 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6273 prior to the declarations under test.
6275 This macro uses an M4 list as first argument:
6276 @example
6277 AC_CHECK_DECLS([strdup])
6278 AC_CHECK_DECLS([strlen])
6279 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6280 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6281 @end example
6283 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6284 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6285 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6286 @emph{sure} that the check was performed, use
6287 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6289 @example
6290 #if !HAVE_DECL_SYMBOL
6291 extern char *symbol;
6292 #endif
6293 @end example
6295 @noindent
6296 If the test may have not been performed, however, because it is safer
6297 @emph{not} to declare a symbol than to use a declaration that conflicts
6298 with the system's one, you should use:
6300 @example
6301 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6302 void *malloc (size_t *s);
6303 #endif
6304 @end example
6306 @noindent
6307 You fall into the second category only in extreme situations: either
6308 your files may be used without being configured, or they are used during
6309 the configuration.  In most cases the traditional approach is enough.
6311 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6312 variables, with characters not suitable for a variable name mapped to
6313 underscores.
6314 @end defmac
6316 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6317 @acindex{CHECK_DECLS_ONCE}
6318 @cvindex HAVE_DECL_@var{symbol}
6319 For each of the @var{symbols} (@emph{comma}-separated list), define
6320 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6321 @var{symbol} is declared in the default include files, otherwise to
6322 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6323 generates the checking code at most once, so that @command{configure} is
6324 smaller and faster; but the checks cannot be conditionalized and are
6325 always done once, early during the @command{configure} run.
6326 @end defmac
6329 @node Structures
6330 @section Structures
6331 @cindex Structure, checking
6333 The following macros check for the presence of certain members in C
6334 structures.  If there is no macro specifically defined to check for a
6335 member you need, then you can use the general structure-member macros
6336 (@pxref{Generic Structures}) or, for more complex tests, you may use
6337 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6339 @menu
6340 * Particular Structures::       Macros to check for certain structure members
6341 * Generic Structures::          How to find other structure members
6342 @end menu
6344 @node Particular Structures
6345 @subsection Particular Structure Checks
6347 The following macros check for certain structures or structure members.
6349 @defmac AC_STRUCT_DIRENT_D_INO
6350 @acindex{STRUCT_DIRENT_D_INO}
6351 @cvindex HAVE_STRUCT_DIRENT_D_INO
6352 @c @caindex header_dirent_dirent_h
6353 @c @caindex member_struct_dirent_d_ino
6354 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6355 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6356 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6358 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6359 @code{d_ino}, not whether its contents are always reliable.
6360 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6361 though current systems hide this detail from the user and never return
6362 zero @code{d_ino} values.
6363 Many current systems report an incorrect @code{d_ino} for a directory
6364 entry that is a mount point.
6365 @end defmac
6367 @defmac AC_STRUCT_DIRENT_D_TYPE
6368 @acindex{STRUCT_DIRENT_D_TYPE}
6369 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6370 @c @caindex header_dirent_dirent_h
6371 @c @caindex member_struct_dirent_d_type
6372 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6373 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6374 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6375 @end defmac
6377 @anchor{AC_STRUCT_ST_BLOCKS}
6378 @defmac AC_STRUCT_ST_BLOCKS
6379 @acindex{STRUCT_ST_BLOCKS}
6380 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6381 @cvindex HAVE_ST_BLOCKS
6382 @ovindex LIBOBJS
6383 @caindex member_struct_stat_st_blocks
6384 If @code{struct stat} contains an @code{st_blocks} member, define
6385 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6386 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6387 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6388 future.
6390 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6391 variable.
6392 @end defmac
6394 @defmac AC_STRUCT_TM
6395 @acindex{STRUCT_TM}
6396 @cvindex TM_IN_SYS_TIME
6397 @hdrindex{time.h}
6398 @hdrindex{sys/time.h}
6399 If @file{time.h} does not define @code{struct tm}, define
6400 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6401 had better define @code{struct tm}.
6403 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6404 current systems.  New programs need not use this macro.
6405 @end defmac
6407 @anchor{AC_STRUCT_TIMEZONE}
6408 @defmac AC_STRUCT_TIMEZONE
6409 @acindex{STRUCT_TIMEZONE}
6410 @cvindex HAVE_DECL_TZNAME
6411 @cvindex HAVE_STRUCT_TM_TM_ZONE
6412 @cvindex HAVE_TM_ZONE
6413 @cvindex HAVE_TZNAME
6414 @c @caindex member_struct_tm_tm_zone
6415 @c @caindex struct_tm
6416 Figure out how to get the current timezone.  If @code{struct tm} has a
6417 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6418 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6419 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6420 define @code{HAVE_DECL_TZNAME}.
6421 @end defmac
6423 @node Generic Structures
6424 @subsection Generic Structure Checks
6426 These macros are used to find structure members not covered by the
6427 ``particular'' test macros.
6429 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6430   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6431   @dvar{includes, AC_INCLUDES_DEFAULT})
6432 @acindex{CHECK_MEMBER}
6433 @caindex member_@var{aggregate}_@var{member}
6434 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6435 If no @var{includes} are specified, the default includes are used
6436 (@pxref{Default Includes}).
6438 @example
6439 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6440                 [AC_MSG_ERROR([We need `passwd.pw_gecos'!])],
6441                 [[#include <pwd.h>]])
6442 @end example
6444 You can use this macro for submembers:
6446 @example
6447 AC_CHECK_MEMBER(struct top.middle.bot)
6448 @end example
6450 This macro caches its result in the
6451 @code{av_cv_member_@var{aggregate}_@var{member}} variable, with
6452 characters not suitable for a variable name mapped to underscores.
6453 @end defmac
6455 @anchor{AC_CHECK_MEMBERS}
6456 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6457   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6458 @acindex{CHECK_MEMBERS}
6459 @cvindex HAVE_@var{aggregate}_@var{member}
6460 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6461 @var{members} using the previous macro.  When @var{member} belongs to
6462 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6463 capitals, with spaces and dots replaced by underscores).  If
6464 @var{action-if-found} is given, it is executed for each of the found
6465 members.  If @var{action-if-not-found} is given, it is executed for each
6466 of the members that could not be found.
6468 @var{includes} is a series of include directives, defaulting to
6469 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6470 prior to the members under test.
6472 This macro uses M4 lists:
6473 @example
6474 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6475 @end example
6476 @end defmac
6479 @node Types
6480 @section Types
6481 @cindex Types
6482 @cindex C types
6484 The following macros check for C types, either builtin or typedefs.  If
6485 there is no macro specifically defined to check for a type you need, and
6486 you don't need to check for any special properties of it, then you can
6487 use a general type-check macro.
6489 @menu
6490 * Particular Types::            Special handling to find certain types
6491 * Generic Types::               How to find other types
6492 @end menu
6494 @node Particular Types
6495 @subsection Particular Type Checks
6497 @hdrindex{sys/types.h}
6498 @hdrindex{stdlib.h}
6499 @hdrindex{stdint.h}
6500 @hdrindex{inttypes.h}
6501 These macros check for particular C types in @file{sys/types.h},
6502 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6503 exist.
6505 The Gnulib @code{stdint} module is an alternate way to define many of
6506 these symbols; it is useful if you prefer your code to assume a
6507 C99-or-better environment.  @xref{Gnulib}.
6509 @anchor{AC_TYPE_GETGROUPS}
6510 @defmac AC_TYPE_GETGROUPS
6511 @acindex{TYPE_GETGROUPS}
6512 @cvindex GETGROUPS_T
6513 @caindex type_getgroups
6514 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6515 is the base type of the array argument to @code{getgroups}.
6517 This macro caches the base type in the @code{ac_cv_type_getgroups}
6518 variable.
6519 @end defmac
6521 @defmac AC_TYPE_INT8_T
6522 @acindex{TYPE_INT8_T}
6523 @cvindex HAVE_INT8_T
6524 @cvindex int8_t
6525 @caindex c_int8_t
6526 If @file{stdint.h} or @file{inttypes.h} does not define the type
6527 @code{int8_t}, define @code{int8_t} to a signed
6528 integer type that is exactly 8 bits wide and that uses two's complement
6529 representation, if such a type exists.
6530 If you are worried about porting to hosts that lack such a type, you can
6531 use the results of this macro in C89-or-later code as follows:
6533 @example
6534 #if HAVE_STDINT_H
6535 # include <stdint.h>
6536 #endif
6537 #if defined INT8_MAX || defined int8_t
6538  @emph{code using int8_t}
6539 #else
6540  @emph{complicated alternative using >8-bit 'signed char'}
6541 #endif
6542 @end example
6544 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6545 @end defmac
6547 @defmac AC_TYPE_INT16_T
6548 @acindex{TYPE_INT16_T}
6549 @cvindex HAVE_INT16_T
6550 @cvindex int16_t
6551 @caindex c_int16_t
6552 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6553 @end defmac
6555 @defmac AC_TYPE_INT32_T
6556 @acindex{TYPE_INT32_T}
6557 @cvindex HAVE_INT32_T
6558 @cvindex int32_t
6559 @caindex c_int32_t
6560 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6561 @end defmac
6563 @defmac AC_TYPE_INT64_T
6564 @acindex{TYPE_INT64_T}
6565 @cvindex HAVE_INT64_T
6566 @cvindex int64_t
6567 @caindex c_int64_t
6568 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6569 @end defmac
6571 @defmac AC_TYPE_INTMAX_T
6572 @acindex{TYPE_INTMAX_T}
6573 @cvindex HAVE_INTMAX_T
6574 @cvindex intmax_t
6575 @c @caindex type_intmax_t
6576 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6577 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6578 widest signed integer type.
6579 @end defmac
6581 @defmac AC_TYPE_INTPTR_T
6582 @acindex{TYPE_INTPTR_T}
6583 @cvindex HAVE_INTPTR_T
6584 @cvindex intptr_t
6585 @c @caindex type_intptr_t
6586 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6587 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6588 signed integer type wide enough to hold a pointer, if such a type
6589 exists.
6590 @end defmac
6592 @defmac AC_TYPE_LONG_DOUBLE
6593 @acindex{TYPE_LONG_DOUBLE}
6594 @cvindex HAVE_LONG_DOUBLE
6595 @caindex type_long_double
6596 If the C compiler supports a working @code{long double} type, define
6597 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6598 same range and precision as @code{double}.
6600 This macro caches its result in the @code{ac_cv_type_long_double}
6601 variable.
6603 This macro is obsolescent, as current C compilers support @code{long
6604 double}.  New programs need not use this macro.
6605 @end defmac
6607 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6608 @acindex{TYPE_LONG_DOUBLE_WIDER}
6609 @cvindex HAVE_LONG_DOUBLE_WIDER
6610 @caindex type_long_double_wider
6611 If the C compiler supports a working @code{long double} type with more
6612 range or precision than the @code{double} type, define
6613 @code{HAVE_LONG_DOUBLE_WIDER}.
6615 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6616 variable.
6617 @end defmac
6619 @defmac AC_TYPE_LONG_LONG_INT
6620 @acindex{TYPE_LONG_LONG_INT}
6621 @cvindex HAVE_LONG_LONG_INT
6622 @caindex type_long_long_int
6623 If the C compiler supports a working @code{long long int} type, define
6624 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6625 @code{long long int} values in preprocessor @code{#if} expressions,
6626 because too many compilers mishandle such expressions.
6627 @xref{Preprocessor Arithmetic}.
6629 This macro caches its result in the @code{ac_cv_type_long_long_int}
6630 variable.
6631 @end defmac
6633 @defmac AC_TYPE_MBSTATE_T
6634 @acindex{TYPE_MBSTATE_T}
6635 @cvindex mbstate_t
6636 @hdrindex{wchar.h}
6637 @caindex type_mbstate_t
6638 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6639 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6640 @code{<wchar.h>} does not declare it.
6642 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6643 variable.
6644 @end defmac
6646 @anchor{AC_TYPE_MODE_T}
6647 @defmac AC_TYPE_MODE_T
6648 @acindex{TYPE_MODE_T}
6649 @cvindex mode_t
6650 @caindex type_mode_t
6651 Define @code{mode_t} to a suitable type, if standard headers do not
6652 define it.
6654 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6655 @end defmac
6657 @anchor{AC_TYPE_OFF_T}
6658 @defmac AC_TYPE_OFF_T
6659 @acindex{TYPE_OFF_T}
6660 @cvindex off_t
6661 @caindex type_off_t
6662 Define @code{off_t} to a suitable type, if standard headers do not
6663 define it.
6665 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6666 @end defmac
6668 @anchor{AC_TYPE_PID_T}
6669 @defmac AC_TYPE_PID_T
6670 @acindex{TYPE_PID_T}
6671 @cvindex pid_t
6672 @caindex type_pid_t
6673 Define @code{pid_t} to a suitable type, if standard headers do not
6674 define it.
6676 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6677 @end defmac
6679 @anchor{AC_TYPE_SIZE_T}
6680 @defmac AC_TYPE_SIZE_T
6681 @acindex{TYPE_SIZE_T}
6682 @cvindex size_t
6683 @caindex type_size_t
6684 Define @code{size_t} to a suitable type, if standard headers do not
6685 define it.
6687 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6688 @end defmac
6690 @defmac AC_TYPE_SSIZE_T
6691 @acindex{TYPE_SSIZE_T}
6692 @cvindex ssize_t
6693 @caindex type_ssize_t
6694 Define @code{ssize_t} to a suitable type, if standard headers do not
6695 define it.
6697 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6698 @end defmac
6700 @anchor{AC_TYPE_UID_T}
6701 @defmac AC_TYPE_UID_T
6702 @acindex{TYPE_UID_T}
6703 @cvindex uid_t
6704 @cvindex gid_t
6705 @caindex type_uid_t
6706 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6707 headers do not define them.
6709 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6710 @end defmac
6712 @defmac AC_TYPE_UINT8_T
6713 @acindex{TYPE_UINT8_T}
6714 @cvindex HAVE_UINT8_T
6715 @cvindex uint8_t
6716 @caindex c_uint8_t
6717 If @file{stdint.h} or @file{inttypes.h} does not define the type
6718 @code{uint8_t}, define @code{uint8_t} to an
6719 unsigned integer type that is exactly 8 bits wide, if such a type
6720 exists.
6721 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6722 @end defmac
6724 @defmac AC_TYPE_UINT16_T
6725 @acindex{TYPE_UINT16_T}
6726 @cvindex HAVE_UINT16_T
6727 @cvindex uint16_t
6728 @caindex c_uint16_t
6729 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6730 @end defmac
6732 @defmac AC_TYPE_UINT32_T
6733 @acindex{TYPE_UINT32_T}
6734 @cvindex HAVE_UINT32_T
6735 @cvindex uint32_t
6736 @caindex c_uint32_t
6737 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6738 @end defmac
6740 @defmac AC_TYPE_UINT64_T
6741 @acindex{TYPE_UINT64_T}
6742 @cvindex HAVE_UINT64_T
6743 @cvindex uint64_t
6744 @caindex c_uint64_t
6745 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6746 @end defmac
6748 @defmac AC_TYPE_UINTMAX_T
6749 @acindex{TYPE_UINTMAX_T}
6750 @cvindex HAVE_UINTMAX_T
6751 @cvindex uintmax_t
6752 @c @caindex type_uintmax_t
6753 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6754 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6755 widest unsigned integer type.
6756 @end defmac
6758 @defmac AC_TYPE_UINTPTR_T
6759 @acindex{TYPE_UINTPTR_T}
6760 @cvindex HAVE_UINTPTR_T
6761 @cvindex uintptr_t
6762 @c @caindex type_uintptr_t
6763 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6764 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6765 unsigned integer type wide enough to hold a pointer, if such a type
6766 exists.
6767 @end defmac
6769 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6770 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6771 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6772 @caindex type_unsigned_long_long_int
6773 If the C compiler supports a working @code{unsigned long long int} type,
6774 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6775 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6776 because too many compilers mishandle such expressions.
6777 @xref{Preprocessor Arithmetic}.
6779 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
6780 variable.
6781 @end defmac
6783 @node Generic Types
6784 @subsection Generic Type Checks
6786 These macros are used to check for types not covered by the ``particular''
6787 test macros.
6789 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6790   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6791 @acindex{CHECK_TYPE}
6792 @caindex type_@var{type}
6793 Check whether @var{type} is defined.  It may be a compiler builtin type
6794 or defined by the @var{includes}.  @var{includes} is a series of include
6795 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6796 Includes}), which are used prior to the type under test.
6798 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6799 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6800 same test is applied when compiling for C++, which means that in C++
6801 @var{type} should be a type-id and should not be an anonymous
6802 @samp{struct} or @samp{union}.
6804 This macro caches its result in the @code{ac_cv_type_@var{type}}
6805 variable, with @samp{*} mapped to @samp{p} and other characters not
6806 suitable for a variable name mapped to underscores.
6807 @end defmac
6810 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6811   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6812 @acindex{CHECK_TYPES}
6813 @cvindex HAVE_@var{type}
6814 For each @var{type} of the @var{types} that is defined, define
6815 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6816 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6817 specified, the default includes are used (@pxref{Default Includes}).  If
6818 @var{action-if-found} is given, it is additional shell code to execute
6819 when one of the types is found.  If @var{action-if-not-found} is given,
6820 it is executed when one of the types is not found.
6822 This macro uses M4 lists:
6823 @example
6824 AC_CHECK_TYPES([ptrdiff_t])
6825 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6826 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6827 @end example
6829 @end defmac
6831 Autoconf, up to 2.13, used to provide to another version of
6832 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6833 compatibility, a simple heuristic, quite safe but not totally, is
6834 implemented.  In case of doubt, read the documentation of the former
6835 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6838 @node Compilers and Preprocessors
6839 @section Compilers and Preprocessors
6840 @cindex Compilers
6841 @cindex Preprocessors
6843 @ovindex EXEEXT
6844 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6845 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6846 the output of the compiler, typically to the empty string if
6847 Posix and @samp{.exe} if a @acronym{DOS} variant.
6849 @ovindex OBJEXT
6850 They also define the output variable @code{OBJEXT} based on the
6851 output of the compiler, after @file{.c} files have been excluded, typically
6852 to @samp{o} if Posix, @samp{obj} if a @acronym{DOS} variant.
6854 If the compiler being used does not produce executables, the tests fail.  If
6855 the executables can't be run, and cross-compilation is not enabled, they
6856 fail too.  @xref{Manual Configuration}, for more on support for cross
6857 compiling.
6859 @menu
6860 * Specific Compiler Characteristics::  Some portability issues
6861 * Generic Compiler Characteristics::  Language independent tests and features
6862 * C Compiler::                  Checking its characteristics
6863 * C++ Compiler::                Likewise
6864 * Objective C Compiler::        Likewise
6865 * Objective C++ Compiler::      Likewise
6866 * Erlang Compiler and Interpreter::  Likewise
6867 * Fortran Compiler::            Likewise
6868 @end menu
6870 @node Specific Compiler Characteristics
6871 @subsection Specific Compiler Characteristics
6873 Some compilers exhibit different behaviors.
6875 @table @asis
6876 @item Static/Dynamic Expressions
6877 Autoconf relies on a trick to extract one bit of information from the C
6878 compiler: using negative array sizes.  For instance the following
6879 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6880 bytes wide:
6882 @example
6883 static int test_array[sizeof (int) == 4 ? 1 : -1];
6884 @end example
6886 @noindent
6887 To our knowledge, there is a single compiler that does not support this
6888 trick: the @acronym{HP} C compilers (the real ones, not only the
6889 ``bundled'') on @acronym{HP-UX} 11.00.
6890 They incorrectly reject the above program with the diagnostic
6891 ``Variable-length arrays cannot have static storage.''
6892 This bug comes from @acronym{HP} compilers' mishandling of @code{sizeof (int)},
6893 not from the @code{? 1 : -1}, and
6894 Autoconf works around this problem by casting @code{sizeof (int)} to
6895 @code{long int} before comparing it.
6896 @end table
6898 @node Generic Compiler Characteristics
6899 @subsection Generic Compiler Characteristics
6901 @anchor{AC_CHECK_SIZEOF}
6902 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
6903   @dvar{includes, AC_INCLUDES_DEFAULT})
6904 @acindex{CHECK_SIZEOF}
6905 @cvindex SIZEOF_@var{type-or-expr}
6906 @caindex sizeof_@var{type-or-expr}
6907 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
6908 the size in bytes of @var{type-or-expr}, which may be either a type or
6909 an expression returning a value that has a size.  If the expression
6910 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
6911 @var{includes} is a series of include directives, defaulting to
6912 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6913 prior to the expression under test.
6915 This macro now works even when cross-compiling.  The @var{unused}
6916 argument was used when cross-compiling.
6918 For example, the call
6920 @example
6921 AC_CHECK_SIZEOF([int *])
6922 @end example
6924 @noindent
6925 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
6927 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
6928 variable, with @samp{*} mapped to @samp{p} and other characters not
6929 suitable for a variable name mapped to underscores.
6930 @end defmac
6932 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
6933 @acindex{CHECK_ALIGNOF}
6934 @cvindex ALIGNOF_@var{type}
6935 @caindex alignof_@var{type-or-expr}
6936 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
6937 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
6938 a structure member declaration.  If @samp{type} is unknown, the result
6939 is 0.  If no @var{includes} are specified, the default includes are used
6940 (@pxref{Default Includes}).
6942 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
6943 variable, with @samp{*} mapped to @samp{p} and other characters not
6944 suitable for a variable name mapped to underscores.
6945 @end defmac
6947 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
6948   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
6949 @acindex{COMPUTE_INT}
6950 Store into the shell variable @var{var} the value of the integer
6951 @var{expression}.  The
6952 value should fit in an initializer in a C variable of type @code{signed
6953 long}.  To support cross compilation (in which case, the macro only works on
6954 hosts that use twos-complement arithmetic), it should be possible to evaluate
6955 the expression at compile-time.  If no @var{includes} are specified, the
6956 default includes are used (@pxref{Default Includes}).
6958 Execute @var{action-if-fails} if the value cannot be determined correctly.
6959 @end defmac
6961 @defmac AC_LANG_WERROR
6962 @acindex{LANG_WERROR}
6963 Normally Autoconf ignores warnings generated by the compiler, linker, and
6964 preprocessor.  If this macro is used, warnings count as fatal
6965 errors for the current language.  This macro is useful when the
6966 results of configuration are used where warnings are unacceptable; for
6967 instance, if parts of a program are built with the @acronym{GCC}
6968 @option{-Werror}
6969 option.  If the whole program is built using @option{-Werror} it is
6970 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
6971 etc.).
6972 @end defmac
6974 @defmac AC_OPENMP
6975 @acindex{OPENMP}
6976 @cvindex _OPENMP
6977 @ovindex OPENMP_CFLAGS
6978 @ovindex OPENMP_CXXFLAGS
6979 @ovindex OPENMP_FFLAGS
6980 @ovindex OPENMP_FCFLAGS
6981 OpenMP (@url{http://@/www.openmp.org/}) specifies extensions of C, C++,
6982 and Fortran that simplify optimization of shared memory parallelism,
6983 which is a common problem on multicore CPUs.
6985 If the current language is C, the macro @code{AC_OPENMP} sets the
6986 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
6987 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
6988 compiler already supports OpenMP, if it has no way to activate OpenMP
6989 support, or if the user rejects OpenMP support by invoking
6990 @samp{configure} with the @samp{--disable-openmp} option.
6992 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
6993 preprocessing program source, and when linking programs.  Therefore you
6994 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
6995 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
6996 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
6997 OpenMP support is revealed at compile time by the preprocessor macro
6998 @code{_OPENMP}.
7000 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7001 shared library to the program's dependencies, so its use is recommended
7002 only on programs that actually require OpenMP.
7004 If the current language is C++, @code{AC_OPENMP} sets the variable
7005 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7006 hold as for C.
7008 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7009 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7010 respectively.  Similar remarks as for C hold, except that
7011 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7012 signals OpenMP support.
7014 For portability, it is best to avoid spaces between @samp{#} and
7015 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7016 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7017 latter.
7018 @end defmac
7020 @node C Compiler
7021 @subsection C Compiler Characteristics
7023 The following macros provide ways to find and exercise a C Compiler.
7024 There are a few constructs that ought to be avoided, but do not deserve
7025 being checked for, since they can easily be worked around.
7027 @table @asis
7028 @item Don't use lines containing solitary backslashes
7029 They tickle a bug in the @acronym{HP-UX} C compiler (checked on
7030 @acronym{HP-UX} 10.20,
7031 11.00, and 11i).  When given the following source:
7033 @example
7034 #ifdef __STDC__
7036 * A comment with backslash-newlines in it.  %@{ %@} *\
7039 char str[] = "\\
7040 " A string with backslash-newlines in it %@{ %@} \\
7042 char apostrophe = '\\
7046 #endif
7047 @end example
7049 @noindent
7050 the compiler incorrectly fails with the diagnostics ``Non-terminating
7051 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7052 Removing the lines with solitary backslashes solves the problem.
7054 @item Don't compile several files at once if output matters to you
7055 Some compilers, such as @acronym{HP}'s, report names of files being
7056 compiled when given more than one file operand.  For instance:
7058 @example
7059 $ @kbd{cc a.c b.c}
7060 a.c:
7061 b.c:
7062 @end example
7064 @noindent
7065 This can cause problems if you observe the output of the compiler to
7066 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7067 b.o} solves the issue.
7069 @item Don't rely on @code{#error} failing
7070 The @sc{irix} C compiler does not fail when #error is preprocessed; it
7071 simply emits a diagnostic and continues, exiting successfully.  So,
7072 instead of an error directive like @code{#error "Unsupported word size"}
7073 it is more portable to use an invalid directive like @code{#Unsupported
7074 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7075 OK, since installers with inadequate compilers like @sc{irix} can simply
7076 examine these compilers' diagnostic output.
7078 @item Don't rely on correct @code{#line} support
7079 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7080 diagnoses @code{#line} directives whose line
7081 numbers are greater than 32767.  Nothing in Posix
7082 makes this invalid.  That is why Autoconf stopped issuing
7083 @code{#line} directives.
7084 @end table
7086 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7087 @acindex{PROG_CC}
7088 @evindex CC
7089 @evindex CFLAGS
7090 @ovindex CC
7091 @ovindex CFLAGS
7092 @caindex prog_cc_c89
7093 Determine a C compiler to use.  If @code{CC} is not already set in the
7094 environment, check for @code{gcc} and @code{cc}, then for other C
7095 compilers.  Set output variable @code{CC} to the name of the compiler
7096 found.
7098 This macro may, however, be invoked with an optional first argument
7099 which, if specified, must be a blank-separated list of C compilers to
7100 search for.  This just gives the user an opportunity to specify an
7101 alternative search list for the C compiler.  For example, if you didn't
7102 like the default order, then you could invoke @code{AC_PROG_CC} like
7103 this:
7105 @example
7106 AC_PROG_CC([gcc cl cc])
7107 @end example
7109 If the C compiler does not handle function prototypes correctly by
7110 default, try to add an option to output variable @code{CC} to make it
7111 so.  This macro tries various options that select standard-conformance
7112 modes on various systems.
7114 After calling this macro you can check whether the C compiler has been
7115 set to accept @acronym{ANSI} C89 (@acronym{ISO} C90); if not, the shell
7116 variable
7117 @code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
7118 @code{AC_C_PROTOTYPES} below.
7120 If using the @acronym{GNU} C compiler, set shell variable @code{GCC} to
7121 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
7122 it to @option{-g -O2} for the @acronym{GNU} C compiler (@option{-O2} on systems
7123 where @acronym{GCC} does not accept @option{-g}), or @option{-g} for
7124 other compilers.
7126 Many Autoconf macros use a compiler, and thus call
7127 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7128 determined before the body of the outermost @code{AC_DEFUN} macro.
7129 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7130 performs certain checks (such as the proper value of @env{EXEEXT}) only
7131 on the first invocation.  Therefore, care must be used when invoking
7132 this macro from within another macro rather than at the top level
7133 (@pxref{Expanded Before Required}).
7134 @end defmac
7136 @anchor{AC_PROG_CC_C_O}
7137 @defmac AC_PROG_CC_C_O
7138 @acindex{PROG_CC_C_O}
7139 @cvindex NO_MINUS_C_MINUS_O
7140 @caindex prog_cc_@var{compiler}_c_o
7141 If the C compiler does not accept the @option{-c} and @option{-o} options
7142 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7143 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7144 the first @code{cc} in the path.  The test fails if one fails.  This
7145 macro was created for @acronym{GNU} Make to choose the default C compilation
7146 rule.
7148 For the compiler @var{compiler}, this macro caches its result in the
7149 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7150 @end defmac
7153 @defmac AC_PROG_CPP
7154 @acindex{PROG_CPP}
7155 @evindex CPP
7156 @ovindex CPP
7157 Set output variable @code{CPP} to a command that runs the
7158 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
7159 It is only portable to run @code{CPP} on files with a @file{.c}
7160 extension.
7162 Some preprocessors don't indicate missing include files by the error
7163 status.  For such preprocessors an internal variable is set that causes
7164 other macros to check the standard error from the preprocessor and
7165 consider the test failed if any warnings have been reported.
7166 For most preprocessors, though, warnings do not cause include-file
7167 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7168 @end defmac
7170 @defmac AC_PROG_CPP_WERROR
7171 @acindex{PROG_CPP_WERROR}
7172 @ovindex CPP
7173 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7174 preprocessor as errors even if the preprocessor exit status indicates
7175 success.  This is useful for avoiding headers that generate mandatory
7176 warnings, such as deprecation notices.
7177 @end defmac
7180 The following macros check for C compiler or machine architecture
7181 features.  To check for characteristics not listed here, use
7182 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7183 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7185 @defmac AC_PROG_CC_STDC
7186 @acindex{PROG_CC_STDC}
7187 @caindex prog_cc_stdc
7188 If the C compiler cannot compile @acronym{ISO} Standard C (currently
7189 C99), try to add an option to output variable @code{CC} to make it work.
7190 If the compiler does not support C99, fall back to supporting
7191 @acronym{ANSI} C89 (@acronym{ISO} C90).
7193 After calling this macro you can check whether the C compiler has been
7194 set to accept Standard C; if not, the shell variable
7195 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7196 @end defmac
7198 @defmac AC_PROG_CC_C89
7199 @acindex{PROG_CC_C89}
7200 @caindex prog_cc_c89
7201 If the C compiler is not in @acronym{ANSI} C89 (@acronym{ISO} C90) mode by
7202 default, try to add an option to output variable @code{CC} to make it
7203 so.  This macro tries various options that select @acronym{ANSI} C89 on
7204 some system or another, preferring extended functionality modes over
7205 strict conformance modes.  It considers the compiler to be in
7206 @acronym{ANSI} C89 mode if it handles function prototypes correctly.
7208 After calling this macro you can check whether the C compiler has been
7209 set to accept @acronym{ANSI} C89; if not, the shell variable
7210 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
7212 This macro is called automatically by @code{AC_PROG_CC}.
7213 @end defmac
7215 @defmac AC_PROG_CC_C99
7216 @acindex{PROG_CC_C99}
7217 @caindex prog_cc_c99
7218 If the C compiler is not in C99 mode by default, try to add an
7219 option to output variable @code{CC} to make it so.  This macro tries
7220 various options that select C99 on some system or another, preferring
7221 extended functionality modes over strict conformance modes.  It
7222 considers the compiler to be in C99 mode if it handles @code{_Bool},
7223 @code{//} comments, flexible array members, @code{inline}, signed and
7224 unsigned @code{long long int}, mixed code and declarations, named
7225 initialization of structs,
7226 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
7227 in @code{for} loops, and variable length arrays.
7229 After calling this macro you can check whether the C compiler has been
7230 set to accept C99; if not, the shell variable
7231 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
7232 @end defmac
7234 @defmac AC_C_BACKSLASH_A
7235 @acindex{C_BACKSLASH_A}
7236 @cvindex HAVE_C_BACKSLASH_A
7237 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7238 @samp{\a}.
7240 This macro is obsolescent, as current C compilers understand @samp{\a}.
7241 New programs need not use this macro.
7242 @end defmac
7244 @anchor{AC_C_BIGENDIAN}
7245 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7246   @ovar{action-if-unknown}, @ovar{action-if-universal})
7247 @acindex{C_BIGENDIAN}
7248 @cvindex WORDS_BIGENDIAN
7249 @cindex Endianness
7250 If words are stored with the most significant byte first (like Motorola
7251 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7252 the least significant byte first (like Intel and VAX CPUs), execute
7253 @var{action-if-false}.
7255 This macro runs a test-case if endianness cannot be determined from the
7256 system header files.  When cross-compiling, the test-case is not run but
7257 grep'ed for some magic values.  @var{action-if-unknown} is executed if
7258 the latter case fails to determine the byte sex of the host system.
7260 In some cases a single run of a compiler can generate code for multiple
7261 architectures.  This can happen, for example, when generating Mac OS X
7262 universal binary files, which work on both PowerPC and Intel
7263 architectures.  In this case, the different variants might be for
7264 different architectures whose endiannesses differ.  If
7265 @command{configure} detects this, it executes @var{action-if-universal}
7266 instead of @var{action-if-unknown}.
7268 The default for @var{action-if-true} is to define
7269 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7270 nothing.  The default for @var{action-if-unknown} is to
7271 abort configure and tell the installer how to bypass this test.
7272 And finally, the default for @var{action-if-universal} is to ensure that
7273 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7274 detected and the current code is big-endian; this default works only if
7275 @command{autoheader} is used (@pxref{autoheader Invocation}).
7277 If you use this macro without specifying @var{action-if-universal}, you
7278 should also use @code{AC_CONFIG_HEADERS}; otherwise
7279 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7280 binary files.
7281 @end defmac
7283 @anchor{AC_C_CONST}
7284 @defmac AC_C_CONST
7285 @acindex{C_CONST}
7286 @cvindex const
7287 @caindex c_const
7288 If the C compiler does not fully support the @code{const} keyword,
7289 define @code{const} to be empty.  Some C compilers that do
7290 not define @code{__STDC__} do support @code{const}; some compilers that
7291 define @code{__STDC__} do not completely support @code{const}.  Programs
7292 can simply use @code{const} as if every C compiler supported it; for
7293 those that don't, the makefile or configuration header file
7294 defines it as empty.
7296 Occasionally installers use a C++ compiler to compile C code, typically
7297 because they lack a C compiler.  This causes problems with @code{const},
7298 because C and C++ treat @code{const} differently.  For example:
7300 @example
7301 const int foo;
7302 @end example
7304 @noindent
7305 is valid in C but not in C++.  These differences unfortunately cannot be
7306 papered over by defining @code{const} to be empty.
7308 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7309 as this generally yields better results in practice.  However, using a
7310 C++ compiler to compile C code is not recommended or supported, and
7311 installers who run into trouble in this area should get a C compiler
7312 like @acronym{GCC} to compile their C code.
7314 This macro caches its result in the @code{ac_cv_c_const} variable.
7316 This macro is obsolescent, as current C compilers support @code{const}.
7317 New programs need not use this macro.
7318 @end defmac
7320 @defmac AC_C_RESTRICT
7321 @acindex{C_RESTRICT}
7322 @cvindex restrict
7323 @caindex c_restrict
7324 If the C compiler recognizes a variant spelling for the @code{restrict}
7325 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7326 then define @code{restrict} to that; this is more likely to do the right
7327 thing with compilers that support language variants where plain
7328 @code{restrict} is not a keyword.  Otherwise, if the C compiler
7329 recognizes the @code{restrict} keyword, don't do anything.
7330 Otherwise, define @code{restrict} to be empty.
7331 Thus, programs may simply use @code{restrict} as if every C compiler
7332 supported it; for those that do not, the makefile
7333 or configuration header defines it away.
7335 Although support in C++ for the @code{restrict} keyword is not
7336 required, several C++ compilers do accept the keyword.
7337 This macro works for them, too.
7339 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7340 if @code{restrict} is not supported, and a supported spelling otherwise.
7341 @end defmac
7343 @defmac AC_C_VOLATILE
7344 @acindex{C_VOLATILE}
7345 @cvindex volatile
7346 If the C compiler does not understand the keyword @code{volatile},
7347 define @code{volatile} to be empty.  Programs can simply use
7348 @code{volatile} as if every C compiler supported it; for those that do
7349 not, the makefile or configuration header defines it as
7350 empty.
7352 If the correctness of your program depends on the semantics of
7353 @code{volatile}, simply defining it to be empty does, in a sense, break
7354 your code.  However, given that the compiler does not support
7355 @code{volatile}, you are at its mercy anyway.  At least your
7356 program compiles, when it wouldn't before.
7357 @xref{Volatile Objects}, for more about @code{volatile}.
7359 In general, the @code{volatile} keyword is a standard C feature, so
7360 you might expect that @code{volatile} is available only when
7361 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7362 support volatile, but does not define @code{__STDC__}.
7364 This macro is obsolescent, as current C compilers support @code{volatile}.
7365 New programs need not use this macro.
7366 @end defmac
7368 @anchor{AC_C_INLINE}
7369 @defmac AC_C_INLINE
7370 @acindex{C_INLINE}
7371 @cvindex inline
7372 If the C compiler supports the keyword @code{inline}, do nothing.
7373 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7374 if it accepts one of those, otherwise define @code{inline} to be empty.
7375 @end defmac
7377 @anchor{AC_C_CHAR_UNSIGNED}
7378 @defmac AC_C_CHAR_UNSIGNED
7379 @acindex{C_CHAR_UNSIGNED}
7380 @cvindex __CHAR_UNSIGNED__
7381 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7382 unless the C compiler predefines it.
7384 These days, using this macro is not necessary.  The same information can
7385 be determined by this portable alternative, thus avoiding the use of
7386 preprocessor macros in the namespace reserved for the implementation.
7388 @example
7389 #include <limits.h>
7390 #if CHAR_MIN == 0
7391 # define CHAR_UNSIGNED 1
7392 #endif
7393 @end example
7394 @end defmac
7396 @defmac AC_C_STRINGIZE
7397 @acindex{C_STRINGIZE}
7398 @cvindex HAVE_STRINGIZE
7399 If the C preprocessor supports the stringizing operator, define
7400 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7401 found in macros such as this:
7403 @example
7404 #define x(y) #y
7405 @end example
7407 This macro is obsolescent, as current C compilers support the
7408 stringizing operator.  New programs need not use this macro.
7409 @end defmac
7411 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7412 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7413 @cvindex FLEXIBLE_ARRAY_MEMBER
7414 If the C compiler supports flexible array members, define
7415 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7416 That way, a declaration like this:
7418 @example
7419 struct s
7420   @{
7421     size_t n_vals;
7422     double val[FLEXIBLE_ARRAY_MEMBER];
7423   @};
7424 @end example
7426 @noindent
7427 will let applications use the ``struct hack'' even with compilers that
7428 do not support flexible array members.  To allocate and use such an
7429 object, you can use code like this:
7431 @example
7432 size_t i;
7433 size_t n = compute_value_count ();
7434 struct s *p =
7435    malloc (offsetof (struct s, val)
7436            + n * sizeof (double));
7437 p->n_vals = n;
7438 for (i = 0; i < n; i++)
7439   p->val[i] = compute_value (i);
7440 @end example
7441 @end defmac
7443 @defmac AC_C_VARARRAYS
7444 @acindex{C_VARARRAYS}
7445 @cvindex HAVE_C_VARARRAYS
7446 If the C compiler supports variable-length arrays, define
7447 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
7448 storage duration whose length is determined at run time, when the array
7449 is declared.
7450 @end defmac
7452 @defmac AC_C_TYPEOF
7453 @acindex{C_TYPEOF}
7454 @cvindex HAVE_TYPEOF
7455 @cvindex typeof
7456 If the C compiler supports @acronym{GCC}'s @code{typeof} syntax either
7457 directly or
7458 through a different spelling of the keyword (e.g., @code{__typeof__}),
7459 define @code{HAVE_TYPEOF}.  If the support is available only through a
7460 different spelling, define @code{typeof} to that spelling.
7461 @end defmac
7463 @defmac AC_C_PROTOTYPES
7464 @acindex{C_PROTOTYPES}
7465 @cvindex PROTOTYPES
7466 @cvindex __PROTOTYPES
7467 @cvindex PARAMS
7468 If function prototypes are understood by the compiler (as determined by
7469 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7470 Defining @code{__PROTOTYPES} is for the benefit of
7471 header files that cannot use macros that infringe on user name space.
7473 This macro is obsolescent, as current C compilers support prototypes.
7474 New programs need not use this macro.
7475 @end defmac
7477 @anchor{AC_PROG_GCC_TRADITIONAL}
7478 @defmac AC_PROG_GCC_TRADITIONAL
7479 @acindex{PROG_GCC_TRADITIONAL}
7480 @ovindex CC
7481 Add @option{-traditional} to output variable @code{CC} if using the
7482 @acronym{GNU} C compiler and @code{ioctl} does not work properly without
7483 @option{-traditional}.  That usually happens when the fixed header files
7484 have not been installed on an old system.
7486 This macro is obsolescent, since current versions of the @acronym{GNU} C
7487 compiler fix the header files automatically when installed.
7488 @end defmac
7491 @node C++ Compiler
7492 @subsection C++ Compiler Characteristics
7495 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7496 @acindex{PROG_CXX}
7497 @evindex CXX
7498 @evindex CXXFLAGS
7499 @ovindex CXX
7500 @ovindex CXXFLAGS
7501 Determine a C++ compiler to use.  Check whether the environment variable
7502 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7503 variable @code{CXX} to its value.
7505 Otherwise, if the macro is invoked without an argument, then search for
7506 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7507 then other names).  If none of those checks succeed, then as a last
7508 resort set @code{CXX} to @code{g++}.
7510 This macro may, however, be invoked with an optional first argument
7511 which, if specified, must be a blank-separated list of C++ compilers to
7512 search for.  This just gives the user an opportunity to specify an
7513 alternative search list for the C++ compiler.  For example, if you
7514 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7515 like this:
7517 @example
7518 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7519 @end example
7521 If using the @acronym{GNU} C++ compiler, set shell variable @code{GXX} to
7522 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7523 it to @option{-g -O2} for the @acronym{GNU} C++ compiler (@option{-O2} on
7524 systems where G++ does not accept @option{-g}), or @option{-g} for other
7525 compilers.
7526 @end defmac
7528 @defmac AC_PROG_CXXCPP
7529 @acindex{PROG_CXXCPP}
7530 @evindex CXXCPP
7531 @ovindex CXXCPP
7532 Set output variable @code{CXXCPP} to a command that runs the C++
7533 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7534 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7535 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7537 Some preprocessors don't indicate missing include files by the error
7538 status.  For such preprocessors an internal variable is set that causes
7539 other macros to check the standard error from the preprocessor and
7540 consider the test failed if any warnings have been reported.  However,
7541 it is not known whether such broken preprocessors exist for C++.
7542 @end defmac
7544 @defmac AC_PROG_CXX_C_O
7545 @acindex{PROG_CXX_C_O}
7546 @cvindex CXX_NO_MINUS_C_MINUS_O
7547 Test whether the C++ compiler accepts the options @option{-c} and
7548 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7549 if it does not.
7550 @end defmac
7553 @node Objective C Compiler
7554 @subsection Objective C Compiler Characteristics
7557 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7558 @acindex{PROG_OBJC}
7559 @evindex OBJC
7560 @evindex OBJCFLAGS
7561 @ovindex OBJC
7562 @ovindex OBJCFLAGS
7563 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7564 set in the environment, check for Objective C compilers.  Set output
7565 variable @code{OBJC} to the name of the compiler found.
7567 This macro may, however, be invoked with an optional first argument
7568 which, if specified, must be a blank-separated list of Objective C compilers to
7569 search for.  This just gives the user an opportunity to specify an
7570 alternative search list for the Objective C compiler.  For example, if you
7571 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7572 like this:
7574 @example
7575 AC_PROG_OBJC([gcc objcc objc])
7576 @end example
7578 If using the @acronym{GNU} Objective C compiler, set shell variable
7579 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7580 already set, set it to @option{-g -O2} for the @acronym{GNU} Objective C
7581 compiler (@option{-O2} on systems where @command{gcc} does not accept
7582 @option{-g}), or @option{-g} for other compilers.
7583 @end defmac
7585 @defmac AC_PROG_OBJCPP
7586 @acindex{PROG_OBJCPP}
7587 @evindex OBJCPP
7588 @ovindex OBJCPP
7589 Set output variable @code{OBJCPP} to a command that runs the Objective C
7590 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7591 @end defmac
7594 @node Objective C++ Compiler
7595 @subsection Objective C++ Compiler Characteristics
7598 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7599 @acindex{PROG_OBJCXX}
7600 @evindex OBJCXX
7601 @evindex OBJCXXFLAGS
7602 @ovindex OBJCXX
7603 @ovindex OBJCXXFLAGS
7604 Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
7605 set in the environment, check for Objective C++ compilers.  Set output
7606 variable @code{OBJCXX} to the name of the compiler found.
7608 This macro may, however, be invoked with an optional first argument
7609 which, if specified, must be a blank-separated list of Objective C++ compilers
7610 to search for.  This just gives the user an opportunity to specify an
7611 alternative search list for the Objective C++ compiler.  For example, if you
7612 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7613 like this:
7615 @example
7616 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7617 @end example
7619 If using the @acronym{GNU} Objective C++ compiler, set shell variable
7620 @code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
7621 already set, set it to @option{-g -O2} for the @acronym{GNU} Objective C++
7622 compiler (@option{-O2} on systems where @command{gcc} does not accept
7623 @option{-g}), or @option{-g} for other compilers.
7624 @end defmac
7626 @defmac AC_PROG_OBJCXXCPP
7627 @acindex{PROG_OBJCXXCPP}
7628 @evindex OBJCXXCPP
7629 @ovindex OBJCXXCPP
7630 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7631 preprocessor.  If @samp{$OBJCXX -E} doesn't work, @file{/lib/cpp} is used.
7632 @end defmac
7635 @node Erlang Compiler and Interpreter
7636 @subsection Erlang Compiler and Interpreter Characteristics
7637 @cindex Erlang
7639 Autoconf defines the following macros for determining paths to the essential
7640 Erlang/OTP programs:
7642 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7643 @acindex{ERLANG_PATH_ERLC}
7644 @evindex ERLC
7645 @evindex ERLCFLAGS
7646 @ovindex ERLC
7647 @ovindex ERLCFLAGS
7648 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7649 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7650 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7651 is not set in the environment, set it to an empty value.
7653 The two optional arguments have the same meaning as the two last arguments of
7654 macro @code{AC_PROG_PATH} for looking for the @command{erlc} program.  For
7655 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7656 directory:
7658 @example
7659 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7660 @end example
7661 @end defmac
7663 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7664 @acindex{ERLANG_NEED_ERLC}
7665 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7666 error message and exits the @command{configure} script if the @command{erlc}
7667 program is not found.
7668 @end defmac
7670 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7671 @acindex{ERLANG_PATH_ERL}
7672 @evindex ERL
7673 @ovindex ERL
7674 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7675 set in the
7676 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7677 complete path of the interpreter command found.
7679 The two optional arguments have the same meaning as the two last arguments of
7680 macro @code{AC_PROG_PATH} for looking for the @command{erl} program.  For
7681 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7682 directory:
7684 @example
7685 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7686 @end example
7687 @end defmac
7689 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7690 @acindex{ERLANG_NEED_ERL}
7691 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7692 error message and exits the @command{configure} script if the @command{erl}
7693 program is not found.
7694 @end defmac
7697 @node Fortran Compiler
7698 @subsection Fortran Compiler Characteristics
7699 @cindex Fortran
7700 @cindex F77
7702 The Autoconf Fortran support is divided into two categories: legacy
7703 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7704 The former are intended for traditional Fortran 77 code, and have output
7705 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7706 are for newer programs that can (or must) compile under the newer
7707 Fortran standards, and have output variables like @code{FC},
7708 @code{FCFLAGS}, and @code{FCLIBS}.
7710 Except for two new macros @code{AC_FC_SRCEXT} and
7711 @code{AC_FC_FREEFORM} (see below), the @code{FC} and @code{F77} macros
7712 behave almost identically, and so they are documented together in this
7713 section.
7716 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7717 @acindex{PROG_F77}
7718 @evindex F77
7719 @evindex FFLAGS
7720 @ovindex F77
7721 @ovindex FFLAGS
7722 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7723 set in the environment, then check for @code{g77} and @code{f77}, and
7724 then some other names.  Set the output variable @code{F77} to the name
7725 of the compiler found.
7727 This macro may, however, be invoked with an optional first argument
7728 which, if specified, must be a blank-separated list of Fortran 77
7729 compilers to search for.  This just gives the user an opportunity to
7730 specify an alternative search list for the Fortran 77 compiler.  For
7731 example, if you didn't like the default order, then you could invoke
7732 @code{AC_PROG_F77} like this:
7734 @example
7735 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7736 @end example
7738 If using @code{g77} (the @acronym{GNU} Fortran 77 compiler), then
7739 set the shell variable @code{G77} to @samp{yes}.
7740 If the output variable @code{FFLAGS} was not already set in the
7741 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7742 where @code{g77} does not accept @option{-g}).  Otherwise, set
7743 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7744 @end defmac
7746 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7747 @acindex{PROG_FC}
7748 @evindex FC
7749 @evindex FCFLAGS
7750 @ovindex FC
7751 @ovindex FCFLAGS
7752 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7753 the environment, then @code{dialect} is a hint to indicate what Fortran
7754 dialect to search for; the default is to search for the newest available
7755 dialect.  Set the output variable @code{FC} to the name of the compiler
7756 found.
7758 By default, newer dialects are preferred over older dialects, but if
7759 @code{dialect} is specified then older dialects are preferred starting
7760 with the specified dialect.  @code{dialect} can currently be one of
7761 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7762 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7763 and no attempt is made to guarantee that a particular language standard
7764 is actually supported.  Thus, it is preferable that you avoid the
7765 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7766 the latest Fortran standard.
7768 This macro may, alternatively, be invoked with an optional first argument
7769 which, if specified, must be a blank-separated list of Fortran
7770 compilers to search for, just as in @code{AC_PROG_F77}.
7772 If the output variable @code{FCFLAGS} was not already set in the
7773 environment, then set it to @option{-g -02} for @acronym{GNU} @code{g77} (or
7774 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7775 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7776 @end defmac
7778 @defmac AC_PROG_F77_C_O
7779 @defmacx AC_PROG_FC_C_O
7780 @acindex{PROG_F77_C_O}
7781 @acindex{PROG_FC_C_O}
7782 @cvindex F77_NO_MINUS_C_MINUS_O
7783 @cvindex FC_NO_MINUS_C_MINUS_O
7784 Test whether the Fortran compiler accepts the options @option{-c} and
7785 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7786 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7787 @end defmac
7789 The following macros check for Fortran compiler characteristics.
7790 To check for characteristics not listed here, use
7791 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7792 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7793 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7794 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7797 @defmac AC_F77_LIBRARY_LDFLAGS
7798 @defmacx AC_FC_LIBRARY_LDFLAGS
7799 @acindex{F77_LIBRARY_LDFLAGS}
7800 @ovindex FLIBS
7801 @acindex{FC_LIBRARY_LDFLAGS}
7802 @ovindex FCLIBS
7803 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7804 @dfn{Fortran intrinsic and runtime libraries} that are required to
7805 successfully link a Fortran program or shared library.  The output
7806 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7807 should be included after @code{LIBS} when linking).
7809 This macro is intended to be used in those situations when it is
7810 necessary to mix, e.g., C++ and Fortran source code in a single
7811 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7812 automake, @acronym{GNU} Automake}).
7814 For example, if object files from a C++ and Fortran compiler must be
7815 linked together, then the C++ compiler/linker must be used for linking
7816 (since special C++-ish things need to happen at link time like calling
7817 global constructors, instantiating templates, enabling exception
7818 support, etc.).
7820 However, the Fortran intrinsic and runtime libraries must be linked in
7821 as well, but the C++ compiler/linker doesn't know by default how to add
7822 these Fortran 77 libraries.  Hence, this macro was created to determine
7823 these Fortran libraries.
7825 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7826 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7827 link C/C++ with Fortran; see below.
7828 @end defmac
7830 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7831 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7832 @acindex{F77_DUMMY_MAIN}
7833 @cvindex F77_DUMMY_MAIN
7834 With many compilers, the Fortran libraries detected by
7835 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7836 their own @code{main} entry function that initializes things like
7837 Fortran I/O, and which then calls a user-provided entry function named
7838 (say) @code{MAIN__} to run the user's program.  The
7839 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7840 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
7841 this interaction.
7843 When using Fortran for purely numerical functions (no I/O, etc.)@: often
7844 one prefers to provide one's own @code{main} and skip the Fortran
7845 library initializations.  In this case, however, one may still need to
7846 provide a dummy @code{MAIN__} routine in order to prevent linking errors
7847 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
7848 detects whether any such routine is @emph{required} for linking, and
7849 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
7850 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
7851 was found, and @code{none} when no such dummy main is needed.
7853 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
7854 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
7855 @emph{if} it is required.  @var{action-if-not-found} defaults to
7856 exiting with an error.
7858 In order to link with Fortran routines, the user's C/C++ program should
7859 then include the following code to define the dummy main if it is
7860 needed:
7862 @example
7863 #ifdef F77_DUMMY_MAIN
7864 #  ifdef __cplusplus
7865      extern "C"
7866 #  endif
7867    int F77_DUMMY_MAIN() @{ return 1; @}
7868 #endif
7869 @end example
7871 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7873 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
7874 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
7875 explicitly unless one wants to change the default actions.
7876 @end defmac
7878 @defmac AC_F77_MAIN
7879 @defmacx AC_FC_MAIN
7880 @acindex{F77_MAIN}
7881 @cvindex F77_MAIN
7882 @acindex{FC_MAIN}
7883 @cvindex FC_MAIN
7884 As discussed above, many Fortran libraries allow you to provide an entry
7885 point called (say) @code{MAIN__} instead of the usual @code{main}, which
7886 is then called by a @code{main} function in the Fortran libraries that
7887 initializes things like Fortran I/O@.  The
7888 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
7889 @emph{possible} to utilize such an alternate main function, and defines
7890 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
7891 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
7892 simply defined to @code{main}.)
7894 Thus, when calling Fortran routines from C that perform things like I/O,
7895 one should use this macro and declare the "main" function like so:
7897 @example
7898 #ifdef __cplusplus
7899   extern "C"
7900 #endif
7901 int F77_MAIN(int argc, char *argv[]);
7902 @end example
7904 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7905 @end defmac
7907 @defmac AC_F77_WRAPPERS
7908 @defmacx AC_FC_WRAPPERS
7909 @acindex{F77_WRAPPERS}
7910 @cvindex F77_FUNC
7911 @cvindex F77_FUNC_
7912 @acindex{FC_WRAPPERS}
7913 @cvindex FC_FUNC
7914 @cvindex FC_FUNC_
7915 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
7916 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
7917 mangle the names of C/C++ identifiers, and identifiers with underscores,
7918 respectively, so that they match the name-mangling scheme used by the
7919 Fortran compiler.
7921 Fortran is case-insensitive, and in order to achieve this the Fortran
7922 compiler converts all identifiers into a canonical case and format.  To
7923 call a Fortran subroutine from C or to write a C function that is
7924 callable from Fortran, the C program must explicitly use identifiers in
7925 the format expected by the Fortran compiler.  In order to do this, one
7926 simply wraps all C identifiers in one of the macros provided by
7927 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
7928 you have the following Fortran 77 subroutine:
7930 @example
7931       subroutine foobar (x, y)
7932       double precision x, y
7933       y = 3.14159 * x
7934       return
7935       end
7936 @end example
7938 You would then declare its prototype in C or C++ as:
7940 @example
7941 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
7942 #ifdef __cplusplus
7943 extern "C"  /* prevent C++ name mangling */
7944 #endif
7945 void FOOBAR_F77(double *x, double *y);
7946 @end example
7948 Note that we pass both the lowercase and uppercase versions of the
7949 function name to @code{F77_FUNC} so that it can select the right one.
7950 Note also that all parameters to Fortran 77 routines are passed as
7951 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, @acronym{GNU}
7952 Automake}).
7954 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7956 Although Autoconf tries to be intelligent about detecting the
7957 name-mangling scheme of the Fortran compiler, there may be Fortran
7958 compilers that it doesn't support yet.  In this case, the above code
7959 generates a compile-time error, but some other behavior
7960 (e.g., disabling Fortran-related features) can be induced by checking
7961 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
7963 Now, to call that routine from a C program, we would do something like:
7965 @example
7967     double x = 2.7183, y;
7968     FOOBAR_F77 (&x, &y);
7970 @end example
7972 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
7973 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
7974 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
7975 because some Fortran compilers mangle names differently if they contain
7976 an underscore.
7977 @end defmac
7979 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
7980 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
7981 @acindex{F77_FUNC}
7982 @acindex{FC_FUNC}
7983 Given an identifier @var{name}, set the shell variable @var{shellvar} to
7984 hold the mangled version @var{name} according to the rules of the
7985 Fortran linker (see also @code{AC_F77_WRAPPERS} or
7986 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
7987 supplied, the shell variable is simply @var{name}.  The purpose of
7988 this macro is to give the caller a way to access the name-mangling
7989 information other than through the C preprocessor as above, for example,
7990 to call Fortran routines from some language other than C/C++.
7991 @end defmac
7993 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
7994   @ovar{action-if-failure})
7995 @acindex{FC_SRCEXT}
7996 By default, the @code{FC} macros perform their tests using a @file{.f}
7997 extension for source-code files.  Some compilers, however, only enable
7998 newer language features for appropriately named files, e.g., Fortran 90
7999 features only for @file{.f90} files.  On the other hand, some other
8000 compilers expect all source files to end in @file{.f} and require
8001 special flags to support other file name extensions.  The
8002 @code{AC_FC_SRCEXT} macro deals with both of these issues.
8004 The @code{AC_FC_SRCEXT} tries to get the @code{FC} compiler to accept files
8005 ending with the extension .@var{ext} (i.e., @var{ext} does @emph{not}
8006 contain the dot).  If any special compiler flags are needed for this, it
8007 stores them in the output variable @code{FCFLAGS_}@var{ext}.  This
8008 extension and these flags are then used for all subsequent @code{FC} tests
8009 (until @code{AC_FC_SRCEXT} is called again).
8011 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8012 @file{.f90} extension in future tests, and it would set the
8013 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8014 to compile such files.
8016 The @code{FCFLAGS_}@var{ext} can @emph{not} be simply absorbed into
8017 @code{FCFLAGS}, for two reasons based on the limitations of some
8018 compilers.  First, only one @code{FCFLAGS_}@var{ext} can be used at a
8019 time, so files with different extensions must be compiled separately.
8020 Second, @code{FCFLAGS_}@var{ext} must appear @emph{immediately} before
8021 the source-code file name when compiling.  So, continuing the example
8022 above, you might compile a @file{foo.f90} file in your makefile with the
8023 command:
8025 @example
8026 foo.o: foo.f90
8027      $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8028 @end example
8030 If @code{AC_FC_SRCEXT} succeeds in compiling files with the @var{ext}
8031 extension, it calls @var{action-if-success} (defaults to nothing).  If
8032 it fails, and cannot find a way to make the @code{FC} compiler accept such
8033 files, it calls @var{action-if-failure} (defaults to exiting with an
8034 error message).
8036 @end defmac
8038 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @ovar{action-if-failure})
8039 @acindex{FC_FREEFORM}
8041 The @code{AC_FC_FREEFORM} tries to ensure that the Fortran compiler
8042 (@code{$FC}) allows free-format source code (as opposed to the older
8043 fixed-format style from Fortran 77).  If necessary, it may add some
8044 additional flags to @code{FCFLAGS}.
8046 This macro is most important if you are using the default @file{.f}
8047 extension, since many compilers interpret this extension as indicating
8048 fixed-format source unless an additional flag is supplied.  If you
8049 specify a different extension with @code{AC_FC_SRCEXT}, such as
8050 @file{.f90} or @file{.f95}, then @code{AC_FC_FREEFORM} ordinarily
8051 succeeds without modifying @code{FCFLAGS}.
8053 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8054 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8055 calls @var{action-if-failure} (defaults to exiting with an error
8056 message).
8057 @end defmac
8059 @node System Services
8060 @section System Services
8062 The following macros check for operating system services or capabilities.
8064 @anchor{AC_PATH_X}
8065 @defmac AC_PATH_X
8066 @acindex{PATH_X}
8067 @evindex XMKMF
8068 @cindex X Window System
8069 Try to locate the X Window System include files and libraries.  If the
8070 user gave the command line options @option{--x-includes=@var{dir}} and
8071 @option{--x-libraries=@var{dir}}, use those directories.
8073 If either or both were not given, get the missing values by running
8074 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8075 environment variable) on a trivial @file{Imakefile} and examining the
8076 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8077 disables this method.
8079 If this method fails to find the X Window System, @command{configure}
8080 looks for the files in several directories where they often reside.
8081 If either method is successful, set the shell variables
8082 @code{x_includes} and @code{x_libraries} to their locations, unless they
8083 are in directories the compiler searches by default.
8085 If both methods fail, or the user gave the command line option
8086 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8087 otherwise set it to the empty string.
8088 @end defmac
8090 @anchor{AC_PATH_XTRA}
8091 @defmac AC_PATH_XTRA
8092 @acindex{PATH_XTRA}
8093 @ovindex X_CFLAGS
8094 @ovindex X_LIBS
8095 @ovindex X_EXTRA_LIBS
8096 @ovindex X_PRE_LIBS
8097 @cvindex X_DISPLAY_MISSING
8098 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8099 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8100 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8101 available.
8103 This macro also checks for special libraries that some systems need in
8104 order to compile X programs.  It adds any that the system needs to
8105 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8106 libraries that need to be linked with before @option{-lX11}, and adds
8107 any found to the output variable @code{X_PRE_LIBS}.
8109 @c This is an incomplete kludge.  Make a real way to do it.
8110 @c If you need to check for other X functions or libraries yourself, then
8111 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8112 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8113 @end defmac
8115 @anchor{AC_SYS_INTERPRETER}
8116 @defmac AC_SYS_INTERPRETER
8117 @acindex{SYS_INTERPRETER}
8118 Check whether the system supports starting scripts with a line of the
8119 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8120 After running this macro, shell code in @file{configure.ac} can check
8121 the shell variable @code{interpval}; it is set to @samp{yes}
8122 if the system supports @samp{#!}, @samp{no} if not.
8123 @end defmac
8125 @defmac AC_SYS_LARGEFILE
8126 @acindex{SYS_LARGEFILE}
8127 @cvindex _FILE_OFFSET_BITS
8128 @cvindex _LARGE_FILES
8129 @ovindex CC
8130 @cindex Large file support
8131 @cindex LFS
8132 Arrange for 64-bit file offsets, known as
8133 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
8134 large-file support}.  On some hosts, one must use special compiler
8135 options to build programs that can access large files.  Append any such
8136 options to the output variable @code{CC}.  Define
8137 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8139 Large-file support can be disabled by configuring with the
8140 @option{--disable-largefile} option.
8142 If you use this macro, check that your program works even when
8143 @code{off_t} is wider than @code{long int}, since this is common when
8144 large-file support is enabled.  For example, it is not correct to print
8145 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8146 (long int) X)}.
8148 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8149 replace their C counterparts @code{fseek} and @code{ftell} that do not
8150 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8151 prototypes available when using them and large-file support is
8152 enabled.
8153 @end defmac
8155 @anchor{AC_SYS_LONG_FILE_NAMES}
8156 @defmac AC_SYS_LONG_FILE_NAMES
8157 @acindex{SYS_LONG_FILE_NAMES}
8158 @cvindex HAVE_LONG_FILE_NAMES
8159 If the system supports file names longer than 14 characters, define
8160 @code{HAVE_LONG_FILE_NAMES}.
8161 @end defmac
8163 @defmac AC_SYS_POSIX_TERMIOS
8164 @acindex{SYS_POSIX_TERMIOS}
8165 @cindex Posix termios headers
8166 @cindex termios Posix headers
8167 @caindex sys_posix_termios
8168 Check to see if the Posix termios headers and functions are available on the
8169 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8170 @samp{yes}.  If not, set the variable to @samp{no}.
8171 @end defmac
8173 @node Posix Variants
8174 @section Posix Variants
8176 The following macro makes it possible to use features of Posix that are
8177 extensions to C, as well as platform extensions not defined by Posix.
8179 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8180 @defmac AC_USE_SYSTEM_EXTENSIONS
8181 @acindex{USE_SYSTEM_EXTENSIONS}
8182 @cvindex _ALL_SOURCE
8183 @cvindex _GNU_SOURCE
8184 @cvindex _MINIX
8185 @cvindex _POSIX_1_SOURCE
8186 @cvindex _POSIX_PTHREAD_SEMANTICS
8187 @cvindex _POSIX_SOURCE
8188 @cvindex _TANDEM_SOURCE
8189 @cvindex __EXTENSIONS__
8190 This macro was introduced in Autoconf 2.60.  If possible, enable
8191 extensions to C or Posix on hosts that normally disable the extensions,
8192 typically due to standards-conformance namespace issues.  This should be
8193 called before any macros that run the C compiler.  The following
8194 preprocessor macros are defined where appropriate:
8196 @table @code
8197 @item _GNU_SOURCE
8198 Enable extensions on @acronym{GNU}/Linux.
8199 @item __EXTENSIONS__
8200 Enable general extensions on Solaris.
8201 @item _POSIX_PTHREAD_SEMANTICS
8202 Enable threading extensions on Solaris.
8203 @item _TANDEM_SOURCE
8204 Enable extensions for the @acronym{HP} NonStop platform.
8205 @item _ALL_SOURCE
8206 Enable extensions for @acronym{AIX} 3, and for Interix.
8207 @item _POSIX_SOURCE
8208 Enable Posix functions for Minix.
8209 @item _POSIX_1_SOURCE
8210 Enable additional Posix functions for Minix.
8211 @item _MINIX
8212 Identify Minix platform.  This particular preprocessor macro is
8213 obsolescent, and may be removed in a future release of Autoconf.
8214 @end table
8215 @end defmac
8218 @node Erlang Libraries
8219 @section Erlang Libraries
8220 @cindex Erlang, Library, checking
8222 The following macros check for an installation of Erlang/OTP, and for the
8223 presence of certain Erlang libraries.  All those macros require the
8224 configuration of an Erlang interpreter and an Erlang compiler
8225 (@pxref{Erlang Compiler and Interpreter}).
8227 @defmac AC_ERLANG_SUBST_ERTS_VER
8228 @acindex{ERLANG_SUBST_ERTS_VER}
8229 @ovindex ERLANG_ERTS_VER
8230 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8231 Erlang runtime system (as returned by Erlang's
8232 @code{erlang:system_info(version)} function).  The result of this test
8233 is cached if caching is enabled when running @command{configure}.  The
8234 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8235 for features of specific ERTS versions, but to be used for substituting
8236 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8237 files), as shown below.
8238 @end defmac
8240 @defmac AC_ERLANG_SUBST_ROOT_DIR
8241 @acindex{ERLANG_SUBST_ROOT_DIR}
8242 @ovindex ERLANG_ROOT_DIR
8243 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8244 directory in which Erlang/OTP is installed (as returned by Erlang's
8245 @code{code:root_dir/0} function).  The result of this test is cached if
8246 caching is enabled when running @command{configure}.
8247 @end defmac
8249 @defmac AC_ERLANG_SUBST_LIB_DIR
8250 @acindex{ERLANG_SUBST_LIB_DIR}
8251 @ovindex ERLANG_LIB_DIR
8252 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8253 directory of Erlang/OTP (as returned by Erlang's
8254 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8255 Erlang/OTP library.  The result of this test is cached if caching is enabled
8256 when running @command{configure}.
8257 @end defmac
8259 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8260   @ovar{action-if-not-found})
8261 @acindex{ERLANG_CHECK_LIB}
8262 @ovindex ERLANG_LIB_DIR_@var{library}
8263 @ovindex ERLANG_LIB_VER_@var{library}
8264 Test whether the Erlang/OTP library @var{library} is installed by
8265 calling Erlang's @code{code:lib_dir/1} function.  The result of this
8266 test is cached if caching is enabled when running @command{configure}.
8267 @var{action-if-found} is a list of shell commands to run if the library
8268 is installed; @var{action-if-not-found} is a list of shell commands to
8269 run if it is not.  Additionally, if the library is installed, the output
8270 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8271 library installation directory, and the output variable
8272 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8273 part of the subdirectory name, if it is in the standard form
8274 (@code{@var{library}-@var{version}}).  If the directory name does not
8275 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8276 empty string.  If the library is not installed,
8277 @samp{ERLANG_LIB_DIR_@var{library}} and
8278 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
8279 example, to check if library @code{stdlib} is installed:
8281 @example
8282 AC_ERLANG_CHECK_LIB([stdlib],
8283   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8284    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8285   [AC_MSG_ERROR([stdlib was not found!])])
8286 @end example
8288 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8289 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8290 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8291 testing for features of specific versions of libraries or of the Erlang
8292 runtime system.  Those variables are intended to be substituted in
8293 Erlang release resource files (@code{.rel} files).  For instance, to
8294 generate a @file{example.rel} file for an application depending on the
8295 @code{stdlib} library, @file{configure.ac} could contain:
8297 @example
8298 AC_ERLANG_SUBST_ERTS_VER
8299 AC_ERLANG_CHECK_LIB([stdlib],
8300   [],
8301   [AC_MSG_ERROR([stdlib was not found!])])
8302 AC_CONFIG_FILES([example.rel])
8303 @end example
8305 @noindent
8306 The @file{example.rel.in} file used to generate @file{example.rel}
8307 should contain:
8309 @example
8310 @{release,
8311     @{"@@PACKAGE@@", "@@VERSION@@"@},
8312     @{erts, "@@ERLANG_ERTS_VER@@"@},
8313     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8314      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8315 @end example
8316 @end defmac
8318 In addition to the above macros, which test installed Erlang libraries, the
8319 following macros determine the paths to the directories into which newly built
8320 Erlang libraries are to be installed:
8322 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8323 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8324 @ovindex ERLANG_INSTALL_LIB_DIR
8326 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8327 which every built Erlang library should be installed in a separate
8328 subdirectory.
8329 If this variable is not set in the environment when @command{configure} runs,
8330 its default value is @code{$ERLANG_LIB_DIR}, which value is set by the
8331 @code{AC_ERLANG_SUBST_LIB_DIR} macro.
8332 @end defmac
8334 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8335 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8336 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8338 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8339 directory into which the built Erlang library @var{library} version
8340 @var{version} should be installed.  If this variable is not set in the
8341 environment when @command{configure} runs, its default value is
8342 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
8343 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
8344 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
8345 @end defmac
8351 @c ========================================================= Writing Tests
8353 @node Writing Tests
8354 @chapter Writing Tests
8356 If the existing feature tests don't do something you need, you have to
8357 write new ones.  These macros are the building blocks.  They provide
8358 ways for other macros to check whether various kinds of features are
8359 available and report the results.
8361 This chapter contains some suggestions and some of the reasons why the
8362 existing tests are written the way they are.  You can also learn a lot
8363 about how to write Autoconf tests by looking at the existing ones.  If
8364 something goes wrong in one or more of the Autoconf tests, this
8365 information can help you understand the assumptions behind them, which
8366 might help you figure out how to best solve the problem.
8368 These macros check the output of the compiler system of the current
8369 language (@pxref{Language Choice}).  They do not cache the results of
8370 their tests for future use (@pxref{Caching Results}), because they don't
8371 know enough about the information they are checking for to generate a
8372 cache variable name.  They also do not print any messages, for the same
8373 reason.  The checks for particular kinds of features call these macros
8374 and do cache their results and print messages about what they're
8375 checking for.
8377 When you write a feature test that could be applicable to more than one
8378 software package, the best thing to do is encapsulate it in a new macro.
8379 @xref{Writing Autoconf Macros}, for how to do that.
8381 @menu
8382 * Language Choice::             Selecting which language to use for testing
8383 * Writing Test Programs::       Forging source files for compilers
8384 * Running the Preprocessor::    Detecting preprocessor symbols
8385 * Running the Compiler::        Detecting language or header features
8386 * Running the Linker::          Detecting library features
8387 * Runtime::                     Testing for runtime features
8388 * Systemology::                 A zoology of operating systems
8389 * Multiple Cases::              Tests for several possible values
8390 @end menu
8392 @node Language Choice
8393 @section Language Choice
8394 @cindex Language
8396 Autoconf-generated @command{configure} scripts check for the C compiler and
8397 its features by default.  Packages that use other programming languages
8398 (maybe more than one, e.g., C and C++) need to test features of the
8399 compilers for the respective languages.  The following macros determine
8400 which programming language is used in the subsequent tests in
8401 @file{configure.ac}.
8403 @anchor{AC_LANG}
8404 @defmac AC_LANG (@var{language})
8405 Do compilation tests using the compiler, preprocessor, and file
8406 extensions for the specified @var{language}.
8408 Supported languages are:
8410 @table @samp
8411 @item C
8412 Do compilation tests using @code{CC} and @code{CPP} and use extension
8413 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
8414 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
8416 @item C++
8417 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8418 extension @file{.C} for test programs.  Use compilation flags:
8419 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8420 @code{CXXFLAGS} with @code{CXX}.
8422 @item Fortran 77
8423 Do compilation tests using @code{F77} and use extension @file{.f} for
8424 test programs.  Use compilation flags: @code{FFLAGS}.
8426 @item Fortran
8427 Do compilation tests using @code{FC} and use extension @file{.f} (or
8428 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
8429 compilation flags: @code{FCFLAGS}.
8431 @item Erlang
8432 @ovindex ERLC
8433 @ovindex ERL
8434 @ovindex ERLCFLAGS
8435 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8436 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
8438 @item Objective C
8439 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8440 extension @file{.m} for test programs.  Use compilation flags:
8441 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8442 @code{OBJCFLAGS} with @code{OBJC}.
8444 @item Objective C++
8445 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
8446 extension @file{.mm} for test programs.  Use compilation flags:
8447 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
8448 @code{OBJCXXFLAGS} with @code{OBJCXX}.
8449 @end table
8450 @end defmac
8452 @anchor{AC_LANG_PUSH}
8453 @defmac AC_LANG_PUSH (@var{language})
8454 @acindex{LANG_PUSH}
8455 Remember the current language (as set by @code{AC_LANG}) on a stack, and
8456 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
8457 in macros that need to temporarily switch to a particular language.
8458 @end defmac
8460 @defmac AC_LANG_POP (@ovar{language})
8461 @acindex{LANG_POP}
8462 Select the language that is saved on the top of the stack, as set by
8463 @code{AC_LANG_PUSH}, and remove it from the stack.
8465 If given, @var{language} specifies the language we just @emph{quit}.  It
8466 is a good idea to specify it when it's known (which should be the
8467 case@dots{}), since Autoconf detects inconsistencies.
8469 @example
8470 AC_LANG_PUSH([Fortran 77])
8471 # Perform some tests on Fortran 77.
8472 # @dots{}
8473 AC_LANG_POP([Fortran 77])
8474 @end example
8475 @end defmac
8477 @defmac AC_LANG_ASSERT (@var{language})
8478 @acindex{LANG_ASSERT} Check statically that the current language is
8479 @var{language}.  You should use this in your language specific macros
8480 to avoid that they be called with an inappropriate language.
8482 This macro runs only at @command{autoconf} time, and incurs no cost at
8483 @command{configure} time.  Sadly enough and because Autoconf is a two
8484 layer language @footnote{Because M4 is not aware of Sh code,
8485 especially conditionals, some optimizations that look nice statically
8486 may produce incorrect results at runtime.}, the macros
8487 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8488 therefore as much as possible you ought to avoid using them to wrap
8489 your code, rather, require from the user to run the macro with a
8490 correct current language, and check it with @code{AC_LANG_ASSERT}.
8491 And anyway, that may help the user understand she is running a Fortran
8492 macro while expecting a result about her Fortran 77 compiler@enddots{}
8493 @end defmac
8496 @defmac AC_REQUIRE_CPP
8497 @acindex{REQUIRE_CPP}
8498 Ensure that whichever preprocessor would currently be used for tests has
8499 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
8500 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
8501 depending on which language is current.
8502 @end defmac
8505 @node Writing Test Programs
8506 @section Writing Test Programs
8508 Autoconf tests follow a common scheme: feed some program with some
8509 input, and most of the time, feed a compiler with some source file.
8510 This section is dedicated to these source samples.
8512 @menu
8513 * Guidelines::                  General rules for writing test programs
8514 * Test Functions::              Avoiding pitfalls in test programs
8515 * Generating Sources::          Source program boilerplate
8516 @end menu
8518 @node Guidelines
8519 @subsection Guidelines for Test Programs
8521 The most important rule to follow when writing testing samples is:
8523 @center @emph{Look for realism.}
8525 This motto means that testing samples must be written with the same
8526 strictness as real programs are written.  In particular, you should
8527 avoid ``shortcuts'' and simplifications.
8529 Don't just play with the preprocessor if you want to prepare a
8530 compilation.  For instance, using @command{cpp} to check whether a header is
8531 functional might let your @command{configure} accept a header which
8532 causes some @emph{compiler} error.  Do not hesitate to check a header with
8533 other headers included before, especially required headers.
8535 Make sure the symbols you use are properly defined, i.e., refrain from
8536 simply declaring a function yourself instead of including the proper
8537 header.
8539 Test programs should not write to standard output.  They
8540 should exit with status 0 if the test succeeds, and with status 1
8541 otherwise, so that success
8542 can be distinguished easily from a core dump or other failure;
8543 segmentation violations and other failures produce a nonzero exit
8544 status.  Unless you arrange for @code{exit} to be declared, test
8545 programs should @code{return}, not @code{exit}, from @code{main},
8546 because on many systems @code{exit} is not declared by default.
8548 Test programs can use @code{#if} or @code{#ifdef} to check the values of
8549 preprocessor macros defined by tests that have already run.  For
8550 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
8551 @file{configure.ac} you can have a test program that includes
8552 @file{stdbool.h} conditionally:
8554 @example
8555 @group
8556 #ifdef HAVE_STDBOOL_H
8557 # include <stdbool.h>
8558 #endif
8559 @end group
8560 @end example
8562 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
8563 work with any standard C compiler.  Some developers prefer @code{#if}
8564 because it is easier to read, while others prefer @code{#ifdef} because
8565 it avoids diagnostics with picky compilers like @acronym{GCC} with the
8566 @option{-Wundef} option.
8568 If a test program needs to use or create a data file, give it a name
8569 that starts with @file{conftest}, such as @file{conftest.data}.  The
8570 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
8571 after running test programs and if the script is interrupted.
8573 @node Test Functions
8574 @subsection Test Functions
8576 These days it's safe to assume support for function prototypes
8577 (introduced in C89).
8579 Functions that test programs declare should also be conditionalized for
8580 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
8581 include any header files containing clashing prototypes.
8583 @example
8584 #ifdef __cplusplus
8585 extern "C"
8586 #endif
8587 void *valloc (size_t);
8588 @end example
8590 If a test program calls a function with invalid parameters (just to see
8591 whether it exists), organize the program to ensure that it never invokes
8592 that function.  You can do this by calling it in another function that is
8593 never invoked.  You can't do it by putting it after a call to
8594 @code{exit}, because @acronym{GCC} version 2 knows that @code{exit}
8595 never returns
8596 and optimizes out any code that follows it in the same block.
8598 If you include any header files, be sure to call the functions
8599 relevant to them with the correct number of arguments, even if they are
8600 just 0, to avoid compilation errors due to prototypes.  @acronym{GCC}
8601 version 2
8602 has internal prototypes for several functions that it automatically
8603 inlines; for example, @code{memcpy}.  To avoid errors when checking for
8604 them, either pass them the correct number of arguments or redeclare them
8605 with a different return type (such as @code{char}).
8608 @node Generating Sources
8609 @subsection Generating Sources
8611 Autoconf provides a set of macros that can be used to generate test
8612 source files.  They are written to be language generic, i.e., they
8613 actually depend on the current language (@pxref{Language Choice}) to
8614 ``format'' the output properly.
8617 @defmac AC_LANG_CONFTEST (@var{source})
8618 @acindex{LANG_CONFTEST}
8619 Save the @var{source} text in the current test source file:
8620 @file{conftest.@var{extension}} where the @var{extension} depends on the
8621 current language.
8623 Note that the @var{source} is evaluated exactly once, like regular
8624 Autoconf macro arguments, and therefore (i) you may pass a macro
8625 invocation, (ii) if not, be sure to double quote if needed.
8626 @end defmac
8628 @defmac AC_LANG_SOURCE (@var{source})
8629 @acindex{LANG_SOURCE}
8630 Expands into the @var{source}, with the definition of
8631 all the @code{AC_DEFINE} performed so far.
8632 @end defmac
8634 For instance executing (observe the double quotation!):
8636 @example
8637 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8638 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8639   [Greetings string.])
8640 AC_LANG(C)
8641 AC_LANG_CONFTEST(
8642    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
8643 gcc -E -dD -o - conftest.c
8644 @end example
8646 @noindent
8647 results in:
8649 @example
8650 @dots{}
8651 # 1 "conftest.c"
8653 #define PACKAGE_NAME "Hello"
8654 #define PACKAGE_TARNAME "hello"
8655 #define PACKAGE_VERSION "1.0"
8656 #define PACKAGE_STRING "Hello 1.0"
8657 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8658 #define HELLO_WORLD "Hello, World\n"
8660 const char hw[] = "Hello, World\n";
8661 @end example
8663 When the test language is Fortran or Erlang, the @code{AC_DEFINE} definitions
8664 are not automatically translated into constants in the source code by this
8665 macro.
8667 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
8668 @acindex{LANG_PROGRAM}
8669 Expands into a source file which consists of the @var{prologue}, and
8670 then @var{body} as body of the main function (e.g., @code{main} in
8671 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
8672 available.
8673 @end defmac
8675 For instance:
8677 @example
8678 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8679 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8680   [Greetings string.])
8681 AC_LANG_CONFTEST(
8682 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8683                  [[fputs (hw, stdout);]])])
8684 gcc -E -dD -o - conftest.c
8685 @end example
8687 @noindent
8688 results in:
8690 @example
8691 @dots{}
8692 # 1 "conftest.c"
8694 #define PACKAGE_NAME "Hello"
8695 #define PACKAGE_TARNAME "hello"
8696 #define PACKAGE_VERSION "1.0"
8697 #define PACKAGE_STRING "Hello 1.0"
8698 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8699 #define HELLO_WORLD "Hello, World\n"
8701 const char hw[] = "Hello, World\n";
8703 main ()
8705 fputs (hw, stdout);
8706   ;
8707   return 0;
8709 @end example
8711 In Erlang tests, the created source file is that of an Erlang module called
8712 @code{conftest} (@file{conftest.erl}).  This module defines and exports
8713 at least
8714 one @code{start/0} function, which is called to perform the test.  The
8715 @var{prologue} is optional code that is inserted between the module header and
8716 the @code{start/0} function definition.  @var{body} is the body of the
8717 @code{start/0} function without the final period (@pxref{Runtime}, about
8718 constraints on this function's behavior).
8720 For instance:
8722 @example
8723 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8724 AC_LANG(Erlang)
8725 AC_LANG_CONFTEST(
8726 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
8727                  [[io:format("~s~n", [?HELLO_WORLD])]])])
8728 cat conftest.erl
8729 @end example
8731 @noindent
8732 results in:
8734 @example
8735 -module(conftest).
8736 -export([start/0]).
8737 -define(HELLO_WORLD, "Hello, world!").
8738 start() ->
8739 io:format("~s~n", [?HELLO_WORLD])
8741 @end example
8743 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
8744 @acindex{LANG_CALL}
8745 Expands into a source file which consists of the @var{prologue}, and
8746 then a call to the @var{function} as body of the main function (e.g.,
8747 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
8748 of the latter are available.
8750 This function will probably be replaced in the future by a version
8751 which would enable specifying the arguments.  The use of this macro is
8752 not encouraged, as it violates strongly the typing system.
8754 This macro cannot be used for Erlang tests.
8755 @end defmac
8757 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
8758 @acindex{LANG_FUNC_LINK_TRY}
8759 Expands into a source file which uses the @var{function} in the body of
8760 the main function (e.g., @code{main} in C).  Since it uses
8761 @code{AC_LANG_PROGRAM}, the features of the latter are available.
8763 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
8764 It is considered to be severely broken, and in the future will be
8765 removed in favor of actual function calls (with properly typed
8766 arguments).
8768 This macro cannot be used for Erlang tests.
8769 @end defmac
8771 @node Running the Preprocessor
8772 @section Running the Preprocessor
8774 Sometimes one might need to run the preprocessor on some source file.
8775 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
8776 your project, not merely run the preprocessor on it; therefore you
8777 certainly want to run the compiler, not the preprocessor.  Resist the
8778 temptation of following the easiest path.
8780 Nevertheless, if you need to run the preprocessor, then use
8781 @code{AC_PREPROC_IFELSE}.
8783 The macros described in this section cannot be used for tests in Erlang or
8784 Fortran, since those languages require no preprocessor.
8786 @anchor{AC_PREPROC_IFELSE}
8787 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
8788   @ovar{action-if-false})
8789 @acindex{PREPROC_IFELSE}
8790 Run the preprocessor of the current language (@pxref{Language Choice})
8791 on the @var{input}, run the shell commands @var{action-if-true} on
8792 success, @var{action-if-false} otherwise.  The @var{input} can be made
8793 by @code{AC_LANG_PROGRAM} and friends.
8795 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
8796 @option{-g}, @option{-O}, etc.@: are not valid options to many C
8797 preprocessors.
8799 It is customary to report unexpected failures with
8800 @code{AC_MSG_FAILURE}.
8801 @end defmac
8803 For instance:
8805 @example
8806 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8807 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8808   [Greetings string.])
8809 AC_PREPROC_IFELSE(
8810    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8811                     [[fputs (hw, stdout);]])],
8812    [AC_MSG_RESULT([OK])],
8813    [AC_MSG_FAILURE([unexpected preprocessor failure])])
8814 @end example
8816 @noindent
8817 results in:
8819 @example
8820 checking for gcc... gcc
8821 checking for C compiler default output file name... a.out
8822 checking whether the C compiler works... yes
8823 checking whether we are cross compiling... no
8824 checking for suffix of executables...
8825 checking for suffix of object files... o
8826 checking whether we are using the GNU C compiler... yes
8827 checking whether gcc accepts -g... yes
8828 checking for gcc option to accept ISO C89... none needed
8829 checking how to run the C preprocessor... gcc -E
8831 @end example
8833 @sp 1
8835 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
8836 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
8837 it impossible to use it to elaborate sources.  You are encouraged to
8838 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
8839 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
8840 to run the @emph{preprocessor} and not the compiler?
8842 @anchor{AC_EGREP_HEADER}
8843 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
8844   @var{action-if-found}, @ovar{action-if-not-found})
8845 @acindex{EGREP_HEADER}
8846 If the output of running the preprocessor on the system header file
8847 @var{header-file} matches the extended regular expression
8848 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
8849 execute @var{action-if-not-found}.
8850 @end defmac
8852 @anchor{AC_EGREP_CPP}
8853 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
8854   @ovar{action-if-found}, @ovar{action-if-not-found})
8855 @acindex{EGREP_CPP}
8856 @var{program} is the text of a C or C++ program, on which shell
8857 variable, back quote, and backslash substitutions are performed.  If the
8858 output of running the preprocessor on @var{program} matches the
8859 extended regular expression @var{pattern}, execute shell commands
8860 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
8861 @end defmac
8865 @node Running the Compiler
8866 @section Running the Compiler
8868 To check for a syntax feature of the current language's (@pxref{Language
8869 Choice}) compiler, such as whether it recognizes a certain keyword, or
8870 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
8871 to compile a small program that uses that feature.
8873 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
8874   @ovar{action-if-false})
8875 @acindex{COMPILE_IFELSE}
8876 Run the compiler and compilation flags of the current language
8877 (@pxref{Language Choice}) on the @var{input}, run the shell commands
8878 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
8879 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8881 It is customary to report unexpected failures with
8882 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
8883 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
8884 Linker}).
8886 This macro uses @code{AC_REQUIRE} for the compiler associated with the
8887 current language, which means that if the compiler has not yet been
8888 determined, the compiler determination will be made prior to the body of
8889 the outermust @code{AC_DEFUN} macro that triggered this macro to
8890 expand (@pxref{Expanded Before Required}).
8891 @end defmac
8893 @ovindex ERL
8894 For tests in Erlang, the @var{input} must be the source code of a module named
8895 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
8896 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
8897 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
8898 to ensure that the Erlang module has the right name.
8900 @node Running the Linker
8901 @section Running the Linker
8903 To check for a library, a function, or a global variable, Autoconf
8904 @command{configure} scripts try to compile and link a small program that
8905 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
8906 @code{ar} on the C library to try to figure out which functions are
8907 available.  Trying to link with the function is usually a more reliable
8908 approach because it avoids dealing with the variations in the options
8909 and output formats of @code{nm} and @code{ar} and in the location of the
8910 standard libraries.  It also allows configuring for cross-compilation or
8911 checking a function's runtime behavior if needed.  On the other hand,
8912 it can be slower than scanning the libraries once, but accuracy is more
8913 important than speed.
8915 @code{AC_LINK_IFELSE} is used to compile test programs to test for
8916 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
8917 to check for libraries (@pxref{Libraries}), by adding the library being
8918 checked for to @code{LIBS} temporarily and trying to link a small
8919 program.
8921 @anchor{AC_LINK_IFELSE}
8922 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
8923   @ovar{action-if-false})
8924 @acindex{LINK_IFELSE}
8925 Run the compiler (and compilation flags) and the linker of the current
8926 language (@pxref{Language Choice}) on the @var{input}, run the shell
8927 commands @var{action-if-true} on success, @var{action-if-false}
8928 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
8929 friends.
8931 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8932 current compilation flags.
8934 It is customary to report unexpected failures with
8935 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
8936 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
8937 @end defmac
8939 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
8940 programs are interpreted and do not require linking.
8944 @node Runtime
8945 @section Checking Runtime Behavior
8947 Sometimes you need to find out how a system performs at runtime, such
8948 as whether a given function has a certain capability or bug.  If you
8949 can, make such checks when your program runs instead of when it is
8950 configured.  You can check for things like the machine's endianness when
8951 your program initializes itself.
8953 If you really need to test for a runtime behavior while configuring,
8954 you can write a test program to determine the result, and compile and
8955 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
8956 possible, because this prevents people from configuring your package for
8957 cross-compiling.
8959 @anchor{AC_RUN_IFELSE}
8960 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
8961   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
8962 @acindex{RUN_IFELSE}
8963 If @var{program} compiles and links successfully and returns an exit
8964 status of 0 when executed, run shell commands @var{action-if-true}.
8965 Otherwise, run shell commands @var{action-if-false}.
8967 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8968 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8969 compilation flags of the current language (@pxref{Language Choice}).
8970 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
8971 for further testing.
8973 If the compiler being used does not produce executables that run on the
8974 system where @command{configure} is being run, then the test program is
8975 not run.  If the optional shell commands @var{action-if-cross-compiling}
8976 are given, they are run instead.  Otherwise, @command{configure} prints
8977 an error message and exits.
8979 In the @var{action-if-false} section, the failing exit status is
8980 available in the shell variable @samp{$?}.  This exit status might be
8981 that of a failed compilation, or it might be that of a failed program
8982 execution.
8984 It is customary to report unexpected failures with
8985 @code{AC_MSG_FAILURE}.
8986 @end defmac
8988 Try to provide a pessimistic default value to use when cross-compiling
8989 makes runtime tests impossible.  You do this by passing the optional
8990 last argument to @code{AC_RUN_IFELSE}.  @command{autoconf} prints a
8991 warning message when creating @command{configure} each time it
8992 encounters a call to @code{AC_RUN_IFELSE} with no
8993 @var{action-if-cross-compiling} argument given.  You may ignore the
8994 warning, though users cannot configure your package for
8995 cross-compiling.  A few of the macros distributed with Autoconf produce
8996 this warning message.
8998 To configure for cross-compiling you can also choose a value for those
8999 parameters based on the canonical system name (@pxref{Manual
9000 Configuration}).  Alternatively, set up a test results cache file with
9001 the correct values for the host system (@pxref{Caching Results}).
9003 @ovindex cross_compiling
9004 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9005 in other macros, including a few of the ones that come with Autoconf,
9006 you can test whether the shell variable @code{cross_compiling} is set to
9007 @samp{yes}, and then use an alternate method to get the results instead
9008 of calling the macros.
9010 It is also permissible to temporarily assign to @code{cross_compiling}
9011 in order to force tests to behave as though they are in a
9012 cross-compilation environment, particularly since this provides a way to
9013 test your @var{action-if-cross-compiling} even when you are not using a
9014 cross-compiler.
9016 @example
9017 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9018 # to use the slow link-only method
9019 save_cross_compiling=$cross_compiling
9020 cross_compiling=yes
9021 AC_COMPUTE_INT([@dots{}])
9022 cross_compiling=$save_cross_compiling
9023 @end example
9025 A C or C++ runtime test should be portable.
9026 @xref{Portable C and C++}.
9028 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9029 function: the given status code is used to determine the success of the test
9030 (status is @code{0}) or its failure (status is different than @code{0}), as
9031 explained above.  It must be noted that data output through the standard output
9032 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9033 Therefore, if a test must output configuration information, it is recommended
9034 to create and to output data into the temporary file named @file{conftest.out},
9035 using the functions of module @code{file}.  The @code{conftest.out} file is
9036 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9037 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9038 macro is:
9040 @example
9041 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9042 AC_ERLANG_NEED_ERL
9043 AC_LANG(Erlang)
9044 AC_RUN_IFELSE(
9045   [AC_LANG_PROGRAM([], [dnl
9046     file:write_file("conftest.out", code:lib_dir()),
9047     halt(0)])],
9048   [echo "code:lib_dir() returned: `cat conftest.out`"],
9049   [AC_MSG_FAILURE([test Erlang program execution failed])])
9050 @end example
9053 @node Systemology
9054 @section Systemology
9055 @cindex Systemology
9057 This section aims at presenting some systems and pointers to
9058 documentation.  It may help you addressing particular problems reported
9059 by users.
9061 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
9062 derived from the @uref{http://@/www.bell-labs.com/@/history/@/unix/, Unix
9063 operating system}.
9065 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9066 contains a table correlating the features of various Posix-conforming
9067 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
9068 simplified diagram of how many Unix systems were derived from each
9069 other.
9071 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9072 provides some variants of traditional implementations of Unix utilities.
9074 @table @asis
9075 @item Darwin
9076 @cindex Darwin
9077 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
9078 case-preserving, but case insensitive.  This can cause nasty problems,
9079 since for instance the installation attempt for a package having an
9080 @file{INSTALL} file can result in @samp{make install} report that
9081 nothing was to be done!
9083 That's all dependent on whether the file system is a UFS (case
9084 sensitive) or HFS+ (case preserving).  By default Apple wants you to
9085 install the OS on HFS+.  Unfortunately, there are some pieces of
9086 software which really need to be built on UFS@.  We may want to rebuild
9087 Darwin to have both UFS and HFS+ available (and put the /local/build
9088 tree on the UFS).
9090 @item @acronym{QNX} 4.25
9091 @cindex @acronym{QNX} 4.25
9092 @c FIXME: Please, if you feel like writing something more precise,
9093 @c it'd be great.  In particular, I can't understand the difference with
9094 @c QNX Neutrino.
9095 @acronym{QNX} is a realtime operating system running on Intel architecture
9096 meant to be scalable from the small embedded systems to the hundred
9097 processor super-computer.  It claims to be Posix certified.  More
9098 information is available on the
9099 @uref{http://@/www.qnx.com/, @acronym{QNX} home page}.
9101 @item Tru64
9102 @cindex Tru64
9103 @uref{http://@/h30097.www3.hp.com/@/docs/,
9104 Documentation of several versions of Tru64} is available in different
9105 formats.
9107 @item Unix version 7
9108 @cindex Unix version 7
9109 @cindex V7
9110 Officially this was called the ``Seventh Edition'' of ``the @sc{unix}
9111 time-sharing system'' but we use the more-common name ``Unix version 7''.
9112 Documentation is available in the
9113 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
9114 Previous versions of Unix are called ``Unix version 6'', etc., but
9115 they were not as widely used.
9116 @end table
9119 @node Multiple Cases
9120 @section Multiple Cases
9122 Some operations are accomplished in several possible ways, depending on
9123 the OS variant.  Checking for them essentially requires a ``case
9124 statement''.  Autoconf does not directly provide one; however, it is
9125 easy to simulate by using a shell variable to keep track of whether a
9126 way to perform the operation has been found yet.
9128 Here is an example that uses the shell variable @code{fstype} to keep
9129 track of whether the remaining cases need to be checked.  Note that
9130 since the value of @code{fstype} is under our control, we don't have to
9131 use the longer @samp{test "x$fstype" = xno}.
9133 @example
9134 @group
9135 AC_MSG_CHECKING([how to get file system type])
9136 fstype=no
9137 # The order of these tests is important.
9138 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9139 #include <sys/fstyp.h>]])],
9140                   [AC_DEFINE([FSTYPE_STATVFS], [1],
9141                      [Define if statvfs exists.])
9142                    fstype=SVR4])
9143 if test $fstype = no; then
9144   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9145 #include <sys/fstyp.h>]])],
9146                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9147                      [Define if USG statfs.])
9148                    fstype=SVR3])
9150 if test $fstype = no; then
9151   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9152 #include <sys/vmount.h>]])]),
9153                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9154                      [Define if AIX statfs.])
9155                    fstype=AIX])
9157 # (more cases omitted here)
9158 AC_MSG_RESULT([$fstype])
9159 @end group
9160 @end example
9162 @c ====================================================== Results of Tests.
9164 @node Results
9165 @chapter Results of Tests
9167 Once @command{configure} has determined whether a feature exists, what can
9168 it do to record that information?  There are four sorts of things it can
9169 do: define a C preprocessor symbol, set a variable in the output files,
9170 save the result in a cache file for future @command{configure} runs, and
9171 print a message letting the user know the result of the test.
9173 @menu
9174 * Defining Symbols::            Defining C preprocessor symbols
9175 * Setting Output Variables::    Replacing variables in output files
9176 * Special Chars in Variables::  Characters to beware of in variables
9177 * Caching Results::             Speeding up subsequent @command{configure} runs
9178 * Printing Messages::           Notifying @command{configure} users
9179 @end menu
9181 @node Defining Symbols
9182 @section Defining C Preprocessor Symbols
9184 A common action to take in response to a feature test is to define a C
9185 preprocessor symbol indicating the results of the test.  That is done by
9186 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9188 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9189 into the output variable @code{DEFS}, which contains an option
9190 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
9191 Autoconf version 1, there is no variable @code{DEFS} defined while
9192 @command{configure} is running.  To check whether Autoconf macros have
9193 already defined a certain C preprocessor symbol, test the value of the
9194 appropriate cache variable, as in this example:
9196 @example
9197 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9198                           [Define if vprintf exists.])])
9199 if test "x$ac_cv_func_vprintf" != xyes; then
9200   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9201                             [Define if _doprnt exists.])])
9203 @end example
9205 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9206 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9207 correct values into @code{#define} statements in a template file.
9208 @xref{Configuration Headers}, for more information about this kind of
9209 output.
9211 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9212 @defmacx AC_DEFINE (@var{variable})
9213 @cvindex @var{variable}
9214 @acindex{DEFINE}
9215 Define @var{variable} to @var{value} (verbatim), by defining a C
9216 preprocessor macro for @var{variable}.  @var{variable} should be a C
9217 identifier, optionally suffixed by a parenthesized argument list to
9218 define a C preprocessor macro with arguments.  The macro argument list,
9219 if present, should be a comma-separated list of C identifiers, possibly
9220 terminated by an ellipsis @samp{...} if C99 syntax is employed.
9221 @var{variable} should not contain comments, white space, trigraphs,
9222 backslash-newlines, universal character names, or non-@acronym{ASCII}
9223 characters.
9225 @var{value} may contain backslash-escaped newlines, which will be
9226 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9227 via @code{@@DEFS@@} (with no effect on the compilation, since the
9228 preprocessor sees only one line in the first place).  @var{value} should
9229 not contain raw newlines.  If you are not using
9230 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9231 characters, as @command{make} tends to eat them.  To use a shell
9232 variable, use @code{AC_DEFINE_UNQUOTED} instead.
9234 @var{description} is only useful if you are using
9235 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
9236 the generated @file{config.h.in} as the comment before the macro define.
9237 The following example defines the C preprocessor variable
9238 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
9240 @example
9241 AC_DEFINE([EQUATION], ["$a > $b"],
9242   [Equation string.])
9243 @end example
9245 If neither @var{value} nor @var{description} are given, then
9246 @var{value} defaults to 1 instead of to the empty string.  This is for
9247 backwards compatibility with older versions of Autoconf, but this usage
9248 is obsolescent and may be withdrawn in future versions of Autoconf.
9250 If the @var{variable} is a literal string, it is passed to
9251 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9253 If multiple @code{AC_DEFINE} statements are executed for the same
9254 @var{variable} name (not counting any parenthesized argument list),
9255 the last one wins.
9256 @end defmac
9258 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9259 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
9260 @acindex{DEFINE_UNQUOTED}
9261 @cvindex @var{variable}
9262 Like @code{AC_DEFINE}, but three shell expansions are
9263 performed---once---on @var{variable} and @var{value}: variable expansion
9264 (@samp{$}), command substitution (@samp{`}), and backslash escaping
9265 (@samp{\}), as if in an unquoted here-document.  Single and double quote
9266 characters in the value have no
9267 special meaning.  Use this macro instead of @code{AC_DEFINE} when
9268 @var{variable} or @var{value} is a shell variable.  Examples:
9270 @example
9271 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
9272   [Configuration machine file.])
9273 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
9274   [getgroups return type.])
9275 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
9276   [Translated header name.])
9277 @end example
9278 @end defmac
9280 Due to a syntactical bizarreness of the Bourne shell, do not use
9281 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
9282 calls from other macro calls or shell code; that can cause syntax errors
9283 in the resulting @command{configure} script.  Use either blanks or
9284 newlines.  That is, do this:
9286 @example
9287 AC_CHECK_HEADER([elf.h],
9288   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
9289 @end example
9291 @noindent
9292 or this:
9294 @example
9295 AC_CHECK_HEADER([elf.h],
9296   [AC_DEFINE([SVR4], [1], [System V Release 4])
9297    LIBS="-lelf $LIBS"])
9298 @end example
9300 @noindent
9301 instead of this:
9303 @example
9304 AC_CHECK_HEADER([elf.h],
9305   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
9306 @end example
9308 @node Setting Output Variables
9309 @section Setting Output Variables
9310 @cindex Output variables
9312 Another way to record the results of tests is to set @dfn{output
9313 variables}, which are shell variables whose values are substituted into
9314 files that @command{configure} outputs.  The two macros below create new
9315 output variables.  @xref{Preset Output Variables}, for a list of output
9316 variables that are always available.
9318 @defmac AC_SUBST (@var{variable}, @ovar{value})
9319 @acindex{SUBST}
9320 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
9321 substitute the variable @var{variable} into output files (typically one
9322 or more makefiles).  This means that @code{AC_OUTPUT}
9323 replaces instances of @samp{@@@var{variable}@@} in input files with the
9324 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
9325 is called.  The value can contain any non-@code{NUL} character, including
9326 newline.  If you are using Automake 1.11 or newer, for newlines in values
9327 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
9328 @command{automake} from adding a line @code{@var{variable} =
9329 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
9330 Automake, automake, Other things Automake recognizes}).
9332 Variable occurrences should not overlap: e.g., an input file should
9333 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
9334 are variable names.
9335 The substituted value is not rescanned for more output variables;
9336 occurrences of @samp{@@@var{variable}@@} in the value are inserted
9337 literally into the output file.  (The algorithm uses the special marker
9338 @code{|#_!!_#|} internally, so neither the substituted value nor the
9339 output file may contain @code{|#_!!_#|}.)
9341 If @var{value} is given, in addition assign it to @var{variable}.
9343 The string @var{variable} is passed to @code{m4_pattern_allow}
9344 (@pxref{Forbidden Patterns}).
9345 @end defmac
9347 @defmac AC_SUBST_FILE (@var{variable})
9348 @acindex{SUBST_FILE}
9349 Another way to create an output variable from a shell variable.  Make
9350 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
9351 named by shell variable @var{variable} into output files.  This means
9352 that @code{AC_OUTPUT} replaces instances of
9353 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
9354 with the contents of the file that the shell variable @var{variable}
9355 names when @code{AC_OUTPUT} is called.  Set the variable to
9356 @file{/dev/null} for cases that do not have a file to insert.
9357 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
9358 line by itself, optionally surrounded by spaces and tabs.  The
9359 substitution replaces the whole line, including the spaces, tabs, and
9360 the terminating newline.
9362 This macro is useful for inserting makefile fragments containing
9363 special dependencies or other @command{make} directives for particular host
9364 or target types into makefiles.  For example, @file{configure.ac}
9365 could contain:
9367 @example
9368 AC_SUBST_FILE([host_frag])
9369 host_frag=$srcdir/conf/sun4.mh
9370 @end example
9372 @noindent
9373 and then a @file{Makefile.in} could contain:
9375 @example
9376 @@host_frag@@
9377 @end example
9379 The string @var{variable} is passed to @code{m4_pattern_allow}
9380 (@pxref{Forbidden Patterns}).
9381 @end defmac
9383 @cindex Precious Variable
9384 @cindex Variable, Precious
9385 Running @command{configure} in varying environments can be extremely
9386 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
9387 ./configure}, then the cache, @file{config.h}, and many other output
9388 files depend upon @command{bizarre-cc} being the C compiler.  If
9389 for some reason the user runs @command{./configure} again, or if it is
9390 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
9391 and @pxref{config.status Invocation}), then the configuration can be
9392 inconsistent, composed of results depending upon two different
9393 compilers.
9395 Environment variables that affect this situation, such as @samp{CC}
9396 above, are called @dfn{precious variables}, and can be declared as such
9397 by @code{AC_ARG_VAR}.
9399 @defmac AC_ARG_VAR (@var{variable}, @var{description})
9400 @acindex{ARG_VAR}
9401 Declare @var{variable} is a precious variable, and include its
9402 @var{description} in the variable section of @samp{./configure --help}.
9404 Being precious means that
9405 @itemize @minus
9406 @item
9407 @var{variable} is substituted via @code{AC_SUBST}.
9409 @item
9410 The value of @var{variable} when @command{configure} was launched is
9411 saved in the cache, including if it was not specified on the command
9412 line but via the environment.  Indeed, while @command{configure} can
9413 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
9414 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
9415 which, unfortunately, is what most users do.
9417 We emphasize that it is the @emph{initial} value of @var{variable} which
9418 is saved, not that found during the execution of @command{configure}.
9419 Indeed, specifying @samp{./configure FOO=foo} and letting
9420 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
9421 different things.
9423 @item
9424 @var{variable} is checked for consistency between two
9425 @command{configure} runs.  For instance:
9427 @example
9428 $ @kbd{./configure --silent --config-cache}
9429 $ @kbd{CC=cc ./configure --silent --config-cache}
9430 configure: error: `CC' was not set in the previous run
9431 configure: error: changes in the environment can compromise \
9432 the build
9433 configure: error: run `make distclean' and/or \
9434 `rm config.cache' and start over
9435 @end example
9437 @noindent
9438 and similarly if the variable is unset, or if its content is changed.
9439 If the content has white space changes only, then the error is degraded
9440 to a warning only, but the old value is reused.
9442 @item
9443 @var{variable} is kept during automatic reconfiguration
9444 (@pxref{config.status Invocation}) as if it had been passed as a command
9445 line argument, including when no cache is used:
9447 @example
9448 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
9449 $ @kbd{./config.status --recheck}
9450 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
9451   CC=/usr/bin/cc  --no-create --no-recursion
9452 @end example
9453 @end itemize
9454 @end defmac
9456 @node Special Chars in Variables
9457 @section Special Characters in Output Variables
9458 @cindex Output variables, special characters in
9460 Many output variables are intended to be evaluated both by
9461 @command{make} and by the shell.  Some characters are expanded
9462 differently in these two contexts, so to avoid confusion these
9463 variables' values should not contain any of the following characters:
9465 @example
9466 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
9467 @end example
9469 Also, these variables' values should neither contain newlines, nor start
9470 with @samp{~}, nor contain white space or @samp{:} immediately followed
9471 by @samp{~}.  The values can contain nonempty sequences of white space
9472 characters like tabs and spaces, but each such sequence might
9473 arbitrarily be replaced by a single space during substitution.
9475 These restrictions apply both to the values that @command{configure}
9476 computes, and to the values set directly by the user.  For example, the
9477 following invocations of @command{configure} are problematic, since they
9478 attempt to use special characters within @code{CPPFLAGS} and white space
9479 within @code{$(srcdir)}:
9481 @example
9482 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
9484 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
9485 @end example
9487 @node Caching Results
9488 @section Caching Results
9489 @cindex Cache
9491 To avoid checking for the same features repeatedly in various
9492 @command{configure} scripts (or in repeated runs of one script),
9493 @command{configure} can optionally save the results of many checks in a
9494 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
9495 runs with caching enabled and finds a cache file, it reads the results
9496 of previous runs from the cache and avoids rerunning those checks.  As a
9497 result, @command{configure} can then run much faster than if it had to
9498 perform all of the checks every time.
9500 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
9501 @acindex{CACHE_VAL}
9502 Ensure that the results of the check identified by @var{cache-id} are
9503 available.  If the results of the check were in the cache file that was
9504 read, and @command{configure} was not given the @option{--quiet} or
9505 @option{--silent} option, print a message saying that the result was
9506 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
9507 the shell commands are run to determine the value, the value is
9508 saved in the cache file just before @command{configure} creates its output
9509 files.  @xref{Cache Variable Names}, for how to choose the name of the
9510 @var{cache-id} variable.
9512 The @var{commands-to-set-it} @emph{must have no side effects} except for
9513 setting the variable @var{cache-id}, see below.
9514 @end defmac
9516 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
9517   @var{commands-to-set-it})
9518 @acindex{CACHE_CHECK}
9519 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
9520 messages.  This macro provides a convenient shorthand for the most
9521 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
9522 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
9523 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
9525 The @var{commands-to-set-it} @emph{must have no side effects} except for
9526 setting the variable @var{cache-id}, see below.
9527 @end defmac
9529 It is common to find buggy macros using @code{AC_CACHE_VAL} or
9530 @code{AC_CACHE_CHECK}, because people are tempted to call
9531 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
9532 @emph{follows} the call to @code{AC_CACHE_VAL} should call
9533 @code{AC_DEFINE}, by examining the value of the cache variable.  For
9534 instance, the following macro is broken:
9536 @example
9537 @group
9538 AC_DEFUN([AC_SHELL_TRUE],
9539 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9540                 [my_cv_shell_true_works=no
9541                  (true) 2>/dev/null && my_cv_shell_true_works=yes
9542                  if test "x$my_cv_shell_true_works" = xyes; then
9543                    AC_DEFINE([TRUE_WORKS], [1],
9544                              [Define if `true(1)' works properly.])
9545                  fi])
9547 @end group
9548 @end example
9550 @noindent
9551 This fails if the cache is enabled: the second time this macro is run,
9552 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
9555 @example
9556 @group
9557 AC_DEFUN([AC_SHELL_TRUE],
9558 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9559                 [my_cv_shell_true_works=no
9560                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
9561  if test "x$my_cv_shell_true_works" = xyes; then
9562    AC_DEFINE([TRUE_WORKS], [1],
9563              [Define if `true(1)' works properly.])
9564  fi
9566 @end group
9567 @end example
9569 Also, @var{commands-to-set-it} should not print any messages, for
9570 example with @code{AC_MSG_CHECKING}; do that before calling
9571 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
9572 the results of the check are retrieved from the cache or determined by
9573 running the shell commands.
9575 @menu
9576 * Cache Variable Names::        Shell variables used in caches
9577 * Cache Files::                 Files @command{configure} uses for caching
9578 * Cache Checkpointing::         Loading and saving the cache file
9579 @end menu
9581 @node Cache Variable Names
9582 @subsection Cache Variable Names
9583 @cindex Cache variable
9585 The names of cache variables should have the following format:
9587 @example
9588 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
9589 @end example
9591 @noindent
9592 for example, @samp{ac_cv_header_stat_broken} or
9593 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
9595 @table @asis
9596 @item @var{package-prefix}
9597 An abbreviation for your package or organization; the same prefix you
9598 begin local Autoconf macros with, except lowercase by convention.
9599 For cache values used by the distributed Autoconf macros, this value is
9600 @samp{ac}.
9602 @item @code{_cv_}
9603 Indicates that this shell variable is a cache value.  This string
9604 @emph{must} be present in the variable name, including the leading
9605 underscore.
9607 @item @var{value-type}
9608 A convention for classifying cache values, to produce a rational naming
9609 system.  The values used in Autoconf are listed in @ref{Macro Names}.
9611 @item @var{specific-value}
9612 Which member of the class of cache values this test applies to.
9613 For example, which function (@samp{alloca}), program (@samp{gcc}), or
9614 output variable (@samp{INSTALL}).
9616 @item @var{additional-options}
9617 Any particular behavior of the specific member that this test applies to.
9618 For example, @samp{broken} or @samp{set}.  This part of the name may
9619 be omitted if it does not apply.
9620 @end table
9622 The values assigned to cache variables may not contain newlines.
9623 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
9624 names of files or functions; so this is not an important restriction.
9625 @ref{Cache Variable Index} for an index of cache variables with
9626 documented semantics.
9629 @node Cache Files
9630 @subsection Cache Files
9632 A cache file is a shell script that caches the results of configure
9633 tests run on one system so they can be shared between configure scripts
9634 and configure runs.  It is not useful on other systems.  If its contents
9635 are invalid for some reason, the user may delete or edit it.
9637 By default, @command{configure} uses no cache file,
9638 to avoid problems caused by accidental
9639 use of stale cache files.
9641 To enable caching, @command{configure} accepts @option{--config-cache} (or
9642 @option{-C}) to cache results in the file @file{config.cache}.
9643 Alternatively, @option{--cache-file=@var{file}} specifies that
9644 @var{file} be the cache file.  The cache file is created if it does not
9645 exist already.  When @command{configure} calls @command{configure} scripts in
9646 subdirectories, it uses the @option{--cache-file} argument so that they
9647 share the same cache.  @xref{Subdirectories}, for information on
9648 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
9650 @file{config.status} only pays attention to the cache file if it is
9651 given the @option{--recheck} option, which makes it rerun
9652 @command{configure}.
9654 It is wrong to try to distribute cache files for particular system types.
9655 There is too much room for error in doing that, and too much
9656 administrative overhead in maintaining them.  For any features that
9657 can't be guessed automatically, use the standard method of the canonical
9658 system type and linking files (@pxref{Manual Configuration}).
9660 The site initialization script can specify a site-wide cache file to
9661 use, instead of the usual per-program cache.  In this case, the cache
9662 file gradually accumulates information whenever someone runs a new
9663 @command{configure} script.  (Running @command{configure} merges the new cache
9664 results with the existing cache file.)  This may cause problems,
9665 however, if the system configuration (e.g., the installed libraries or
9666 compilers) changes and the stale cache file is not deleted.
9668 @node Cache Checkpointing
9669 @subsection Cache Checkpointing
9671 If your configure script, or a macro called from @file{configure.ac}, happens
9672 to abort the configure process, it may be useful to checkpoint the cache
9673 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
9674 reduces the amount of time it takes to rerun the configure script with
9675 (hopefully) the error that caused the previous abort corrected.
9677 @c FIXME: Do we really want to document this guy?
9678 @defmac AC_CACHE_LOAD
9679 @acindex{CACHE_LOAD}
9680 Loads values from existing cache file, or creates a new cache file if a
9681 cache file is not found.  Called automatically from @code{AC_INIT}.
9682 @end defmac
9684 @defmac AC_CACHE_SAVE
9685 @acindex{CACHE_SAVE}
9686 Flushes all cached values to the cache file.  Called automatically from
9687 @code{AC_OUTPUT}, but it can be quite useful to call
9688 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
9689 @end defmac
9691 For instance:
9693 @example
9694 @r{ @dots{} AC_INIT, etc. @dots{}}
9695 @group
9696 # Checks for programs.
9697 AC_PROG_CC
9698 AC_PROG_AWK
9699 @r{ @dots{} more program checks @dots{}}
9700 AC_CACHE_SAVE
9701 @end group
9703 @group
9704 # Checks for libraries.
9705 AC_CHECK_LIB([nsl], [gethostbyname])
9706 AC_CHECK_LIB([socket], [connect])
9707 @r{ @dots{} more lib checks @dots{}}
9708 AC_CACHE_SAVE
9709 @end group
9711 @group
9712 # Might abort@dots{}
9713 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
9714 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
9715 @end group
9716 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
9717 @end example
9719 @node Printing Messages
9720 @section Printing Messages
9721 @cindex Messages, from @command{configure}
9723 @command{configure} scripts need to give users running them several kinds
9724 of information.  The following macros print messages in ways appropriate
9725 for each kind.  The arguments to all of them get enclosed in shell
9726 double quotes, so the shell performs variable and back-quote
9727 substitution on them.
9729 These macros are all wrappers around the @command{echo} shell command.
9730 They direct output to the appropriate file descriptor (@pxref{File
9731 Descriptor Macros}).
9732 @command{configure} scripts should rarely need to run @command{echo} directly
9733 to print messages for the user.  Using these macros makes it easy to
9734 change how and when each kind of message is printed; such changes need
9735 only be made to the macro definitions and all the callers change
9736 automatically.
9738 To diagnose static issues, i.e., when @command{autoconf} is run, see
9739 @ref{Diagnostic Macros}.
9741 @defmac AC_MSG_CHECKING (@var{feature-description})
9742 @acindex{MSG_CHECKING}
9743 Notify the user that @command{configure} is checking for a particular
9744 feature.  This macro prints a message that starts with @samp{checking }
9745 and ends with @samp{...} and no newline.  It must be followed by a call
9746 to @code{AC_MSG_RESULT} to print the result of the check and the
9747 newline.  The @var{feature-description} should be something like
9748 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
9749 c89}.
9751 This macro prints nothing if @command{configure} is run with the
9752 @option{--quiet} or @option{--silent} option.
9753 @end defmac
9755 @anchor{AC_MSG_RESULT}
9756 @defmac AC_MSG_RESULT (@var{result-description})
9757 @acindex{MSG_RESULT}
9758 Notify the user of the results of a check.  @var{result-description} is
9759 almost always the value of the cache variable for the check, typically
9760 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
9761 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
9762 the completion of the message printed by the call to
9763 @code{AC_MSG_CHECKING}.
9765 This macro prints nothing if @command{configure} is run with the
9766 @option{--quiet} or @option{--silent} option.
9767 @end defmac
9769 @anchor{AC_MSG_NOTICE}
9770 @defmac AC_MSG_NOTICE (@var{message})
9771 @acindex{MSG_NOTICE}
9772 Deliver the @var{message} to the user.  It is useful mainly to print a
9773 general description of the overall purpose of a group of feature checks,
9774 e.g.,
9776 @example
9777 AC_MSG_NOTICE([checking if stack overflow is detectable])
9778 @end example
9780 This macro prints nothing if @command{configure} is run with the
9781 @option{--quiet} or @option{--silent} option.
9782 @end defmac
9784 @anchor{AC_MSG_ERROR}
9785 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
9786 @acindex{MSG_ERROR}
9787 Notify the user of an error that prevents @command{configure} from
9788 completing.  This macro prints an error message to the standard error
9789 output and exits @command{configure} with @var{exit-status} (@samp{$?}
9790 by default, except that @samp{0} is converted to @samp{1}).
9791 @var{error-description} should be something like @samp{invalid value
9792 $HOME for \$HOME}.
9794 The @var{error-description} should start with a lower-case letter, and
9795 ``cannot'' is preferred to ``can't''.
9796 @end defmac
9798 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
9799 @acindex{MSG_FAILURE}
9800 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
9801 prevents @command{configure} from completing @emph{and} that additional
9802 details are provided in @file{config.log}.  This is typically used when
9803 abnormal results are found during a compilation.
9804 @end defmac
9806 @anchor{AC_MSG_WARN}
9807 @defmac AC_MSG_WARN (@var{problem-description})
9808 @acindex{MSG_WARN}
9809 Notify the @command{configure} user of a possible problem.  This macro
9810 prints the message to the standard error output; @command{configure}
9811 continues running afterward, so macros that call @code{AC_MSG_WARN} should
9812 provide a default (back-up) behavior for the situations they warn about.
9813 @var{problem-description} should be something like @samp{ln -s seems to
9814 make hard links}.
9815 @end defmac
9819 @c ====================================================== Programming in M4.
9821 @node Programming in M4
9822 @chapter Programming in M4
9823 @cindex M4
9825 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
9826 convenient macros for pure M4 programming, and @dfn{M4sh}, which
9827 provides macros dedicated to shell script generation.
9829 As of this version of Autoconf, these two layers still contain
9830 experimental macros, whose interface might change in the future.  As a
9831 matter of fact, @emph{anything that is not documented must not be used}.
9833 @menu
9834 * M4 Quotation::                Protecting macros from unwanted expansion
9835 * Using autom4te::              The Autoconf executables backbone
9836 * Programming in M4sugar::      Convenient pure M4 macros
9837 * Debugging via autom4te::      Figuring out what M4 was doing
9838 @end menu
9840 @node M4 Quotation
9841 @section M4 Quotation
9842 @cindex M4 quotation
9843 @cindex quotation
9845 The most common problem with existing macros is an improper quotation.
9846 This section, which users of Autoconf can skip, but which macro writers
9847 @emph{must} read, first justifies the quotation scheme that was chosen
9848 for Autoconf and then ends with a rule of thumb.  Understanding the
9849 former helps one to follow the latter.
9851 @menu
9852 * Active Characters::           Characters that change the behavior of M4
9853 * One Macro Call::              Quotation and one macro call
9854 * Quoting and Parameters::      M4 vs. shell parameters
9855 * Quotation and Nested Macros::  Macros calling macros
9856 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
9857 * Quadrigraphs::                Another way to escape special characters
9858 * Balancing Parentheses::       Dealing with unbalanced parentheses
9859 * Quotation Rule Of Thumb::     One parenthesis, one quote
9860 @end menu
9862 @node Active Characters
9863 @subsection Active Characters
9865 To fully understand where proper quotation is important, you first need
9866 to know what the special characters are in Autoconf: @samp{#} introduces
9867 a comment inside which no macro expansion is performed, @samp{,}
9868 separates arguments, @samp{[} and @samp{]} are the quotes
9869 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
9870 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
9871 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
9872 @samp{$} inside a macro definition.
9874 In order to understand the delicate case of macro calls, we first have
9875 to present some obvious failures.  Below they are ``obvious-ified'',
9876 but when you find them in real life, they are usually in disguise.
9878 Comments, introduced by a hash and running up to the newline, are opaque
9879 tokens to the top level: active characters are turned off, and there is
9880 no macro expansion:
9882 @example
9883 # define([def], ine)
9884 @result{}# define([def], ine)
9885 @end example
9887 Each time there can be a macro expansion, there is a quotation
9888 expansion, i.e., one level of quotes is stripped:
9890 @example
9891 int tab[10];
9892 @result{}int tab10;
9893 [int tab[10];]
9894 @result{}int tab[10];
9895 @end example
9897 Without this in mind, the reader might try hopelessly to use her macro
9898 @code{array}:
9900 @example
9901 define([array], [int tab[10];])
9902 array
9903 @result{}int tab10;
9904 [array]
9905 @result{}array
9906 @end example
9908 @noindent
9909 How can you correctly output the intended results@footnote{Using
9910 @code{defn}.}?
9913 @node One Macro Call
9914 @subsection One Macro Call
9916 Let's proceed on the interaction between active characters and macros
9917 with this small macro, which just returns its first argument:
9919 @example
9920 define([car], [$1])
9921 @end example
9923 @noindent
9924 The two pairs of quotes above are not part of the arguments of
9925 @code{define}; rather, they are understood by the top level when it
9926 tries to find the arguments of @code{define}.  Therefore, assuming
9927 @code{car} is not already defined, it is equivalent to write:
9929 @example
9930 define(car, $1)
9931 @end example
9933 @noindent
9934 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
9935 quotes, it is bad practice for Autoconf macros which must both be more
9936 robust and also advocate perfect style.
9938 At the top level, there are only two possibilities: either you
9939 quote or you don't:
9941 @example
9942 car(foo, bar, baz)
9943 @result{}foo
9944 [car(foo, bar, baz)]
9945 @result{}car(foo, bar, baz)
9946 @end example
9948 Let's pay attention to the special characters:
9950 @example
9951 car(#)
9952 @error{}EOF in argument list
9953 @end example
9955 The closing parenthesis is hidden in the comment; with a hypothetical
9956 quoting, the top level understood it this way:
9958 @example
9959 car([#)]
9960 @end example
9962 @noindent
9963 Proper quotation, of course, fixes the problem:
9965 @example
9966 car([#])
9967 @result{}#
9968 @end example
9970 Here are more examples:
9972 @example
9973 car(foo, bar)
9974 @result{}foo
9975 car([foo, bar])
9976 @result{}foo, bar
9977 car((foo, bar))
9978 @result{}(foo, bar)
9979 car([(foo], [bar)])
9980 @result{}(foo
9981 define([a], [b])
9982 @result{}
9983 car(a)
9984 @result{}b
9985 car([a])
9986 @result{}b
9987 car([[a]])
9988 @result{}a
9989 car([[[a]]])
9990 @result{}[a]
9991 @end example
9993 @node Quoting and Parameters
9994 @subsection Quoting and Parameters
9996 When M4 encounters @samp{$} within a macro definition, followed
9997 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
9998 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
9999 expansion.  This happens regardless of how many layers of quotes the
10000 parameter expansion is nested within, or even if it occurs in text that
10001 will be rescanned as a comment.
10003 @example
10004 define([none], [$1])
10005 @result{}
10006 define([one], [[$1]])
10007 @result{}
10008 define([two], [[[$1]]])
10009 @result{}
10010 define([comment], [# $1])
10011 @result{}
10012 define([active], [ACTIVE])
10013 @result{}
10014 none([active])
10015 @result{}ACTIVE
10016 one([active])
10017 @result{}active
10018 two([active])
10019 @result{}[active]
10020 comment([active])
10021 @result{}# active
10022 @end example
10024 On the other hand, since autoconf generates shell code, you often want
10025 to output shell variable expansion, rather than performing M4 parameter
10026 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10027 from the next character in the definition of your macro.  If the macro
10028 definition occurs in single-quoted text, then insert another level of
10029 quoting; if the usage is already inside a double-quoted string, then
10030 split it into concatenated strings.
10032 @example
10033 define([single], [a single-quoted $[]1 definition])
10034 @result{}
10035 define([double], [[a double-quoted $][1 definition]])
10036 @result{}
10037 single
10038 @result{}a single-quoted $1 definition
10039 double
10040 @result{}a double-quoted $1 definition
10041 @end example
10043 Posix states that M4 implementations are free to provide implementation
10044 extensions when @samp{$@{} is encountered in a macro definition.
10045 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10046 extensions that will be available in the future @acronym{GNU} M4 2.0,
10047 but guarantees that all other instances of @samp{$@{} will be output
10048 literally.  Therefore, this idiom can also be used to output shell code
10049 parameter references:
10051 @example
10052 define([first], [$@{1@}])first
10053 @result{}$@{1@}
10054 @end example
10056 Posix also states that @samp{$11} should expand to the first parameter
10057 concatenated with a literal @samp{1}, although some versions of
10058 @acronym{GNU} M4 expand the eleventh parameter instead.  For
10059 portability, you should only use single-digit M4 parameter expansion.
10061 With this in mind, we can explore the cases where macros invoke
10062 macros@enddots{}
10064 @node Quotation and Nested Macros
10065 @subsection Quotation and Nested Macros
10067 The examples below use the following macros:
10069 @example
10070 define([car], [$1])
10071 define([active], [ACT, IVE])
10072 define([array], [int tab[10]])
10073 @end example
10075 Each additional embedded macro call introduces other possible
10076 interesting quotations:
10078 @example
10079 car(active)
10080 @result{}ACT
10081 car([active])
10082 @result{}ACT, IVE
10083 car([[active]])
10084 @result{}active
10085 @end example
10087 In the first case, the top level looks for the arguments of @code{car},
10088 and finds @samp{active}.  Because M4 evaluates its arguments
10089 before applying the macro, @samp{active} is expanded, which results in:
10091 @example
10092 car(ACT, IVE)
10093 @result{}ACT
10094 @end example
10096 @noindent
10097 In the second case, the top level gives @samp{active} as first and only
10098 argument of @code{car}, which results in:
10100 @example
10101 active
10102 @result{}ACT, IVE
10103 @end example
10105 @noindent
10106 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10107 In the third case, @code{car} receives @samp{[active]}, which results in:
10109 @example
10110 [active]
10111 @result{}active
10112 @end example
10114 @noindent
10115 exactly as we already saw above.
10117 The example above, applied to a more realistic example, gives:
10119 @example
10120 car(int tab[10];)
10121 @result{}int tab10;
10122 car([int tab[10];])
10123 @result{}int tab10;
10124 car([[int tab[10];]])
10125 @result{}int tab[10];
10126 @end example
10128 @noindent
10129 Huh?  The first case is easily understood, but why is the second wrong,
10130 and the third right?  To understand that, you must know that after
10131 M4 expands a macro, the resulting text is immediately subjected
10132 to macro expansion and quote removal.  This means that the quote removal
10133 occurs twice---first before the argument is passed to the @code{car}
10134 macro, and second after the @code{car} macro expands to the first
10135 argument.
10137 As the author of the Autoconf macro @code{car}, you then consider it to
10138 be incorrect that your users have to double-quote the arguments of
10139 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
10140 quoted car:
10142 @example
10143 define([qar], [[$1]])
10144 @end example
10146 @noindent
10147 and check that @code{qar} is properly fixed:
10149 @example
10150 qar([int tab[10];])
10151 @result{}int tab[10];
10152 @end example
10154 @noindent
10155 Ahhh!  That's much better.
10157 But note what you've done: now that the result of @code{qar} is always
10158 a literal string, the only time a user can use nested macros is if she
10159 relies on an @emph{unquoted} macro call:
10161 @example
10162 qar(active)
10163 @result{}ACT
10164 qar([active])
10165 @result{}active
10166 @end example
10168 @noindent
10169 leaving no way for her to reproduce what she used to do with @code{car}:
10171 @example
10172 car([active])
10173 @result{}ACT, IVE
10174 @end example
10176 @noindent
10177 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10178 macros:
10180 @example
10181 define([my_includes], [#include <stdio.h>])
10182 car([my_includes])
10183 @result{}#include <stdio.h>
10184 qar(my_includes)
10185 @error{}EOF in argument list
10186 @end example
10188 This macro, @code{qar}, because it double quotes its arguments, forces
10189 its users to leave their macro calls unquoted, which is dangerous.
10190 Commas and other active symbols are interpreted by M4 before
10191 they are given to the macro, often not in the way the users expect.
10192 Also, because @code{qar} behaves differently from the other macros,
10193 it's an exception that should be avoided in Autoconf.
10195 @node Changequote is Evil
10196 @subsection @code{changequote} is Evil
10197 @cindex @code{changequote}
10199 The temptation is often high to bypass proper quotation, in particular
10200 when it's late at night.  Then, many experienced Autoconf hackers
10201 finally surrender to the dark side of the force and use the ultimate
10202 weapon: @code{changequote}.
10204 The M4 builtin @code{changequote} belongs to a set of primitives that
10205 allow one to adjust the syntax of the language to adjust it to one's
10206 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
10207 quotes, but in the context of shell programming (and actually of most
10208 programming languages), that's about the worst choice one can make:
10209 because of strings and back-quoted expressions in shell code (such as
10210 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
10211 programming languages (as in @samp{'0'}), there are many unbalanced
10212 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
10213 not impossible.  In order to make M4 useful in such a context, its
10214 designers have equipped it with @code{changequote}, which makes it
10215 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
10216 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
10217 because they are unlikely characters, but @emph{because they are
10218 characters unlikely to be unbalanced}.
10220 There are other magic primitives, such as @code{changecom} to specify
10221 what syntactic forms are comments (it is common to see
10222 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10223 @code{changeword} and @code{changesyntax} to change other syntactic
10224 details (such as the character to denote the @var{n}th argument, @samp{$} by
10225 default, the parentheses around arguments, etc.).
10227 These primitives are really meant to make M4 more useful for specific
10228 domains: they should be considered like command line options:
10229 @option{--quotes}, @option{--comments}, @option{--words}, and
10230 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
10231 it makes M4 libraries self contained (no need for additional options).
10233 There lies the problem@enddots{}
10235 @sp 1
10237 The problem is that it is then tempting to use them in the middle of an
10238 M4 script, as opposed to its initialization.  This, if not carefully
10239 thought out, can lead to disastrous effects: @emph{you are changing the
10240 language in the middle of the execution}.  Changing and restoring the
10241 syntax is often not enough: if you happened to invoke macros in between,
10242 these macros are lost, as the current syntax is probably not
10243 the one they were implemented with.
10245 @c FIXME: I've been looking for a short, real case example, but I
10246 @c lost them all :(
10249 @node Quadrigraphs
10250 @subsection Quadrigraphs
10251 @cindex quadrigraphs
10252 @cindex @samp{@@S|@@}
10253 @cindex @samp{@@&t@@}
10254 @c Info cannot handle `:' in index entries.
10255 @c @cindex @samp{@@<:@@}
10256 @c @cindex @samp{@@:>@@}
10257 @c @cindex @samp{@@%:@@}
10258 @c @cindex @samp{@@@{:@@}
10259 @c @cindex @samp{@@:@}@@}
10261 When writing an Autoconf macro you may occasionally need to generate
10262 special characters that are difficult to express with the standard
10263 Autoconf quoting rules.  For example, you may need to output the regular
10264 expression @samp{[^[]}, which matches any character other than @samp{[}.
10265 This expression contains unbalanced brackets so it cannot be put easily
10266 into an M4 macro.
10268 Additionally, there are a few m4sugar macros (such as @code{m4_split}
10269 and @code{m4_expand}) which internally use special markers in addition
10270 to the regular quoting characters.  If the arguments to these macros
10271 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
10272 might behave incorrectly.
10274 You can work around these problems by using one of the following
10275 @dfn{quadrigraphs}:
10277 @table @samp
10278 @item @@<:@@
10279 @samp{[}
10280 @item @@:>@@
10281 @samp{]}
10282 @item @@S|@@
10283 @samp{$}
10284 @item @@%:@@
10285 @samp{#}
10286 @item @@@{:@@
10287 @samp{(}
10288 @item @@:@}@@
10289 @samp{)}
10290 @item @@&t@@
10291 Expands to nothing.
10292 @end table
10294 Quadrigraphs are replaced at a late stage of the translation process,
10295 after @command{m4} is run, so they do not get in the way of M4 quoting.
10296 For example, the string @samp{^@@<:@@}, independently of its quotation,
10297 appears as @samp{^[} in the output.
10299 The empty quadrigraph can be used:
10301 @itemize @minus
10302 @item to mark trailing spaces explicitly
10304 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
10306 @item to produce quadrigraphs and other strings reserved by m4sugar
10308 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
10309 contrived example:
10311 @example
10312 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
10313 m4_split([a )@}>=- b -=<@{( c])
10314 @result{}[a], [], [B], [], [c]
10315 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
10316 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
10317 @end example
10319 @item to escape @emph{occurrences} of forbidden patterns
10321 For instance you might want to mention @code{AC_FOO} in a comment, while
10322 still being sure that @command{autom4te} still catches unexpanded
10323 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
10324 @end itemize
10326 The name @samp{@@&t@@} was suggested by Paul Eggert:
10328 @quotation
10329 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
10330 own invention, but the @samp{t} came from the source code of the
10331 @sc{algol68c} compiler, written by Steve Bourne (of Bourne shell fame),
10332 and which used @samp{mt} to denote the empty string.  In C, it would
10333 have looked like something like:
10335 @example
10336 char const mt[] = "";
10337 @end example
10339 @noindent
10340 but of course the source code was written in Algol 68.
10342 I don't know where he got @samp{mt} from: it could have been his own
10343 invention, and I suppose it could have been a common pun around the
10344 Cambridge University computer lab at the time.
10345 @end quotation
10348 @node Balancing Parentheses
10349 @subsection Dealing with unbalanced parentheses
10350 @cindex balancing parentheses
10351 @cindex parentheses, balancing
10352 @cindex unbalanced parentheses, managing
10354 One of the pitfalls of portable shell programming is that @command{case}
10355 statements require unbalanced parentheses (@pxref{case, , Limitations of
10356 Shell Builtins}).  With syntax highlighting
10357 editors, the presence of unbalanced @samp{)} can interfere with editors
10358 that perform syntax highlighting of macro contents based on finding the
10359 matching @samp{(}.  Another concern is how much editing must be done
10360 when transferring code snippets between shell scripts and macro
10361 definitions.  But most importantly, the presence of unbalanced
10362 parentheses can introduce expansion bugs.
10364 For an example, here is an underquoted attempt to use the macro
10365 @code{my_case}, which happens to expand to a portable @command{case}
10366 statement:
10368 @example
10369 AC_DEFUN([my_case],
10370 [case $file_name in
10371   *.c) echo "C source code";;
10372 esac])
10373 AS_IF(:, my_case)
10374 @end example
10376 @noindent
10377 In the above example, the @code{AS_IF} call underquotes its arguments.
10378 As a result, the unbalanced @samp{)} generated by the premature
10379 expansion of @code{my_case} results in expanding @code{AS_IF} with a
10380 truncated parameter, and the expansion is syntactically invalid:
10382 @example
10383 if :; then
10384   case $file_name in
10385   *.c
10386 fi echo "C source code";;
10387 esac)
10388 @end example
10390 If nothing else, this should emphasize the importance of the quoting
10391 arguments to macro calls.  On the other hand, there are several
10392 variations for defining @code{my_case} to be more robust, even when used
10393 without proper quoting, each with some benefits and some drawbacks.
10395 @itemize @w{}
10396 @item Creative literal shell comment
10397 @example
10398 AC_DEFUN([my_case],
10399 [case $file_name in #(
10400   *.c) echo "C source code";;
10401 esac])
10402 @end example
10403 @noindent
10404 This version provides balanced parentheses to several editors, and can
10405 be copied and pasted into a terminal as is.  Unfortunately, it is still
10406 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
10407 that masks the normal properties of @samp{(}.
10409 @item Quadrigraph shell comment
10410 @example
10411 AC_DEFUN([my_case],
10412 [case $file_name in @@%:@@(
10413   *.c) echo "C source code";;
10414 esac])
10415 @end example
10416 @noindent
10417 This version provides balanced parentheses to even more editors, and can
10418 be used as a balanced Autoconf argument.  Unfortunately, it requires
10419 some editing before it can be copied and pasted into a terminal, and the
10420 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
10422 @item Quoting just the parenthesis
10423 @example
10424 AC_DEFUN([my_case],
10425 [case $file_name in
10426   *.c[)] echo "C source code";;
10427 esac])
10428 @end example
10429 @noindent
10430 This version quotes the @samp{)}, so that it can be used as a balanced
10431 Autoconf argument.  As written, this is not balanced to an editor, but
10432 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
10433 still requires some edits before it can be copied and pasted into a
10434 terminal.
10436 @item Double-quoting the entire statement
10437 @example
10438 AC_DEFUN([my_case],
10439 [[case $file_name in #(
10440   *.c) echo "C source code";;
10441 esac]])
10442 @end example
10443 @noindent
10444 Since the entire macro is double-quoted, there is no problem with using
10445 this as an Autoconf argument; and since the double-quoting is over the
10446 entire statement, this code can be easily copied and pasted into a
10447 terminal.  However, the double quoting prevents the expansion of any
10448 macros inside the case statement, which may cause its own set of
10449 problems.
10451 @item Using @code{AS_CASE}
10452 @example
10453 AC_DEFUN([my_case],
10454 [AS_CASE([$file_name],
10455   [*.c], [echo "C source code"])])
10456 @end example
10457 @noindent
10458 This version avoids the balancing issue altogether, by relying on
10459 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
10460 expansion of @code{AC_REQUIRE} to occur prior to the entire case
10461 statement, rather than within a branch of the case statement that might
10462 not be taken.  However, the abstraction comes with a penalty that it is
10463 no longer a quick copy, paste, and edit to get back to shell code.
10464 @end itemize
10467 @node Quotation Rule Of Thumb
10468 @subsection Quotation Rule Of Thumb
10470 To conclude, the quotation rule of thumb is:
10472 @center @emph{One pair of quotes per pair of parentheses.}
10474 Never over-quote, never under-quote, in particular in the definition of
10475 macros.  In the few places where the macros need to use brackets
10476 (usually in C program text or regular expressions), properly quote
10477 @emph{the arguments}!
10479 It is common to read Autoconf programs with snippets like:
10481 @example
10482 AC_TRY_LINK(
10483 changequote(<<, >>)dnl
10484 <<#include <time.h>
10485 #ifndef tzname /* For SGI.  */
10486 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10487 #endif>>,
10488 changequote([, ])dnl
10489 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
10490 @end example
10492 @noindent
10493 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
10494 double quoting, so you just need:
10496 @example
10497 AC_TRY_LINK(
10498 [#include <time.h>
10499 #ifndef tzname /* For SGI.  */
10500 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10501 #endif],
10502             [atoi (*tzname);],
10503             [ac_cv_var_tzname=yes],
10504             [ac_cv_var_tzname=no])
10505 @end example
10507 @noindent
10508 The M4-fluent reader might note that these two examples are rigorously
10509 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
10510 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
10511 quotes are not part of the arguments!
10513 Simplified, the example above is just doing this:
10515 @example
10516 changequote(<<, >>)dnl
10517 <<[]>>
10518 changequote([, ])dnl
10519 @end example
10521 @noindent
10522 instead of simply:
10524 @example
10525 [[]]
10526 @end example
10528 With macros that do not double quote their arguments (which is the
10529 rule), double-quote the (risky) literals:
10531 @example
10532 AC_LINK_IFELSE([AC_LANG_PROGRAM(
10533 [[#include <time.h>
10534 #ifndef tzname /* For SGI.  */
10535 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10536 #endif]],
10537                                 [atoi (*tzname);])],
10538                [ac_cv_var_tzname=yes],
10539                [ac_cv_var_tzname=no])
10540 @end example
10542 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
10543 should be using @code{AC_LINK_IFELSE} instead.
10545 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
10546 where quoting does not suffice.
10548 When you create a @command{configure} script using newly written macros,
10549 examine it carefully to check whether you need to add more quotes in
10550 your macros.  If one or more words have disappeared in the M4
10551 output, you need more quotes.  When in doubt, quote.
10553 However, it's also possible to put on too many layers of quotes.  If
10554 this happens, the resulting @command{configure} script may contain
10555 unexpanded macros.  The @command{autoconf} program checks for this problem
10556 by looking for the string @samp{AC_} in @file{configure}.  However, this
10557 heuristic does not work in general: for example, it does not catch
10558 overquoting in @code{AC_DEFINE} descriptions.
10561 @c ---------------------------------------- Using autom4te
10563 @node Using autom4te
10564 @section Using @command{autom4te}
10566 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
10567 to Autoconf per se, heavily rely on M4.  All these different uses
10568 revealed common needs factored into a layer over M4:
10569 @command{autom4te}@footnote{
10571 Yet another great name from Lars J. Aas.
10575 @command{autom4te} is a preprocessor that is like @command{m4}.
10576 It supports M4 extensions designed for use in tools like Autoconf.
10578 @menu
10579 * autom4te Invocation::         A @acronym{GNU} M4 wrapper
10580 * Customizing autom4te::        Customizing the Autoconf package
10581 @end menu
10583 @node autom4te Invocation
10584 @subsection Invoking @command{autom4te}
10586 The command line arguments are modeled after M4's:
10588 @example
10589 autom4te @var{options} @var{files}
10590 @end example
10592 @noindent
10593 @evindex M4
10594 where the @var{files} are directly passed to @command{m4}.  By default,
10595 @acronym{GNU} M4 is found during configuration, but the environment
10596 variable
10597 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
10598 to the regular expansion, it handles the replacement of the quadrigraphs
10599 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
10600 output.  It supports an extended syntax for the @var{files}:
10602 @table @file
10603 @item @var{file}.m4f
10604 This file is an M4 frozen file.  Note that @emph{all the previous files
10605 are ignored}.  See the option @option{--melt} for the rationale.
10607 @item @var{file}?
10608 If found in the library path, the @var{file} is included for expansion,
10609 otherwise it is ignored instead of triggering a failure.
10610 @end table
10612 @sp 1
10614 Of course, it supports the Autoconf common subset of options:
10616 @table @option
10617 @item --help
10618 @itemx -h
10619 Print a summary of the command line options and exit.
10621 @item --version
10622 @itemx -V
10623 Print the version number of Autoconf and exit.
10625 @item --verbose
10626 @itemx -v
10627 Report processing steps.
10629 @item --debug
10630 @itemx -d
10631 Don't remove the temporary files and be even more verbose.
10633 @item --include=@var{dir}
10634 @itemx -I @var{dir}
10635 Also look for input files in @var{dir}.  Multiple invocations
10636 accumulate.
10638 @item --output=@var{file}
10639 @itemx -o @var{file}
10640 Save output (script or trace) to @var{file}.  The file @option{-} stands
10641 for the standard output.
10642 @end table
10644 @sp 1
10646 As an extension of @command{m4}, it includes the following options:
10648 @table @option
10649 @item --warnings=@var{category}
10650 @itemx -W @var{category}
10651 @evindex WARNINGS
10652 @c FIXME: Point to the M4sugar macros, not Autoconf's.
10653 Report the warnings related to @var{category} (which can actually be a
10654 comma separated list).  @xref{Reporting Messages}, macro
10655 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
10656 values include:
10658 @table @samp
10659 @item all
10660 report all the warnings
10662 @item none
10663 report none
10665 @item error
10666 treats warnings as errors
10668 @item no-@var{category}
10669 disable warnings falling into @var{category}
10670 @end table
10672 Warnings about @samp{syntax} are enabled by default, and the environment
10673 variable @env{WARNINGS}, a comma separated list of categories, is
10674 honored.  @samp{autom4te -W @var{category}} actually
10675 behaves as if you had run:
10677 @example
10678 autom4te --warnings=syntax,$WARNINGS,@var{category}
10679 @end example
10681 @noindent
10682 For example, if you want to disable defaults and @env{WARNINGS}
10683 of @command{autom4te}, but enable the warnings about obsolete
10684 constructs, you would use @option{-W none,obsolete}.
10686 @cindex Back trace
10687 @cindex Macro invocation stack
10688 @command{autom4te} displays a back trace for errors, but not for
10689 warnings; if you want them, just pass @option{-W error}.
10691 @item --melt
10692 @itemx -M
10693 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
10694 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
10695 are executed only when the files are frozen, typically
10696 @code{m4_define}.  For instance, running:
10698 @example
10699 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
10700 @end example
10702 @noindent
10703 is roughly equivalent to running:
10705 @example
10706 m4 1.m4 2.m4 3.m4 4.m4 input.m4
10707 @end example
10709 @noindent
10710 while
10712 @example
10713 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
10714 @end example
10716 @noindent
10717 is equivalent to:
10719 @example
10720 m4 --reload-state=4.m4f input.m4
10721 @end example
10723 @item --freeze
10724 @itemx -F
10725 Produce a frozen state file.  @command{autom4te} freezing is stricter
10726 than M4's: it must produce no warnings, and no output other than empty
10727 lines (a line with white space is @emph{not} empty) and comments
10728 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
10729 this option takes no argument:
10731 @example
10732 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
10733 @end example
10735 @noindent
10736 corresponds to
10738 @example
10739 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
10740 @end example
10742 @item --mode=@var{octal-mode}
10743 @itemx -m @var{octal-mode}
10744 Set the mode of the non-traces output to @var{octal-mode}; by default
10745 @samp{0666}.
10746 @end table
10748 @sp 1
10750 @cindex @file{autom4te.cache}
10751 As another additional feature over @command{m4}, @command{autom4te}
10752 caches its results.  @acronym{GNU} M4 is able to produce a regular
10753 output and traces at the same time.  Traces are heavily used in the
10754 @acronym{GNU} Build System: @command{autoheader} uses them to build
10755 @file{config.h.in}, @command{autoreconf} to determine what
10756 @acronym{GNU} Build System components are used, @command{automake} to
10757 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
10758 traces are cached while performing regular expansion,
10759 and conversely.  This cache is (actually, the caches are) stored in
10760 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
10761 at any moment (especially if for some reason @command{autom4te}
10762 considers it trashed).
10764 @table @option
10765 @item --cache=@var{directory}
10766 @itemx -C @var{directory}
10767 Specify the name of the directory where the result should be cached.
10768 Passing an empty value disables caching.  Be sure to pass a relative
10769 file name, as for the time being, global caches are not supported.
10771 @item --no-cache
10772 Don't cache the results.
10774 @item --force
10775 @itemx -f
10776 If a cache is used, consider it obsolete (but update it anyway).
10777 @end table
10779 @sp 1
10781 Because traces are so important to the @acronym{GNU} Build System,
10782 @command{autom4te} provides high level tracing features as compared to
10783 M4, and helps exploiting the cache:
10785 @table @option
10786 @item --trace=@var{macro}[:@var{format}]
10787 @itemx -t @var{macro}[:@var{format}]
10788 Trace the invocations of @var{macro} according to the @var{format}.
10789 Multiple @option{--trace} arguments can be used to list several macros.
10790 Multiple @option{--trace} arguments for a single macro are not
10791 cumulative; instead, you should just make @var{format} as long as
10792 needed.
10794 The @var{format} is a regular string, with newlines if desired, and
10795 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
10796 use the following special escapes:
10798 @table @samp
10799 @item $$
10800 The character @samp{$}.
10802 @item $f
10803 The file name from which @var{macro} is called.
10805 @item $l
10806 The line number from which @var{macro} is called.
10808 @item $d
10809 The depth of the @var{macro} call.  This is an M4 technical detail that
10810 you probably don't want to know about.
10812 @item $n
10813 The name of the @var{macro}.
10815 @item $@var{num}
10816 The @var{num}th argument of the call to @var{macro}.
10818 @item $@@
10819 @itemx $@var{sep}@@
10820 @itemx $@{@var{separator}@}@@
10821 All the arguments passed to @var{macro}, separated by the character
10822 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
10823 argument is quoted, i.e., enclosed in a pair of square brackets.
10825 @item $*
10826 @itemx $@var{sep}*
10827 @itemx $@{@var{separator}@}*
10828 As above, but the arguments are not quoted.
10830 @item $%
10831 @itemx $@var{sep}%
10832 @itemx $@{@var{separator}@}%
10833 As above, but the arguments are not quoted, all new line characters in
10834 the arguments are smashed, and the default separator is @samp{:}.
10836 The escape @samp{$%} produces single-line trace outputs (unless you put
10837 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
10838 not.
10839 @end table
10841 @xref{autoconf Invocation}, for examples of trace uses.
10843 @item --preselect=@var{macro}
10844 @itemx -p @var{macro}
10845 Cache the traces of @var{macro}, but do not enable traces.  This is
10846 especially important to save CPU cycles in the future.  For instance,
10847 when invoked, @command{autoconf} preselects all the macros that
10848 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
10849 trace, so that running @command{m4} is not needed to trace them: the
10850 cache suffices.  This results in a huge speed-up.
10851 @end table
10853 @sp 1
10855 @cindex Autom4te Library
10856 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
10857 libraries}.  They consists in a powerful yet extremely simple feature:
10858 sets of combined command line arguments:
10860 @table @option
10861 @item --language=@var{language}
10862 @itemx -l @var{language}
10863 Use the @var{language} Autom4te library.  Current languages include:
10865 @table @code
10866 @item M4sugar
10867 create M4sugar output.
10869 @item M4sh
10870 create M4sh executable shell scripts.
10872 @item Autotest
10873 create Autotest executable test suites.
10875 @item Autoconf-without-aclocal-m4
10876 create Autoconf executable configure scripts without
10877 reading @file{aclocal.m4}.
10879 @item Autoconf
10880 create Autoconf executable configure scripts.  This language inherits
10881 all the characteristics of @code{Autoconf-without-aclocal-m4} and
10882 additionally reads @file{aclocal.m4}.
10883 @end table
10885 @item --prepend-include=@var{dir}
10886 @itemx -B @var{dir}
10887 Prepend directory @var{dir} to the search path.  This is used to include
10888 the language-specific files before any third-party macros.
10890 @end table
10892 @cindex @file{autom4te.cfg}
10893 As an example, if Autoconf is installed in its default location,
10894 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
10895 strictly equivalent to the command:
10897 @example
10898 autom4te --prepend-include /usr/local/share/autoconf \
10899   m4sugar/m4sugar.m4f --warnings syntax foo.m4
10900 @end example
10902 @noindent
10903 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
10904 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
10905 foo.m4}, i.e.:
10907 @example
10908 autom4te --prepend-include /usr/local/share/autoconf \
10909   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
10910 @end example
10912 @noindent
10913 The definition of the languages is stored in @file{autom4te.cfg}.
10915 @node Customizing autom4te
10916 @subsection Customizing @command{autom4te}
10918 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
10919 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
10920 as found in the directory from which @command{autom4te} is run).  The
10921 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
10922 then @file{./.autom4te.cfg}, and finally the command line arguments.
10924 In these text files, comments are introduced with @code{#}, and empty
10925 lines are ignored.  Customization is performed on a per-language basis,
10926 wrapped in between a @samp{begin-language: "@var{language}"},
10927 @samp{end-language: "@var{language}"} pair.
10929 Customizing a language stands for appending options (@pxref{autom4te
10930 Invocation}) to the current definition of the language.  Options, and
10931 more generally arguments, are introduced by @samp{args:
10932 @var{arguments}}.  You may use the traditional shell syntax to quote the
10933 @var{arguments}.
10935 As an example, to disable Autoconf caches (@file{autom4te.cache})
10936 globally, include the following lines in @file{~/.autom4te.cfg}:
10938 @verbatim
10939 ## ------------------ ##
10940 ## User Preferences.  ##
10941 ## ------------------ ##
10943 begin-language: "Autoconf-without-aclocal-m4"
10944 args: --no-cache
10945 end-language: "Autoconf-without-aclocal-m4"
10946 @end verbatim
10949 @node Programming in M4sugar
10950 @section Programming in M4sugar
10952 @cindex M4sugar
10953 M4 by itself provides only a small, but sufficient, set of all-purpose
10954 macros.  M4sugar introduces additional generic macros.  Its name was
10955 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
10956 M4sugar''.
10958 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
10959 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
10960 define your own macros into these namespaces.
10962 @menu
10963 * Redefined M4 Macros::         M4 builtins changed in M4sugar
10964 * Diagnostic Macros::           Diagnostic messages from M4sugar
10965 * Diversion support::           Diversions in M4sugar
10966 * Conditional constructs::      Conditions in M4
10967 * Looping constructs::          Iteration in M4
10968 * Evaluation Macros::           More quotation and evaluation control
10969 * Text processing Macros::      String manipulation in M4
10970 * Number processing Macros::    Arithmetic computation in M4
10971 * Set manipulation Macros::     Set manipulation in M4
10972 * Forbidden Patterns::          Catching unexpanded macros
10973 @end menu
10975 @node Redefined M4 Macros
10976 @subsection Redefined M4 Macros
10978 @msindex{builtin}
10979 @msindex{changecom}
10980 @msindex{changequote}
10981 @msindex{debugfile}
10982 @msindex{debugmode}
10983 @msindex{decr}
10984 @msindex{define}
10985 @msindex{divnum}
10986 @msindex{errprint}
10987 @msindex{esyscmd}
10988 @msindex{eval}
10989 @msindex{format}
10990 @msindex{ifdef}
10991 @msindex{incr}
10992 @msindex{index}
10993 @msindex{indir}
10994 @msindex{len}
10995 @msindex{pushdef}
10996 @msindex{shift}
10997 @msindex{substr}
10998 @msindex{syscmd}
10999 @msindex{sysval}
11000 @msindex{traceoff}
11001 @msindex{traceon}
11002 @msindex{translit}
11003 With a few exceptions, all the M4 native macros are moved in the
11004 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11005 @code{m4_define} etc.
11007 The list of macros unchanged from M4, except for their name, is:
11008 @itemize @minus
11009 @item m4_builtin
11010 @item m4_changecom
11011 @item m4_changequote
11012 @item m4_debugfile
11013 @item m4_debugmode
11014 @item m4_decr
11015 @item m4_define
11016 @item m4_divnum
11017 @item m4_errprint
11018 @item m4_esyscmd
11019 @item m4_eval
11020 @item m4_format
11021 @item m4_ifdef
11022 @item m4_incr
11023 @item m4_index
11024 @item m4_indir
11025 @item m4_len
11026 @item m4_pushdef
11027 @item m4_shift
11028 @item m4_substr
11029 @item m4_syscmd
11030 @item m4_sysval
11031 @item m4_traceoff
11032 @item m4_traceon
11033 @item m4_translit
11034 @end itemize
11036 Some M4 macros are redefined, and are slightly incompatible with their
11037 native equivalent.
11039 @defmac __file__
11040 @defmacx __line__
11041 @MSindex __file__
11042 @MSindex __line__
11043 All M4 macros starting with @samp{__} retain their original name: for
11044 example, no @code{m4__file__} is defined.
11045 @end defmac
11047 @defmac __oline__
11048 @MSindex __oline__
11049 This is not technically a macro, but a feature of Autom4te.  The
11050 sequence @code{__oline__} can be used similarly to the other m4sugar
11051 location macros, but rather than expanding to the location of the input
11052 file, it is translated to the line number where it appears in the output
11053 file after all other M4 expansions.
11054 @end defmac
11056 @defmac dnl
11057 @MSindex dnl
11058 This macro kept its original name: no @code{m4_dnl} is defined.
11059 @end defmac
11061 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11062 @msindex{bpatsubst}
11063 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
11064 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
11065 released and supports extended regular expression syntax.
11066 @end defmac
11068 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11069 @msindex{bregexp}
11070 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
11071 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
11072 released and supports extended regular expression syntax.
11073 @end defmac
11075 @defmac m4_copy (@var{source}, @var{dest})
11076 @defmacx m4_copy_force (@var{source}, @var{dest})
11077 @defmacx m4_rename (@var{source}, @var{dest})
11078 @defmacx m4_rename_force (@var{source}, @var{dest})
11079 @msindex{copy}
11080 @msindex{copy_force}
11081 @msindex{rename}
11082 @msindex{rename_force}
11083 These macros aren't directly builtins, but are closely related to
11084 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
11085 @code{m4_rename} ensure that @var{dest} is undefined, while
11086 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11087 definition.  All four macros then proceed to copy the entire pushdef
11088 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
11089 and @code{m4_copy_force} preserve the source (including in the special
11090 case where @var{source} is undefined), while @code{m4_rename} and
11091 @code{m4_rename_force} undefine the original macro name (making it an
11092 error to rename an undefined @var{source}).
11094 Note that attempting to invoke a renamed macro might not work, since the
11095 macro may have a dependence on helper macros accessed via composition of
11096 @samp{$0} but that were not also renamed; likewise, other macros may
11097 have a hard-coded dependence on @var{source} and could break if
11098 @var{source} has been deleted.  On the other hand, it is always safe to
11099 rename a macro to temporarily move it out of the way, then rename it
11100 back later to restore original semantics.
11101 @end defmac
11103 @defmac m4_defn (@var{macro}@dots{})
11104 @msindex{defn}
11105 This macro fails if @var{macro} is not defined, even when using older
11106 versions of M4 that did not warn.  See @code{m4_undefine}.
11107 Unfortunately, in order to support these older versions of M4, there are
11108 some situations involving unbalanced quotes where concatenating multiple
11109 macros together will work in newer M4 but not in m4sugar; use
11110 quadrigraphs to work around this.
11111 @end defmac
11113 @defmac m4_divert (@var{diversion})
11114 @msindex{divert}
11115 M4sugar relies heavily on diversions, so rather than behaving as a
11116 primitive, @code{m4_divert} behaves like:
11117 @example
11118 m4_divert_pop()m4_divert_push([@var{diversion}])
11119 @end example
11120 @noindent
11121 @xref{Diversion support}, for more details about the use of the
11122 diversion stack.  In particular, this implies that @var{diversion}
11123 should be a named diversion rather than a raw number.  But be aware that
11124 it is seldom necessary to explicitly change the diversion stack, and
11125 that when done incorrectly, it can lead to syntactically invalid
11126 scripts.
11127 @end defmac
11129 @defmac m4_dumpdef (@var{name}@dots{})
11130 @defmacx m4_dumpdefs (@var{name}@dots{})
11131 @msindex{dumpdef}
11132 @msindex{dumpdefs}
11133 @code{m4_dumpdef} is like the M4 builtin, except that this version
11134 requires at least one argument, output always goes to standard error
11135 rather than the current debug file, no sorting is done on multiple
11136 arguments, and an error is issued if any
11137 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
11138 calls @code{m4_dumpdef} for all of the
11139 @code{m4_pushdef} stack of definitions, starting with the current, and
11140 silently does nothing if @var{name} is undefined.
11142 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11143 builtin is output as the empty string.  This behavior is rectified by
11144 using M4 1.6 or newer.  However, this behavior difference means that
11145 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11146 and never in the final published form of a macro.
11147 @end defmac
11149 @defmac m4_esyscmd_s (@var{command})
11150 @msindex{esyscmd_s}
11151 Like @code{m4_esyscmd}, this macro expands to the result of running
11152 @var{command} in a shell.  The difference is that any trailing newlines
11153 are removed, so that the output behaves more like shell command
11154 substitution.
11155 @end defmac
11157 @defmac m4_exit (@var{exit-status})
11158 @msindex{exit}
11159 This macro corresponds to @code{m4exit}.
11160 @end defmac
11162 @defmac m4_if (@var{comment})
11163 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11164 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11165   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11166 @msindex{if}
11167 This macro corresponds to @code{ifelse}.  @var{string-1} and
11168 @var{string-2} are compared literally, so usually one of the two
11169 arguments is passed unquoted.  @xref{Conditional constructs}, for more
11170 conditional idioms.
11171 @end defmac
11173 @defmac m4_include (@var{file})
11174 @defmacx m4_sinclude (@var{file})
11175 @msindex{include}
11176 @msindex{sinclude}
11177 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11178 @end defmac
11180 @defmac m4_mkstemp (@var{template})
11181 @defmacx m4_maketemp (@var{template})
11182 @msindex{maketemp}
11183 @msindex{mkstemp}
11184 Posix requires @code{maketemp} to replace the trailing @samp{X}
11185 characters in @var{template} with the process id, without regards to the
11186 existence of a file by that name, but this a security hole.  When this
11187 was pointed out to the Posix folks, they agreed to invent a new macro
11188 @code{mkstemp} that always creates a uniquely named file, but not all
11189 versions of @acronym{GNU} M4 support the new macro.  In M4sugar,
11190 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11191 and both have the secure semantics regardless of which macro the
11192 underlying M4 provides.
11193 @end defmac
11195 @defmac m4_popdef (@var{macro}@dots{})
11196 @msindex{popdef}
11197 This macro fails if @var{macro} is not defined, even when using older
11198 versions of M4 that did not warn.  See @code{m4_undefine}.
11199 @end defmac
11201 @defmac m4_undefine (@var{macro}@dots{})
11202 @msindex{undefine}
11203 This macro fails if @var{macro} is not defined, even when using older
11204 versions of M4 that did not warn.  Use
11206 @example
11207 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11208 @end example
11210 @noindent
11211 if you are not sure whether @var{macro} is defined.
11212 @end defmac
11214 @defmac m4_undivert (@var{diversion}@dots{})
11215 @msindex{undivert}
11216 Unlike the M4 builtin, at least one @var{diversion} must be specified.
11217 Also, since the M4sugar diversion stack prefers named
11218 diversions, the use of @code{m4_undivert} to include files is risky.
11219 @xref{Diversion support}, for more details about the use of the
11220 diversion stack.  But be aware that it is seldom necessary to explicitly
11221 change the diversion stack, and that when done incorrectly, it can lead
11222 to syntactically invalid scripts.
11223 @end defmac
11225 @defmac m4_wrap (@var{text})
11226 @defmacx m4_wrap_lifo (@var{text})
11227 @msindex{wrap}
11228 @msindex{wrap_lifo}
11229 These macros correspond to @code{m4wrap}.  Posix requires arguments of
11230 multiple wrap calls to be reprocessed at @acronym{EOF} in the same order
11231 as the original calls (first-in, first-out).  @acronym{GNU} M4 versions
11232 through 1.4.10, however, reprocess them in reverse order (last-in,
11233 first-out).  Both orders are useful, therefore, you can rely on
11234 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11235 LIFO semantics, regardless of the underlying @acronym{GNU} M4 version.
11237 Unlike the @acronym{GNU} M4 builtin, these macros only recognize one
11238 argument, and avoid token pasting between consecutive invocations.  On
11239 the other hand, nested calls to @code{m4_wrap} from within wrapped text
11240 work just as in the builtin.
11241 @end defmac
11244 @node Diagnostic Macros
11245 @subsection Diagnostic messages from M4sugar
11246 @cindex Messages, from @command{M4sugar}
11248 When macros statically diagnose abnormal situations, benign or fatal,
11249 they should report them using these macros.  For issuing dynamic issues,
11250 i.e., when @command{configure} is run, see @ref{Printing Messages}.
11252 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
11253 @msindex{assert}
11254 Assert that the arithmetic @var{expression} evaluates to non-zero.
11255 Otherwise, issue a fatal error, and exit @command{autom4te} with
11256 @var{exit-status}.
11257 @end defmac
11259 @defmac m4_errprintn (@var{message})
11260 @msindex{errprintn}
11261 Similar to the builtin @code{m4_errprint}, except that a newline is
11262 guaranteed after @var{message}.
11263 @end defmac
11265 @anchor{m4_fatal}
11266 @defmac m4_fatal (@var{message})
11267 @msindex{fatal}
11268 Report a severe error @var{message} prefixed with the current location,
11269 and have @command{autom4te} die.
11270 @end defmac
11272 @defmac m4_location
11273 @msindex{location}
11274 Useful as a prefix in a message line.  Short for:
11275 @example
11276 __file__:__line__
11277 @end example
11278 @end defmac
11280 @anchor{m4_warn}
11281 @defmac m4_warn (@var{category}, @var{message})
11282 @msindex{warn}
11283 Report @var{message} as a warning (or as an error if requested by the
11284 user) if warnings of the @var{category} are turned on.  If the message
11285 is emitted, it is prefixed with the current location, and followed by a
11286 call trace of all macros defined via @code{AC_DEFUN} used to get to the
11287 current expansion.  You are encouraged to use standard categories, which
11288 currently include:
11290 @table @samp
11291 @item all
11292 messages that don't fall into one of the following categories.  Use of an
11293 empty @var{category} is equivalent.
11295 @item cross
11296 related to cross compilation issues.
11298 @item obsolete
11299 use of an obsolete construct.
11301 @item syntax
11302 dubious syntactic constructs, incorrectly ordered macro calls.
11303 @end table
11304 @end defmac
11307 @node Diversion support
11308 @subsection Diversion support
11310 M4sugar makes heavy use of diversions under the hood, because it is
11311 often the case that
11312 text that must appear early in the output is not discovered until late
11313 in the input.  Additionally, some of the topological sorting algorithms
11314 used in resolving macro dependencies use diversions.  However, most
11315 macros should not need to change diversions directly, but rather rely on
11316 higher-level M4sugar macros to manage diversions transparently.  If you
11317 change diversions improperly, you risk generating a syntactically
11318 invalid script, because an incorrect diversion will violate assumptions
11319 made by many macros about whether prerequisite text has been previously
11320 output.  In short, if you manually change the diversion, you should not
11321 expect any macros provided by the Autoconf package to work until you
11322 have restored the diversion stack back to its original state.
11324 In the rare case that it is necessary to write a macro that explicitly
11325 outputs text to a different diversion, it is important to be aware of an
11326 M4 limitation regarding diversions: text only goes to a diversion if it
11327 is not part of argument collection.  Therefore, any macro that changes
11328 the current diversion cannot be used as an unquoted argument to another
11329 macro, but must be expanded at the top level.  The macro
11330 @code{m4_expand} will diagnose any attempt to change diversions, since
11331 it is generally useful only as an argument to another macro.  The
11332 following example shows what happens when diversion manipulation is
11333 attempted within macro arguments:
11335 @example
11336 m4_do([normal text]
11337 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
11338 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
11339 @result{}normal text
11340 @result{}unwanted
11341 @end example
11343 @noindent
11344 Notice that the unquoted text @code{unwanted} is output, even though it
11345 was processed while the current diversion was @code{KILL}, because it
11346 was collected as part of the argument to @code{m4_do}.  However, the
11347 text @code{discarded} disappeared as desired, because the diversion
11348 changes were single-quoted, and were not expanded until the top-level
11349 rescan of the output of @code{m4_do}.
11351 To make diversion management easier, M4sugar uses the concept of named
11352 diversions.  Rather than using diversion numbers directly, it is nicer
11353 to associate a name with each diversion.  The diversion number associated
11354 with a particular diversion name is an implementation detail, and a
11355 syntax warning is issued if a diversion number is used instead of a
11356 name.  In general, you should not output text
11357 to a named diversion until after calling the appropriate initialization
11358 routine for your language (@code{m4_init}, @code{AS_INIT},
11359 @code{AT_INIT}, @dots{}), although there are some exceptions documented
11360 below.
11362 M4sugar defines two named diversions.
11363 @table @code
11364 @item KILL
11365 Text written to this diversion is discarded.  This is the default
11366 diversion once M4sugar is initialized.
11367 @item GROW
11368 This diversion is used behind the scenes by topological sorting macros,
11369 such as @code{AC_REQUIRE}.
11370 @end table
11372 M4sh adds several more named diversions.
11373 @table @code
11374 @item BINSH
11375 This diversion is reserved for the @samp{#!} interpreter line.
11376 @item HEADER-REVISION
11377 This diversion holds text from @code{AC_REVISION}.
11378 @item HEADER-COMMENT
11379 This diversion holds comments about the purpose of a file.
11380 @item HEADER-COPYRIGHT
11381 This diversion is managed by @code{AC_COPYRIGHT}.
11382 @item M4SH-SANITIZE
11383 This diversion contains M4sh sanitization code, used to ensure M4sh is
11384 executing in a reasonable shell environment.
11385 @item M4SH-INIT
11386 This diversion contains M4sh initialization code, initializing variables
11387 that are required by other M4sh macros.
11388 @item BODY
11389 This diversion contains the body of the shell code, and is the default
11390 diversion once M4sh is initialized.
11391 @end table
11393 Autotest inherits diversions from M4sh, and changes the default
11394 diversion from @code{BODY} back to @code{KILL}.  It also adds several
11395 more named diversions, with the following subset designed for developer
11396 use.
11397 @table @code
11398 @item PREPARE_TESTS
11399 This diversion contains initialization sequences which are executed
11400 after @file{atconfig} and @file{atlocal}, and after all command line
11401 arguments have been parsed, but prior to running any tests.  It can be
11402 used to set up state that is required across all tests.  This diversion
11403 will work even before @code{AT_INIT}.
11404 @end table
11406 Autoconf inherits diversions from M4sh, and adds the following named
11407 diversions which developers can utilize.
11408 @table @code
11409 @item DEFAULTS
11410 This diversion contains shell variable assignments to set defaults that
11411 must be in place before arguments are parsed.  This diversion is placed
11412 early enough in @file{configure} that it is unsafe to expand any
11413 autoconf macros into this diversion.
11414 @item HELP_ENABLE
11415 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
11416 diversion will be included as part of a quoted here-doc providing all of
11417 the @option{--help} output of @file{configure} related to options
11418 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
11419 @item INIT_PREPARE
11420 This diversion occurs after all command line options have been parsed,
11421 but prior to the main body of the @file{configure} script.  This
11422 diversion is the last chance to insert shell code such as variable
11423 assignments or shell function declarations that will used by the
11424 expansion of other macros.
11425 @end table
11427 For now, the remaining named diversions of Autoconf, Autoheader, and
11428 Autotest are not documented.  In other words,
11429 intentionally outputting text into an undocumented diversion is subject
11430 to breakage in a future release of Autoconf.
11432 @defmac m4_cleardivert (@var{diversion}@dots{})
11433 @msindex{cleardivert}
11434 Permanently discard any text that has been diverted into
11435 @var{diversion}.
11436 @end defmac
11438 @defmac m4_divert_once (@var{diversion}, @ovar{content})
11439 @msindex{divert_once}
11440 Similar to @code{m4_divert_text}, except that @var{content} is only
11441 output to @var{diversion} if this is the first time that
11442 @code{m4_divert_once} has been called with its particular arguments.
11443 @end defmac
11445 @defmac m4_divert_pop (@ovar{diversion})
11446 @msindex{divert_pop}
11447 If provided, check that the current diversion is indeed @var{diversion}.
11448 Then change to the diversion located earlier on the stack, giving an
11449 error if an attempt is made to pop beyond the initial m4sugar diversion
11450 of @code{KILL}.
11451 @end defmac
11453 @defmac m4_divert_push (@var{diversion})
11454 @msindex{divert_push}
11455 Remember the former diversion on the diversion stack, and output
11456 subsequent text into @var{diversion}.  M4sugar maintains a diversion
11457 stack, and issues an error if there is not a matching pop for every
11458 push.
11459 @end defmac
11461 @defmac m4_divert_text (@var{diversion}, @ovar{content})
11462 @msindex{divert_text}
11463 Output @var{content} and a newline into @var{diversion}, without
11464 affecting the current diversion.  Shorthand for:
11465 @example
11466 m4_divert_push([@var{diversion}])@var{content}
11467 m4_divert_pop([@var{diversion}])dnl
11468 @end example
11470 One use of @code{m4_divert_text} is to develop two related macros, where
11471 macro @samp{MY_A} does the work, but adjusts what work is performed
11472 based on whether the optional macro @samp{MY_B} has also been expanded.
11473 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
11474 require that @samp{MY_B} occurs first, if it occurs at all.  But this
11475 imposes an ordering restriction on the user; it would be nicer if macros
11476 @samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
11477 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
11478 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
11479 expanded.
11481 @example
11482 AC_DEFUN([MY_A],
11483 [# various actions
11484 if test -n "$b_was_used"; then
11485   # extra action
11486 fi])
11487 AC_DEFUN([MY_B],
11488 [AC_REQUIRE([MY_A])dnl
11489 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
11490 @end example
11492 @end defmac
11494 @defmac m4_init
11495 @msindex{init}
11496 Initialize the M4sugar environment, setting up the default named
11497 diversion to be @code{KILL}.
11498 @end defmac
11500 @node Conditional constructs
11501 @subsection Conditional constructs
11503 The following macros provide additional conditional constructs as
11504 convenience wrappers around @code{m4_if}.
11506 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
11507   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
11508 @msindex{bmatch}
11509 The string @var{string} is repeatedly compared against a series of
11510 @var{regex} arguments; if a match is found, the expansion is the
11511 corresponding @var{value}, otherwise, the macro moves on to the next
11512 @var{regex}.  If no @var{regex} match, then the result is the optional
11513 @var{default}, or nothing.
11514 @end defmac
11516 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
11517   @ovar{regex-2}, @ovar{subst-2}, @dots{})
11518 @msindex{bpatsubsts}
11519 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
11520 as if by:
11521 @example
11522 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
11523 @end example
11525 @noindent
11526 The result of the substitution is then passed through the next set of
11527 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
11528 deletion of any matched portions in the current string.  Note that this
11529 macro over-quotes @var{string}; this behavior is intentional, so that
11530 the result of each step of the recursion remains as a quoted string.
11531 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
11532 will line up with the extra quotations, and not the characters of the
11533 original string.  The overquoting is removed after the final
11534 substitution.
11535 @end defmac
11537 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
11538   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
11539 @msindex{case}
11540 Test @var{string} against multiple @var{value} possibilities, resulting
11541 in the first @var{if-value} for a match, or in the optional
11542 @var{default}.  This is shorthand for:
11543 @example
11544 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
11545       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
11546       [@var{default}])
11547 @end example
11548 @end defmac
11550 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
11551   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
11552 @msindex{cond}
11553 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
11554 except that each @var{test} is expanded only when it is encountered.
11555 This is useful for short-circuiting expensive tests; while @code{m4_if}
11556 requires all its strings to be expanded up front before doing
11557 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
11558 tests have failed.
11560 For an example, these two sequences give the same result, but in the
11561 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
11562 version only expands @code{m4_index} once, instead of five times, for
11563 faster computation if this is a common case for @samp{$1}.  Notice that
11564 every third argument is unquoted for @code{m4_if}, and quoted for
11565 @code{m4_cond}:
11567 @example
11568 m4_if(m4_index([$1], [\]), [-1], [$2],
11569       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
11570       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
11571       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
11572       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
11573       [$2])
11574 m4_cond([m4_index([$1], [\])], [-1], [$2],
11575         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
11576         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
11577         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
11578         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
11579         [$2])
11580 @end example
11581 @end defmac
11583 @defmac m4_default (@var{expr-1}, @var{expr-2})
11584 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
11585 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
11586 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
11587 @msindex{default}
11588 @msindex{default_quoted}
11589 @msindex{default_nblank}
11590 @msindex{default_nblank_quoted}
11591 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
11592 @code{m4_default} expands the result, while @code{m4_default_quoted}
11593 does not.  Useful for providing a fixed default if the expression that
11594 results in @var{expr-1} would otherwise be empty.  The difference
11595 between @code{m4_default} and @code{m4_default_nblank} is whether an
11596 argument consisting of just blanks (space, tab, newline) is
11597 significant.  When using the expanding versions, note that an argument
11598 may contain text but still expand to an empty string.
11600 @example
11601 m4_define([active], [ACTIVE])dnl
11602 m4_define([empty], [])dnl
11603 m4_define([demo1], [m4_default([$1], [$2])])dnl
11604 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
11605 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
11606 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
11607 demo1([active], [default])
11608 @result{}ACTIVE
11609 demo1([], [active])
11610 @result{}ACTIVE
11611 demo1([empty], [text])
11612 @result{}
11613 -demo1([ ], [active])-
11614 @result{}- -
11615 demo2([active], [default])
11616 @result{}active
11617 demo2([], [active])
11618 @result{}active
11619 demo2([empty], [text])
11620 @result{}empty
11621 -demo2([ ], [active])-
11622 @result{}- -
11623 demo3([active], [default])
11624 @result{}ACTIVE
11625 demo3([], [active])
11626 @result{}ACTIVE
11627 demo3([empty], [text])
11628 @result{}
11629 -demo3([ ], [active])-
11630 @result{}-ACTIVE-
11631 demo4([active], [default])
11632 @result{}active
11633 demo4([], [active])
11634 @result{}active
11635 demo4([empty], [text])
11636 @result{}empty
11637 -demo4([ ], [active])-
11638 @result{}-active-
11639 @end example
11640 @end defmac
11642 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
11643 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
11644 @msindex{ifblank}
11645 @msindex{ifnblank}
11646 If @var{cond} is empty or consists only of blanks (space, tab, newline),
11647 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
11648 variants exist, in order to make it easier to select the correct logical
11649 sense when using only two parameters.  Note that this is more efficient
11650 than the equivalent behavior of:
11651 @example
11652 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-cond})
11653 @end example
11654 @end defmac
11656 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
11657 @msindex{ifndef}
11658 This is shorthand for:
11659 @example
11660 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
11661 @end example
11662 @end defmac
11664 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
11665 @msindex{ifset}
11666 If @var{macro} is undefined, or is defined as the empty string, expand
11667 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
11668 @example
11669 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
11670 @end example
11671 @noindent
11672 except that it is not an error if @var{macro} is undefined.
11673 @end defmac
11675 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
11676 @msindex{ifval}
11677 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
11678 @var{if-false}.  This is shorthand for:
11679 @example
11680 m4_if([@var{cond}], [], [@var{if-true}], [@var{if-false}])
11681 @end example
11682 @end defmac
11684 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
11685 @msindex{ifvaln}
11686 Similar to @code{m4_ifval}, except guarantee that a newline is present
11687 after any non-empty expansion.  Often followed by @code{dnl}.
11688 @end defmac
11690 @defmac m4_n (@var{text})
11691 @msindex{n}
11692 Expand to @var{text}, and add a newline if @var{text} is not empty.
11693 Often followed by @code{dnl}.
11694 @end defmac
11697 @node Looping constructs
11698 @subsection Looping constructs
11700 The following macros are useful in implementing recursive algorithms in
11701 M4, including loop operations.  An M4 list is formed by quoting a list
11702 of quoted elements; generally the lists are comma-separated, although
11703 @code{m4_foreach_w} is whitespace-separated.  For example, the list
11704 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
11705 It is common to see lists with unquoted elements when those elements are
11706 not likely to be macro names, as in @samp{[fputc_unlocked,
11707 fgetc_unlocked]}.
11709 Although not generally recommended, it is possible for quoted lists to
11710 have side effects; all side effects are expanded only once, and prior to
11711 visiting any list element.  On the other hand, the fact that unquoted
11712 macros are expanded exactly once means that macros without side effects
11713 can be used to generate lists.  For example,
11715 @example
11716 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
11717 @error{}hi
11718 @result{}123
11719 m4_define([list], [[1], [2], [3]])
11720 @result{}
11721 m4_foreach([i], [list], [i])
11722 @result{}123
11723 @end example
11725 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
11726 @msindex{argn}
11727 Extracts argument @var{n} (larger than 0) from the remaining arguments.
11728 If there are too few arguments, the empty string is used.  For any
11729 @var{n} besides 1, this is more efficient than the similar
11730 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
11731 @end defmac
11733 @defmac m4_car (@var{arg}@dots{})
11734 @msindex{car}
11735 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
11736 to recursively iterate
11737 through a list.  Generally, when using quoted lists of quoted elements,
11738 @code{m4_car} should be called without any extra quotes.
11739 @end defmac
11741 @defmac m4_cdr (@var{arg}@dots{})
11742 @msindex{cdr}
11743 Expands to a quoted list of all but the first @var{arg}, or the empty
11744 string if there was only one argument.  Generally, when using quoted
11745 lists of quoted elements, @code{m4_cdr} should be called without any
11746 extra quotes.
11748 For example, this is a simple implementation of @code{m4_map}; note how
11749 each iteration checks for the end of recursion, then merely applies the
11750 first argument to the first element of the list, then repeats with the
11751 rest of the list.  (The actual implementation in M4sugar is a bit more
11752 involved, to gain some speed and share code with @code{m4_map_sep}, and
11753 also to avoid expanding side effects in @samp{$2} twice).
11754 @example
11755 m4_define([m4_map], [m4_ifval([$2],
11756   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
11757 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
11758 @result{} 1 2 a
11759 @end example
11760 @end defmac
11762 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
11763   @var{expression})
11764 @msindex{for}
11765 Loop over the numeric values between @var{first} and @var{last}
11766 including bounds by increments of @var{step}.  For each iteration,
11767 expand @var{expression} with the numeric value assigned to @var{var}.
11768 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
11769 on the order of the limits.  If given, @var{step} has to match this
11770 order.  The number of iterations is determined independently from
11771 definition of @var{var}; iteration cannot be short-circuited or
11772 lengthened by modifying @var{var} from within @var{expression}.
11773 @end defmac
11775 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
11776 @msindex{foreach}
11777 Loop over the comma-separated M4 list @var{list}, assigning each value
11778 to @var{var}, and expand @var{expression}.  The following example
11779 outputs two lines:
11781 @example
11782 m4_foreach([myvar], [[foo], [bar, baz]],
11783            [echo myvar
11784 ])dnl
11785 @result{}echo foo
11786 @result{}echo bar, baz
11787 @end example
11789 Note that for some forms of @var{expression}, it may be faster to use
11790 @code{m4_map_args}.
11791 @end defmac
11793 @anchor{m4_foreach_w}
11794 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
11795 @msindex{foreach_w}
11796 Loop over the white-space-separated list @var{list}, assigning each value
11797 to @var{var}, and expand @var{expression}.  If @var{var} is only
11798 referenced once in @var{expression}, it is more efficient to use
11799 @code{m4_map_args_w}.
11801 The deprecated macro @code{AC_FOREACH} is an alias of
11802 @code{m4_foreach_w}.
11803 @end defmac
11805 @defmac m4_map (@var{macro}, @var{list})
11806 @defmacx m4_mapall (@var{macro}, @var{list})
11807 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
11808 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
11809 @msindex{map}
11810 @msindex{mapall}
11811 @msindex{map_sep}
11812 @msindex{mapall_sep}
11813 Loop over the comma separated quoted list of argument descriptions in
11814 @var{list}, and invoke @var{macro} with the arguments.  An argument
11815 description is in turn a comma-separated quoted list of quoted elements,
11816 suitable for @code{m4_apply}.  The macros @code{m4_map} and
11817 @code{m4_map_sep} ignore empty argument descriptions, while
11818 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
11819 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
11820 additionally expand @var{separator} between invocations of @var{macro}.
11822 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
11823 separating output with commas, this means that the map result can be
11824 used as a series of arguments, by using a single-quoted comma as
11825 @var{separator}, or as a single string, by using a double-quoted comma.
11827 @example
11828 m4_map([m4_count], [])
11829 @result{}
11830 m4_map([ m4_count], [[],
11831                      [[1]],
11832                      [[1], [2]]])
11833 @result{} 1 2
11834 m4_mapall([ m4_count], [[],
11835                         [[1]],
11836                         [[1], [2]]])
11837 @result{} 0 1 2
11838 m4_map_sep([m4_eval], [,], [[[1+2]],
11839                             [[10], [16]]])
11840 @result{}3,a
11841 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
11842 @result{}a,b
11843 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
11844 @result{}2
11845 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
11846 @result{}a,b
11847 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
11848 @result{}1
11849 @end example
11850 @end defmac
11852 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
11853 @msindex{map_args}
11854 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
11855 argument.  In the following example, three solutions are presented with
11856 the same expansion; the solution using @code{m4_map_args} is the most
11857 efficient.
11858 @example
11859 m4_define([active], [ACTIVE])dnl
11860 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
11861 @result{} plain active
11862 m4_map([ m4_echo], [[[plain]], [[active]]])
11863 @result{} plain active
11864 m4_map_args([ m4_echo], [plain], [active])
11865 @result{} plain active
11866 @end example
11868 In cases where it is useful to operate on additional parameters besides
11869 the list elements, the macro @code{m4_curry} can be used in @var{macro}
11870 to supply the argument currying necessary to generate the desired
11871 argument list.  In the following example, @code{list_add_n} is more
11872 efficient than @code{list_add_x}.  On the other hand, using
11873 @code{m4_map_args_sep} can be even more efficient.
11875 @example
11876 m4_define([list], [[1], [2], [3]])dnl
11877 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
11878 dnl list_add_n(N, ARG...)
11879 dnl Output a list consisting of each ARG added to N
11880 m4_define([list_add_n],
11881 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
11882 list_add_n([1], list)
11883 @result{}2,3,4
11884 list_add_n([2], list)
11885 @result{}3,4,5
11886 m4_define([list_add_x],
11887 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
11888   [,add([$1],m4_defn([var]))]))])dnl
11889 list_add_x([1], list)
11890 @result{}2,3,4
11891 @end example
11892 @end defmac
11894 @defmac m4_map_args_pair (@var{macro}, @dvar{macro-end, macro}, @
11895   @var{arg}@dots{})
11896 @msindex{map_args_pair}
11897 For every pair of arguments @var{arg}, invoke @var{macro} with two
11898 arguments.  If there is an odd number of arguments, invoke
11899 @var{macro-end}, which defaults to @var{macro}, with the remaining
11900 argument.
11902 @example
11903 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
11904 @result{}, 2, 1, 3
11905 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
11906 @result{}, 2, 1, [3]
11907 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
11908 @result{}, 2, 1, 4, 3
11909 @end example
11910 @end defmac
11912 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
11913 @msindex{map_args_sep}
11914 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
11915 argument, additionally expanding @var{sep} between arguments.  One
11916 common use of this macro is constructing a macro call, where the opening
11917 and closing parentheses are split between @var{pre} and @var{post}; in
11918 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
11919 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
11920 macro provides the most efficient means for iterating over an arbitrary
11921 list of arguments, particularly when repeatedly constructing a macro
11922 call with more arguments than @var{arg}.
11923 @end defmac
11925 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
11926 @msindex{map_args_w}
11927 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
11928 the whitespace-separated @var{string}, additionally expanding @var{sep}
11929 between words.  This macro provides the most efficient means for
11930 iterating over a whitespace-separated string.  In particular,
11931 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
11932 efficient than @code{m4_foreach_w([var], [@var{string}],
11933 [@var{action}(m4_defn([var]))])}.
11934 @end defmac
11936 @defmac m4_shiftn (@var{count}, @dots{})
11937 @defmacx m4_shift2 (@dots{})
11938 @defmacx m4_shift3 (@dots{})
11939 @msindex{shift2}
11940 @msindex{shift3}
11941 @msindex{shiftn}
11942 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
11943 along with validation that enough arguments were passed in to match the
11944 shift count, and that the count is positive.  @code{m4_shift2} and
11945 @code{m4_shift3} are specializations
11946 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
11947 for two and three shifts, respectively.
11948 @end defmac
11950 @defmac m4_stack_foreach (@var{macro}, @var{action})
11951 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
11952 @msindex{stack_foreach}
11953 @msindex{stack_foreach_lifo}
11954 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
11955 @var{action} with the single argument of a definition of @var{macro}.
11956 @code{m4_stack_foreach} starts with the oldest definition, while
11957 @code{m4_stack_foreach_lifo} starts with the current definition.
11958 @var{action} should not push or pop definitions of @var{macro}, nor is
11959 there any guarantee that the current definition of @var{macro} matches
11960 the argument that was passed to @var{action}.  The macro @code{m4_curry}
11961 can be used if @var{action} needs more than one argument, although in
11962 that case it is more efficient to use @var{m4_stack_foreach_sep}.
11964 Due to technical limitations, there are a few low-level m4sugar
11965 functions, such as @code{m4_pushdef}, that cannot be used as the
11966 @var{macro} argument.
11968 @example
11969 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
11970 m4_stack_foreach([a], [ m4_incr])
11971 @result{} 2 3
11972 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
11973 @result{} cd bcd
11974 @end example
11975 @end defmac
11977 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
11978 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
11979   @ovar{sep})
11980 @msindex{stack_foreach_sep}
11981 @msindex{stack_foreach_sep_lifo}
11982 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
11983 @code{m4_pushdef} definition of @var{macro}, additionally expanding
11984 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
11985 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
11986 the current definition first.  This macro provides the most efficient
11987 means for iterating over a pushdef stack.  In particular,
11988 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
11989 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
11990 @end defmac
11992 @node Evaluation Macros
11993 @subsection Evaluation Macros
11995 The following macros give some control over the order of the evaluation
11996 by adding or removing levels of quotes.
11998 @defmac m4_apply (@var{macro}, @var{list})
11999 @msindex{apply}
12000 Apply the elements of the quoted, comma-separated @var{list} as the
12001 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12002 without arguments.  Note the difference between @code{m4_indir}, which
12003 expects its first argument to be a macro name but can use names that are
12004 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12005 other text, but must end in a valid macro name.
12006 @example
12007 m4_apply([m4_count], [])
12008 @result{}0
12009 m4_apply([m4_count], [[]])
12010 @result{}1
12011 m4_apply([m4_count], [[1], [2]])
12012 @result{}2
12013 m4_apply([m4_join], [[|], [1], [2]])
12014 @result{}1|2
12015 @end example
12016 @end defmac
12018 @defmac m4_count (@var{arg}, @dots{})
12019 @msindex{count}
12020 This macro returns the decimal count of the number of arguments it was
12021 passed.
12022 @end defmac
12024 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12025 @msindex{curry}
12026 This macro performs argument currying.  The expansion of this macro is
12027 another macro name that expects exactly one argument; that argument is
12028 then appended to the @var{arg} list, and then @var{macro} is expanded
12029 with the resulting argument list.
12031 @example
12032 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12033 @result{}3, 2, 1
12034 @end example
12036 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12037 pass the definition of a builtin macro as the argument to the output of
12038 @code{m4_curry}; the empty string is used instead of the builtin token.
12039 This behavior is rectified by using M4 1.6 or newer.
12040 @end defmac
12042 @defmac m4_do (@var{arg}, @dots{})
12043 @msindex{do}
12044 This macro loops over its arguments and expands each @var{arg} in
12045 sequence.  Its main use is for readability; it allows the use of
12046 indentation and fewer @code{dnl} to result in the same expansion.  This
12047 macro guarantees that no expansion will be concatenated with subsequent
12048 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12049 @var{arg@dots{}}))}.
12051 @example
12052 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12053 m4_do([a],[b])c
12054 @result{}abc
12055 m4_unquote(m4_join([],[a],[b]))c
12056 @result{}3
12057 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12058 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12059 m4_do([a],[b])c
12060 @result{}ABC
12061 m4_unquote(m4_join([],[a],[b]))c
12062 @result{}3
12063 @end example
12064 @end defmac
12066 @defmac m4_dquote (@var{arg}, @dots{})
12067 @msindex{dquote}
12068 Return the arguments as a quoted list of quoted arguments.
12069 Conveniently, if there is just one @var{arg}, this effectively adds a
12070 level of quoting.
12071 @end defmac
12073 @defmac m4_dquote_elt (@var{arg}, @dots{})
12074 @msindex{dquote_elt}
12075 Return the arguments as a series of double-quoted arguments.  Whereas
12076 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12077 as many arguments as it was passed.
12078 @end defmac
12080 @defmac m4_echo (@var{arg}, @dots{})
12081 @msindex{echo}
12082 Return the arguments, with the same level of quoting.  Other than
12083 discarding whitespace after unquoted commas, this macro is a no-op.
12084 @end defmac
12086 @defmac m4_expand (@var{arg})
12087 @msindex{expand}
12088 Return the expansion of @var{arg} as a quoted string.  Whereas
12089 @code{m4_quote} is designed to collect expanded text into a single
12090 argument, @code{m4_expand} is designed to perform one level of expansion
12091 on quoted text.  One distinction is in the treatment of whitespace
12092 following a comma in the original @var{arg}.  Any time multiple
12093 arguments are collected into one with @code{m4_quote}, the M4 argument
12094 collection rules discard the whitespace.  However, with @code{m4_expand},
12095 whitespace is preserved, even after the expansion of macros contained in
12096 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
12097 would involve an unterminated comment, whereas expanding that same text
12098 as the argument to @code{m4_quote} runs into difficulty in finding the
12099 end of the argument.  Since manipulating diversions during argument
12100 collection is inherently unsafe, @code{m4_expand} issues an error if
12101 @var{arg} attempts to change the current diversion (@pxref{Diversion
12102 support}).
12104 @example
12105 m4_define([active], [ACT, IVE])dnl
12106 m4_define([active2], [[ACT, IVE]])dnl
12107 m4_quote(active, active)
12108 @result{}ACT,IVE,ACT,IVE
12109 m4_expand([active, active])
12110 @result{}ACT, IVE, ACT, IVE
12111 m4_quote(active2, active2)
12112 @result{}ACT, IVE,ACT, IVE
12113 m4_expand([active2, active2])
12114 @result{}ACT, IVE, ACT, IVE
12115 m4_expand([# m4_echo])
12116 @result{}# m4_echo
12117 m4_quote(# m4_echo)
12119 @result{}# m4_echo)
12120 @result{}
12121 @end example
12123 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12124 literal unbalanced quotes, but that quadrigraphs can be used when
12125 unbalanced output is necessary.  Likewise, unbalanced parentheses should
12126 be supplied with double quoting or a quadrigraph.
12128 @example
12129 m4_define([pattern], [[!@@<:@@]])dnl
12130 m4_define([bar], [BAR])dnl
12131 m4_expand([case $foo in
12132   m4_defn([pattern])@@:@}@@ bar ;;
12133   *[)] blah ;;
12134 esac])
12135 @result{}case $foo in
12136 @result{}  [![]) BAR ;;
12137 @result{}  *) blah ;;
12138 @result{}esac
12139 @end example
12140 @end defmac
12142 @defmac m4_ignore (@dots{})
12143 @msindex{ignore}
12144 This macro was introduced in Autoconf 2.62.  Expands to nothing,
12145 ignoring all of its arguments.  By itself, this isn't very useful.
12146 However, it can be used to conditionally ignore an arbitrary number of
12147 arguments, by deciding which macro name to apply to a list of arguments.
12148 @example
12149 dnl foo outputs a message only if [debug] is defined.
12150 m4_define([foo],
12151 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12152 @end example
12154 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12155 serve the same purpose, although it is less readable.
12156 @end defmac
12158 @defmac m4_make_list (@var{arg}, @dots{})
12159 @msindex{make_list}
12160 This macro exists to aid debugging of M4sugar algorithms.  Its net
12161 effect is similar to @code{m4_dquote}---it produces a quoted list of
12162 quoted arguments, for each @var{arg}.  The difference is that this
12163 version uses a comma-newline separator instead of just comma, to improve
12164 readability of the list; with the result that it is less efficient than
12165 @code{m4_dquote}.
12166 @example
12167 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12168 m4_dquote(zero, [one], [[two]])
12169 @result{}[0],[one],[[two]]
12170 m4_make_list(zero, [one], [[two]])
12171 @result{}[0],
12172 @result{}[one],
12173 @result{}[[two]]
12174 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12175 @result{} 0 1 two
12176 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12177 @result{} 0 1 two
12178 @end example
12179 @end defmac
12181 @c m4_noquote is too dangerous to document - it invokes macros that
12182 @c probably rely on @samp{[]} nested quoting for proper operation.  The
12183 @c user should generally prefer m4_unquote instead.
12185 @defmac m4_quote (@var{arg}, @dots{})
12186 @msindex{quote}
12187 Return the arguments as a single entity, i.e., wrap them into a pair of
12188 quotes.  This effectively collapses multiple arguments into one,
12189 although it loses whitespace after unquoted commas in the process.
12190 @end defmac
12192 @defmac m4_reverse (@var{arg}, @dots{})
12193 @msindex{reverse}
12194 Outputs each argument with the same level of quoting, but in reverse
12195 order, and with space following each comma for readability.
12197 @example
12198 m4_define([active], [ACT,IVE])
12199 @result{}
12200 m4_reverse(active, [active])
12201 @result{}active, IVE, ACT
12202 @end example
12203 @end defmac
12205 @defmac m4_unquote (@var{arg}, @dots{})
12206 @msindex{unquote}
12207 This macro was introduced in Autoconf 2.62.  Expand each argument,
12208 separated by commas.  For a single @var{arg}, this effectively removes a
12209 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12210 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
12211 this results in an unquoted list of expansions.  This is commonly used
12212 with @code{m4_split}, in order to convert a single quoted list into a
12213 series of quoted elements.
12214 @end defmac
12216 The following example aims at emphasizing the difference between several
12217 scenarios: not using these macros, using @code{m4_defn}, using
12218 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
12220 @example
12221 $ @kbd{cat example.m4}
12222 dnl Overquote, so that quotes are visible.
12223 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
12224 m4_define([a], [A])
12225 m4_define([mkargs], [1, 2[,] 3])
12226 m4_define([arg1], [[$1]])
12227 m4_divert([0])dnl
12228 show(a, b)
12229 show([a, b])
12230 show(m4_quote(a, b))
12231 show(m4_dquote(a, b))
12232 show(m4_expand([a, b]))
12234 arg1(mkargs)
12235 arg1([mkargs])
12236 arg1(m4_defn([mkargs]))
12237 arg1(m4_quote(mkargs))
12238 arg1(m4_dquote(mkargs))
12239 arg1(m4_expand([mkargs]))
12240 $ @kbd{autom4te -l m4sugar example.m4}
12241 $1 = A, $@@ = [A],[b]
12242 $1 = a, b, $@@ = [a, b]
12243 $1 = A,b, $@@ = [A,b]
12244 $1 = [A],[b], $@@ = [[A],[b]]
12245 $1 = A, b, $@@ = [A, b]
12248 mkargs
12249 1, 2[,] 3
12250 1,2, 3
12251 [1],[2, 3]
12252 1, 2, 3
12253 @end example
12256 @node Text processing Macros
12257 @subsection String manipulation in M4
12259 The following macros may be used to manipulate strings in M4.  Many of
12260 the macros in this section intentionally result in quoted strings as
12261 output, rather than subjecting the arguments to further expansions.  As
12262 a result, if you are manipulating text that contains active M4
12263 characters, the arguments are passed with single quoting rather than
12264 double.
12266 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
12267 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
12268   @ovar{if-uniq}, @ovar{if-duplicate})
12269 @msindex{append}
12270 @msindex{append_uniq}
12271 Redefine @var{macro-name} to its former contents with @var{separator}
12272 and @var{string} added at the end.  If @var{macro-name} was undefined
12273 before (but not if it was defined but empty), then no @var{separator} is
12274 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
12275 are expanded during this macro; instead, they are expanded when
12276 @var{macro-name} is invoked.
12278 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
12279 to grow strings without duplicating substrings.  Additionally,
12280 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
12281 @var{if-uniq} is expanded if @var{string} was appended, and
12282 @var{if-duplicate} is expanded if @var{string} was already present.
12283 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
12284 occurs within @var{string}, since that can lead to duplicates.
12286 Note that @code{m4_append} can scale linearly in the length of the final
12287 string, depending on the quality of the underlying M4 implementation,
12288 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
12289 If an algorithm can tolerate duplicates in the final string, use the
12290 former for speed.  If duplicates must be avoided, consider using
12291 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
12293 @example
12294 m4_define([active], [ACTIVE])dnl
12295 m4_append([sentence], [This is an])dnl
12296 m4_append([sentence], [ active ])dnl
12297 m4_append([sentence], [symbol.])dnl
12298 sentence
12299 @result{}This is an ACTIVE symbol.
12300 m4_undefine([active])dnl
12301 @result{}This is an active symbol.
12302 m4_append_uniq([list], [one], [, ], [new], [existing])
12303 @result{}new
12304 m4_append_uniq([list], [one], [, ], [new], [existing])
12305 @result{}existing
12306 m4_append_uniq([list], [two], [, ], [new], [existing])
12307 @result{}new
12308 m4_append_uniq([list], [three], [, ], [new], [existing])
12309 @result{}new
12310 m4_append_uniq([list], [two], [, ], [new], [existing])
12311 @result{}existing
12312 list
12313 @result{}one, two, three
12314 m4_dquote(list)
12315 @result{}[one],[two],[three]
12316 m4_append([list2], [one], [[, ]])dnl
12317 m4_append_uniq([list2], [two], [[, ]])dnl
12318 m4_append([list2], [three], [[, ]])dnl
12319 list2
12320 @result{}one, two, three
12321 m4_dquote(list2)
12322 @result{}[one, two, three]
12323 @end example
12324 @end defmac
12326 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
12327 @msindex{append_uniq_w}
12328 This macro was introduced in Autoconf 2.62.  It is similar to
12329 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
12330 separated list of words to append, and only appends unique words.
12331 @var{macro-name} is updated with a single space between new words.
12332 @example
12333 m4_append_uniq_w([numbers], [1 1 2])dnl
12334 m4_append_uniq_w([numbers], [ 2 3 ])dnl
12335 numbers
12336 @result{}1 2 3
12337 @end example
12338 @end defmac
12340 @defmac m4_chomp (@var{string})
12341 @defmacx m4_chomp_all (@var{string})
12342 @msindex{chomp}
12343 @msindex{chomp_all}
12344 Output @var{string} in quotes, but without a trailing newline.  The
12345 macro @code{m4_chomp} is slightly faster, and removes at most one
12346 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
12347 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
12348 and backslash does not influence the result.
12349 @end defmac
12351 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
12352   @var{suffix-1}, @ovar{suffix-2}, @dots{})
12353 @msindex{combine}
12354 This macro produces a quoted string containing the pairwise combination
12355 of every element of the quoted, comma-separated @var{prefix-list}, and
12356 every element from the @var{suffix} arguments.  Each pairwise
12357 combination is joined with @var{infix} in the middle, and successive
12358 pairs are joined by @var{separator}.  No expansion occurs on any of the
12359 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
12360 list is empty, but the lists can contain empty elements.
12361 @example
12362 m4_define([a], [oops])dnl
12363 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
12364 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
12365 m4_combine([, ], [[a], [b]], [-])
12366 @result{}
12367 m4_combine([, ], [[a], [b]], [-], [])
12368 @result{}a-, b-
12369 m4_combine([, ], [], [-], [1], [2])
12370 @result{}
12371 m4_combine([, ], [[]], [-], [1], [2])
12372 @result{}-1, -2
12373 @end example
12374 @end defmac
12376 @defmac m4_escape (@var{string})
12377 @msindex{escape}
12378 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
12379 within @var{string} into their respective quadrigraphs.  The result is
12380 still a quoted string.
12381 @end defmac
12383 @defmac m4_flatten (@var{string})
12384 @msindex{flatten}
12385 Flatten @var{string} into a single line.  Delete all backslash-newline
12386 pairs, and replace all remaining newlines with a space.  The result is
12387 still a quoted string.
12388 @end defmac
12390 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
12391 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
12392 @msindex{join}
12393 @msindex{joinall}
12394 Concatenate each @var{arg}, separated by @var{separator}.
12395 @code{joinall} uses every argument, while @code{join} omits empty
12396 arguments so that there are no back-to-back separators in the output.
12397 The result is a quoted string.
12398 @example
12399 m4_define([active], [ACTIVE])dnl
12400 m4_join([|], [one], [], [active], [two])
12401 @result{}one|active|two
12402 m4_joinall([|], [one], [], [active], [two])
12403 @result{}one||active|two
12404 @end example
12406 Note that if all you intend to do is join @var{args} with commas between
12407 them, to form a quoted list suitable for @code{m4_foreach}, it is more
12408 efficient to use @code{m4_dquote}.
12409 @end defmac
12411 @defmac m4_newline (@ovar{text})
12412 @msindex{newline}
12413 This macro was introduced in Autoconf 2.62, and expands to a newline,
12414 followed by any @var{text}.
12415 It is primarily useful for maintaining macro formatting, and ensuring
12416 that M4 does not discard leading whitespace during argument collection.
12417 @end defmac
12419 @defmac m4_normalize (@var{string})
12420 @msindex{normalize}
12421 Remove leading and trailing spaces and tabs, sequences of
12422 backslash-then-newline, and replace multiple spaces, tabs, and newlines
12423 with a single space.  This is a combination of @code{m4_flatten} and
12424 @code{m4_strip}.  To determine if @var{string} consists only of bytes
12425 that would be removed by @code{m4_normalize}, you can use
12426 @code{m4_ifblank}.
12427 @end defmac
12429 @defmac m4_re_escape (@var{string})
12430 @msindex{re_escape}
12431 Backslash-escape all characters in @var{string} that are active in
12432 regexps.
12433 @end defmac
12435 @defmac m4_split (@var{string}, @dvar{regexp, [\t ]+})
12436 @msindex{split}
12437 Split @var{string} into an M4 list of elements quoted by @samp{[} and
12438 @samp{]}, while keeping white space at the beginning and at the end.
12439 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
12440 If @var{string} is empty, the result is an empty list.
12441 @end defmac
12443 @defmac m4_strip (@var{string})
12444 @msindex{strip}
12445 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
12446 reduced to a single space, then leading and trailing spaces are removed.
12447 The result is still a quoted string.  Note that this does not interfere
12448 with newlines; if you want newlines stripped as well, consider
12449 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
12450 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
12451 @end defmac
12453 @defmac m4_text_box (@var{message}, @dvar{frame, -})
12454 @msindex{text_box}
12455 Add a text box around @var{message}, using @var{frame} as the border
12456 character above and below the message.  The frame correctly accounts for
12457 the subsequent expansion of @var{message}.  For example:
12458 @example
12459 m4_define([macro], [abc])dnl
12460 m4_text_box([macro])
12461 @result{}## --- ##
12462 @result{}## abc ##
12463 @result{}## --- ##
12464 @end example
12466 The @var{message} must contain balanced quotes and parentheses, although
12467 quadrigraphs can be used to work around this.
12468 @end defmac
12470 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
12471   @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
12472 @msindex{text_wrap}
12473 Break @var{string} into a series of whitespace-separated words, then
12474 output those words separated by spaces, and wrapping lines any time the
12475 output would exceed @var{width} columns.  If given, @var{prefix1} begins
12476 the first line, and @var{prefix} begins all wrapped lines.  If
12477 @var{prefix1} is longer than @var{prefix}, then the first line consists
12478 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
12479 padding is inserted so that the first word of @var{string} begins at the
12480 same indentation as all wrapped lines.  Note that using literal tab
12481 characters in any of the arguments will interfere with the calculation
12482 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
12483 words of @var{string}, although quadrigraphs are recognized.
12485 For some examples:
12486 @example
12487 m4_text_wrap([Short string */], [   ], [/* ], [20])
12488 @result{}/* Short string */
12489 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
12490 @result{}/* Much longer
12491 @result{}   string */
12492 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
12493 @result{}  --short Short doc.
12494 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
12495 @result{}  --too-wide
12496 @result{}          Short doc.
12497 m4_text_wrap([Super long documentation.], [     ],
12498              [  --too-wide ], 30)
12499 @result{}  --too-wide
12500 @result{}     Super long
12501 @result{}     documentation.
12502 @end example
12503 @end defmac
12505 @defmac m4_tolower (@var{string})
12506 @defmacx m4_toupper (@var{string})
12507 @msindex{tolower}
12508 @msindex{toupper}
12509 Return @var{string} with letters converted to upper or lower case,
12510 respectively.
12511 @end defmac
12513 @node Number processing Macros
12514 @subsection Arithmetic computation in M4
12516 The following macros facilitate integer arithmetic operations.
12517 Where a parameter is documented as taking an arithmetic expression, you
12518 can use anything that can be parsed by @code{m4_eval}.
12520 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
12521 @msindex{cmp}
12522 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
12523 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
12524 equal, and @samp{1} if @var{expr-1} is larger.
12525 @end defmac
12527 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
12528 @msindex{list_cmp}
12529 Compare the two M4 lists consisting of comma-separated arithmetic
12530 expressions, left to right.  Expand to @samp{-1} for the first element
12531 pairing where the value from @var{list-1} is smaller, @samp{1} where the
12532 value from @var{list-2} is smaller, or @samp{0} if both lists have the
12533 same values.  If one list is shorter than the other, the remaining
12534 elements of the longer list are compared against zero.
12535 @example
12536 m4_list_cmp([1, 0],       [1])
12537 @result{}0
12538 m4_list_cmp([1, [1 * 0]], [1, 0])
12539 @result{}0
12540 m4_list_cmp([1, 2],       [1, 0])
12541 @result{}1
12542 m4_list_cmp([1, [1+1], 3],[1, 2])
12543 @result{}1
12544 m4_list_cmp([1, 2, -3],   [1, 2])
12545 @result{}-1
12546 m4_list_cmp([1, 0],       [1, 2])
12547 @result{}-1
12548 m4_list_cmp([1],          [1, 2])
12549 @result{}-1
12550 @end example
12551 @end defmac
12553 @defmac m4_max (@var{arg}, @dots{})
12554 @msindex{max}
12555 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
12556 of the maximum arithmetic expression among all the arguments.
12557 @end defmac
12559 @defmac m4_min (@var{arg}, @dots{})
12560 @msindex{min}
12561 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
12562 of the minimum arithmetic expression among all the arguments.
12563 @end defmac
12565 @defmac m4_sign (@var{expr})
12566 @msindex{sign}
12567 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
12568 @samp{1} if it is positive, and @samp{0} if it is zero.
12569 @end defmac
12571 @anchor{m4_version_compare}
12572 @defmac m4_version_compare (@var{version-1}, @var{version-2})
12573 @msindex{version_compare}
12574 This macro was introduced in Autoconf 2.53, but had a number of
12575 usability limitations that were not lifted until Autoconf 2.62.  Compare
12576 the version strings @var{version-1} and @var{version-2}, and expand to
12577 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
12578 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
12579 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
12580 element is a number along with optional case-insensitive letters
12581 designating beta releases.  The comparison stops at the leftmost element
12582 that contains a difference, although a 0 element compares equal to a
12583 missing element.
12585 It is permissible to include commit identifiers in @var{version}, such
12586 as an abbreviated SHA1 of the commit, provided there is still a
12587 monotonically increasing prefix to allow for accurate version-based
12588 comparisons.  For example, this paragraph was written when the
12589 development snapshot of autoconf claimed to be at version
12590 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
12591 abbreviated commit identification of @samp{dc51}.
12593 @example
12594 m4_version_compare([1.1], [2.0])
12595 @result{}-1
12596 m4_version_compare([2.0b], [2.0a])
12597 @result{}1
12598 m4_version_compare([1.1.1], [1.1.1a])
12599 @result{}-1
12600 m4_version_compare([1.2], [1.1.1a])
12601 @result{}1
12602 m4_version_compare([1.0], [1])
12603 @result{}0
12604 m4_version_compare([1.1pre], [1.1PRE])
12605 @result{}0
12606 m4_version_compare([1.1a], [1,10])
12607 @result{}-1
12608 m4_version_compare([2.61a], [2.61a-248-dc51])
12609 @result{}-1
12610 m4_version_compare([2.61b], [2.61a-248-dc51])
12611 @result{}1
12612 @end example
12613 @end defmac
12615 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
12616   @dvar{if-old, m4_fatal})
12617 @msindex{version_prereq}
12618 Compares @var{version} against the version of Autoconf currently
12619 running.  If the running version is at @var{version} or newer, expand
12620 @var{if-new-enough}, but if @var{version} is larger than the version
12621 currently executing, expand @var{if-old}, which defaults to printing an
12622 error message and exiting m4sugar with status 63.  When given only one
12623 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
12624 Remember that the autoconf philosophy favors feature checks over version
12625 checks.
12626 @end defmac
12628 @node Set manipulation Macros
12629 @subsection Set manipulation in M4
12630 @cindex Set manipulation
12631 @cindex Data structure, set
12632 @cindex Unordered set manipulation
12634 Sometimes, it is necessary to track a set of data, where the order does
12635 not matter and where there are no duplicates in the set.  The following
12636 macros facilitate set manipulations.  Each set is an opaque object,
12637 which can only be accessed via these basic operations.  The underlying
12638 implementation guarantees linear scaling for set creation, which is more
12639 efficient than using the quadratic @code{m4_append_uniq}.  Both set
12640 names and values can be arbitrary strings, except for unbalanced quotes.
12641 This implementation ties up memory for removed elements until the next
12642 operation that must traverse all the elements of a set; and although
12643 that may slow down some operations until the memory for removed elements
12644 is pruned, it still guarantees linear performance.
12646 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
12647 @msindex{set_add}
12648 Adds the string @var{value} as a member of set @var{set}.  Expand
12649 @var{if-uniq} if the element was added, or @var{if-dup} if it was
12650 previously in the set.  Operates in amortized constant time, so that set
12651 creation scales linearly.
12652 @end defmac
12654 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
12655 @msindex{set_add_all}
12656 Adds each @var{value} to the set @var{set}.  This is slightly more
12657 efficient than repeatedly invoking @code{m4_set_add}.
12658 @end defmac
12660 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
12661  @ovar{if-absent})
12662 @msindex{set_contains}
12663 Expands @var{if-present} if the string @var{value} is a member of
12664 @var{set}, otherwise @var{if-absent}.
12666 @example
12667 m4_set_contains([a], [1], [yes], [no])
12668 @result{}no
12669 m4_set_add([a], [1], [added], [dup])
12670 @result{}added
12671 m4_set_add([a], [1], [added], [dup])
12672 @result{}dup
12673 m4_set_contains([a], [1], [yes], [no])
12674 @result{}yes
12675 m4_set_remove([a], [1], [removed], [missing])
12676 @result{}removed
12677 m4_set_contains([a], [1], [yes], [no])
12678 @result{}no
12679 m4_set_remove([a], [1], [removed], [missing])
12680 @result{}missing
12681 @end example
12682 @end defmac
12684 @defmac m4_set_contents (@var{set}, @ovar{sep})
12685 @defmacx m4_set_dump (@var{set}, @ovar{sep})
12686 @msindex{set_contents}
12687 @msindex{set_dump}
12688 Expands to a single string consisting of all the members of the set
12689 @var{set}, each separated by @var{sep}, which is not expanded.
12690 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
12691 memory occupied by removed elements, while @code{m4_set_dump} is a
12692 faster one-shot action that also deletes the set.  No provision is made
12693 for disambiguating members that contain a non-empty @var{sep} as a
12694 substring; use @code{m4_set_empty} to distinguish between an empty set
12695 and the set containing only the empty string.  The order of the output
12696 is unspecified; in the current implementation, part of the speed of
12697 @code{m4_set_dump} results from using a different output order than
12698 @code{m4_set_contents}.  These macros scale linearly in the size of the
12699 set before memory pruning, and @code{m4_set_contents([@var{set}],
12700 [@var{sep}])} is faster than
12701 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
12703 @example
12704 m4_set_add_all([a], [1], [2], [3])
12705 @result{}
12706 m4_set_contents([a], [-])
12707 @result{}1-2-3
12708 m4_joinall([-]m4_set_listc([a]))
12709 @result{}1-2-3
12710 m4_set_dump([a], [-])
12711 @result{}3-2-1
12712 m4_set_contents([a])
12713 @result{}
12714 m4_set_add([a], [])
12715 @result{}
12716 m4_set_contents([a], [-])
12717 @result{}
12718 @end example
12719 @end defmac
12721 @defmac m4_set_delete (@var{set})
12722 @msindex{set_delete}
12723 Delete all elements and memory associated with @var{set}.  This is
12724 linear in the set size, and faster than removing one element at a time.
12725 @end defmac
12727 @defmac m4_set_difference (@var{seta}, @var{setb})
12728 @defmacx m4_set_intersection (@var{seta}, @var{setb})
12729 @defmacx m4_set_union (@var{seta}, @var{setb})
12730 @msindex{set_difference}
12731 @msindex{set_intersection}
12732 @msindex{set_union}
12733 Compute the relation between @var{seta} and @var{setb}, and output the
12734 result as a list of quoted arguments without duplicates and with a
12735 leading comma.  Set difference selects the elements in @var{seta} but
12736 not @var{setb}, intersection selects only elements in both sets, and
12737 union selects elements in either set.  These actions are linear in the
12738 sum of the set sizes.  The leading comma is necessary to distinguish
12739 between no elements and the empty string as the only element.
12741 @example
12742 m4_set_add_all([a], [1], [2], [3])
12743 @result{}
12744 m4_set_add_all([b], [3], [], [4])
12745 @result{}
12746 m4_set_difference([a], [b])
12747 @result{},1,2
12748 m4_set_difference([b], [a])
12749 @result{},,4
12750 m4_set_intersection([a], [b])
12751 @result{},3
12752 m4_set_union([a], [b])
12753 @result{},1,2,3,,4
12754 @end example
12755 @end defmac
12757 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
12758 @msindex{set_empty}
12759 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
12760 expand @var{if-elements}.  This macro operates in constant time.  Using
12761 this macro can help disambiguate output from @code{m4_set_contents} or
12762 @code{m4_set_list}.
12763 @end defmac
12765 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
12766 @msindex{set_foreach}
12767 For each element in the set @var{set}, expand @var{action} with the
12768 macro @var{variable} defined as the set element.  Behavior is
12769 unspecified if @var{action} recursively lists the contents of @var{set}
12770 (although listing other sets is acceptable), or if it modifies the set
12771 in any way other than removing the element currently contained in
12772 @var{variable}.  This macro is faster than the corresponding
12773 @code{m4_foreach([@var{variable}],
12774 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
12775 although @code{m4_set_map} might be faster still.
12777 @example
12778 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
12779 @result{}
12780 m4_set_contents([a])
12781 @result{}12345
12782 m4_set_foreach([a], [i],
12783   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
12784 @result{}24
12785 m4_set_contents([a])
12786 @result{}135
12787 @end example
12788 @end defmac
12790 @defmac m4_set_list (@var{set})
12791 @defmacx m4_set_listc (@var{set})
12792 @msindex{set_list}
12793 @msindex{set_listc}
12794 Produce a list of arguments, where each argument is a quoted element
12795 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
12796 by adding a leading comma if there are any set elements, whereas the
12797 variant @code{m4_set_list} cannot distinguish between an empty set and a
12798 set containing only the empty string.  These can be directly used in
12799 macros that take multiple arguments, such as @code{m4_join} or
12800 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
12801 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
12802 memory occupied by removed elements is reclaimed during these macros.
12804 @example
12805 m4_set_add_all([a], [1], [2], [3])
12806 @result{}
12807 m4_set_list([a])
12808 @result{}1,2,3
12809 m4_set_list([b])
12810 @result{}
12811 m4_set_listc([b])
12812 @result{}
12813 m4_count(m4_set_list([b]))
12814 @result{}1
12815 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
12816 @result{}0
12817 m4_set_add([b], [])
12818 @result{}
12819 m4_set_list([b])
12820 @result{}
12821 m4_set_listc([b])
12822 @result{},
12823 m4_count(m4_set_list([b]))
12824 @result{}1
12825 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
12826 @result{}1
12827 @end example
12828 @end defmac
12830 @defmac m4_set_map (@var{set}, @var{action})
12831 @msindex{set_map}
12832 For each element in the set @var{set}, expand @var{action} with a single
12833 argument of the set element.  Behavior is unspecified if @var{action}
12834 recursively lists the contents of @var{set} (although listing other sets
12835 is acceptable), or if it modifies the set in any way other than removing
12836 the element passed as an argument.  This macro is faster than either
12837 corresponding counterpart of
12838 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
12839 @code{m4_set_foreach([@var{set}], [var],
12840 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
12841 if more than one argument is needed for @var{action}, although it is
12842 more efficient to use @code{m4_set_map_sep} in that case.
12843 @end defmac
12845 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
12846 @msindex{set_map_sep}
12847 For each element in the set @var{set}, expand
12848 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
12849 between elements.  Behavior is unspecified if the expansion recursively
12850 lists the contents of @var{set} (although listing other sets
12851 is acceptable), or if it modifies the set in any way other than removing
12852 the element visited by the expansion.  This macro provides the most
12853 efficient means for non-destructively visiting the elements of a set; in
12854 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
12855 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
12856 @end defmac
12858 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
12859  @ovar{if-absent})
12860 @msindex{set_remove}
12861 If @var{value} is an element in the set @var{set}, then remove it and
12862 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
12863 operates in constant time so that multiple removals will scale linearly
12864 rather than quadratically; but when used outside of
12865 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
12866 until the set is later
12867 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
12868 other set operations are then less efficient between the time of element
12869 removal and subsequent memory compaction, but still maintain their
12870 guaranteed scaling performance.
12871 @end defmac
12873 @defmac m4_set_size (@var{set})
12874 @msindex{set_size}
12875 Expand to the size of the set @var{set}.  This implementation operates
12876 in constant time, and is thus more efficient than
12877 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
12878 @end defmac
12881 @node Forbidden Patterns
12882 @subsection Forbidden Patterns
12883 @cindex Forbidden patterns
12884 @cindex Patterns, forbidden
12886 M4sugar provides a means to define suspicious patterns, patterns
12887 describing tokens which should not be found in the output.  For
12888 instance, if an Autoconf @file{configure} script includes tokens such as
12889 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
12890 wrong (typically a macro was not evaluated because of overquotation).
12892 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
12893 Additional layers, such as M4sh and Autoconf, add additional forbidden
12894 patterns to the list.
12896 @defmac m4_pattern_forbid (@var{pattern})
12897 @msindex{pattern_forbid}
12898 Declare that no token matching @var{pattern} must be found in the output.
12899 Comments are not checked; this can be a problem if, for instance, you
12900 have some macro left unexpanded after an @samp{#include}.  No consensus
12901 is currently found in the Autoconf community, as some people consider it
12902 should be valid to name macros in comments (which doesn't make sense to
12903 the authors of this documentation: input, such as macros, should be
12904 documented by @samp{dnl} comments; reserving @samp{#}-comments to
12905 document the output).
12906 @end defmac
12908 Of course, you might encounter exceptions to these generic rules, for
12909 instance you might have to refer to @samp{$m4_flags}.
12911 @defmac m4_pattern_allow (@var{pattern})
12912 @msindex{pattern_allow}
12913 Any token matching @var{pattern} is allowed, including if it matches an
12914 @code{m4_pattern_forbid} pattern.
12915 @end defmac
12917 @node Debugging via autom4te
12918 @section Debugging via autom4te
12919 @cindex debugging tips
12920 @cindex autom4te debugging tips
12921 @cindex m4sugar debugging tips
12922 At times, it is desirable to see what was happening inside m4, to see
12923 why output was not matching expectations.  However, post-processing done
12924 by @command{autom4te} means that directly using the m4 builtin
12925 @code{m4_traceon} is likely to interfere with operation.  Also, frequent
12926 diversion changes and the concept of forbidden tokens make it difficult
12927 to use @code{m4_defn} to generate inline comments in the final output.
12929 There are a couple of tools to help with this.  One is the use of the
12930 @option{--trace} option provided by @command{autom4te} (as well as each
12931 of the programs that wrap @command{autom4te}, such as
12932 @command{autoconf}), in order to inspect when a macro is called and with
12933 which arguments.  For example, when this paragraph was written, the
12934 autoconf version could be found by:
12936 @example
12937 $ @kbd{autoconf --trace=AC_INIT}
12938 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
12939 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
12940 version is 2.63b.95-3963
12941 @end example
12943 Another trick is to print out the expansion of various m4 expressions to
12944 standard error or to an independent file, with no further m4 expansion,
12945 and without interfering with diversion changes or the post-processing
12946 done to standard output.  @code{m4_errprintn} shows a given expression
12947 on standard error.  For example, if you want to see the expansion of an
12948 autoconf primitive or of one of your autoconf macros, you can do it like
12949 this:
12951 @example
12952 $ @kbd{cat <<\EOF > configure.ac}
12953 AC_INIT
12954 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
12955 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
12956 AC_OUTPUT
12958 $ @kbd{autoconf}
12959 @error{}The definition of AC_DEFINE_UNQUOTED:
12960 @error{}_AC_DEFINE_Q([], $@@)
12961 @end example
12963 @node Programming in M4sh
12964 @chapter Programming in M4sh
12966 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
12967 scripts.  This name was coined by Lars J. Aas, who notes that,
12968 according to the Webster's Revised Unabridged Dictionary (1913):
12970 @quotation
12971 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
12972 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
12974 @enumerate 1
12975 @item
12976 A mass of mixed ingredients reduced to a soft pulpy state by beating or
12977 pressure@enddots{}
12979 @item
12980 A mixture of meal or bran and water fed to animals.
12982 @item
12983 A mess; trouble.  [Obs.] --Beau.@: & Fl.
12984 @end enumerate
12985 @end quotation
12987 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
12988 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
12989 and environment variable namespace @samp{^as_}, and the here-document
12990 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
12991 define your own macros or output shell code that conflicts with these
12992 namespaces.
12994 @menu
12995 * Common Shell Constructs::     Portability layer for common shell constructs
12996 * Polymorphic Variables::       Support for indirect variable names
12997 * Initialization Macros::       Macros to establish a sane shell environment
12998 * File Descriptor Macros::      File descriptor macros for input and output
12999 @end menu
13001 @node Common Shell Constructs
13002 @section Common Shell Constructs
13004 M4sh provides portable alternatives for some common shell constructs
13005 that unfortunately are not portable in practice.
13007 @c Deprecated, to be replaced by a better API
13008 @ignore
13009 @defmac AS_BASENAME (@var{file-name})
13010 @asindex{BASENAME}
13011 Output the non-directory portion of @var{file-name}.  For example,
13012 if @code{$file} is @samp{/one/two/three}, the command
13013 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13014 @end defmac
13015 @end ignore
13017 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13018   @dots{}, @ovar{default})
13019 @asindex{CASE}
13020 Expand into a shell @samp{case} statement, where @var{word} is matched
13021 against one or more patterns.  @var{if-matched} is run if the
13022 corresponding pattern matched @var{word}, else @var{default} is run.
13023 Avoids several portability issues (@pxref{case, , Limitations of Shell
13024 Builtins}).
13025 @end defmac
13027 @c Deprecated, to be replaced by a better API
13028 @defmac AS_DIRNAME (@var{file-name})
13029 @asindex{DIRNAME}
13030 Output the directory portion of @var{file-name}.  For example,
13031 if @code{$file} is @samp{/one/two/three}, the command
13032 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13034 This interface may be improved in the future to avoid forks and losing
13035 trailing newlines.
13036 @end defmac
13038 @defmac AS_ECHO (@var{word})
13039 @asindex{ECHO}
13040 Emits @var{word} to the standard output, followed by a newline.  @var{word}
13041 must be a single shell word (typically a quoted string).  The bytes of
13042 @var{word} are output as-is, even if it starts with "-" or contains "\".
13043 Redirections can be placed outside the macro invocation.  This is much
13044 more portable than using @command{echo} (@pxref{echo, , Limitations of
13045 Shell Builtins}).
13046 @end defmac
13048 @defmac AS_ECHO_N (@var{word})
13049 @asindex{ECHO_N}
13050 Emits @var{word} to the standard output, without a following newline.
13051 @var{word} must be a single shell word (typically a quoted string) and,
13052 for portability, should not include more than one newline.  The bytes of
13053 @var{word} are output as-is, even if it starts with "-" or contains "\".
13054 Redirections can be placed outside the macro invocation.
13055 @end defmac
13057 @defmac AS_ESCAPE (@var{string}, @dvar{chars, `\"$})
13058 @asindex{ESCAPE}
13059 Expands to @var{string}, with any characters in @var{chars} escaped with
13060 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
13061 and only contain characters from the set @samp{`\"$}; however,
13062 characters may be safely listed more than once in @var{chars} for the
13063 sake of syntax highlighting editors.  The current implementation expands
13064 @var{string} after adding escapes; if @var{string} contains macro calls
13065 that in turn expand to text needing shell quoting, you can use
13066 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13068 The default for @var{chars} (@samp{\"$`}) is the set of characters
13069 needing escapes when @var{string} will be used literally within double
13070 quotes.  One common variant is the set of characters to protect when
13071 @var{string} will be used literally within back-ticks or an unquoted
13072 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
13073 be used to form a double-quoted string containing the same expansions
13074 that would have occurred if @var{string} were expanded in an unquoted
13075 here-document; however, when using this variant, care must be taken that
13076 @var{string} does not use double quotes within complex variable
13077 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13078 with improper escapes.
13080 This macro is often used with @code{AS_ECHO}.  For an example, observe
13081 the output generated by the shell code generated from this snippet:
13083 @example
13084 foo=bar
13085 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13086 @result{}"$foo" = "bar"
13087 m4_define([macro], [a, [\b]])
13088 AS_ECHO(["AS_ESCAPE([[macro]])"])
13089 @result{}macro
13090 AS_ECHO(["AS_ESCAPE([macro])"])
13091 @result{}a, b
13092 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13093 @result{}a, \b
13094 @end example
13096 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13097 @comment the case of @var{string} that does not contain '.
13098 To escape a string that will be placed within single quotes, use:
13100 @example
13101 m4_bpatsubst([[@var{string}]], ['], ['\\''])
13102 @end example
13103 @end defmac
13105 @defmac AS_EXIT (@dvar{status, $?})
13106 @asindex{EXIT}
13107 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13108 This macro
13109 works around shells that see the exit status of the command prior to
13110 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13111 of Shell Builtins}).
13112 @end defmac
13114 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13115 @asindex{IF}
13116 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
13117 run shell code @var{run-if-true1}, else examine further tests.  If no test
13118 exits with a zero status, run shell code @var{run-if-false}, with
13119 simplifications if either @var{run-if-true1} or @var{run-if-false}
13120 is empty.  For example,
13122 @example
13123 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13124       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13125       [echo foo not specified])
13126 @end example
13128 @noindent
13129 ensures any required macros of @code{HANDLE_FOO}
13130 are expanded before the first test.
13131 @end defmac
13133 @defmac AS_MKDIR_P (@var{file-name})
13134 @asindex{MKDIR_P}
13135 Make the directory @var{file-name}, including intervening directories
13136 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
13137 except that it is portable to older versions of @command{mkdir} that
13138 lack support for the @option{-p} option or for the @option{--}
13139 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
13140 @code{AS_MKDIR_P}
13141 succeeds if @var{file-name} is a symbolic link to an existing directory,
13142 even though Posix is unclear whether @samp{mkdir -p} should
13143 succeed in that case.  If creation of @var{file-name} fails, exit the
13144 script.
13146 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
13147 @end defmac
13149 @defmac AS_SET_STATUS (@var{status})
13150 @asindex{SET_STATUS}
13151 Emit shell code to set the value of @samp{$?} to @var{status}, as
13152 efficiently as possible.  However, this is not guaranteed to abort a
13153 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
13154 Builtins}).  This should also be used at the end of a complex shell
13155 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
13156 a @acronym{DJGPP} shell bug.
13157 @end defmac
13159 @defmac AS_TR_CPP (@var{expression})
13160 @asindex{TR_CPP}
13161 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
13162 For example:
13164 @example
13165 # This outputs "#define HAVE_CHAR_P 1".
13166 # Notice the m4 quoting around #, to prevent an m4 comment
13167 type="char *"
13168 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
13169 @end example
13170 @end defmac
13172 @defmac AS_TR_SH (@var{expression})
13173 @asindex{TR_SH}
13174 Transform @var{expression} into a valid shell variable name.  For example:
13176 @example
13177 # This outputs "Have it!".
13178 header="sys/some file.h"
13179 AS_TR_SH([HAVE_$header])=yes
13180 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
13181 @end example
13182 @end defmac
13184 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
13185 @asindex{SET_CATFILE}
13186 Set the shell variable @var{var} to @var{dir}/@var{file}, but
13187 optimizing the common cases (@var{dir} or @var{file} is @samp{.},
13188 @var{file} is absolute, etc.).
13189 @end defmac
13191 @defmac AS_UNSET (@var{var})
13192 @asindex{UNSET}
13193 Unsets the shell variable @var{var}, working around bugs in older
13194 shells (@pxref{unset, , Limitations of Shell
13195 Builtins}).  @var{var} can be a literal or indirect variable name.
13196 @end defmac
13198 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
13199   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
13200 @asindex{VERSION_COMPARE}
13201 Compare two strings @var{version-1} and @var{version-2}, possibly
13202 containing shell variables, as version strings, and expand
13203 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
13204 depending upon the result.
13205 The algorithm to compare is similar to the one used by strverscmp in
13206 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
13207 The @acronym{GNU} C Library}).
13208 @end defmac
13210 @node Polymorphic Variables
13211 @section Support for indirect variable names
13212 @cindex variable name indirection
13213 @cindex polymorphic variable name
13214 @cindex indirection, variable name
13216 Often, it is convenient to write a macro that will emit shell code
13217 operating on a shell variable.  The simplest case is when the variable
13218 name is known.  But a more powerful idiom is writing shell code that can
13219 work through an indirection, where another variable or command
13220 substitution produces the name of the variable to actually manipulate.
13221 M4sh supports the notion of polymorphic shell variables, making it easy
13222 to write a macro that can deal with either literal or indirect variable
13223 names and output shell code appropriate for both use cases.  Behavior is
13224 undefined if expansion of an indirect variable does not result in a
13225 literal variable name.
13227 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not})
13228 @asindex{LITERAL_IF}
13229 If the expansion of @var{expression} is definitely a shell literal,
13230 expand @var{if-literal}.  If the expansion of @var{expression} looks
13231 like it might contain shell indirections (such as @code{$var} or
13232 @code{`expr`}), then @var{if-not} is expanded.  In order to reduce the
13233 time spent deciding whether an expression is literal, the implementation
13234 is somewhat conservative (for example, @samp{'[$]'} is a single-quoted
13235 shell literal, but causes @var{if-not} to be expanded).  While this
13236 macro is often used for recognizing shell variable names, it can also be
13237 used in other contexts.
13239 @example
13240 AC_DEFUN([MY_ACTION],
13241 [AS_LITERAL_IF([$1],
13242 [echo "$1"],
13243 [AS_VAR_COPY([tmp], [$1])
13244 echo "$tmp"])])
13245 @end example
13246 @end defmac
13248 @defmac AS_VAR_APPEND (@var{var}, @var{text})
13249 @asindex{VAR_APPEND}
13250 Emit shell code to append the shell expansion of @var{text} to the end
13251 of the current contents of the polymorphic shell variable @var{var},
13252 taking advantage of shells that provide the @samp{+=} extension for more
13253 efficient scaling.
13255 For situations where the final contents of @var{var} are relatively
13256 short (less than 256 bytes), it is more efficient to use the simpler
13257 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
13258 polymorphic equivalent of @code{AS_VAR_COPY([tmp], [@var{var}])} and
13259 @code{AS_VAR_SET([@var{var}], ["$tmp"@var{text}])}).  But in the case
13260 when the script will be repeatedly appending text into @code{var},
13261 issues of scaling start to become apparent.  A naive implementation
13262 requires execution time linear to the length of the current contents of
13263 @var{var} as well as the length of @var{text} for a single append, for
13264 an overall quadratic scaling with multiple appends.  This macro takes
13265 advantage of shells which provide the extension
13266 @code{@var{var}+=@var{text}}, which can provide amortized constant time
13267 for a single append, for an overall linear scaling with multiple
13268 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
13269 @var{text} be quoted properly to avoid field splitting and file name
13270 expansion.
13271 @end defmac
13273 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
13274 @asindex{VAR_ARITH}
13275 Emit shell code to compute the arithmetic expansion of @var{expression},
13276 assigning the result as the contents of the polymorphic shell variable
13277 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
13278 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
13279 syntax for a valid @var{expression} is rather limited: all operators
13280 must occur as separate shell arguments and with proper quoting, there is
13281 no portable equality operator, all variables containing numeric values
13282 must be expanded prior to the computation, all numeric values must be
13283 provided in decimal without leading zeroes, and the first shell argument
13284 should not be a negative number.  In the following example, this snippet
13285 will print @samp{(2+3)*4 == 20}.
13287 @example
13288 bar=3
13289 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
13290 echo "(2+$bar)*4 == $foo"
13291 @end example
13292 @end defmac
13294 @defmac AS_VAR_COPY (@var{dest}, @var{source})
13295 @asindex{VAR_COPY}
13296 Emit shell code to assign the contents of the polymorphic shell variable
13297 @var{source} to the polymorphic shell variable @var{dest}.  For example,
13298 executing this M4sh snippet will output @samp{bar hi}:
13300 @example
13301 foo=bar bar=hi
13302 AS_VAR_COPY([a], [foo])
13303 AS_VAR_COPY([b], [$foo])
13304 echo "$a $b"
13305 @end example
13307 When it is necessary to access the contents of an indirect variable
13308 inside a shell double-quoted context, the recommended idiom is to first
13309 copy the contents into a temporary literal shell variable.
13311 @smallexample
13312 for header in stdint_h inttypes_h ; do
13313   AS_VAR_COPY([var], [ac_cv_header_$header])
13314   echo "$header detected: $var"
13315 done
13316 @end smallexample
13317 @end defmac
13319 @comment AS_VAR_GET is intentionally undocumented; it can't handle
13320 @comment trailing newlines uniformly, and forks too much.
13322 @defmac AS_VAR_IF (@var{var}, @ovar{value}, @ovar{if-equal}, @
13323   @ovar{if-not-equal})
13324 @asindex{VAR_IF}
13325 Output a shell conditional statement.  If the contents of the
13326 polymorphic shell variable @var{var} match the string @var{value},
13327 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  Avoids
13328 shell bugs if an interrupt signal arrives while a command substitution
13329 in @var{var} is being expanded.
13330 @end defmac
13332 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
13333 @defmacx AS_VAR_POPDEF (@var{m4-name})
13334 @asindex{VAR_PUSHDEF}
13335 @asindex{VAR_POPDEF}
13336 @cindex composing variable names
13337 @cindex variable names, composing
13338 A common M4sh idiom involves composing shell variable names from an m4
13339 argument (for example, writing a macro that uses a cache variable).
13340 @var{value} can be an arbitrary string, which will be transliterated
13341 into a valid shell name by @code{AS_TR_SH}.  In order to access the
13342 composed variable name based on @var{value}, it is easier to declare a
13343 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
13344 that macro as the argument to subsequent @code{AS_VAR} macros as a
13345 polymorphic variable name, and finally free the temporary macro with
13346 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
13347 to avoid excess newlines in the output.
13349 Here is an involved example, that shows the power of writing macros that
13350 can handle composed shell variable names:
13352 @example
13353 m4_define([MY_CHECK_HEADER],
13354 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
13355 AS_VAR_IF([my_Header], [yes], [echo "header $1 available"])dnl
13356 AS_VAR_POPDEF([my_Header])dnl
13358 MY_CHECK_HEADER([stdint.h])
13359 for header in inttypes.h stdlib.h ; do
13360   MY_CHECK_HEADER([$header])
13361 done
13362 @end example
13364 @noindent
13365 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
13366 variable names.  In the first invocation, the m4 argument is
13367 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
13368 As a result, the temporary macro @code{my_Header} expands to the literal
13369 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
13370 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
13371 temporary macro @code{my_Header} expands to the indirect shell name
13372 @samp{$as_my_Header}.  During the shell execution of the for loop, when
13373 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
13374 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
13375 platform where all three headers have been previously detected, the
13376 output of the script will include:
13378 @smallexample
13379 header stdint.h detected
13380 header inttypes.h detected
13381 header stdlib.h detected
13382 @end smallexample
13383 @end defmac
13385 @defmac AS_VAR_SET (@var{var}, @ovar{value})
13386 @asindex{VAR_SET}
13387 Emit shell code to assign the contents of the polymorphic shell variable
13388 @var{var} to the shell expansion of @var{value}.  @var{value} is not
13389 subject to field splitting or file name expansion, so if command
13390 substitution is used, it may be done with @samp{`""`} rather than using
13391 an intermediate variable (@pxref{Shell Substitutions}).  However,
13392 @var{value} does undergo rescanning for additional macro names; behavior
13393 is unspecified if late expansion results in any shell meta-characters.
13394 @end defmac
13396 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
13397 @asindex{VAR_SET_IF}
13398 Emit a shell conditional statement, which executes @var{if-set} if the
13399 polymorphic shell variable @code{var} is set to any value, and
13400 @var{if-undef} otherwise.
13401 @end defmac
13403 @defmac AS_VAR_TEST_SET (@var{var})
13404 @asindex{VAR_TEST_SET}
13405 Emit a shell statement that results in a successful exit status only if
13406 the polymorphic shell variable @code{var} is set.
13407 @end defmac
13409 @node Initialization Macros
13410 @section Initialization Macros
13412 @defmac AS_BOURNE_COMPATIBLE
13413 @asindex{BOURNE_COMPATIBLE}
13414 Set up the shell to be more compatible with the Bourne shell as
13415 standardized by Posix, if possible.  This may involve setting
13416 environment variables, or setting options, or similar
13417 implementation-specific actions.  This macro is deprecated, since
13418 @code{AS_INIT} already invokes it.
13419 @end defmac
13421 @defmac AS_INIT
13422 @asindex{INIT}
13423 @evindex LC_ALL
13424 @evindex SHELL
13425 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
13426 outputs the @code{#! /bin/sh} line, a notice about where the output was
13427 generated from, and code to sanitize the environment for the rest of the
13428 script.  Among other initializations, this sets @env{SHELL} to the shell
13429 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
13430 ensure the C locale.  Finally, it changes the current diversion to
13431 @code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
13432 and @code{AT_INIT}, so shell code in @file{configure},
13433 @file{config.status}, and @file{testsuite} all benefit from a sanitized
13434 shell environment.
13435 @end defmac
13437 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
13438 @asindex{INIT_GENERATED}
13439 Emit shell code to start the creation of a subsidiary shell script in
13440 @var{file}, including changing @var{file} to be executable.  This macro
13441 populates the child script with information learned from the parent
13442 (thus, the emitted code is equivalent in effect, but more efficient,
13443 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
13444 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
13445 beginning of the child, prior to the shell initialization code, and is
13446 subject to parameter expansion, command substitution, and backslash
13447 quote removal.  The
13448 parent script should check the exit status after this macro, in case
13449 @var{file} could not be properly created (for example, if the disk was
13450 full).  If successfully created, the parent script can then proceed to
13451 append additional M4sh constructs into the child script.
13453 Note that the child script starts life without a log file open, so if
13454 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
13455 must temporarily disable any attempts to use the log file until after
13456 emitting code to open a log within the child.  On the other hand, if the
13457 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
13458 @samp{1}, then the child script already has code that copies stdout to
13459 that descriptor.  Currently, the suggested
13460 idiom for writing a M4sh shell script from within another script is:
13462 @example
13463 AS_INIT_GENERATED([@var{file}], [[# My child script.
13464 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
13465 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
13466 cat >> "@var{file}" <<\__EOF__
13467 # Code to initialize AS_MESSAGE_LOG_FD
13468 m4_popdef([AS_MESSAGE_LOG_FD])dnl
13469 # Additional code
13470 __EOF__
13471 @end example
13473 This, however, may change in the future as the M4sh interface is
13474 stabilized further.
13476 Also, be aware that use of @env{LINENO} within the child script may
13477 report line numbers relative to their location in the parent script,
13478 even when using @code{AS_LINENO_PREPARE}, if the parent script was
13479 unable to locate a shell with working @env{LINENO} support.
13480 @end defmac
13482 @defmac AS_LINENO_PREPARE
13483 @asindex{LINENO_PREPARE}
13484 @evindex LINENO
13485 Find a shell that supports the special variable @env{LINENO}, which
13486 contains the number of the currently executing line.  This macro is
13487 automatically invoked by @code{AC_INIT} in configure scripts.
13488 @end defmac
13490 @defmac AS_ME_PREPARE
13491 @asindex{ME_PREPARE}
13492 Set up variable @env{as_me} to be the basename of the currently executing
13493 script.  This macro is automatically invoked by @code{AC_INIT} in
13494 configure scripts.
13495 @end defmac
13497 @defmac AS_SHELL_SANITIZE
13498 @asindex{SHELL_SANITIZE}
13499 Initialize the shell suitably for @command{configure} scripts.  This has
13500 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
13501 environment variables for predictable results from configuration tests.
13502 For example, it sets @env{LC_ALL} to change to the default C locale.
13503 @xref{Special Shell Variables}.  This macro is deprecated, since
13504 @code{AS_INIT} already invokes it.
13505 @end defmac
13508 @node File Descriptor Macros
13509 @section File Descriptor Macros
13510 @cindex input
13511 @cindex standard input
13512 @cindex file descriptors
13513 @cindex descriptors
13514 @cindex low-level output
13515 @cindex output, low-level
13517 The following macros define file descriptors used to output messages
13518 (or input values) from @file{configure} scripts.
13519 For example:
13521 @example
13522 echo "$wombats found" >&AS_MESSAGE_LOG_FD
13523 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
13524 read kangaroos <&AS_ORIGINAL_STDIN_FD`
13525 @end example
13527 @noindent
13528 However doing so is seldom needed, because Autoconf provides higher
13529 level macros as described below.
13531 @defmac AS_MESSAGE_FD
13532 @asindex{MESSAGE_FD}
13533 The file descriptor for @samp{checking for...}  messages and results.
13534 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
13535 clients.  However, @code{AC_INIT} shuffles things around to another file
13536 descriptor, in order to allow the @option{-q} option of
13537 @command{configure} to choose whether messages should go to the script's
13538 standard output or be discarded.
13540 If you want to display some messages, consider using one of the printing
13541 macros (@pxref{Printing Messages}) instead.  Copies of messages output
13542 via these macros are also recorded in @file{config.log}.
13543 @end defmac
13545 @anchor{AS_MESSAGE_LOG_FD}
13546 @defmac AS_MESSAGE_LOG_FD
13547 @asindex{MESSAGE_LOG_FD}
13548 This must either be empty, or expand to a file descriptor for log
13549 messages.  By default, @code{AS_INIT} sets this macro to the empty
13550 string for standalone M4sh clients, thus disabling logging.  However,
13551 @code{AC_INIT} shuffles things around so that both @command{configure}
13552 and @command{config.status} use @file{config.log} for log messages.
13553 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
13554 Compiler}), redirect all output to this descriptor.  You may want to do
13555 so if you develop such a low-level macro.
13556 @end defmac
13558 @defmac AS_ORIGINAL_STDIN_FD
13559 @asindex{ORIGINAL_STDIN_FD}
13560 This must expand to a file descriptor for the original standard input.
13561 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
13562 M4sh clients.  However, @code{AC_INIT} shuffles things around for
13563 safety.
13565 When @command{configure} runs, it may accidentally execute an
13566 interactive command that has the same name as the non-interactive meant
13567 to be used or checked.  If the standard input was the terminal, such
13568 interactive programs would cause @command{configure} to stop, pending
13569 some user input.  Therefore @command{configure} redirects its standard
13570 input from @file{/dev/null} during its initialization.  This is not
13571 normally a problem, since @command{configure} normally does not need
13572 user input.
13574 In the extreme case where your @file{configure} script really needs to
13575 obtain some values from the original standard input, you can read them
13576 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
13577 @end defmac
13580 @c =================================================== Writing Autoconf Macros.
13582 @node Writing Autoconf Macros
13583 @chapter Writing Autoconf Macros
13585 When you write a feature test that could be applicable to more than one
13586 software package, the best thing to do is encapsulate it in a new macro.
13587 Here are some instructions and guidelines for writing Autoconf macros.
13589 @menu
13590 * Macro Definitions::           Basic format of an Autoconf macro
13591 * Macro Names::                 What to call your new macros
13592 * Reporting Messages::          Notifying @command{autoconf} users
13593 * Dependencies Between Macros::  What to do when macros depend on other macros
13594 * Obsoleting Macros::           Warning about old ways of doing things
13595 * Coding Style::                Writing Autoconf macros @`a la Autoconf
13596 @end menu
13598 @node Macro Definitions
13599 @section Macro Definitions
13601 @defmac AC_DEFUN (@var{name}, @ovar{body})
13602 @acindex{DEFUN}
13603 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
13604 similar to the M4 builtin @code{m4_define} macro; this creates a macro
13605 named @var{name} and with @var{body} as its expansion.  In addition to
13606 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
13607 constrain the order in which macros are called, while avoiding redundant
13608 output (@pxref{Prerequisite Macros}).
13609 @end defmac
13611 An Autoconf macro definition looks like this:
13613 @example
13614 AC_DEFUN(@var{macro-name}, @var{macro-body})
13615 @end example
13617 You can refer to any arguments passed to the macro as @samp{$1},
13618 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
13619 @acronym{GNU} M4}, for more complete information on writing M4 macros.
13621 Most macros fall in one of two general categories.  The first category
13622 includes macros which take arguments, in order to generate output
13623 parameterized by those arguments.  Macros in this category are designed
13624 to be directly expanded, often multiple times, and should not be used as
13625 the argument to @code{AC_REQUIRE}.  The other category includes macros
13626 which are shorthand for a fixed block of text, and therefore do not take
13627 arguments.  For this category of macros, directly expanding the macro
13628 multiple times results in redundant output, so it is more common to use
13629 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
13630 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
13632 Be sure to properly quote both the @var{macro-body} @emph{and} the
13633 @var{macro-name} to avoid any problems if the macro happens to have
13634 been previously defined.
13636 Each macro should have a header comment that gives its prototype, and a
13637 brief description.  When arguments have default values, display them in
13638 the prototype.  For example:
13640 @example
13641 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
13642 # --------------------------------------
13643 m4_define([AC_MSG_ERROR],
13644   [@{ AS_MESSAGE([error: $1], [2])
13645      exit m4_default([$2], [1]); @}])
13646 @end example
13648 Comments about the macro should be left in the header comment.  Most
13649 other comments make their way into @file{configure}, so just keep
13650 using @samp{#} to introduce comments.
13652 @cindex @code{dnl}
13653 If you have some special comments about pure M4 code, comments
13654 that make no sense in @file{configure} and in the header comment, then
13655 use the builtin @code{dnl}: it causes M4 to discard the text
13656 through the next newline.
13658 Keep in mind that @code{dnl} is rarely needed to introduce comments;
13659 @code{dnl} is more useful to get rid of the newlines following macros
13660 that produce no output, such as @code{AC_REQUIRE}.
13662 Public third-party macros need to use @code{AC_DEFUN}, and not
13663 @code{m4_define}, in order to be found by @command{aclocal}
13664 (@pxref{Extending aclocal,,, automake, @acronym{GNU} Automake}).
13665 Additionally, if it is ever determined that a macro should be made
13666 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
13667 in order to have @command{autoupdate} assist the user in choosing a
13668 better alternative, but there is no corresponding way to make
13669 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
13671 There is another subtle, but important, difference between using
13672 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
13673 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
13674 block of text with a @code{m4_define} macro that will expand to the same
13675 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
13676 the same content does not necessarily give the same results, because it
13677 changes the location where any embedded but unsatisfied
13678 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
13679 example of this, see @ref{Expanded Before Required}.
13681 @node Macro Names
13682 @section Macro Names
13684 All of the public Autoconf macros have all-uppercase names in the
13685 namespace @samp{^AC_} to prevent them from accidentally conflicting with
13686 other text; Autoconf also reserves the namespace @samp{^_AC_} for
13687 internal macros.  All shell variables that they use for internal
13688 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
13689 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
13690 @command{configure}, files produced by Autoconf make heavy use of the
13691 file system namespace @samp{^conf}.
13693 Since Autoconf is built on top of M4sugar (@pxref{Programming in
13694 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
13695 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
13696 @file{configure.ac} is also designed to be scanned by Autoheader,
13697 Autoscan, Autoupdate, and Automake, you should be aware of the
13698 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
13699 the namespace of a package that does not own the macro or shell code you
13700 are writing.
13702 To ensure that your macros don't conflict with present or future
13703 Autoconf macros, you should prefix your own macro names and any shell
13704 variables they use with some other sequence.  Possibilities include your
13705 initials, or an abbreviation for the name of your organization or
13706 software package.  Historically, people have not always followed the
13707 rule of using a namespace appropriate for their package, and this has
13708 made it difficult for determining the origin of a macro (and where to
13709 report bugs about that macro), as well as difficult for the true
13710 namespace owner to add new macros without interference from pre-existing
13711 uses of third-party macros.  Perhaps the best example of this confusion
13712 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
13713 to Gettext.
13715 Most of the Autoconf macros' names follow a structured naming convention
13716 that indicates the kind of feature check by the name.  The macro names
13717 consist of several words, separated by underscores, going from most
13718 general to most specific.  The names of their cache variables use the
13719 same convention (@pxref{Cache Variable Names}, for more information on
13720 them).
13722 The first word of the name after the namespace initials (such as
13723 @samp{AC_}) usually tells the category
13724 of the feature being tested.  Here are the categories used in Autoconf for
13725 specific test macros, the kind of macro that you are more likely to
13726 write.  They are also used for cache variables, in all-lowercase.  Use
13727 them where applicable; where they're not, invent your own categories.
13729 @table @code
13730 @item C
13731 C language builtin features.
13732 @item DECL
13733 Declarations of C variables in header files.
13734 @item FUNC
13735 Functions in libraries.
13736 @item GROUP
13737 Posix group owners of files.
13738 @item HEADER
13739 Header files.
13740 @item LIB
13741 C libraries.
13742 @item PROG
13743 The base names of programs.
13744 @item MEMBER
13745 Members of aggregates.
13746 @item SYS
13747 Operating system features.
13748 @item TYPE
13749 C builtin or declared types.
13750 @item VAR
13751 C variables in libraries.
13752 @end table
13754 After the category comes the name of the particular feature being
13755 tested.  Any further words in the macro name indicate particular aspects
13756 of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
13757 C compiler supports @acronym{ISO} Standard C.
13759 An internal macro should have a name that starts with an underscore;
13760 Autoconf internals should therefore start with @samp{_AC_}.
13761 Additionally, a macro that is an internal subroutine of another macro
13762 should have a name that starts with an underscore and the name of that
13763 other macro, followed by one or more words saying what the internal
13764 macro does.  For example, @code{AC_PATH_X} has internal macros
13765 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
13767 @node Reporting Messages
13768 @section Reporting Messages
13769 @cindex Messages, from @command{autoconf}
13771 When macros statically diagnose abnormal situations, benign or fatal, it
13772 is possible to make @command{autoconf} detect the problem, and refuse to
13773 create @file{configure} in the case of an error.  The macros in this
13774 section are considered obsolescent, and new code should use M4sugar
13775 macros for this purpose, see @ref{Diagnostic Macros}.
13777 On the other hand, it is possible to want to detect errors when
13778 @command{configure} is run, which are dependent on the environment of
13779 the user rather than the maintainer.  For dynamic diagnostics, see
13780 @ref{Printing Messages}.
13782 @defmac AC_DIAGNOSE (@var{category}, @var{message})
13783 @acindex{DIAGNOSE}
13784 Report @var{message} as a warning (or as an error if requested by the
13785 user) if warnings of the @var{category} are turned on.  This macro is
13786 obsolescent; you are encouraged to use:
13787 @example
13788 m4_warn([@var{category}], [@var{message}])
13789 @end example
13790 @noindent
13791 instead.  @xref{m4_warn}, for more details, including valid
13792 @var{category} names.
13793 @end defmac
13795 @defmac AC_WARNING (@var{message})
13796 @acindex{WARNING}
13797 Report @var{message} as a syntax warning.  This macro is obsolescent;
13798 you are encouraged to use:
13799 @example
13800 m4_warn([syntax], [@var{message}])
13801 @end example
13802 @noindent
13803 instead.  @xref{m4_warn}, for more details, as well as better
13804 finer-grained categories of warnings (not all problems have to do with
13805 syntax).
13806 @end defmac
13808 @defmac AC_FATAL (@var{message})
13809 @acindex{FATAL}
13810 Report a severe error @var{message}, and have @command{autoconf} die.
13811 This macro is obsolescent; you are encouraged to use:
13812 @example
13813 m4_fatal([@var{message}])
13814 @end example
13815 @noindent
13816 instead.  @xref{m4_fatal}, for more details.
13817 @end defmac
13819 When the user runs @samp{autoconf -W error}, warnings from
13820 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
13821 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
13823 @node Dependencies Between Macros
13824 @section Dependencies Between Macros
13825 @cindex Dependencies between macros
13827 Some Autoconf macros depend on other macros having been called first in
13828 order to work correctly.  Autoconf provides a way to ensure that certain
13829 macros are called if needed and a way to warn the user if macros are
13830 called in an order that might cause incorrect operation.
13832 @menu
13833 * Prerequisite Macros::         Ensuring required information
13834 * Suggested Ordering::          Warning about possible ordering problems
13835 * One-Shot Macros::             Ensuring a macro is called only once
13836 @end menu
13838 @node Prerequisite Macros
13839 @subsection Prerequisite Macros
13840 @cindex Prerequisite macros
13841 @cindex Macros, prerequisites
13843 A macro that you write might need to use values that have previously
13844 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
13845 examines the output of @code{flex} or @code{lex}, so it depends on
13846 @code{AC_PROG_LEX} having been called first to set the shell variable
13847 @code{LEX}.
13849 Rather than forcing the user of the macros to keep track of the
13850 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
13851 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
13852 called if it is needed, and only called once.
13854 @defmac AC_REQUIRE (@var{macro-name})
13855 @acindex{REQUIRE}
13856 If the M4 macro @var{macro-name} has not already been called, call it
13857 (without any arguments).  Make sure to quote @var{macro-name} with
13858 square brackets.  @var{macro-name} must have been defined using
13859 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
13860 that it has been called.
13862 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
13863 must not be called from the top level.  Also, it does not make sense to
13864 require a macro that takes parameters.
13865 @end defmac
13867 @code{AC_REQUIRE} is often misunderstood.  It really implements
13868 dependencies between macros in the sense that if one macro depends upon
13869 another, the latter is expanded @emph{before} the body of the
13870 former.  To be more precise, the required macro is expanded before
13871 the outermost defined macro in the current expansion stack.
13872 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
13873 @code{FOO}.  For instance, this definition of macros:
13875 @example
13876 @group
13877 AC_DEFUN([TRAVOLTA],
13878 [test "$body_temperature_in_celsius" -gt "38" &&
13879   dance_floor=occupied])
13880 AC_DEFUN([NEWTON_JOHN],
13881 [test "x$hair_style" = xcurly &&
13882   dance_floor=occupied])
13883 @end group
13885 @group
13886 AC_DEFUN([RESERVE_DANCE_FLOOR],
13887 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
13888   AC_REQUIRE([TRAVOLTA])
13889   AC_REQUIRE([NEWTON_JOHN])
13890 fi])
13891 @end group
13892 @end example
13894 @noindent
13895 with this @file{configure.ac}
13897 @example
13898 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
13899 RESERVE_DANCE_FLOOR
13900 if test "x$dance_floor" = xoccupied; then
13901   AC_MSG_ERROR([cannot pick up here, let's move])
13903 @end example
13905 @noindent
13906 does not leave you with a better chance to meet a kindred soul at
13907 other times than Saturday night since it expands into:
13909 @example
13910 @group
13911 test "$body_temperature_in_Celsius" -gt "38" &&
13912   dance_floor=occupied
13913 test "x$hair_style" = xcurly &&
13914   dance_floor=occupied
13916 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
13920 @end group
13921 @end example
13923 This behavior was chosen on purpose: (i) it prevents messages in
13924 required macros from interrupting the messages in the requiring macros;
13925 (ii) it avoids bad surprises when shell conditionals are used, as in:
13927 @example
13928 @group
13929 if @dots{}; then
13930   AC_REQUIRE([SOME_CHECK])
13932 @dots{}
13933 SOME_CHECK
13934 @end group
13935 @end example
13937 However, this implementation can lead to another class of problems.
13938 Consider the case where an outer macro first expands, then indirectly
13939 requires, an inner macro:
13941 @example
13942 AC_DEFUN([TESTA], [[echo in A
13943 if test -n "$SEEN_A" ; then echo duplicate ; fi
13944 SEEN_A=:]])
13945 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
13946 if test -z "$SEEN_A" ; then echo bug ; fi]])
13947 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
13948 AC_DEFUN([OUTER], [[echo in OUTER]
13949 TESTA
13950 TESTC])
13951 OUTER
13952 @end example
13954 @noindent
13955 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
13956 recognized that @code{TESTB} needed to be hoisted prior to the expansion
13957 of @code{OUTER}, but because @code{TESTA} had already been directly
13958 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
13959 @code{TESTB} occurs prior to its prerequisites, leading to the following
13960 output:
13962 @example
13963 in B
13965 in OUTER
13966 in A
13967 in C
13968 @end example
13970 @noindent
13971 Newer Autoconf is smart enough to recognize this situation, and hoists
13972 @code{TESTA} even though it has already been expanded, but issues a
13973 syntax warning in the process.  This is because the hoisted expansion of
13974 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
13975 redundant code, and causes its own set of problems if the hoisted macro
13976 is not idempotent:
13978 @example
13979 in A
13980 in B
13981 in OUTER
13982 in A
13983 duplicate
13984 in C
13985 @end example
13987 The bug is not in Autoconf, but in the macro definitions.  If you ever
13988 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
13989 that the macro only needs to be expanded once.  But to enforce this,
13990 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
13991 this only helps in Autoconf 2.64 or newer), or all
13992 uses of that macro should be through @code{AC_REQUIRE}; directly
13993 expanding the macro defeats the point of using @code{AC_REQUIRE} to
13994 eliminate redundant expansion.  In the example, this rule of thumb was
13995 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
13996 directly expands it.  One way of fixing the bug is to factor
13997 @code{TESTA} into two macros, the portion designed for direct and
13998 repeated use (here, named @code{TESTA}), and the portion designed for
13999 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14000 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
14001 calling convention according to their needs:
14003 @example
14004 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14005 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14006 if test -n "$SEEN_A" ; then echo duplicate ; fi
14007 SEEN_A=:]])
14008 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14009 if test -z "$SEEN_A" ; then echo bug ; fi]])
14010 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14011 AC_DEFUN([OUTER], [[echo in OUTER]
14012 TESTA
14013 TESTC])
14014 OUTER
14015 @end example
14017 @noindent
14018 the resulting output will then obey all dependency rules and avoid any
14019 syntax warnings, whether the script is built with old or new Autoconf
14020 versions:
14022 @example
14023 in A_PREREQ
14024 in B
14025 in OUTER
14026 in A
14027 in C
14028 @end example
14030 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
14031 enforce expansion of required macros outside of shell conditional
14032 constructs.  You are furthermore encouraged, although not required, to
14033 put all @code{AC_REQUIRE} calls
14034 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
14035 lines they leave.
14037 @node Suggested Ordering
14038 @subsection Suggested Ordering
14039 @cindex Macros, ordering
14040 @cindex Ordering macros
14042 Some macros should be run before another macro if both are called, but
14043 neither @emph{requires} that the other be called.  For example, a macro
14044 that changes the behavior of the C compiler should be called before any
14045 macros that run the C compiler.  Many of these dependencies are noted in
14046 the documentation.
14048 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14049 with this kind of dependency appear out of order in a
14050 @file{configure.ac} file.  The warning occurs when creating
14051 @command{configure} from @file{configure.ac}, not when running
14052 @command{configure}.
14054 For example, @code{AC_PROG_CPP} checks whether the C compiler
14055 can run the C preprocessor when given the @option{-E} option.  It should
14056 therefore be called after any macros that change which C compiler is
14057 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
14059 @example
14060 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14061 @end example
14063 @noindent
14064 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14065 when @code{AC_PROG_CC} is called.
14067 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14068 @acindex{BEFORE}
14069 Make M4 print a warning message to the standard error output if
14070 @var{called-macro-name} has already been called.  @var{this-macro-name}
14071 should be the name of the macro that is calling @code{AC_BEFORE}.  The
14072 macro @var{called-macro-name} must have been defined using
14073 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14074 that it has been called.
14075 @end defmac
14077 @node One-Shot Macros
14078 @subsection One-Shot Macros
14079 @cindex One-shot macros
14080 @cindex Macros, called once
14082 Some macros should be called only once, either because calling them
14083 multiple time is unsafe, or because it is bad style.  For instance
14084 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14085 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
14086 sense to run these expensive checks more than once.  Such one-shot
14087 macros can be defined using @code{AC_DEFUN_ONCE}.
14089 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14090 @acindex{DEFUN_ONCE}
14091 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14092 Definitions}), but add additional logic that guarantees that only the
14093 first use of the macro (whether by direct expansion or
14094 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14095 expansion will occur before the start of any enclosing macro defined by
14096 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
14097 Generally, it does not make sense for @var{macro-body} to use parameters
14098 such as @code{$1}.
14099 @end defmac
14101 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14102 emit a warning if it was directly expanded a second time, so for
14103 portability, it is better to use @code{AC_REQUIRE} than direct
14104 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14105 (@pxref{Prerequisite Macros}).
14107 @node Obsoleting Macros
14108 @section Obsoleting Macros
14109 @cindex Obsoleting macros
14110 @cindex Macros, obsoleting
14112 Configuration and portability technology has evolved over the years.
14113 Often better ways of solving a particular problem are developed, or
14114 ad-hoc approaches are systematized.  This process has occurred in many
14115 parts of Autoconf.  One result is that some of the macros are now
14116 considered @dfn{obsolete}; they still work, but are no longer considered
14117 the best thing to do, hence they should be replaced with more modern
14118 macros.  Ideally, @command{autoupdate} should replace the old macro calls
14119 with their modern implementation.
14121 Autoconf provides a simple means to obsolete a macro.
14123 @anchor{AU_DEFUN}
14124 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
14125 @auindex{DEFUN}
14126 Define @var{old-macro} as @var{implementation}.  The only difference
14127 with @code{AC_DEFUN} is that the user is warned that
14128 @var{old-macro} is now obsolete.
14130 If she then uses @command{autoupdate}, the call to @var{old-macro} is
14131 replaced by the modern @var{implementation}.  @var{message} should
14132 include information on what to do after running @command{autoupdate};
14133 @command{autoupdate} prints it as a warning, and includes it
14134 in the updated @file{configure.ac} file.
14136 The details of this macro are hairy: if @command{autoconf} encounters an
14137 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
14138 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
14139 macros are expanded here, while all other macros are disabled and
14140 appear literally in the updated @file{configure.ac}.
14141 @end defmac
14143 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
14144 @auindex{ALIAS}
14145 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
14146 with the same parameters.  This happens for example if the macro was renamed.
14147 @end defmac
14149 @node Coding Style
14150 @section Coding Style
14151 @cindex Coding style
14153 The Autoconf macros follow a strict coding style.  You are encouraged to
14154 follow this style, especially if you intend to distribute your macro,
14155 either by contributing it to Autoconf itself or the
14156 @uref{http://@/www.nongnu.org/@/autoconf-archive, Autoconf
14157 archive}, or by other means.
14159 The first requirement is to pay great attention to the quotation.  For
14160 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
14162 Do not try to invent new interfaces.  It is likely that there is a macro
14163 in Autoconf that resembles the macro you are defining: try to stick to
14164 this existing interface (order of arguments, default values, etc.).  We
14165 @emph{are} conscious that some of these interfaces are not perfect;
14166 nevertheless, when harmless, homogeneity should be preferred over
14167 creativity.
14169 Be careful about clashes both between M4 symbols and between shell
14170 variables.
14172 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
14173 you are unlikely to generate conflicts.  Nevertheless, when you need to
14174 set a special value, @emph{avoid using a regular macro name}; rather,
14175 use an ``impossible'' name.  For instance, up to version 2.13, the macro
14176 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
14177 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
14178 But since there is a macro named @code{AC_SUBST_FILE}, it was just
14179 impossible to @samp{AC_SUBST(FILE)}!  In this case,
14180 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
14181 have been used (yes, with the parentheses).
14182 @c or better yet, high-level macros such as @code{m4_expand_once}
14184 No Autoconf macro should ever enter the user-variable name space; i.e.,
14185 except for the variables that are the actual result of running the
14186 macro, all shell variables should start with @code{ac_}.  In
14187 addition, small macros or any macro that is likely to be embedded in
14188 other macros should be careful not to use obvious names.
14190 @cindex @code{dnl}
14191 Do not use @code{dnl} to introduce comments: most of the comments you
14192 are likely to write are either header comments which are not output
14193 anyway, or comments that should make their way into @file{configure}.
14194 There are exceptional cases where you do want to comment special M4
14195 constructs, in which case @code{dnl} is right, but keep in mind that it
14196 is unlikely.
14198 M4 ignores the leading blanks and newlines before each argument.
14199 Use this feature to
14200 indent in such a way that arguments are (more or less) aligned with the
14201 opening parenthesis of the macro being called.  For instance, instead of
14203 @example
14204 AC_CACHE_CHECK(for EMX OS/2 environment,
14205 ac_cv_emxos2,
14206 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
14207 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
14208 @end example
14210 @noindent
14211 write
14213 @example
14214 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14215 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14216                    [ac_cv_emxos2=yes],
14217                    [ac_cv_emxos2=no])])
14218 @end example
14220 @noindent
14221 or even
14223 @example
14224 AC_CACHE_CHECK([for EMX OS/2 environment],
14225                [ac_cv_emxos2],
14226                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
14227                                                    [return __EMX__;])],
14228                                   [ac_cv_emxos2=yes],
14229                                   [ac_cv_emxos2=no])])
14230 @end example
14232 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
14233 cross-compiling, provide a pessimistic value (typically @samp{no}).
14235 Feel free to use various tricks to prevent auxiliary tools, such as
14236 syntax-highlighting editors, from behaving improperly.  For instance,
14237 instead of:
14239 @example
14240 m4_bpatsubst([$1], [$"])
14241 @end example
14243 @noindent
14246 @example
14247 m4_bpatsubst([$1], [$""])
14248 @end example
14250 @noindent
14251 so that Emacsen do not open an endless ``string'' at the first quote.
14252 For the same reasons, avoid:
14254 @example
14255 test $[#] != 0
14256 @end example
14258 @noindent
14259 and use:
14261 @example
14262 test $[@@%:@@] != 0
14263 @end example
14265 @noindent
14266 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
14267 breaking the bracket-matching highlighting from Emacsen.  Note the
14268 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
14269 not escape when it is unnecessary.  Common examples of useless quotation
14270 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
14271 etc.  If you add portability issues to the picture, you'll prefer
14272 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
14273 better than hacking Autoconf @code{:-)}.
14275 When using @command{sed}, don't use @option{-e} except for indenting
14276 purposes.  With the @code{s} and @code{y} commands, the preferred
14277 separator is @samp{/} unless @samp{/} itself might appear in the pattern
14278 or replacement, in which case you should use @samp{|}, or optionally
14279 @samp{,} if you know the pattern and replacement cannot contain a file
14280 name.  If none of these characters will do, choose a printable character
14281 that cannot appear in the pattern or replacement.  Characters from the
14282 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
14283 replacement might contain a file name, since they have special meaning
14284 to the shell and are less likely to occur in file names.
14286 @xref{Macro Definitions}, for details on how to define a macro.  If a
14287 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
14288 of an @code{AC_REQUIRE} directive, and macros required by other macros
14289 inside arguments do not need to be expanded before this macro, then
14290 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
14291 Also take into account that public third-party macros need to use
14292 @code{AC_DEFUN} in order to be found by @command{aclocal}
14293 (@pxref{Extending aclocal,,, automake, @acronym{GNU} Automake}).
14294 All the @code{AC_REQUIRE} statements should be at the beginning of the
14295 macro, and each statement should be followed by @code{dnl}.
14297 You should not rely on the number of arguments: instead of checking
14298 whether an argument is missing, test that it is not empty.  It provides
14299 both a simpler and a more predictable interface to the user, and saves
14300 room for further arguments.
14302 Unless the macro is short, try to leave the closing @samp{])} at the
14303 beginning of a line, followed by a comment that repeats the name of the
14304 macro being defined.  This introduces an additional newline in
14305 @command{configure}; normally, that is not a problem, but if you want to
14306 remove it you can use @samp{[]dnl} on the last line.  You can similarly
14307 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
14308 is recommended instead of @samp{dnl} to ensure that M4 does not
14309 interpret the @samp{dnl} as being attached to the preceding text or
14310 macro output.  For example, instead of:
14312 @example
14313 AC_DEFUN([AC_PATH_X],
14314 [AC_MSG_CHECKING([for X])
14315 AC_REQUIRE_CPP()
14316 @r{# @dots{}omitted@dots{}}
14317   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14318 fi])
14319 @end example
14321 @noindent
14322 you would write:
14324 @example
14325 AC_DEFUN([AC_PATH_X],
14326 [AC_REQUIRE_CPP()[]dnl
14327 AC_MSG_CHECKING([for X])
14328 @r{# @dots{}omitted@dots{}}
14329   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14330 fi[]dnl
14331 ])# AC_PATH_X
14332 @end example
14334 If the macro is long, try to split it into logical chunks.  Typically,
14335 macros that check for a bug in a function and prepare its
14336 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
14337 this setup.  Do not hesitate to introduce auxiliary macros to factor
14338 your code.
14340 In order to highlight the recommended coding style, here is a macro
14341 written the old way:
14343 @example
14344 dnl Check for EMX on OS/2.
14345 dnl _AC_EMXOS2
14346 AC_DEFUN(_AC_EMXOS2,
14347 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
14348 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
14349 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
14350 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
14351 @end example
14353 @noindent
14354 and the new way:
14356 @example
14357 # _AC_EMXOS2
14358 # ----------
14359 # Check for EMX on OS/2.
14360 m4_define([_AC_EMXOS2],
14361 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14362 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14363                    [ac_cv_emxos2=yes],
14364                    [ac_cv_emxos2=no])])
14365 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
14366 ])# _AC_EMXOS2
14367 @end example
14372 @c ============================================= Portable Shell Programming
14374 @node Portable Shell
14375 @chapter Portable Shell Programming
14376 @cindex Portable shell programming
14378 When writing your own checks, there are some shell-script programming
14379 techniques you should avoid in order to make your code portable.  The
14380 Bourne shell and upward-compatible shells like the Korn shell and Bash
14381 have evolved over the years, and many features added to the original
14382 System7 shell are now supported on all interesting porting targets.
14383 However, the following discussion between Russ Allbery and Robert Lipe
14384 is worth reading:
14386 @noindent
14387 Russ Allbery:
14389 @quotation
14390 The @acronym{GNU} assumption that @command{/bin/sh} is the one and only shell
14391 leads to a permanent deadlock.  Vendors don't want to break users'
14392 existing shell scripts, and there are some corner cases in the Bourne
14393 shell that are not completely compatible with a Posix shell.  Thus,
14394 vendors who have taken this route will @emph{never} (OK@dots{}``never say
14395 never'') replace the Bourne shell (as @command{/bin/sh}) with a
14396 Posix shell.
14397 @end quotation
14399 @noindent
14400 Robert Lipe:
14402 @quotation
14403 This is exactly the problem.  While most (at least most System V's) do
14404 have a Bourne shell that accepts shell functions most vendor
14405 @command{/bin/sh} programs are not the Posix shell.
14407 So while most modern systems do have a shell @emph{somewhere} that meets the
14408 Posix standard, the challenge is to find it.
14409 @end quotation
14411 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
14412 is to find such a shell.  But to prevent trouble, if you're not using
14413 M4sh you should not take advantage of features that were added after Unix
14414 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
14415 negated character classes, or even @command{unset}.  @code{#} comments,
14416 while not in Unix version 7, were retrofitted in the original Bourne
14417 shell and can be assumed to be part of the least common denominator.
14419 On the other hand, if you're using M4sh you can assume that the shell
14420 has the features that were added in SVR2 (circa 1984), including shell
14421 functions,
14422 @command{return}, @command{unset}, and I/O redirection for builtins.  For
14423 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
14424 However, some pitfalls have to be avoided for portable use of these
14425 constructs; these will be documented in the rest of this chapter.
14426 See in particular @ref{Shell Functions} and @ref{Limitations of
14427 Builtins, , Limitations of Shell Builtins}.
14429 Some ancient systems have quite
14430 small limits on the length of the @samp{#!} line; for instance, 32
14431 bytes (not including the newline) on SunOS 4.
14432 However, these ancient systems are no longer of practical concern.
14434 The set of external programs you should run in a @command{configure} script
14435 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
14436 Makefiles, standards, @acronym{GNU} Coding Standards}, for the list.  This
14437 restriction allows users to start out with a fairly small set of
14438 programs and build the rest, avoiding too many interdependencies between
14439 packages.
14441 Some of these external utilities have a portable subset of features; see
14442 @ref{Limitations of Usual Tools}.
14444 There are other sources of documentation about shells.  The
14445 specification for the Posix
14446 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
14447 Command Language}, though more generous than the restrictive shell
14448 subset described above, is fairly portable nowadays.  Also please see
14449 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
14451 @menu
14452 * Shellology::                  A zoology of shells
14453 * Here-Documents::              Quirks and tricks
14454 * File Descriptors::            FDs and redirections
14455 * File System Conventions::     File names
14456 * Shell Pattern Matching::      Pattern matching
14457 * Shell Substitutions::         Variable and command expansions
14458 * Assignments::                 Varying side effects of assignments
14459 * Parentheses::                 Parentheses in shell scripts
14460 * Slashes::                     Slashes in shell scripts
14461 * Special Shell Variables::     Variables you should not change
14462 * Shell Functions::             What to look out for if you use them
14463 * Limitations of Builtins::     Portable use of not so portable /bin/sh
14464 * Limitations of Usual Tools::  Portable use of portable tools
14465 @end menu
14467 @node Shellology
14468 @section Shellology
14469 @cindex Shellology
14471 There are several families of shells, most prominently the Bourne family
14472 and the C shell family which are deeply incompatible.  If you want to
14473 write portable shell scripts, avoid members of the C shell family.  The
14474 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
14475 Shell difference FAQ} includes a small history of Posix shells, and a
14476 comparison between several of them.
14478 Below we describe some of the members of the Bourne shell family.
14480 @table @asis
14481 @item Ash
14482 @cindex Ash
14483 Ash is often used on @acronym{GNU}/Linux and @acronym{BSD}
14484 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
14485 bugs that are fixed in the 0.3.x series, but portable shell scripts
14486 should work around them, since version 0.2 is still shipped with many
14487 @acronym{GNU}/Linux distributions.
14489 To be compatible with Ash 0.2:
14491 @itemize @minus
14492 @item
14493 don't use @samp{$?} after expanding empty or unset variables,
14494 or at the start of an @command{eval}:
14496 @example
14497 foo=
14498 false
14499 $foo
14500 echo "Do not use it: $?"
14501 false
14502 eval 'echo "Do not use it: $?"'
14503 @end example
14505 @item
14506 don't use command substitution within variable expansion:
14508 @example
14509 cat $@{FOO=`bar`@}
14510 @end example
14512 @item
14513 beware that single builtin substitutions are not performed by a
14514 subshell, hence their effect applies to the current shell!  @xref{Shell
14515 Substitutions}, item ``Command Substitution''.
14516 @end itemize
14518 @item Bash
14519 @cindex Bash
14520 To detect whether you are running Bash, test whether
14521 @code{BASH_VERSION} is set.  To require
14522 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
14523 Mode, , Bash Posix Mode, bash, The @acronym{GNU} Bash Reference
14524 Manual}, for details.
14526 @item Bash 2.05 and later
14527 @cindex Bash 2.05 and later
14528 Versions 2.05 and later of Bash use a different format for the
14529 output of the @command{set} builtin, designed to make evaluating its
14530 output easier.  However, this output is not compatible with earlier
14531 versions of Bash (or with many other shells, probably).  So if
14532 you use Bash 2.05 or higher to execute @command{configure},
14533 you'll need to use Bash 2.05 for all other build tasks as well.
14535 @item Ksh
14536 @cindex Ksh
14537 @cindex Korn shell
14538 @prindex @samp{ksh}
14539 @prindex @samp{ksh88}
14540 @prindex @samp{ksh93}
14541 The Korn shell is compatible with the Bourne family and it mostly
14542 conforms to Posix.  It has two major variants commonly
14543 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
14544 release.  It is usually called @command{ksh}, but is called @command{sh}
14545 on some hosts if you set your path appropriately.
14547 Solaris systems have three variants:
14548 @prindex @command{/usr/bin/ksh} on Solaris
14549 @command{/usr/bin/ksh} is @samp{ksh88}; it is
14550 standard on Solaris 2.0 and later.
14551 @prindex @command{/usr/xpg4/bin/sh} on Solaris
14552 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
14553 @samp{ksh88}; it is standard on Solaris 9 and later.
14554 @prindex @command{/usr/dt/bin/dtksh} on Solaris
14555 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
14556 Variants that are not standard may be parts of optional
14557 packages.  There is no extra charge for these packages, but they are
14558 not part of a minimal OS install and therefore some installations may
14559 not have it.
14561 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
14562 is also available as @command{/usr/bin/posix/sh}.  If the environment
14563 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
14564 the standard shell conform to Posix.
14566 @item Pdksh
14567 @prindex @samp{pdksh}
14568 A public-domain clone of the Korn shell called @command{pdksh} is widely
14569 available: it has most of the @samp{ksh88} features along with a few of
14570 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
14571 @command{/bin/sh} on Open@acronym{BSD}, and similarly to Bash you can require
14572 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
14573 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
14574 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
14575 at least one respect:
14577 @example
14578 $ @kbd{echo "`echo \"hello\"`"}
14579 hello
14580 $ @kbd{set -o posix}
14581 $ @kbd{echo "`echo \"hello\"`"}
14582 "hello"
14583 @end example
14585 The last line of output contains spurious quotes.  This is yet another
14586 reason why portable shell code should not contain
14587 @code{"`@dots{}\"@dots{}\"@dots{}`"} constructs (@pxref{Shell
14588 Substitutions}).
14590 @item Zsh
14591 @cindex Zsh
14592 To detect whether you are running @command{zsh}, test whether
14593 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
14594 compatible with the Bourne shell: you must execute @samp{emulate sh},
14595 and for @command{zsh} versions before 3.1.6-dev-18 you must also
14596 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
14597 zsh, The Z Shell Manual}, for details.
14599 The default Mac OS X @command{sh} was originally Zsh; it was changed to
14600 Bash in Mac OS X 10.2.
14601 @end table
14603 @node Here-Documents
14604 @section Here-Documents
14605 @cindex Here-documents
14606 @cindex Shell here-documents
14608 Don't rely on @samp{\} being preserved just because it has no special
14609 meaning together with the next symbol.  In the native @command{sh}
14610 on Open@acronym{BSD} 2.7 @samp{\"} expands to @samp{"} in here-documents with
14611 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
14612 use @samp{\\} to get @samp{\}.
14614 With Open@acronym{BSD} 2.7's @command{sh}
14616 @example
14617 @group
14618 $ @kbd{cat <<EOF
14619 > \" \\
14620 > EOF}
14621 " \
14622 @end group
14623 @end example
14625 @noindent
14626 and with Bash:
14628 @example
14629 @group
14630 bash-2.04$ @kbd{cat <<EOF
14631 > \" \\
14632 > EOF}
14633 \" \
14634 @end group
14635 @end example
14637 Some shells mishandle large here-documents: for example,
14638 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
14639 derived from Korn shell version M-12/28/93d, mishandle braced variable
14640 expansion that crosses a 1024- or 4096-byte buffer boundary
14641 within a here-document.  Only the part of the variable name after the boundary
14642 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
14643 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
14644 boundary, the shell reports an error, as if you used @code{$@{@}}.
14645 Instead of @code{$@{variable-default@}}, the shell may expand
14646 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
14647 be worked around by omitting the braces: @code{$variable}.  The bug was
14648 fixed in
14649 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
14650 still shipping older versions with the bug.
14652 Many shells (including the Bourne shell) implement here-documents
14653 inefficiently.  In particular, some shells can be extremely inefficient when
14654 a single statement contains many here-documents.  For instance if your
14655 @file{configure.ac} includes something like:
14657 @example
14658 @group
14659 if <cross_compiling>; then
14660   assume this and that
14661 else
14662   check this
14663   check that
14664   check something else
14665   @dots{}
14666   on and on forever
14667   @dots{}
14669 @end group
14670 @end example
14672 A shell parses the whole @code{if}/@code{fi} construct, creating
14673 temporary files for each here-document in it.  Some shells create links
14674 for such here-documents on every @code{fork}, so that the clean-up code
14675 they had installed correctly removes them.  It is creating the links
14676 that can take the shell forever.
14678 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
14679 @code{if}/@code{fi} constructs, would improve the performance
14680 significantly.  Anyway, this kind of construct is not exactly the
14681 typical use of Autoconf.  In fact, it's even not recommended, because M4
14682 macros can't look into shell conditionals, so we may fail to expand a
14683 macro when it was expanded before in a conditional path, and the
14684 condition turned out to be false at runtime, and we end up not
14685 executing the macro at all.
14687 @node File Descriptors
14688 @section File Descriptors
14689 @cindex Descriptors
14690 @cindex File descriptors
14691 @cindex Shell file descriptors
14693 Most shells, if not all (including Bash, Zsh, Ash), output traces on
14694 stderr, even for subshells.  This might result in undesirable content
14695 if you meant to capture the standard-error output of the inner command:
14697 @example
14698 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
14699 $ @kbd{cat stderr}
14700 + eval echo foo >&2
14701 + echo foo
14703 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
14704 $ @kbd{cat stderr}
14705 + eval 'echo foo >&2'
14706 ++ echo foo
14708 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
14709 @i{# Traces on startup files deleted here.}
14710 $ @kbd{cat stderr}
14711 +zsh:1> eval echo foo >&2
14712 +zsh:1> echo foo
14714 @end example
14716 @noindent
14717 One workaround is to grep out uninteresting lines, hoping not to remove
14718 good ones.
14720 If you intend to redirect both standard error and standard output,
14721 redirect standard output first.  This works better with @acronym{HP-UX},
14722 since its shell mishandles tracing if standard error is redirected
14723 first:
14725 @example
14726 $ @kbd{sh -x -c ': 2>err >out'}
14727 + :
14728 + 2> err $ @kbd{cat err}
14729 1> out
14730 @end example
14732 Don't try to redirect the standard error of a command substitution.  It
14733 must be done @emph{inside} the command substitution.  When running
14734 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
14735 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
14737 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
14738 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
14740 Some shells, like @command{ash}, don't recognize bi-directional
14741 redirection (@samp{<>}).  And even on shells that recognize it, it is
14742 not portable to use on fifos: Posix does not require read-write support
14743 for named pipes, and Cygwin does not support it:
14745 @example
14746 $ @kbd{mkfifo fifo}
14747 $ @kbd{exec 5<>fifo}
14748 $ @kbd{echo hi >&5}
14749 bash: echo: write error: Communication error on send
14750 @end example
14752 When catering to old systems, don't redirect the same file descriptor
14753 several times, as you are doomed to failure under Ultrix.
14755 @example
14756 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
14757 UWS V4.4 (Rev. 11)
14758 $ @kbd{eval 'echo matter >fullness' >void}
14759 illegal io
14760 $ @kbd{eval '(echo matter >fullness)' >void}
14761 illegal io
14762 $ @kbd{(eval '(echo matter >fullness)') >void}
14763 Ambiguous output redirect.
14764 @end example
14766 @noindent
14767 In each case the expected result is of course @file{fullness} containing
14768 @samp{matter} and @file{void} being empty.  However, this bug is
14769 probably not of practical concern to modern platforms.
14771 Solaris 10 @command{sh} will try to optimize away a @command{:} command
14772 in a loop after the first iteration, even if it is redirected:
14774 @example
14775 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
14776 $ @kbd{ls}
14778 @end example
14780 @noindent
14781 As a workaround, @command{echo} or @command{eval} can be used.
14783 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
14784 subsidiary program.  If any of these descriptors is closed, the
14785 operating system may open an unspecified file for the descriptor in the
14786 new process image.  Posix says this may be done only if the subsidiary
14787 program is set-user-ID or set-group-ID, but @acronym{HP-UX} 11.23 does
14788 it even for ordinary programs.
14790 Don't rely on open file descriptors being open in child processes.  In
14791 @command{ksh}, file descriptors above 2 which are opened using
14792 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
14793 that involved in the fork-and-exec which runs a program or script).
14794 Thus, using @command{sh}, we have:
14796 @example
14797 $ @kbd{cat ./descrips}
14798 #!/bin/sh -
14799 echo hello >&5
14800 $ @kbd{exec 5>t}
14801 $ @kbd{./descrips}
14802 $ @kbd{cat t}
14803 hello
14805 @end example
14807 @noindent
14808 But using ksh:
14810 @example
14811 $ @kbd{exec 5>t}
14812 $ @kbd{./descrips}
14813 hello
14814 $ @kbd{cat t}
14816 @end example
14818 @noindent
14819 Within the process which runs the @samp{descrips} script, file
14820 descriptor 5 is closed.
14822 Don't rely on redirection to a closed file descriptor to cause an
14823 error.  With Solaris @command{/bin/sh}, when the redirection fails, the
14824 output goes to the original file descriptor.
14826 @example
14827 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
14828 bash: 3: Bad file descriptor
14830 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
14833 @end example
14835 @acronym{DOS} variants cannot rename or remove open files, such as in
14836 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
14837 perfectly portable among Posix hosts.
14839 A few ancient systems reserved some file descriptors.  By convention,
14840 file descriptor 3 was opened to @file{/dev/tty} when you logged into
14841 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
14842 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
14843 1990), though we don't now remember what it was.  Both these systems are
14844 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
14845 other file descriptors.
14847 @node File System Conventions
14848 @section File System Conventions
14849 @cindex File system conventions
14851 Autoconf uses shell-script processing extensively, so the file names
14852 that it processes should not contain characters that are special to the
14853 shell.  Special characters include space, tab, newline, @sc{nul}, and
14854 the following:
14856 @example
14857 " # $ & ' ( ) * ; < = > ? [ \ ` |
14858 @end example
14860 Also, file names should not begin with @samp{~} or @samp{-}, and should
14861 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
14862 immediately after @samp{:}.  On Posix-like platforms, directory names
14863 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
14864 path separator.
14866 These restrictions apply not only to the files that you distribute, but
14867 also to the absolute file names of your source, build, and destination
14868 directories.
14870 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
14871 they should be avoided.
14873 Posix lets implementations treat leading @file{//} specially, but
14874 requires leading @file{///} and beyond to be equivalent to @file{/}.
14875 Most Unix variants treat @file{//} like @file{/}.  However, some treat
14876 @file{//} as a ``super-root'' that can provide access to files that are
14877 not otherwise reachable from @file{/}.  The super-root tradition began
14878 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
14879 has revived it.
14881 While @command{autoconf} and friends are usually run on some Posix
14882 variety, they can be used on other systems, most notably @acronym{DOS}
14883 variants.  This impacts several assumptions regarding file names.
14885 @noindent
14886 For example, the following code:
14888 @example
14889 case $foo_dir in
14890   /*) # Absolute
14891      ;;
14892   *)
14893      foo_dir=$dots$foo_dir ;;
14894 esac
14895 @end example
14897 @noindent
14898 fails to properly detect absolute file names on those systems, because
14899 they can use a drivespec, and usually use a backslash as directory
14900 separator.  If you want to be portable to @acronym{DOS} variants (at the
14901 price of rejecting valid but oddball Posix file names like @file{a:\b}),
14902 you can check for absolute file names like this:
14904 @cindex absolute file names, detect
14905 @example
14906 case $foo_dir in
14907   [\\/]* | ?:[\\/]* ) # Absolute
14908      ;;
14909   *)
14910      foo_dir=$dots$foo_dir ;;
14911 esac
14912 @end example
14914 @noindent
14915 Make sure you quote the brackets if appropriate and keep the backslash as
14916 first character (@pxref{case, , Limitations of Shell Builtins}).
14918 Also, because the colon is used as part of a drivespec, these systems don't
14919 use it as path separator.  When creating or accessing paths, you can use the
14920 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
14921 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
14922 starts up.
14924 File names need extra care as well.  While @acronym{DOS} variants
14925 that are Posixy enough to run @command{autoconf} (such as @acronym{DJGPP})
14926 are usually able to handle long file names properly, there are still
14927 limitations that can seriously break packages.  Several of these issues
14928 can be easily detected by the
14929 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
14930 package.
14932 A short overview follows; problems are marked with @sc{sfn}/@sc{lfn} to
14933 indicate where they apply: @sc{sfn} means the issues are only relevant to
14934 plain @acronym{DOS}, not to @acronym{DOS} under Microsoft Windows
14935 variants, while @sc{lfn} identifies problems that exist even under
14936 Microsoft Windows variants.
14938 @table @asis
14939 @item No multiple dots (@sc{sfn})
14940 @acronym{DOS} cannot handle multiple dots in file names.  This is an especially
14941 important thing to remember when building a portable configure script,
14942 as @command{autoconf} uses a .in suffix for template files.
14944 This is perfectly OK on Posix variants:
14946 @example
14947 AC_CONFIG_HEADERS([config.h])
14948 AC_CONFIG_FILES([source.c foo.bar])
14949 AC_OUTPUT
14950 @end example
14952 @noindent
14953 but it causes problems on @acronym{DOS}, as it requires @samp{config.h.in},
14954 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
14955 to @acronym{DOS}-based environments, you should use this instead:
14957 @example
14958 AC_CONFIG_HEADERS([config.h:config.hin])
14959 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
14960 AC_OUTPUT
14961 @end example
14963 @item No leading dot (@sc{sfn})
14964 @acronym{DOS} cannot handle file names that start with a dot.  This is usually
14965 not important for @command{autoconf}.
14967 @item Case insensitivity (@sc{lfn})
14968 @acronym{DOS} is case insensitive, so you cannot, for example, have both a
14969 file called @samp{INSTALL} and a directory called @samp{install}.  This
14970 also affects @command{make}; if there's a file called @samp{INSTALL} in
14971 the directory, @samp{make install} does nothing (unless the
14972 @samp{install} target is marked as PHONY).
14974 @item The 8+3 limit (@sc{sfn})
14975 Because the @acronym{DOS} file system only stores the first 8 characters of
14976 the file name and the first 3 of the extension, those must be unique.
14977 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
14978 @file{foobar-prettybird.c} all resolve to the same file name
14979 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
14980 @file{foo.bartender}.
14982 The 8+3 limit is not usually a problem under Microsoft Windows, as it
14983 uses numeric
14984 tails in the short version of file names to make them unique.  However, a
14985 registry setting can turn this behavior off.  While this makes it
14986 possible to share file trees containing long file names between @sc{sfn}
14987 and @sc{lfn} environments, it also means the above problem applies there
14988 as well.
14990 @item Invalid characters (@sc{lfn})
14991 Some characters are invalid in @acronym{DOS} file names, and should therefore
14992 be avoided.  In a @sc{lfn} environment, these are @samp{/}, @samp{\},
14993 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
14994 In a @sc{sfn} environment, other characters are also invalid.  These
14995 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
14997 @item Invalid names (@sc{lfn})
14998 Some @acronym{DOS} file names are reserved, and cause problems if you
14999 try to use files with those names.  These names include @file{CON},
15000 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
15001 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
15002 File names are case insensitive, so even names like
15003 @file{aux/config.guess} are disallowed.
15005 @end table
15007 @node Shell Pattern Matching
15008 @section Shell Pattern Matching
15009 @cindex Shell pattern matching
15011 Nowadays portable patterns can use negated character classes like
15012 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
15013 some shells but not others; hence portable scripts should never use
15014 @samp{^} as the first character of a bracket pattern.
15016 Outside the C locale, patterns like @samp{[a-z]} are problematic since
15017 they may match characters that are not lower-case letters.
15019 @node Shell Substitutions
15020 @section Shell Substitutions
15021 @cindex Shell substitutions
15023 Contrary to a persistent urban legend, the Bourne shell does not
15024 systematically split variables and back-quoted expressions, in particular
15025 on the right-hand side of assignments and in the argument of @code{case}.
15026 For instance, the following code:
15028 @example
15029 case "$given_srcdir" in
15030 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
15031 *)  top_srcdir="$dots$given_srcdir" ;;
15032 esac
15033 @end example
15035 @noindent
15036 is more readable when written as:
15038 @example
15039 case $given_srcdir in
15040 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
15041 *)  top_srcdir=$dots$given_srcdir ;;
15042 esac
15043 @end example
15045 @noindent
15046 and in fact it is even @emph{more} portable: in the first case of the
15047 first attempt, the computation of @code{top_srcdir} is not portable,
15048 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"}.
15049 Worse yet, not all shells understand @code{"`@dots{}\"@dots{}\"@dots{}`"}
15050 the same way.  There is just no portable way to use double-quoted
15051 strings inside double-quoted back-quoted expressions (pfew!).
15053 @table @code
15054 @item $@@
15055 @cindex @samp{"$@@"}
15056 One of the most famous shell-portability issues is related to
15057 @samp{"$@@"}.  When there are no positional arguments, Posix says
15058 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
15059 original Unix version 7 Bourne shell treated it as equivalent to
15060 @samp{""} instead, and this behavior survives in later implementations
15061 like Digital Unix 5.0.
15063 The traditional way to work around this portability problem is to use
15064 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
15065 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
15066 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
15068 @example
15069 zsh $ @kbd{emulate sh}
15070 zsh $ @kbd{for i in "$@@"; do echo $i; done}
15071 Hello World
15073 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
15074 Hello
15075 World
15077 @end example
15079 @noindent
15080 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
15081 @samp{"$@@"} because of the portability problems mentioned above.
15082 One workaround relies on Zsh's ``global aliases'' to convert
15083 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
15085 @example
15086 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
15087 @end example
15089 Zsh only recognizes this alias when a shell word matches it exactly;
15090 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
15091 case always yields at least one shell word, use plain @samp{"$@@"}.
15093 A more conservative workaround is to avoid @samp{"$@@"} if it is
15094 possible that there may be no positional arguments.  For example,
15095 instead of:
15097 @example
15098 cat conftest.c "$@@"
15099 @end example
15101 you can use this instead:
15103 @example
15104 case $# in
15105 0) cat conftest.c;;
15106 *) cat conftest.c "$@@";;
15107 esac
15108 @end example
15110 Autoconf macros often use the @command{set} command to update
15111 @samp{$@@}, so if you are writing shell code intended for
15112 @command{configure} you should not assume that the value of @samp{$@@}
15113 persists for any length of time.
15116 @item $@{10@}
15117 @cindex positional parameters
15118 The 10th, 11th, @dots{} positional parameters can be accessed only after
15119 a @code{shift}.  The 7th Edition shell reported an error if given
15120 @code{$@{10@}}, and
15121 Solaris 10 @command{/bin/sh} still acts that way:
15123 @example
15124 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
15125 $ @kbd{echo $@{10@}}
15126 bad substitution
15127 @end example
15129 @item $@{@var{var}:-@var{value}@}
15130 @c Info cannot handle `:' in index entries.
15131 @c @cindex $@{@var{var}:-@var{value}@}
15132 Old @acronym{BSD} shells, including the Ultrix @code{sh}, don't accept the
15133 colon for any shell substitution, and complain and die.
15134 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
15136 @item $@{@var{var}=@var{literal}@}
15137 @cindex $@{@var{var}=@var{literal}@}
15138 Be sure to quote:
15140 @example
15141 : $@{var='Some words'@}
15142 @end example
15144 @noindent
15145 otherwise some shells, such as on Digital Unix V 5.0, die because
15146 of a ``bad substitution''.
15148 @sp 1
15150 Solaris @command{/bin/sh} has a frightening bug in its interpretation
15151 of this.  Imagine you need set a variable to a string containing
15152 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
15153 when the affected variable was already set.  This bug can be exercised
15154 by running:
15156 @example
15157 $ @kbd{unset foo}
15158 $ @kbd{foo=$@{foo='@}'@}}
15159 $ @kbd{echo $foo}
15161 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
15162 $ @kbd{echo $foo}
15164 $ @kbd{foo=$@{foo='@}'@}}
15165 $ @kbd{echo $foo}
15166 @}@}
15167  ^ ugh!
15168 @end example
15170 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
15171 though it is enclosed in single quotes.  The problem doesn't happen
15172 using double quotes.
15174 @item $@{@var{var}=@var{expanded-value}@}
15175 @cindex $@{@var{var}=@var{expanded-value}@}
15176 On Ultrix,
15177 running
15179 @example
15180 default="yu,yaa"
15181 : $@{var="$default"@}
15182 @end example
15184 @noindent
15185 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
15186 each char is set.  You don't observe the phenomenon using a simple
15187 @samp{echo $var} since apparently the shell resets the 8th bit when it
15188 expands $var.  Here are two means to make this shell confess its sins:
15190 @example
15191 $ @kbd{cat -v <<EOF
15192 $var
15193 EOF}
15194 @end example
15196 @noindent
15199 @example
15200 $ @kbd{set | grep '^var=' | cat -v}
15201 @end example
15203 One classic incarnation of this bug is:
15205 @example
15206 default="a b c"
15207 : $@{list="$default"@}
15208 for c in $list; do
15209   echo $c
15210 done
15211 @end example
15213 @noindent
15214 You'll get @samp{a b c} on a single line.  Why?  Because there are no
15215 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
15216 bit set, hence no IFS splitting is performed!!!
15218 One piece of good news is that Ultrix works fine with @samp{:
15219 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
15220 then that @acronym{QNX} 4.25 then sets @var{list} to the @emph{last} item of
15221 @var{default}!
15223 The portable way out consists in using a double assignment, to switch
15224 the 8th bit twice on Ultrix:
15226 @example
15227 list=$@{list="$default"@}
15228 @end example
15230 @noindent
15231 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
15232 use:
15234 @example
15235 test "$@{var+set@}" = set || var=@var{@{value@}}
15236 @end example
15238 @item $@{#@var{var}@}
15239 @itemx $@{@var{var}%@var{word}@}
15240 @itemx $@{@var{var}%%@var{word}@}
15241 @itemx $@{@var{var}#@var{word}@}
15242 @itemx $@{@var{var}##@var{word}@}
15243 @cindex $@{#@var{var}@}
15244 @cindex $@{@var{var}%@var{word}@}
15245 @cindex $@{@var{var}%%@var{word}@}
15246 @cindex $@{@var{var}#@var{word}@}
15247 @cindex $@{@var{var}##@var{word}@}
15248 Posix requires support for these usages, but they do not work with many
15249 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
15251 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
15252 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
15253 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
15254 yields the empty string.
15257 @item `@var{commands}`
15258 @cindex `@var{commands}`
15259 @cindex Command Substitution
15260 Posix requires shells to trim all trailing newlines from command
15261 output before substituting it, so assignments like
15262 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
15263 @samp{$file} ends in a newline.
15265 While in general it makes no sense, do not substitute a single builtin
15266 with side effects, because Ash 0.2, trying to optimize, does not fork a
15267 subshell to perform the command.
15269 For instance, if you wanted to check that @command{cd} is silent, do not
15270 use @samp{test -z "`cd /`"} because the following can happen:
15272 @example
15273 $ @kbd{pwd}
15274 /tmp
15275 $ @kbd{test -z "`cd /`" && pwd}
15277 @end example
15279 @noindent
15280 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
15282 The MSYS shell leaves a stray byte in the expansion of a double-quoted
15283 command substitution of a native program, if the end of the substitution
15284 is not aligned with the end of the double quote.  This may be worked
15285 around by inserting another pair of quotes:
15287 @example
15288 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
15289 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
15290 - broken differ: char 4, line 1
15291 @end example
15293 Upon interrupt or SIGTERM, some shells may abort a command substitution,
15294 replace it with a null string, and wrongly evaluate the enclosing
15295 command before entering the trap or ending the script.  This can lead to
15296 spurious errors:
15298 @example
15299 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
15300 $ @kbd{^C}
15301 sh: test: hi: unexpected operator/operand
15302 @end example
15304 @noindent
15305 You can avoid this by assigning the command substitution to a temporary
15306 variable:
15308 @example
15309 $ @kbd{sh -c 'res=`sleep 5; echo hi`
15310          if test "x$res" = xhi; then echo yes; fi'}
15311 $ @kbd{^C}
15312 @end example
15314 @item $(@var{commands})
15315 @cindex $(@var{commands})
15316 This construct is meant to replace @samp{`@var{commands}`},
15317 and it has most of the problems listed under @code{`@var{commands}`}.
15319 This construct can be
15320 nested while this is impossible to do portably with back quotes.
15321 Unfortunately it is not yet universally supported.  Most notably, even recent
15322 releases of Solaris don't support it:
15324 @example
15325 $ @kbd{showrev -c /bin/sh | grep version}
15326 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
15327 $ @kbd{echo $(echo blah)}
15328 syntax error: `(' unexpected
15329 @end example
15331 @noindent
15332 nor does @sc{irix} 6.5's Bourne shell:
15333 @example
15334 $ @kbd{uname -a}
15335 IRIX firebird-image 6.5 07151432 IP22
15336 $ @kbd{echo $(echo blah)}
15337 $(echo blah)
15338 @end example
15340 If you do use @samp{$(@var{commands})}, make sure that the commands
15341 do not start with a parenthesis, as that would cause confusion with
15342 a different notation @samp{$((@var{expression}))} that in modern
15343 shells is an arithmetic expression not a command.  To avoid the
15344 confusion, insert a space between the two opening parentheses.
15346 Avoid @var{commands} that contain unbalanced parentheses in
15347 here-documents, comments, or case statement patterns, as many shells
15348 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
15349 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
15351 @example
15352 echo $(case x in x) echo hello;; esac)
15353 @end example
15356 @item $((@var{expression}))
15357 @cindex $((@var{expression}))
15358 Arithmetic expansion is not portable as some shells (most
15359 notably Solaris 10 @command{/bin/sh}) don't support it.
15361 Among shells that do support @samp{$(( ))}, not all of them obey the
15362 Posix rule that octal and hexadecimal constants must be recognized:
15364 @example
15365 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
15367 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
15369 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
15371 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
15372 pdksh:  010 + 0x10 : bad number `0x10'
15373 $ @kbd{pdksh -c 'echo $(( 010 ))'}
15375 @end example
15377 When it is available, using arithmetic expansion provides a noticeable
15378 speedup in script execution; but testing for support requires
15379 @command{eval} to avoid syntax errors.  The following construct is used
15380 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
15381 arguments are provided in decimal and without a leading zero, and all
15382 operators are properly quoted and appear as distinct arguments:
15384 @example
15385 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
15386   eval 'func_arith ()
15387   @{
15388     func_arith_result=$(( $* ))
15389   @}'
15390 else
15391   func_arith ()
15392   @{
15393     func_arith_result=`expr "$@@"`
15394   @}
15396 func_arith 1 + 1
15397 foo=$func_arith_result
15398 @end example
15401 @item ^
15402 @cindex ^ quoting
15403 Always quote @samp{^}, otherwise traditional shells such as
15404 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
15406 @end table
15409 @node Assignments
15410 @section Assignments
15411 @cindex Shell assignments
15413 When setting several variables in a row, be aware that the order of the
15414 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
15415 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
15416 You must use
15417 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
15419 Don't rely on the following to find @file{subdir/program}:
15421 @example
15422 PATH=subdir$PATH_SEPARATOR$PATH program
15423 @end example
15425 @noindent
15426 as this does not work with Zsh 3.0.6.  Use something like this
15427 instead:
15429 @example
15430 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
15431 @end example
15433 Don't rely on the exit status of an assignment: Ash 0.2 does not change
15434 the status and propagates that of the last statement:
15436 @example
15437 $ @kbd{false || foo=bar; echo $?}
15439 $ @kbd{false || foo=`:`; echo $?}
15441 @end example
15443 @noindent
15444 and to make things even worse, @acronym{QNX} 4.25 just sets the exit status
15445 to 0 in any case:
15447 @example
15448 $ @kbd{foo=`exit 1`; echo $?}
15450 @end example
15452 To assign default values, follow this algorithm:
15454 @enumerate
15455 @item
15456 If the default value is a literal and does not contain any closing
15457 brace, use:
15459 @example
15460 : $@{var='my literal'@}
15461 @end example
15463 @item
15464 If the default value contains no closing brace, has to be expanded, and
15465 the variable being initialized is not intended to be IFS-split
15466 (i.e., it's not a list), then use:
15468 @example
15469 : $@{var="$default"@}
15470 @end example
15472 @item
15473 If the default value contains no closing brace, has to be expanded, and
15474 the variable being initialized is intended to be IFS-split (i.e., it's a list),
15475 then use:
15477 @example
15478 var=$@{var="$default"@}
15479 @end example
15481 @item
15482 If the default value contains a closing brace, then use:
15484 @example
15485 test "$@{var+set@}" = set || var="has a '@}'"
15486 @end example
15487 @end enumerate
15489 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
15490 doubt, just use the last form.  @xref{Shell Substitutions}, items
15491 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
15492 for the rationale.
15494 @node Parentheses
15495 @section Parentheses in Shell Scripts
15496 @cindex Shell parentheses
15498 Beware of two opening parentheses in a row, as many shell
15499 implementations treat them specially.  Posix requires that the command
15500 @samp{((cat))} must behave like @samp{(cat)}, but many shells, including
15501 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
15502 expression equivalent to @samp{let "cat"}, and may or may not report an
15503 error when they detect that @samp{cat} is not a number.  As another
15504 example, @samp{pdksh} 5.2.14 misparses the following code:
15506 @example
15507 if ((true) || false); then
15508   echo ok
15510 @end example
15512 @noindent
15513 To work around this problem, insert a space between the two opening
15514 parentheses.  There is a similar problem and workaround with
15515 @samp{$((}; see @ref{Shell Substitutions}.
15517 @node Slashes
15518 @section Slashes in Shell Scripts
15519 @cindex Shell slashes
15521 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
15522 arguments that contain two trailing slashes:
15524 @example
15525 $ @kbd{echo / // /// //// .// //.}
15526 / / // /// ./ //.
15527 $ @kbd{x=//}
15528 $ @kbd{eval "echo \$x"}
15530 $ @kbd{set -x}
15531 $ @kbd{echo abc | tr -t ab //}
15532 + echo abc
15533 + tr -t ab /
15535 @end example
15537 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
15538 variable is empty and the second double-quote is followed by a word that
15539 begins and ends with slash:
15541 @example
15542 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
15544 + echo //ouch/
15545 //ouch/
15546 @end example
15548 However, our understanding is that patches are available, so perhaps
15549 it's not worth worrying about working around these horrendous bugs.
15551 @node Special Shell Variables
15552 @section Special Shell Variables
15553 @cindex Shell variables
15554 @cindex Special shell variables
15556 Some shell variables should not be used, since they can have a deep
15557 influence on the behavior of the shell.  In order to recover a sane
15558 behavior from the shell, some variables should be unset; M4sh takes
15559 care of this and provides fallback values, whenever needed, to cater
15560 for a very old @file{/bin/sh} that does not support @command{unset}.
15561 (@pxref{Portable Shell, , Portable Shell Programming}).
15563 As a general rule, shell variable names containing a lower-case letter
15564 are safe; you can define and use these variables without worrying about
15565 their effect on the underlying system, and without worrying about
15566 whether the shell changes them unexpectedly.  (The exception is the
15567 shell variable @code{status}, as described below.)
15569 Here is a list of names that are known to cause trouble.  This list is
15570 not exhaustive, but you should be safe if you avoid the name
15571 @code{status} and names containing only upper-case letters and
15572 underscores.
15574 @c Alphabetical order, case insensitive, `A' before `a'.
15575 @table @code
15576 @item ?
15577 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
15578 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
15579 correctly in shell functions (@pxref{Shell Functions}) or in traps
15580 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
15581 @samp{$?} to zero after an empty command.
15583 @example
15584 $ @kbd{bash -c 'false; $empty; echo $?'}
15586 $ @kbd{zsh -c 'false; $empty; echo $?'}
15588 @end example
15590 @item _
15591 @evindex _
15592 Many shells reserve @samp{$_} for various purposes, e.g., the name of
15593 the last command executed.
15595 @item BIN_SH
15596 @evindex BIN_SH
15597 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15598 the standard shell conform to Posix.
15600 @item CDPATH
15601 @evindex CDPATH
15602 When this variable is set it specifies a list of directories to search
15603 when invoking @code{cd} with a relative file name that did not start
15604 with @samp{./} or @samp{../}.  Posix
15605 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
15606 is used successfully, @code{cd} prints the resulting absolute
15607 file name.  Unfortunately this output can break idioms like
15608 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
15609 Also, many shells do not conform to this part of Posix; for
15610 example, @command{zsh} prints the result only if a directory name
15611 other than @file{.} was chosen from @env{CDPATH}.
15613 In practice the shells that have this problem also support
15614 @command{unset}, so you can work around the problem as follows:
15616 @example
15617 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
15618 @end example
15620 You can also avoid output by ensuring that your directory name is
15621 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
15623 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
15624 possible, so you need not worry about this problem in those scripts.
15626 @item CLICOLOR_FORCE
15627 @evindex CLICOLOR_FORCE
15628 When this variable is set, some implementations of tools like
15629 @command{ls} attempt to add color to their output via terminal escape
15630 sequences, even when the output is not directed to a terminal, and can
15631 thus cause spurious failures in scripts.  Configure scripts use M4sh,
15632 which automatically unsets this variable.
15634 @item DUALCASE
15635 @evindex DUALCASE
15636 In the MKS shell, case statements and file name generation are
15637 case-insensitive unless @env{DUALCASE} is nonzero.
15638 Autoconf-generated scripts export this variable when they start up.
15640 @item ENV
15641 @itemx MAIL
15642 @itemx MAILPATH
15643 @itemx PS1
15644 @itemx PS2
15645 @itemx PS4
15646 @evindex ENV
15647 @evindex MAIL
15648 @evindex MAILPATH
15649 @evindex PS1
15650 @evindex PS2
15651 @evindex PS4
15652 These variables should not matter for shell scripts, since they are
15653 supposed to affect only interactive shells.  However, at least one
15654 shell (the pre-3.0 @sc{uwin} Korn shell) gets confused about
15655 whether it is interactive, which means that (for example) a @env{PS1}
15656 with a side effect can unexpectedly modify @samp{$?}.  To work around
15657 this bug, M4sh scripts (including @file{configure} scripts) do something
15658 like this:
15660 @example
15661 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
15662 PS1='$ '
15663 PS2='> '
15664 PS4='+ '
15665 @end example
15667 @noindent
15668 (actually, there is some complication due to bugs in @command{unset};
15669 see @pxref{unset, , Limitations of Shell Builtins}).
15671 @item FPATH
15672 @evindex FPATH
15673 The Korn shell uses @env{FPATH} to find shell functions, so avoid
15674 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
15675 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
15676 to find whether a command exists, since they might report the wrong
15677 result if @env{FPATH} is also set.
15679 @item GREP_OPTIONS
15680 @evindex GREP_OPTIONS
15681 When this variable is set, some implementations of @command{grep} honor
15682 these options, even if the options include direction to enable colored
15683 output via terminal escape sequences, and the result can cause spurious
15684 failures when the output is not directed to a terminal.  Configure
15685 scripts use M4sh, which automatically unsets this variable.
15687 @item IFS
15688 @evindex IFS
15689 Long ago, shell scripts inherited @env{IFS} from the environment,
15690 but this caused many problems so modern shells ignore any environment
15691 settings for @env{IFS}.
15693 Don't set the first character of @code{IFS} to backslash.  Indeed,
15694 Bourne shells use the first character (backslash) when joining the
15695 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
15696 backslash escapes, so you can end up with backspace and other strange
15697 characters.
15699 The proper value for @code{IFS} (in regular code, not when performing
15700 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
15701 especially important, as it is used to join the arguments in @samp{$*};
15702 however, note that traditional shells, but also bash-2.04, fail to adhere
15703 to this and join with a space anyway.
15705 @item LANG
15706 @itemx LC_ALL
15707 @itemx LC_COLLATE
15708 @itemx LC_CTYPE
15709 @itemx LC_MESSAGES
15710 @itemx LC_MONETARY
15711 @itemx LC_NUMERIC
15712 @itemx LC_TIME
15713 @evindex LANG
15714 @evindex LC_ALL
15715 @evindex LC_COLLATE
15716 @evindex LC_CTYPE
15717 @evindex LC_MESSAGES
15718 @evindex LC_MONETARY
15719 @evindex LC_NUMERIC
15720 @evindex LC_TIME
15722 You should set all these variables to @samp{C} because so much
15723 configuration code assumes the C locale and Posix requires that locale
15724 environment variables be set to @samp{C} if the C locale is desired;
15725 @file{configure} scripts and M4sh do that for you.
15726 Export these variables after setting them.
15728 @c  However, some older, nonstandard
15729 @c  systems (notably @acronym{SCO}) break if locale environment variables
15730 @c  are set to @samp{C}, so when running on these systems
15731 @c  Autoconf-generated scripts unset the variables instead.
15733 @item LANGUAGE
15734 @evindex LANGUAGE
15736 @env{LANGUAGE} is not specified by Posix, but it is a @acronym{GNU}
15737 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
15738 should set it too.
15740 @item LC_ADDRESS
15741 @itemx LC_IDENTIFICATION
15742 @itemx LC_MEASUREMENT
15743 @itemx LC_NAME
15744 @itemx LC_PAPER
15745 @itemx LC_TELEPHONE
15746 @evindex LC_ADDRESS
15747 @evindex LC_IDENTIFICATION
15748 @evindex LC_MEASUREMENT
15749 @evindex LC_NAME
15750 @evindex LC_PAPER
15751 @evindex LC_TELEPHONE
15753 These locale environment variables are @acronym{GNU} extensions.  They
15754 are treated like their Posix brethren (@env{LC_COLLATE},
15755 etc.)@: as described above.
15757 @item LINENO
15758 @evindex LINENO
15759 Most modern shells provide the current line number in @code{LINENO}.
15760 Its value is the line number of the beginning of the current command.
15761 M4sh, and hence Autoconf, attempts to execute @command{configure} with
15762 a shell that supports @code{LINENO}.  If no such shell is available, it
15763 attempts to implement @code{LINENO} with a Sed prepass that replaces each
15764 instance of the string @code{$LINENO} (not followed by an alphanumeric
15765 character) with the line's number.  In M4sh scripts you should execute
15766 @code{AS_LINENO_PREPARE} so that these workarounds are included in
15767 your script; configure scripts do this automatically in @code{AC_INIT}.
15769 You should not rely on @code{LINENO} within @command{eval} or shell
15770 functions, as the behavior differs in practice.  The presence of a
15771 quoted newline within simple commands can alter which line number is
15772 used as the starting point for @code{$LINENO} substitutions within that
15773 command.  Also, the possibility of the Sed prepass means that you should
15774 not rely on @code{$LINENO} when quoted, when in here-documents, or when
15775 line continuations are used.  Subshells should be OK, though.  In the
15776 following example, lines 1, 9, and 14 are portable, but the other
15777 instances of @code{$LINENO} do not have deterministic values:
15779 @example
15780 @group
15781 $ @kbd{cat lineno}
15782 echo 1. $LINENO
15783 echo "2. $LINENO
15784 3. $LINENO"
15785 cat <<EOF
15786 5. $LINENO
15787 6. $LINENO
15788 7. \$LINENO
15790 ( echo 9. $LINENO )
15791 eval 'echo 10. $LINENO'
15792 eval 'echo 11. $LINENO
15793 echo 12. $LINENO'
15794 echo 13. '$LINENO'
15795 echo 14. $LINENO '
15796 15.' $LINENO
15797 f () @{ echo $1 $LINENO;
15798 echo $1 $LINENO @}
15799 f 18.
15800 echo 19. \
15801 $LINENO
15802 @end group
15803 @group
15804 $ @kbd{bash-3.2 ./lineno}
15805 1. 1
15806 2. 3
15807 3. 3
15808 5. 4
15809 6. 4
15810 7. $LINENO
15811 9. 9
15812 10. 10
15813 11. 12
15814 12. 13
15815 13. $LINENO
15816 14. 14
15817 15. 14
15818 18. 16
15819 18. 17
15820 19. 19
15821 @end group
15822 @group
15823 $ @kbd{zsh-4.3.4 ./lineno}
15824 1. 1
15825 2. 2
15826 3. 2
15827 5. 4
15828 6. 4
15829 7. $LINENO
15830 9. 9
15831 10. 1
15832 11. 1
15833 12. 2
15834 13. $LINENO
15835 14. 14
15836 15. 14
15837 18. 0
15838 18. 1
15839 19. 19
15840 @end group
15841 @group
15842 $ @kbd{pdksh-5.2.14 ./lineno}
15843 1. 1
15844 2. 2
15845 3. 2
15846 5. 4
15847 6. 4
15848 7. $LINENO
15849 9. 9
15850 10. 0
15851 11. 0
15852 12. 0
15853 13. $LINENO
15854 14. 14
15855 15. 14
15856 18. 16
15857 18. 17
15858 19. 19
15859 @end group
15860 @group
15861 $ @kbd{sed '=' <lineno |}
15862 > @kbd{  sed '}
15863 > @kbd{    N}
15864 > @kbd{    s,$,-,}
15865 > @kbd{    t loop}
15866 > @kbd{    :loop}
15867 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
15868 > @kbd{    t loop}
15869 > @kbd{    s,-$,,}
15870 > @kbd{    s,^[0-9]*\n,,}
15871 > @kbd{  ' |}
15872 > @kbd{  sh}
15873 1. 1
15874 2. 2
15875 3. 3
15876 5. 5
15877 6. 6
15878 7. \7
15879 9. 9
15880 10. 10
15881 11. 11
15882 12. 12
15883 13. 13
15884 14. 14
15885 15. 15
15886 18. 16
15887 18. 17
15888 19. 20
15889 @end group
15890 @end example
15892 In particular, note that @file{config.status} (and any other subsidiary
15893 script created by @code{AS_INIT_GENERATED}) might report line numbers
15894 relative to the parent script as a result of the potential Sed pass.
15896 @item NULLCMD
15897 @evindex NULLCMD
15898 When executing the command @samp{>foo}, @command{zsh} executes
15899 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
15900 compatibility mode and the @command{zsh} version is newer
15901 than 3.1.6-dev-18.  If you are using an older @command{zsh}
15902 and forget to set @env{NULLCMD},
15903 your script might be suspended waiting for data on its standard input.
15905 @item PATH_SEPARATOR
15906 @evindex PATH_SEPARATOR
15907 On @acronym{DJGPP} systems, the @env{PATH_SEPARATOR} environment
15908 variable can be set to either @samp{:} or @samp{;} to control the path
15909 separator Bash uses to set up certain environment variables (such as
15910 @env{PATH}).  You can set this variable to @samp{;} if you want
15911 @command{configure} to use @samp{;} as a separator; this might be useful
15912 if you plan to use non-Posix shells to execute files.  @xref{File System
15913 Conventions}, for more information about @code{PATH_SEPARATOR}.
15915 @item PWD
15916 @evindex PWD
15917 Posix 1003.1-2001 requires that @command{cd} and
15918 @command{pwd} must update the @env{PWD} environment variable to point
15919 to the logical name of the current directory, but traditional shells
15920 do not support this.  This can cause confusion if one shell instance
15921 maintains @env{PWD} but a subsidiary and different shell does not know
15922 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
15923 points to the wrong directory.  Use @samp{`pwd`} rather than
15924 @samp{$PWD}.
15926 @item RANDOM
15927 @evindex RANDOM
15928 Many shells provide @code{RANDOM}, a variable that returns a different
15929 integer each time it is used.  Most of the time, its value does not
15930 change when it is not used, but on @sc{irix} 6.5 the value changes all
15931 the time.  This can be observed by using @command{set}.  It is common
15932 practice to use @code{$RANDOM} as part of a file name, but code
15933 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
15935 @item status
15936 @evindex status
15937 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
15938 hence read-only.  Do not use it.
15939 @end table
15941 @node Shell Functions
15942 @section Shell Functions
15943 @cindex Shell Functions
15945 Nowadays, it is difficult to find a shell that does not support
15946 shell functions at all.  However, some differences should be expected.
15948 Inside a shell function, you should not rely on the error status of a
15949 subshell if the last command of that subshell was @code{exit} or
15950 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
15951 find a shell that does not exhibit the bug, zsh might be the only shell
15952 present on the user's machine.
15954 Likewise, the state of @samp{$?} is not reliable when entering a shell
15955 function.  This has the effect that using a function as the first
15956 command in a @command{trap} handler can cause problems.
15958 @example
15959 $ @kbd{bash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
15962 $ @kbd{ash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
15965 @end example
15967 @acronym{DJGPP} bash 2.04 has a bug in that @command{return} from a
15968 shell function which also used a command substitution causes a
15969 segmentation fault.  To work around the issue, you can use
15970 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
15971 in the execution flow of the function (@pxref{Common Shell Constructs}).
15973 Not all shells treat shell functions as simple commands impacted by
15974 @samp{set -e}, for example with Solaris 10 @command{bin/sh}:
15976 @example
15977 $ @kbd{bash -c 'f()@{ return 1; @}; set -e; f; echo oops}
15978 $ @kbd{/bin/sh -c 'f()@{ return 1; @}; set -e; f; echo oops}
15979 oops
15980 @end example
15982 Shell variables and functions may share the same namespace, for example
15983 with Solaris 10 @command{/bin/sh}:
15985 @example
15986 $ @kbd{f () @{ :; @}; f=; f}
15987 f: not found
15988 @end example
15990 @noindent
15991 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
15992 uses the prefix @samp{as_fn_} for its functions.
15994 Handling of positional parameters and shell options varies among shells.
15995 For example, Korn shells reset and restore trace output (@samp{set -x})
15996 and other options upon function entry and exit.  Inside a function,
15997 @acronym{IRIX} sh sets @samp{$0} to the function name.
15999 It is not portable to pass temporary environment variables to shell
16000 functions.  Solaris @command{/bin/sh} does not see the variable.
16001 Meanwhile, not all shells follow the Posix rule that the assignment must
16002 affect the current environment in the same manner as special built-ins.
16004 @example
16005 $ @kbd{/bin/sh -c 'func()@{ echo $a;@}; a=1 func; echo $a'}
16006 @result{}
16007 @result{}
16008 $ @kbd{ash -c 'func()@{ echo $a;@}; a=1 func; echo $a'}
16009 @result{}1
16010 @result{}
16011 $ @kbd{bash -c 'set -o posix; func()@{ echo $a;@}; a=1 func; echo $a'}
16012 @result{}1
16013 @result{}1
16014 @end example
16016 Some ancient Bourne shell variants with function support did not reset
16017 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
16018 arguments of the script were lost after the first function invocation.
16019 It is probably not worth worrying about these shells any more.
16021 With @acronym{AIX} sh, a @command{trap} on 0 installed in a shell function
16022 triggers at function exit rather than at script exit, see @xref{trap, ,
16023 Limitations of Shell Builtins}.
16025 @node Limitations of Builtins
16026 @section Limitations of Shell Builtins
16027 @cindex Shell builtins
16028 @cindex Limitations of shell builtins
16030 No, no, we are serious: some shells do have limitations!  :)
16032 You should always keep in mind that any builtin or command may support
16033 options, and therefore differ in behavior with arguments
16034 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
16035 can give unexpected results when @code{word} starts with a dash.  It is
16036 often possible to avoid this problem using @samp{echo "x$word"}, taking
16037 the @samp{x} into account later in the pipe.  Many of these limitations
16038 can be worked around using M4sh (@pxref{Programming in M4sh}).
16040 @c This table includes things like `@command{test} (files)', so we can't
16041 @c use @table @command.
16042 @table @asis
16043 @item @command{.}
16044 @c --------------
16045 @prindex @command{.}
16046 Use @command{.} only with regular files (use @samp{test -f}).  Bash
16047 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
16048 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
16049 some shells, including bash 3.2, implicitly append the current directory
16050 to this @env{PATH} search, even though Posix forbids it.  So if you want
16051 to use @command{.} on a file @file{foo} in the current directory, you
16052 must use @samp{. ./foo}.
16054 Not all shells gracefully handle syntax errors within a sourced file.
16055 On one extreme, some non-interactive shells abort the entire script.  On
16056 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
16057 syntax error.
16059 @example
16060 $ @kbd{echo 'fi' > syntax}
16061 $ @kbd{bash -c '. ./syntax; echo $?'}
16062 ./syntax: line 1: syntax error near unexpected token `fi'
16063 ./syntax: line 1: `fi'
16065 $ @kbd{ash -c '. ./syntax; echo $?'}
16066 ./syntax: 1: Syntax error: "fi" unexpected
16067 $ @kbd{zsh -c '. ./syntax; echo $?'}
16068 ./syntax:1: parse error near `fi'
16070 @end example
16072 @item @command{!}
16073 @c --------------
16074 @prindex @command{!}
16075 The Unix version 7 shell did not support
16076 negating the exit status of commands with @command{!}, and this feature
16077 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
16078 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
16079 bugs when using @command{!}:
16081 @example
16082 $ @kbd{sh -c '! : | :'; echo $?}
16084 $ @kbd{ash -c '! : | :'; echo $?}
16086 $ @kbd{sh -c '! @{ :; @}'; echo $?}
16088 $ @kbd{ash -c '! @{ :; @}'; echo $?}
16089 @{: not found
16090 Syntax error: "@}" unexpected
16092 @end example
16094 Shell code like this:
16096 @example
16097 if ! cmp file1 file2 >/dev/null 2>&1; then
16098   echo files differ or trouble
16100 @end example
16102 is therefore not portable in practice.  Typically it is easy to rewrite
16103 such code, e.g.:
16105 @example
16106 cmp file1 file2 >/dev/null 2>&1 ||
16107   echo files differ or trouble
16108 @end example
16110 More generally, one can always rewrite @samp{! @var{command}} as:
16112 @example
16113 if @var{command}; then (exit 1); else :; fi
16114 @end example
16117 @item @command{@{...@}}
16118 @c --------------------
16119 @prindex @command{@{...@}}
16120 Bash 3.2 (and earlier versions) sometimes does not properly set
16121 @samp{$?} when failing to write redirected output of a compound command.
16122 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
16123 not occur with @samp{(@dots{})}.  For example:
16125 @example
16126 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
16127 bash: line 1: /bad: Permission denied
16129 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
16130 bash: line 1: /bad: Permission denied
16132 @end example
16134 To work around the bug, prepend @samp{:;}:
16136 @example
16137 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
16138 bash: line 1: /bad: Permission denied
16140 @end example
16142 Posix requires a syntax error if a brace list has no contents.  However,
16143 not all shells obey this rule; and on shells where empty lists are
16144 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
16145 ensure that a brace list is never empty.
16147 @example
16148 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
16149 bash: line 1: syntax error near unexpected token `@}'
16150 bash: line 1: `false; @{ @}; echo $?'
16152 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
16154 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
16156 @end example
16159 @item @command{break}
16160 @c ------------------
16161 @prindex @command{break}
16162 The use of @samp{break 2} etc.@: is safe.
16165 @anchor{case}
16166 @item @command{case}
16167 @c -----------------
16168 @prindex @command{case}
16169 You don't need to quote the argument; no splitting is performed.
16171 You don't need the final @samp{;;}, but you should use it.
16173 Posix requires support for @code{case} patterns with opening
16174 parentheses like this:
16176 @example
16177 case $file_name in
16178   (*.c) echo "C source code";;
16179 esac
16180 @end example
16182 @noindent
16183 but the @code{(} in this example is not portable to many Bourne
16184 shell implementations, which is a pity for those of us using tools that
16185 rely on balanced parentheses.  For instance, with Solaris
16186 @command{/bin/sh}:
16188 @example
16189 $ @kbd{case foo in (foo) echo foo;; esac}
16190 @error{}syntax error: `(' unexpected
16191 @end example
16193 @noindent
16194 The leading @samp{(} can be omitted safely.  Unfortunately, there are
16195 contexts where unbalanced parentheses cause other problems, such as when
16196 using a syntax-highlighting editor that searches for the balancing
16197 counterpart, or more importantly, when using a case statement as an
16198 underquoted argument to an Autoconf macro.  @xref{Balancing
16199 Parentheses}, for tradeoffs involved in various styles of dealing with
16200 unbalanced @samp{)}.
16202 Zsh handles pattern fragments derived from parameter expansions or
16203 command substitutions as though quoted:
16205 @example
16206 $ pat=\?; case aa in ?$pat) echo match;; esac
16207 $ pat=\?; case a? in ?$pat) echo match;; esac
16208 match
16209 @end example
16211 @noindent
16212 Because of a bug in its @code{fnmatch}, Bash fails to properly
16213 handle backslashes in character classes:
16215 @example
16216 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
16217 bash-2.02$
16218 @end example
16220 @noindent
16221 This is extremely unfortunate, since you are likely to use this code to
16222 handle Posix or @sc{ms-dos} absolute file names.  To work around this
16223 bug, always put the backslash first:
16225 @example
16226 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
16228 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
16230 @end example
16232 Many Bourne shells cannot handle closing brackets in character classes
16233 correctly.
16235 Some shells also have problems with backslash escaping in case you do not want
16236 to match the backslash: both a backslash and the escaped character match this
16237 pattern.  To work around this, specify the character class in a variable, so
16238 that quote removal does not apply afterwards, and the special characters don't
16239 have to be backslash-escaped:
16241 @example
16242 $ @kbd{case '\' in [\<]) echo OK;; esac}
16244 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
16246 @end example
16248 Even with this, Solaris @command{ksh} matches a backslash if the set
16249 contains any
16250 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
16252 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
16253 a closing parenthesis if not specified in a character class:
16255 @example
16256 $ @kbd{case foo in *\)*) echo fail ;; esac}
16257 fail
16258 $ @kbd{case foo in *')'*) echo fail ;; esac}
16259 fail
16260 @end example
16262 Some shells, such as Ash 0.3.8, are confused by an empty
16263 @code{case}/@code{esac}:
16265 @example
16266 ash-0.3.8 $ @kbd{case foo in esac;}
16267 @error{}Syntax error: ";" unexpected (expecting ")")
16268 @end example
16270 Posix requires @command{case} to give an exit status of 0 if no cases
16271 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
16272 rule.  Meanwhile, it is unclear whether a case that matches, but
16273 contains no statements, must also change the exit status to 0.  The M4sh
16274 macro @code{AS_CASE} works around these inconsistencies.
16276 @example
16277 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
16279 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
16281 @end example
16284 @item @command{cd}
16285 @c ---------------
16286 @prindex @command{cd}
16287 Posix 1003.1-2001 requires that @command{cd} must support
16288 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
16289 with @option{-L} being the default.  However, traditional shells do
16290 not support these options, and their @command{cd} command has the
16291 @option{-P} behavior.
16293 Portable scripts should assume neither option is supported, and should
16294 assume neither behavior is the default.  This can be a bit tricky,
16295 since the Posix default behavior means that, for example,
16296 @samp{ls ..} and @samp{cd ..} may refer to different directories if
16297 the current logical directory is a symbolic link.  It is safe to use
16298 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
16299 Also, Autoconf-generated scripts check for this problem when computing
16300 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
16301 so it is safe to @command{cd} to these variables.
16303 See @xref{Special Shell Variables}, for portability problems involving
16304 @command{cd} and the @env{CDPATH} environment variable.
16305 Also please see the discussion of the @command{pwd} command.
16308 @anchor{echo}
16309 @item @command{echo}
16310 @c -----------------
16311 @prindex @command{echo}
16312 The simple @command{echo} is probably the most surprising source of
16313 portability troubles.  It is not possible to use @samp{echo} portably
16314 unless both options and escape sequences are omitted.  Don't expect any
16315 option.
16317 Do not use backslashes in the arguments, as there is no consensus on
16318 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
16319 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
16320 The problem is truly @command{echo}: all the shells
16321 understand @samp{'\n'} as the string composed of a backslash and an
16322 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
16323 mess up the internal state of ksh88 on AIX 6.1 so that it will print
16324 the first character @samp{s} only, followed by a newline, and then
16325 entirely drop the output of the next echo in a command substitution.
16327 Because of these problems, do not pass a string containing arbitrary
16328 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
16329 only if you know that @var{foo}'s value cannot contain backslashes and
16330 cannot start with @samp{-}.
16332 If this may not be true, @command{printf} is in general safer and
16333 easier to use than @command{echo} and @command{echo -n}.  Thus, scripts
16334 where portability is not a major concern should use @command{printf
16335 '%s\n'} whenever @command{echo} could fail, and similarly use
16336 @command{printf %s} instead of @command{echo -n}. For portable shell
16337 scripts, instead, it is suggested to use a here-document like this:
16339 @example
16340 cat <<EOF
16341 $foo
16343 @end example
16345 Alternatively, M4sh provides @code{AS_ECHO} and @code{AS_ECHO_N} macros
16346 which choose between various portable implementations: @samp{echo}
16347 or @samp{print} where they work, @command{printf} if it is available,
16348 or else other creative tricks in order to work around the above problems.
16351 @item @command{eval}
16352 @c -----------------
16353 @prindex @command{eval}
16354 The @command{eval} command is useful in limited circumstances, e.g.,
16355 using commands like @samp{eval table_$key=\$value} and @samp{eval
16356 value=table_$key} to simulate a hash table when the key is known to be
16357 alphanumeric.
16359 You should also be wary of common bugs in @command{eval} implementations.
16360 In some shell implementations (e.g., older @command{ash}, Open@acronym{BSD} 3.8
16361 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
16362 4.2.5), the arguments of @samp{eval} are evaluated in a context where
16363 @samp{$?} is 0, so they exhibit behavior like this:
16365 @example
16366 $ @kbd{false; eval 'echo $?'}
16368 @end example
16370 The correct behavior here is to output a nonzero value,
16371 but portable scripts should not rely on this.
16373 You should not rely on @code{LINENO} within @command{eval}.
16374 @xref{Special Shell Variables}.
16376 Note that, even though these bugs are easily avoided,
16377 @command{eval} is tricky to use on arbitrary arguments.
16378 It is obviously unwise to use @samp{eval $cmd} if the string value of
16379 @samp{cmd} was derived from an untrustworthy source.  But even if the
16380 string value is valid, @samp{eval $cmd} might not work as intended,
16381 since it causes field splitting and file name expansion to occur twice,
16382 once for the @command{eval} and once for the command itself.  It is
16383 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
16384 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
16385 equivalent of @samp{cat test;.c} if there happens to be a file named
16386 @file{test;.c} in the current directory; and this in turn
16387 mistakenly attempts to invoke @command{cat} on the file @file{test} and
16388 then execute the command @command{.c}.  To avoid this problem, use
16389 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
16391 However, suppose that you want to output the text of the evaluated
16392 command just before executing it.  Assuming the previous example,
16393 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
16394 this output doesn't show the user that @samp{test;.c} is the actual name
16395 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
16396 works on this example, but it fails with @samp{cmd='cat foo >bar'},
16397 since it mistakenly replaces the contents of @file{bar} by the
16398 string @samp{cat foo}.  No simple, general, and portable solution to
16399 this problem is known.
16401 @item @command{exec}
16402 @c -----------------
16403 @prindex @command{exec}
16404 Posix describes several categories of shell built-ins.  Special
16405 built-ins (such as @command{exit}) must impact the environment of the
16406 current shell, and need not be available through @command{exec}.  All
16407 other built-ins are regular, and must not propagate variable assignments
16408 to the environment of the current shell.  However, the group of regular
16409 built-ins is further distinguished by commands that do not require a
16410 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
16411 are offered as a more efficient version of something that must still be
16412 found in a @env{PATH} search (such as @command{echo}).  Posix is not
16413 clear on whether @command{exec} must work with the list of 17 utilities
16414 that are invoked without a @env{PATH} search, and many platforms lack an
16415 executable for some of those built-ins:
16417 @example
16418 $ @kbd{sh -c 'exec cd /tmp'}
16419 sh: line 0: exec: cd: not found
16420 @end example
16422 All other built-ins that provide utilities specified by Posix must have
16423 a counterpart executable that exists on @env{PATH}, although Posix
16424 allows @command{exec} to use the built-in instead of the executable.
16425 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
16427 @example
16428 $ @kbd{bash -c 'pwd --version' | head -n1}
16429 bash: line 0: pwd: --: invalid option
16430 pwd: usage: pwd [-LP]
16431 $ @kbd{bash -c 'exec pwd --version' | head -n1}
16432 pwd (GNU coreutils) 6.10
16433 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
16434 pdksh: pwd: --: unknown option
16435 @end example
16437 When it is desired to avoid a regular shell built-in, the workaround is
16438 to use some other forwarding command, such as @command{env} or
16439 @command{nice}, that will ensure a path search:
16441 @example
16442 $ @kbd{pdksh -c 'exec true --version' | head -n1}
16443 $ @kbd{pdksh -c 'nice true --version' | head -n1}
16444 true (GNU coreutils) 6.10
16445 $ @kbd{pdksh -c 'env true --version' | head -n1}
16446 true (GNU coreutils) 6.10
16447 @end example
16449 @item @command{exit}
16450 @c -----------------
16451 @prindex @command{exit}
16452 The default value of @command{exit} is supposed to be @code{$?};
16453 unfortunately, some shells, such as the @acronym{DJGPP} port of Bash 2.04, just
16454 perform @samp{exit 0}.
16456 @example
16457 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
16458 fail
16459 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
16460 fail
16461 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
16462 bash-2.04$
16463 @end example
16465 Using @samp{exit $?} restores the expected behavior.
16467 Some shell scripts, such as those generated by @command{autoconf}, use a
16468 trap to clean up before exiting.  If the last shell command exited with
16469 nonzero status, the trap also exits with nonzero status so that the
16470 invoker can tell that an error occurred.
16472 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
16473 trap ignores the @code{exit} command's argument.  In these shells, a trap
16474 cannot determine whether it was invoked by plain @code{exit} or by
16475 @code{exit 1}.  Instead of calling @code{exit} directly, use the
16476 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
16479 @anchor{export}
16480 @item @command{export}
16481 @c -------------------
16482 @prindex @command{export}
16483 The builtin @command{export} dubs a shell variable @dfn{environment
16484 variable}.  Each update of exported variables corresponds to an update
16485 of the environment variables.  Conversely, each environment variable
16486 received by the shell when it is launched should be imported as a shell
16487 variable marked as exported.
16489 Alas, many shells, such as Solaris @command{/bin/sh},
16490 @sc{irix} 6.3, @sc{irix} 5.2,
16491 @acronym{AIX} 4.1.5, and Digital Unix 4.0, forget to
16492 @command{export} the environment variables they receive.  As a result,
16493 two variables coexist: the environment variable and the shell
16494 variable.  The following code demonstrates this failure:
16496 @example
16497 #!/bin/sh
16498 echo $FOO
16499 FOO=bar
16500 echo $FOO
16501 exec /bin/sh $0
16502 @end example
16504 @noindent
16505 when run with @samp{FOO=foo} in the environment, these shells print
16506 alternately @samp{foo} and @samp{bar}, although they should print only
16507 @samp{foo} and then a sequence of @samp{bar}s.
16509 Therefore you should @command{export} again each environment variable
16510 that you update; the export can occur before or after the assignment.
16512 Posix is not clear on whether the @command{export} of an undefined
16513 variable causes the variable to be defined with the value of an empty
16514 string, or merely marks any future definition of a variable by that name
16515 for export.  Various shells behave differently in this regard:
16517 @example
16518 $ @kbd{sh -c 'export foo; env | grep foo'}
16519 $ @kbd{ash -c 'export foo; env | grep foo'}
16520 foo=
16521 @end example
16523 @item @command{false}
16524 @c ------------------
16525 @prindex @command{false}
16526 Don't expect @command{false} to exit with status 1: in native
16527 Solaris @file{/bin/false} exits with status 255.
16530 @item @command{for}
16531 @c ----------------
16532 @prindex @command{for}
16533 To loop over positional arguments, use:
16535 @example
16536 for arg
16538   echo "$arg"
16539 done
16540 @end example
16542 @noindent
16543 You may @emph{not} leave the @code{do} on the same line as @code{for},
16544 since some shells improperly grok:
16546 @example
16547 for arg; do
16548   echo "$arg"
16549 done
16550 @end example
16552 If you want to explicitly refer to the positional arguments, given the
16553 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
16555 @example
16556 for arg in $@{1+"$@@"@}; do
16557   echo "$arg"
16558 done
16559 @end example
16561 @noindent
16562 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
16563 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
16564 item @samp{$@@}, for more.
16567 @anchor{if}
16568 @item @command{if}
16569 @c ---------------
16570 @prindex @command{if}
16571 Using @samp{!} is not portable.  Instead of:
16573 @example
16574 if ! cmp -s file file.new; then
16575   mv file.new file
16577 @end example
16579 @noindent
16580 use:
16582 @example
16583 if cmp -s file file.new; then :; else
16584   mv file.new file
16586 @end example
16588 @noindent
16589 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
16590 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
16591 of conditionals:
16593 @example
16594 AS_IF([cmp -s file file.new], [], [mv file.new file])
16595 @end example
16597 This is especially useful in other M4 macros, where the @dfn{then} and
16598 @dfn{else} branches might be macro arguments.
16600 Some very old shells did not reset the exit status from an @command{if}
16601 with no @command{else}:
16603 @example
16604 $ @kbd{if (exit 42); then true; fi; echo $?}
16606 @end example
16608 @noindent
16609 whereas a proper shell should have printed @samp{0}.  But this is no
16610 longer a portability problem; any shell that supports functions gets it
16611 correct.  However, it explains why some makefiles have lengthy
16612 constructs:
16614 @example
16615 if test -f "$file"; then
16616   install "$file" "$dest"
16617 else
16618   :
16620 @end example
16623 @item @command{printf}
16624 @c ------------------
16625 @prindex @command{printf}
16626 A format string starting with a @samp{-} can cause problems.
16627 Bash interprets it as an option and
16628 gives an error.  And @samp{--} to mark the end of options is not good
16629 in the Net@acronym{BSD} Almquist shell (e.g., 0.4.6) which takes that
16630 literally as the format string.  Putting the @samp{-} in a @samp{%c}
16631 or @samp{%s} is probably easiest:
16633 @example
16634 printf %s -foo
16635 @end example
16637 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
16639 @example
16640 $ @kbd{printf '\045'}
16641 bash: printf: `%': missing format character
16642 @end example
16644 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
16645 example, @file{/usr/bin/printf} is buggy, so when using
16646 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
16647 core.
16649 Since @command{printf} is not always a shell builtin, there is a
16650 potential speed penalty for using @code{printf '%s\n'} as a replacement
16651 for an @command{echo} that does not interpret @samp{\} or leading
16652 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
16653 -r --} for this role instead.
16655 For a discussion of portable alternatives to both @command{printf}
16656 and @command{echo}, @xref{echo, , Limitations of Shell Builtins}.
16659 @item @command{pwd}
16660 @c ----------------
16661 @prindex @command{pwd}
16662 With modern shells, plain @command{pwd} outputs a ``logical''
16663 directory name, some of whose components may be symbolic links.  These
16664 directory names are in contrast to ``physical'' directory names, whose
16665 components are all directories.
16667 Posix 1003.1-2001 requires that @command{pwd} must support
16668 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
16669 with @option{-L} being the default.  However, traditional shells do
16670 not support these options, and their @command{pwd} command has the
16671 @option{-P} behavior.
16673 Portable scripts should assume neither option is supported, and should
16674 assume neither behavior is the default.  Also, on many hosts
16675 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
16676 does not require this behavior and portable scripts should not rely on
16679 Typically it's best to use plain @command{pwd}.  On modern hosts this
16680 outputs logical directory names, which have the following advantages:
16682 @itemize @bullet
16683 @item
16684 Logical names are what the user specified.
16685 @item
16686 Physical names may not be portable from one installation
16687 host to another due to network file system gymnastics.
16688 @item
16689 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
16690 some parent directory, but plain @command{pwd} cannot fail for this
16691 reason.
16692 @end itemize
16694 Also please see the discussion of the @command{cd} command.
16697 @item @command{read}
16698 @c -----------------
16699 @prindex @command{read}
16700 No options are portable, not even support @option{-r} (Solaris
16701 @command{/bin/sh} for example).
16704 @anchor{set}
16705 @item @command{set}
16706 @c ----------------
16707 @prindex @command{set}
16708 With the Free@acronym{BSD} 6.0 shell, the @command{set} command (without
16709 any options) does not sort its output.
16711 The @command{set} builtin faces the usual problem with arguments
16712 starting with a
16713 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
16714 the end of the options (any argument after @option{--} is a parameter,
16715 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
16716 10 @command{/bin/sh}) simply stop option
16717 processing as soon as a non-option argument is found.  Therefore, use
16718 @samp{dummy} or simply @samp{x} to end the option processing, and use
16719 @command{shift} to pop it out:
16721 @example
16722 set x $my_list; shift
16723 @end example
16725 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
16726 longer requires support for this command, and in traditional shells
16727 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
16728 makes scripts harder to debug.
16730 Some nonstandard shells do not recognize more than one option
16731 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
16732 better to combine them:
16734 @example
16735 set -ex
16736 @end example
16738 @cindex @command{set -e}
16739 The option @option{-e} has historically been underspecified, with enough
16740 ambiguities to cause numerous differences across various shell
16741 implementations.  Perhaps the best reference is
16742 @uref{http://www.opengroup.org/@/austin/@/mailarchives/@/ag-review/@/msg03507.html,
16743 this link}, recommending a change to Posix 2008 to match @command{ksh88}
16744 behavior.  Note that mixing @code{set -e} and shell functions is asking
16745 for surprises:
16747 @example
16748 set -e
16749 doit()
16751   rm file
16752   echo one
16754 doit || echo two
16755 @end example
16757 @noindent
16758 According to the recommendation, @samp{one} should always be output
16759 regardless of whether the @command{rm} failed, because it occurs within
16760 the body of the shell function @samp{doit} invoked on the left side of
16761 @samp{||}, where the effects of @samp{set -e} are not enforced.
16762 Likewise, @samp{two} should never be printed, since the failure of
16763 @command{rm} does not abort the function, such that the status of
16764 @samp{doit} is 0.
16766 The @acronym{BSD} shell has had several problems with the @option{-e}
16767 option.  Older versions of the @acronym{BSD}
16768 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
16769 @samp{case} when @option{-e} was in effect, causing the shell to exit
16770 unexpectedly in some cases.  This was particularly a problem with
16771 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
16772 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
16773 wrapper works around the bug (@pxref{Failure in Make Rules}).
16775 Even relatively-recent versions of the @acronym{BSD} shell (e.g.,
16776 Open@acronym{BSD} 3.4) wrongly exit with @option{-e} if a command within
16777 @samp{&&} fails inside a compound statement.  For example:
16779 @example
16780 #! /bin/sh
16781 set -e
16782 foo=''
16783 test -n "$foo" && exit 1
16784 echo one
16785 if :; then
16786   test -n "$foo" && exit 1
16788 echo two
16789 @end example
16791 @noindent
16792 does not print @samp{two}.  One workaround is to use @samp{if test -n
16793 "$foo"; then exit 1; fi} rather than @samp{test -n "$foo" && exit 1}.
16794 Another possibility is to warn @acronym{BSD} users not to use @samp{sh -e}.
16796 When @samp{set -e} is in effect, a failed command substitution in
16797 Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
16799 @example
16800 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
16801 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
16804 @end example
16806 @noindent
16807 Moreover, a command substitution, successful or not, causes this shell to
16808 exit from a failing outer command even in presence of an @samp{&&} list:
16810 @example
16811 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
16813 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
16815 @end example
16817 Portable scripts should not use @samp{set -e} if @command{trap} is used
16818 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
16819 sometimes enters the trap handler with the exit status of the command
16820 prior to the one that triggered the errexit handler:
16822 @example
16823 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
16825 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
16827 @end example
16829 @noindent
16830 Thus, when writing a script in M4sh, rather than trying to rely on
16831 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
16832 statement where it is desirable to abort on failure.
16834 @cindex @command{set -b}
16835 @cindex @command{set -m}
16836 Job control is not provided by all shells, so the use of @samp{set -m}
16837 or @samp{set -b} must be done with care.  When using @command{zsh} in
16838 native mode, asynchronous notification (@samp{set -b}) is enabled by
16839 default, and using @samp{emulate sh} to switch to Posix mode does not
16840 clear this setting (although asynchronous notification has no impact
16841 unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
16842 earlier have a bug where job control can be manipulated in interactive
16843 shells, but not in subshells or scripts.  Furthermore, some shells, like
16844 @command{pdksh}, fail to treat subshells as interactive, even though the
16845 parent shell was.
16847 @example
16848 $ @kbd{echo $ZSH_VERSION}
16849 4.3.10
16850 $ @kbd{set -m; echo $?}
16852 $ @kbd{zsh -c 'set -m; echo $?'}
16853 set: can't change option: -m
16854 $ @kbd{(set -m); echo $?}
16855 set: can't change option: -m
16857 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
16860 @end example
16863 @item @command{shift}
16864 @c ------------------
16865 @prindex @command{shift}
16866 Not only is @command{shift}ing a bad idea when there is nothing left to
16867 shift, but in addition it is not portable: the shell of @acronym{MIPS
16868 RISC/OS} 4.52 refuses to do it.
16870 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
16871 it is also absent in many pre-Posix shells.
16874 @item @command{source}
16875 @c -------------------
16876 @prindex @command{source}
16877 This command is not portable, as Posix does not require it; use
16878 @command{.} instead.
16881 @item @command{test}
16882 @c -----------------
16883 @prindex @command{test}
16884 The @code{test} program is the way to perform many file and string
16885 tests.  It is often invoked by the alternate name @samp{[}, but using
16886 that name in Autoconf code is asking for trouble since it is an M4 quote
16887 character.
16889 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
16890 present in all implementations, and have been marked obsolete by Posix
16891 2008.  This is because there are inherent ambiguities in using them.
16892 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
16893 check whether two strings are both non-empty, but if @samp{$1} is the
16894 literal @samp{!}, then some implementations of @command{test} treat it
16895 as a negation of the unary operator @option{-a}.
16897 Thus, portable uses of @command{test} should never have more than four
16898 arguments, and scripts should use shell constructs like @samp{&&} and
16899 @samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
16900 statement, keep in mind that they have equal precedence, so it is often
16901 better to parenthesize even when this is redundant.  For example:
16903 @smallexample
16904 # Not portable:
16905 test "X$a" = "X$b" -a \
16906   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
16908 # Portable:
16909 test "X$a" = "X$b" &&
16910   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
16911 @end smallexample
16913 @command{test} does not process options like most other commands do; for
16914 example, it does not recognize the @option{--} argument as marking the
16915 end of options.
16917 It is safe to use @samp{!} as a @command{test} operator.  For example,
16918 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
16919 -d foo; @dots{}} is not.
16922 @item @command{test} (files)
16923 @c -------------------------
16924 To enable @command{configure} scripts to support cross-compilation, they
16925 shouldn't do anything that tests features of the build system instead of
16926 the host system.  But occasionally you may find it necessary to check
16927 whether some arbitrary file exists.  To do so, use @samp{test -f} or
16928 @samp{test -r}.  Do not use @samp{test -x}, because 4.3@acronym{BSD} does not
16929 have it.  Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
16930 lacks it.  To test for symbolic links on systems that have them, use
16931 @samp{test -h} rather than @samp{test -L}; either form conforms to
16932 Posix 1003.1-2001, but older shells like Solaris 8
16933 @code{/bin/sh} support only @option{-h}.
16935 @item @command{test} (strings)
16936 @c ---------------------------
16937 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
16938 not null, but this usage is not portable to traditional platforms like
16939 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
16940 @samp{-n}.
16942 Posix also says that @samp{test ! "@var{string}"},
16943 @samp{test -n "@var{string}"} and
16944 @samp{test -z "@var{string}"} work with any string, but many
16945 shells (such as Solaris, @acronym{AIX} 3.2, @sc{unicos} 10.0.0.6,
16946 Digital Unix 4, etc.)@: get confused if
16947 @var{string} looks like an operator:
16949 @example
16950 $ @kbd{test -n =}
16951 test: argument expected
16952 $ @kbd{test ! -n}
16953 test: argument expected
16954 @end example
16956 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
16957 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
16958 strings, but in practice this is not true for troublesome strings that
16959 look like operators or parentheses, or that begin with @samp{-}.
16961 It is best to protect such strings with a leading @samp{X}, e.g.,
16962 @samp{test "X@var{string}" != X} rather than @samp{test -n
16963 "@var{string}"} or @samp{test ! "@var{string}"}.
16965 It is common to find variations of the following idiom:
16967 @example
16968 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
16969   @var{action}
16970 @end example
16972 @noindent
16973 to take an action when a token matches a given pattern.  Such constructs
16974 should be avoided by using:
16976 @example
16977 case $ac_feature in
16978   *[!-a-zA-Z0-9_]*) @var{action};;
16979 esac
16980 @end example
16982 If the pattern is a complicated regular expression that cannot be
16983 expressed as a shell pattern, use something like this instead:
16985 @example
16986 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
16987   @var{action}
16988 @end example
16990 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
16991 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
16992 @samp{@var{foo}} contains backslashes.
16995 @anchor{trap}
16996 @item @command{trap}
16997 @c -----------------
16998 @prindex @command{trap}
16999 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
17000 trap 0, i.e., have the @command{trap} run when the script ends (either via an
17001 explicit @command{exit}, or the end of the script).  The trap for 0 should be
17002 installed outside of a shell function, or @acronym{AIX} 5.3 @command{/bin/sh}
17003 will invoke the trap at the end of this function.
17005 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
17006 specified signals to their default values, but many common shells (e.g.,
17007 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
17008 ``command'' named @command{-} when the specified conditions arise.
17009 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
17010 reset traps, as this is supported by a larger set of shells, but there
17011 are still shells like @command{dash} that mistakenly try to execute
17012 @command{1} instead of resetting the traps.  Therefore, there is no
17013 portable workaround, except for @samp{trap - 0}, for which
17014 @samp{trap '' 0} is a portable substitute.
17016 Although Posix is not absolutely clear on this point, it is widely
17017 admitted that when entering the trap @samp{$?} should be set to the exit
17018 status of the last command run before the trap.  The ambiguity can be
17019 summarized as: ``when the trap is launched by an @command{exit}, what is
17020 the @emph{last} command run: that before @command{exit}, or
17021 @command{exit} itself?''
17023 Bash considers @command{exit} to be the last command, while Zsh and
17024 Solaris @command{/bin/sh} consider that when the trap is run it is
17025 @emph{still} in the @command{exit}, hence it is the previous exit status
17026 that the trap receives:
17028 @example
17029 $ @kbd{cat trap.sh}
17030 trap 'echo $?' 0
17031 (exit 42); exit 0
17032 $ @kbd{zsh trap.sh}
17034 $ @kbd{bash trap.sh}
17036 @end example
17038 The portable solution is then simple: when you want to @samp{exit 42},
17039 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
17040 set the exit status to 42 for Zsh, and the second to trigger the trap
17041 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
17042 @code{AS_EXIT}.
17044 The shell in Free@acronym{BSD} 4.0 has the following bug: @samp{$?} is
17045 reset to 0 by empty lines if the code is inside @command{trap}.
17047 @example
17048 $ @kbd{trap 'false}
17050 echo $?' 0
17051 $ @kbd{exit}
17053 @end example
17055 @noindent
17056 Fortunately, this bug only affects @command{trap}.
17058 Several shells fail to execute an exit trap that is defined inside a
17059 subshell, when the last command of that subshell is not a builtin.  A
17060 workaround is to use @samp{exit $?} as the shell builtin.
17062 @example
17063 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
17065 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
17066 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
17068 @end example
17070 @noindent
17071 Likewise, older implementations of @command{bash} failed to preserve
17072 @samp{$?} across an exit trap consisting of a single cleanup command.
17074 @example
17075 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
17077 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
17079 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
17081 @end example
17083 @item @command{true}
17084 @c -----------------
17085 @prindex @command{true}
17086 @c Info cannot handle `:' in index entries.
17087 @c @prindex @command{:}
17088 Don't worry: as far as we know @command{true} is portable.
17089 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
17090 portable shell community tends to prefer using @command{:}.  This has a
17091 funny side effect: when asked whether @command{false} is more portable
17092 than @command{true} Alexandre Oliva answered:
17094 @quotation
17095 In a sense, yes, because if it doesn't exist, the shell will produce an
17096 exit status of failure, which is correct for @command{false}, but not
17097 for @command{true}.
17098 @end quotation
17101 @anchor{unset}
17102 @item @command{unset}
17103 @c ------------------
17104 @prindex @command{unset}
17105 In some nonconforming shells (e.g., Bash 2.05a), @code{unset FOO} fails
17106 when @code{FOO} is not set.  You can use
17108 @smallexample
17109 FOO=; unset FOO
17110 @end smallexample
17112 if you are not sure that @code{FOO} is set.
17114 A few ancient shells lack @command{unset} entirely.  For some variables
17115 such as @code{PS1}, you can use a neutralizing value instead:
17117 @smallexample
17118 PS1='$ '
17119 @end smallexample
17121 Usually, shells that do not support @command{unset} need less effort to
17122 make the environment sane, so for example is not a problem if you cannot
17123 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
17124 @code{unset MAIL} in some cases and dumps core.  So, you should do
17125 something like
17127 @smallexample
17128 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
17129 @end smallexample
17131 @noindent
17132 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
17133 @ref{export, , Limitations of Builtins}, for
17134 the case of environment variables.
17136 @item @command{wait}
17137 @c -----------------
17138 @prindex @command{wait}
17139 The exit status of @command{wait} is not always reliable.
17140 @end table
17142 @node Limitations of Usual Tools
17143 @section Limitations of Usual Tools
17144 @cindex Limitations of usual tools
17146 The small set of tools you can expect to find on any machine can still
17147 include some limitations you should be aware of.
17149 @comment Between this list and the list of builtins above, we should
17150 @comment mention all the tools in GNU Coding Standards ``Utilities in
17151 @comment Makefiles''.
17153 @c This table includes things like `@command{expr} (|)', so we can't
17154 @c use @table @command.
17155 @table @asis
17156 @item @command{awk}
17157 @c ----------------
17158 @prindex @command{awk}
17159 Don't leave white space before the opening parenthesis in a user function call.
17160 Posix does not allow this and @acronym{GNU} Awk rejects it:
17162 @example
17163 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
17164         BEGIN @{ die () @}'}
17165 gawk: cmd. line:2:         BEGIN @{ die () @}
17166 gawk: cmd. line:2:                      ^ parse error
17167 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
17168         BEGIN @{ die() @}'}
17169 Aaaaarg!
17170 @end example
17172 Posix says that if a program contains only @samp{BEGIN} actions, and
17173 contains no instances of @code{getline}, then the program merely
17174 executes the actions without reading input.  However, traditional Awk
17175 implementations (such as Solaris 10 @command{awk}) read and discard
17176 input in this case.  Portable scripts can redirect input from
17177 @file{/dev/null} to work around the problem.  For example:
17179 @example
17180 awk 'BEGIN @{print "hello world"@}' </dev/null
17181 @end example
17183 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
17184 @samp{$1}) retain their value from the last record read, if no
17185 intervening @samp{getline} occurred.  However, some implementations
17186 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
17187 @samp{awk}) reset these variables.  A workaround is to use an
17188 intermediate variable prior to the @samp{END} block.  For example:
17190 @example
17191 $ @kbd{cat end.awk}
17192 @{ tmp = $1 @}
17193 END @{ print "a", $1, $NF, "b", tmp @}
17194 $ @kbd{echo 1 | awk -f end.awk}
17195 a   b 1
17196 $ @kbd{echo 1 | gawk -f end.awk}
17197 a 1 1 b 1
17198 @end example
17200 If you want your program to be deterministic, don't depend on @code{for}
17201 on arrays:
17203 @example
17204 $ @kbd{cat for.awk}
17205 END @{
17206   arr["foo"] = 1
17207   arr["bar"] = 1
17208   for (i in arr)
17209     print i
17211 $ @kbd{gawk -f for.awk </dev/null}
17214 $ @kbd{nawk -f for.awk </dev/null}
17217 @end example
17219 Some Awk implementations, such as @acronym{HP-UX} 11.0's native one,
17220 mishandle anchors:
17222 @example
17223 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
17224 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
17226 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
17227 xfoo
17228 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
17230 @end example
17232 @noindent
17233 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
17234 or use a simple test to reject such implementations.
17236 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
17237 after @code{%u}:
17239 @example
17240 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
17241 0 0
17242 @end example
17244 @acronym{AIX} version 5.2 has an arbitrary limit of 399 on the
17245 length of regular expressions and literal strings in an Awk program.
17247 Traditional Awk implementations derived from Unix version 7, such as
17248 Solaris @command{/bin/awk}, have many limitations and do not
17249 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
17250 Programs}) finds you an Awk that doesn't have these problems, but if
17251 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
17252 address them.
17254 Traditional Awk does not support multidimensional arrays or user-defined
17255 functions.
17257 Traditional Awk does not support the @option{-v} option.  You can use
17258 assignments after the program instead, e.g., @code{$AWK '@{print v
17259 $1@}' v=x}; however, don't forget that such assignments are not
17260 evaluated until they are encountered (e.g., after any @code{BEGIN}
17261 action).
17263 Traditional Awk does not support the keywords @code{delete} or @code{do}.
17265 Traditional Awk does not support the expressions
17266 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
17267 or @code{@var{a}^=@var{b}}.
17269 Traditional Awk does not support the predefined @code{CONVFMT} variable.
17271 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
17272 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
17273 @code{sqrt}, and @code{substr}.
17275 Traditional Awk @code{getline} is not at all compatible with Posix;
17276 avoid it.
17278 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
17279 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
17281 In code portable to both traditional and modern Awk, @code{FS} must be a
17282 string containing just one ordinary character, and similarly for the
17283 field-separator argument to @code{split}.
17285 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
17286 implementations, like Tru64's, split the input even if you don't refer
17287 to any field in the script, to circumvent this problem, set @samp{FS}
17288 to an unusual character and use @code{split}.
17290 Traditional Awk has a limit of at most 99 bytes in a number formatted by
17291 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
17292 dumps core.
17294 The original version of Awk had a limit of at most 99 bytes per
17295 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
17296 per run of non-special characters in a @code{printf} format, but these
17297 bugs have been fixed on all practical hosts that we know of.
17299 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
17300 of at most 3070 bytes.
17302 @item @command{basename}
17303 @c ---------------------
17304 @prindex @command{basename}
17305 Not all hosts have a working @command{basename}.
17306 You can use @command{expr} instead.
17308 @c AS_BASENAME is to be replaced by a better API.
17309 @ignore
17310 Not all hosts have a working @command{basename}, and you should instead
17311 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
17312 @command{expr} if you need to strip a suffix.  For example:
17314 @example
17315 a=`basename "$aname"`       # This is not portable.
17316 a=`AS_BASENAME(["$aname"])` # This is more portable.
17318 # This is not portable.
17319 c=`basename "$cname" .c`
17321 # This is more portable.
17322 c=`AS_BASENAME(["$cname"])`
17323 case $c in
17324 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
17325 esac
17326 @end example
17327 @end ignore
17330 @item @command{cat}
17331 @c ----------------
17332 @prindex @command{cat}
17333 Don't rely on any option.
17336 @item @command{cc}
17337 @c ---------------
17338 @prindex @command{cc}
17339 The command @samp{cc -c foo.c} traditionally produces an object file
17340 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
17341 with @option{-o} to specify a different object file name, but
17342 Posix does not require this combination and a few compilers
17343 lack support for it.  @xref{C Compiler}, for how @acronym{GNU} Make
17344 tests for this feature with @code{AC_PROG_CC_C_O}.
17346 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
17347 (such as @sc{cds} on Reliant Unix) leave a @file{foo.o}.
17349 @acronym{HP-UX} @command{cc} doesn't accept @file{.S} files to preprocess and
17350 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
17351 nothing.
17353 The default executable, produced by @samp{cc foo.c}, can be
17355 @itemize
17356 @item @file{a.out} --- usual Posix convention.
17357 @item @file{b.out} --- i960 compilers (including @command{gcc}).
17358 @item @file{a.exe} --- @acronym{DJGPP} port of @command{gcc}.
17359 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
17360 @item @file{foo.exe} --- various MS-DOS compilers.
17361 @end itemize
17363 The C compiler's traditional name is @command{cc}, but other names like
17364 @command{gcc} are common.  Posix 1003.1-2001 specifies the
17365 name @command{c99}, but older Posix editions specified
17366 @command{c89} and anyway these standard names are rarely used in
17367 practice.  Typically the C compiler is invoked from makefiles that use
17368 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
17369 compiler name.
17371 @item @command{chgrp}
17372 @itemx @command{chown}
17373 @c -------------------
17374 @prindex @command{chgrp}
17375 @prindex @command{chown}
17376 It is not portable to change a file's group to a group that the owner
17377 does not belong to.
17379 @item @command{chmod}
17380 @c ------------------
17381 @prindex @command{chmod}
17382 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
17383 instead, for two reasons.  First, plain @option{-w} does not necessarily
17384 make the file unwritable, since it does not affect mode bits that
17385 correspond to bits in the file mode creation mask.  Second,
17386 Posix says that the @option{-w} might be interpreted as an
17387 implementation-specific option, not as a mode; Posix suggests
17388 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
17389 @samp{--} does not work on some older hosts.
17392 @item @command{cmp}
17393 @c ----------------
17394 @prindex @command{cmp}
17395 @command{cmp} performs a raw data comparison of two files, while
17396 @command{diff} compares two text files.  Therefore, if you might compare
17397 DOS files, even if only checking whether two files are different, use
17398 @command{diff} to avoid spurious differences due to differences of
17399 newline encoding.
17402 @item @command{cp}
17403 @c ---------------
17404 @prindex @command{cp}
17405 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
17406 obsolescent and its behavior on special files is implementation-defined.
17407 Use @option{-R} instead.  On @acronym{GNU} hosts the two options
17408 are equivalent, but on Solaris hosts (for example) @code{cp -r}
17409 reads from pipes instead of replicating them.
17411 Some @command{cp} implementations (e.g., @acronym{BSD/OS} 4.2) do not allow
17412 trailing slashes at the end of nonexistent destination directories.  To
17413 avoid this problem, omit the trailing slashes.  For example, use
17414 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
17415 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
17417 @c This is thanks to Ian.
17418 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
17419 its @command{mv} does.
17421 @cindex timestamp resolution
17422 Traditionally, file timestamps had 1-second resolution, and @samp{cp
17423 -p} copied the timestamps exactly.  However, many modern file systems
17424 have timestamps with 1-nanosecond resolution.  Unfortunately, @samp{cp
17425 -p} implementations truncate timestamps when copying files, so this
17426 can result in the destination file appearing to be older than the
17427 source.  The exact amount of truncation depends on the resolution of
17428 the system calls that @command{cp} uses; traditionally this was
17429 @code{utime}, which has 1-second resolution, but some newer
17430 @command{cp} implementations use @code{utimes}, which has
17431 1-microsecond resolution.  These newer implementations include @acronym{GNU}
17432 Core Utilities 5.0.91 or later, and Solaris 8 (sparc) patch 109933-02 or
17433 later.  Unfortunately as of January 2006 there is still no system
17434 call to set timestamps to the full nanosecond resolution.
17436 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
17437 ownerships.  But whether it actually does copy ownerships or not is a
17438 system dependent policy decision implemented by the kernel.  If the
17439 kernel allows it then it happens.  If the kernel does not allow it then
17440 it does not happen.  It is not something @command{cp} itself has control
17441 over.
17443 In Unix System V any user can chown files to any other user, and System
17444 V also has a non-sticky @file{/tmp}.  That probably derives from the
17445 heritage of System V in a business environment without hostile users.
17446 @acronym{BSD} changed this
17447 to be a more secure model where only root can @command{chown} files and
17448 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
17449 of @acronym{BSD} in a campus environment.
17451 @acronym{GNU}/Linux and Solaris by default follow @acronym{BSD}, but
17452 can be configured to allow a System V style @command{chown}.  On the
17453 other hand, @acronym{HP-UX} follows System V, but can
17454 be configured to use the modern security model and disallow
17455 @command{chown}.  Since it is an administrator-configurable parameter
17456 you can't use the name of the kernel as an indicator of the behavior.
17460 @item @command{date}
17461 @c -----------------
17462 @prindex @command{date}
17463 Some versions of @command{date} do not recognize special @samp{%} directives,
17464 and unfortunately, instead of complaining, they just pass them through,
17465 and exit with success:
17467 @example
17468 $ @kbd{uname -a}
17469 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
17470 $ @kbd{date "+%s"}
17472 @end example
17475 @item @command{diff}
17476 @c -----------------
17477 @prindex @command{diff}
17478 Option @option{-u} is nonportable.
17480 Some implementations, such as Tru64's, fail when comparing to
17481 @file{/dev/null}.  Use an empty file instead.
17484 @item @command{dirname}
17485 @c --------------------
17486 @prindex @command{dirname}
17487 Not all hosts have a working @command{dirname}, and you should instead
17488 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
17490 @example
17491 dir=`dirname "$file"`       # This is not portable.
17492 dir=`AS_DIRNAME(["$file"])` # This is more portable.
17493 @end example
17496 @item @command{egrep}
17497 @c ------------------
17498 @prindex @command{egrep}
17499 Posix 1003.1-2001 no longer requires @command{egrep},
17500 but many hosts do not yet support the Posix
17501 replacement @code{grep -E}.  Also, some traditional implementations do
17502 not work on long input lines.  To work around these problems, invoke
17503 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
17505 Portable extended regular expressions should use @samp{\} only to escape
17506 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
17507 is not portable, even though it typically matches @samp{@}}.
17509 The empty alternative is not portable.  Use @samp{?} instead.  For
17510 instance with Digital Unix v5.0:
17512 @example
17513 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
17514 |foo
17515 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
17516 bar|
17517 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
17519 |bar
17520 @end example
17522 @command{$EGREP} also suffers the limitations of @command{grep}
17523 (@pxref{grep, , Limitations of Usual Tools}).
17525 @item @command{expr}
17526 @c -----------------
17527 @prindex @command{expr}
17528 Not all implementations obey the Posix rule that @samp{--} separates
17529 options from arguments; likewise, not all implementations provide the
17530 extension to Posix that the first argument can be treated as part of a
17531 valid expression rather than an invalid option if it begins with
17532 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
17533 @samp{$var} might be a negative number, to keep @command{expr} from
17534 interpreting it as an option.
17536 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
17537 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
17538 misinterpreting @var{word}.
17540 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
17542 @item @command{expr} (@samp{|})
17543 @prindex @command{expr} (@samp{|})
17544 You can use @samp{|}.  Although Posix does require that @samp{expr
17545 ''} return the empty string, it does not specify the result when you
17546 @samp{|} together the empty string (or zero) with the empty string.  For
17547 example:
17549 @example
17550 expr '' \| ''
17551 @end example
17553 Posix 1003.2-1992 returns the empty string
17554 for this case, but traditional Unix returns @samp{0} (Solaris is
17555 one such example).  In Posix 1003.1-2001, the specification was
17556 changed to match traditional Unix's behavior (which is
17557 bizarre, but it's too late to fix this).  Please note that the same
17558 problem does arise when the empty string results from a computation,
17559 as in:
17561 @example
17562 expr bar : foo \| foo : bar
17563 @end example
17565 @noindent
17566 Avoid this portability problem by avoiding the empty string.
17569 @item @command{expr} (@samp{:})
17570 @c ----------------------------
17571 @prindex @command{expr}
17572 Portable @command{expr} regular expressions should use @samp{\} to
17573 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
17574 For example, alternation, @samp{\|}, is common but Posix does not
17575 require its support, so it should be avoided in portable scripts.
17576 Similarly, @samp{\+} and @samp{\?} should be avoided.
17578 Portable @command{expr} regular expressions should not begin with
17579 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
17580 not needed anyway.
17582 On the other hand, the behavior of the @samp{$} anchor is not portable
17583 on multi-line strings.  Posix is ambiguous whether the anchor applies to
17584 each line, as was done in older versions of @acronym{GNU} Coreutils, or
17585 whether it applies only to the end of the overall string, as in
17586 Coreutils 6.0 and most other implementations.
17588 @example
17589 $ @kbd{baz='foo}
17590 > @kbd{bar'}
17591 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
17593 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
17595 @end example
17597 The Posix standard is ambiguous as to whether
17598 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
17599 In practice, it outputs the empty string on most platforms, but portable
17600 scripts should not assume this.  For instance, the @acronym{QNX} 4.25 native
17601 @command{expr} returns @samp{0}.
17603 One might think that a way to get a uniform behavior would be to use
17604 the empty string as a default value:
17606 @example
17607 expr a : '\(b\)' \| ''
17608 @end example
17610 @noindent
17611 Unfortunately this behaves exactly as the original expression; see the
17612 @command{expr} (@samp{|}) entry for more information.
17614 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
17615 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
17616 @command{expr} to fail if the matched substring is longer than 120
17617 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
17618 @command{expr} fails.  Nowadays this is of practical importance only for
17619 the rare installer who mistakenly puts @file{/usr/ucb} before
17620 @file{/usr/bin} in @env{PATH}.
17622 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
17623 some cases.  For example, the command
17624 @example
17625 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
17626 @end example
17628 @noindent
17629 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
17630 This particular case can be worked around by substituting @samp{[^--]}
17631 for @samp{[^-]}.
17633 Don't leave, there is some more!
17635 The @acronym{QNX} 4.25 @command{expr}, in addition of preferring @samp{0} to
17636 the empty string, has a funny behavior in its exit status: it's always 1
17637 when parentheses are used!
17639 @example
17640 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
17641 0: 1
17642 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
17643 1: 0
17645 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
17646 1: a
17647 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
17648 1: 0
17649 @end example
17651 @noindent
17652 In practice this can be a big problem if you are ready to catch failures
17653 of @command{expr} programs with some other method (such as using
17654 @command{sed}), since you may get twice the result.  For instance
17656 @example
17657 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
17658 @end example
17660 @noindent
17661 outputs @samp{a} on most hosts, but @samp{aa} on @acronym{QNX} 4.25.  A
17662 simple workaround consists of testing @command{expr} and using a variable
17663 set to @command{expr} or to @command{false} according to the result.
17665 Tru64 @command{expr} incorrectly treats the result as a number, if it
17666 can be interpreted that way:
17668 @example
17669 $ @kbd{expr 00001 : '.*\(...\)'}
17671 @end example
17673 On @acronym{HP-UX} 11, @command{expr} only supports a single
17674 sub-expression.
17676 @example
17677 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
17678 expr: More than one '\(' was used.
17679 @end example
17682 @item @command{fgrep}
17683 @c ------------------
17684 @prindex @command{fgrep}
17685 Posix 1003.1-2001 no longer requires @command{fgrep},
17686 but many hosts do not yet support the Posix
17687 replacement @code{grep -F}.  Also, some traditional implementations do
17688 not work on long input lines.  To work around these problems, invoke
17689 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
17692 @item @command{find}
17693 @c -----------------
17694 @prindex @command{find}
17695 The option @option{-maxdepth} seems to be @acronym{GNU} specific.
17696 Tru64 v5.1, Net@acronym{BSD} 1.5 and Solaris @command{find}
17697 commands do not understand it.
17699 The replacement of @samp{@{@}} is guaranteed only if the argument is
17700 exactly @emph{@{@}}, not if it's only a part of an argument.  For
17701 instance on DU, and @acronym{HP-UX} 10.20 and @acronym{HP-UX} 11:
17703 @example
17704 $ @kbd{touch foo}
17705 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
17706 @{@}-@{@}
17707 @end example
17709 @noindent
17710 while @acronym{GNU} @command{find} reports @samp{./foo-./foo}.
17713 @anchor{grep}
17714 @item @command{grep}
17715 @c -----------------
17716 @prindex @command{grep}
17717 Portable scripts can rely on the @command{grep} options @option{-c},
17718 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
17719 options.  For example, don't use @option{-w}, as Posix does not require
17720 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
17721 portable scripts should not combine @option{-c} with @option{-l},
17722 as Posix does not allow this.
17724 Some of the options required by Posix are not portable in practice.
17725 Don't use @samp{grep -q} to suppress output, because many @command{grep}
17726 implementations (e.g., Solaris) do not support @option{-q}.
17727 Don't use @samp{grep -s} to suppress output either, because Posix
17728 says @option{-s} does not suppress output, only some error messages;
17729 also, the @option{-s} option of traditional @command{grep} behaved
17730 like @option{-q} does in most modern implementations.  Instead,
17731 redirect the standard output and standard error (in case the file
17732 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
17733 status of @code{grep} to determine whether it found a match.
17735 Some traditional @command{grep} implementations do not work on long
17736 input lines.  On AIX the default @code{grep} silently truncates long
17737 lines on the input before matching.
17739 Also, many implementations do not support multiple regexps
17740 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
17741 or honor only the last pattern (e.g., @acronym{IRIX} 6.5 and NeXT).  To
17742 work around these problems, invoke @code{AC_PROG_GREP} and then use
17743 @code{$GREP}.
17745 Another possible workaround for the multiple @option{-e} problem is to
17746 separate the patterns by newlines, for example:
17748 @example
17749 grep 'foo
17750 bar' in.txt
17751 @end example
17753 @noindent
17754 except that this fails with traditional @command{grep}
17755 implementations and with Open@acronym{BSD} 3.8 @command{grep}.
17757 Traditional @command{grep} implementations (e.g., Solaris) do not
17758 support the @option{-E} or @option{-F} options.  To work around these
17759 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
17760 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
17761 willing to require support for Posix @command{grep}, your script should
17762 not use both @option{-E} and @option{-F}, since Posix does not allow
17763 this combination.
17765 Portable @command{grep} regular expressions should use @samp{\} only to
17766 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
17767 alternation, @samp{\|}, is common but Posix does not require its
17768 support in basic regular expressions, so it should be avoided in
17769 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
17770 Similarly, the following escape sequences should also be avoided:
17771 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
17772 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
17774 Posix does not specify the behavior of @command{grep} on binary files.
17775 An example where this matters is using @acronym{BSD} @command{grep} to
17776 search text that includes embedded @acronym{ANSI} escape sequences for
17777 colored output to terminals (@samp{\033[m} is the sequence to restore
17778 normal output); the behavior depends on whether input is seekable:
17780 @example
17781 $ @kbd{printf 'esc\033[mape\n' > sample}
17782 $ @kbd{grep . sample}
17783 Binary file sample matches
17784 $ @kbd{cat sample | grep .}
17785 escape
17786 @end example
17789 @item @command{join}
17790 @c -----------------
17791 @prindex @command{join}
17792 Solaris 8 @command{join} has bugs when the second operand is standard
17793 input, and when standard input is a pipe.  For example, the following
17794 shell script causes Solaris 8 @command{join} to loop forever:
17796 @example
17797 cat >file <<'EOF'
17798 1 x
17799 2 y
17801 cat file | join file -
17802 @end example
17804 Use @samp{join - file} instead.
17807 @item @command{ln}
17808 @c ---------------
17809 @prindex @command{ln}
17810 @cindex Symbolic links
17811 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
17812 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
17814 For versions of the @acronym{DJGPP} before 2.04,
17815 @command{ln} emulates symbolic links
17816 to executables by generating a stub that in turn calls the real
17817 program.  This feature also works with nonexistent files like in the
17818 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
17819 which attempts to call @file{file.exe} if run.  But this feature only
17820 works for executables, so @samp{cp -p} is used instead for these
17821 systems.  @acronym{DJGPP} versions 2.04 and later have full support
17822 for symbolic links.
17825 @item @command{ls}
17826 @c ---------------
17827 @prindex @command{ls}
17828 @cindex Listing directories
17829 The portable options are @option{-acdilrtu}.  Current practice is for
17830 @option{-l} to output both owner and group, even though ancient versions
17831 of @command{ls} omitted the group.
17833 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
17834 to standard output if @file{foo} did not exist.  Hence a shell command
17835 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
17836 was equivalent to @samp{sources='*.c not found'} in the absence of
17837 @samp{.c} files.  This is no longer a practical problem, since current
17838 @command{ls} implementations send diagnostics to standard error.
17840 The behavior of @command{ls} on a directory that is being concurrently
17841 modified is not always predictable, because of a data race where cached
17842 information returned by @code{readdir} does not match the current
17843 directory state.  In fact, MacOS 10.5 has an intermittent bug where
17844 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
17845 once if other files were added or removed from the directory immediately
17846 prior to the @command{ls} call.  Since @command{ls} already sorts its
17847 output, the duplicate entries can be avoided by piping the results
17848 through @code{uniq}.
17850 @anchor{mkdir}
17851 @item @command{mkdir}
17852 @c ------------------
17853 @prindex @command{mkdir}
17854 @cindex Making directories
17855 No @command{mkdir} option is portable to older systems.  Instead of
17856 @samp{mkdir -p @var{file-name}}, you should use
17857 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
17858 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
17860 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
17861 go-w -p @var{dir}}, often leads to trouble.  Free@acronym{BSD}
17862 @command{mkdir} incorrectly attempts to change the permissions of
17863 @var{dir} even if it already exists.  @acronym{HP-UX} 11.23 and
17864 @acronym{IRIX} 6.5 @command{mkdir} often assign the wrong permissions to
17865 any newly-created parents of @var{dir}.
17867 Posix does not clearly specify whether @samp{mkdir -p foo}
17868 should succeed when @file{foo} is a symbolic link to an already-existing
17869 directory.  The @acronym{GNU} Core Utilities 5.1.0 @command{mkdir}
17870 succeeds, but Solaris @command{mkdir} fails.
17872 Traditional @code{mkdir -p} implementations suffer from race conditions.
17873 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
17874 at the same time, both processes might detect that @file{a} is missing,
17875 one might create @file{a}, then the other might try to create @file{a}
17876 and fail with a @code{File exists} diagnostic.  The @acronym{GNU} Core
17877 Utilities (@samp{fileutils} version 4.1), Free@acronym{BSD} 5.0,
17878 Net@acronym{BSD} 2.0.2, and Open@acronym{BSD} 2.4 are known to be
17879 race-free when two processes invoke @code{mkdir -p} simultaneously, but
17880 earlier versions are vulnerable.  Solaris @command{mkdir} is still
17881 vulnerable as of Solaris 10, and other traditional Unix systems are
17882 probably vulnerable too.  This possible race is harmful in parallel
17883 builds when several Make rules call @code{mkdir -p} to
17884 construct directories.  You may use
17885 @code{install-sh -d} as a safe replacement, provided this script is
17886 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
17887 OK, but copies from older versions are vulnerable.
17890 @item @command{mkfifo}
17891 @itemx @command{mknod}
17892 @c -------------------
17893 @prindex @command{mkfifo}
17894 @prindex @command{mknod}
17895 The @acronym{GNU} Coding Standards state that @command{mknod} is safe to use on
17896 platforms where it has been tested to exist; but it is generally portable
17897 only for creating named FIFOs, since device numbers are
17898 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
17899 testsuites.  Posix states that behavior is unspecified when opening a
17900 named FIFO for both reading and writing; on at least Cygwin, this
17901 results in failure on any attempt to read or write to that file
17902 descriptor.
17904 @item @command{mktemp}
17905 @c -------------------
17906 @prindex @command{mktemp}
17907 @cindex Creating temporary files
17908 Shell scripts can use temporary files safely with @command{mktemp}, but
17909 it does not exist on all systems.  A portable way to create a safe
17910 temporary file name is to create a temporary directory with mode 700 and
17911 use a file inside this directory.  Both methods prevent attackers from
17912 gaining control, though @command{mktemp} is far less likely to fail
17913 gratuitously under attack.
17915 Here is sample code to create a new temporary directory safely:
17917 @example
17918 # Create a temporary directory $tmp in $TMPDIR (default /tmp).
17919 # Use mktemp if possible; otherwise fall back on mkdir,
17920 # with $RANDOM to make collisions less likely.
17921 : $@{TMPDIR=/tmp@}
17923   tmp=`
17924     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
17925   ` &&
17926   test -n "$tmp" && test -d "$tmp"
17927 @} || @{
17928   tmp=$TMPDIR/foo$$-$RANDOM
17929   (umask 077 && mkdir "$tmp")
17930 @} || exit $?
17931 @end example
17934 @item @command{mv}
17935 @c ---------------
17936 @prindex @command{mv}
17937 @cindex Moving open files
17938 The only portable options are @option{-f} and @option{-i}.
17940 Moving individual files between file systems is portable (it was in Unix
17941 version 6),
17942 but it is not always atomic: when doing @samp{mv new existing}, there's
17943 a critical section where neither the old nor the new version of
17944 @file{existing} actually exists.
17946 On some systems moving files from @file{/tmp} can sometimes cause
17947 undesirable (but perfectly valid) warnings, even if you created these
17948 files.  This is because @file{/tmp} belongs to a group that ordinary
17949 users are not members of, and files created in @file{/tmp} inherit
17950 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
17951 a diagnostic without failing:
17953 @smallexample
17954 $ @kbd{touch /tmp/foo}
17955 $ @kbd{mv /tmp/foo .}
17956 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
17957 $ @kbd{echo $?}
17959 $ @kbd{ls foo}
17961 @end smallexample
17963 @noindent
17964 This annoying behavior conforms to Posix, unfortunately.
17966 Moving directories across mount points is not portable, use @command{cp}
17967 and @command{rm}.
17969 @acronym{DOS} variants cannot rename or remove open files, and do not
17970 support commands like @samp{mv foo bar >foo}, even though this is
17971 perfectly portable among Posix hosts.
17974 @item @command{od}
17975 @c ---------------
17976 @prindex @command{od}
17978 In Mac OS X 10.3, @command{od} does not support the
17979 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
17980 @option{-t}, or the @acronym{XSI} option @option{-s}.  The only
17981 supported Posix option is @option{-v}, and the only supported
17982 @acronym{XSI} options are those in @option{-bcdox}.  The @acronym{BSD}
17983 @command{hexdump} program can be used instead.
17985 This problem no longer exists in Mac OS X 10.4.3.
17988 @item @command{rm}
17989 @c ---------------
17990 @prindex @command{rm}
17991 The @option{-f} and @option{-r} options are portable.
17993 It is not portable to invoke @command{rm} without operands.  For
17994 example, on many systems @samp{rm -f -r} (with no other arguments)
17995 silently succeeds without doing anything, but it fails with a diagnostic
17996 on Net@acronym{BSD} 2.0.2.
17998 A file might not be removed even if its parent directory is writable
17999 and searchable.  Many Posix hosts cannot remove a mount point, a named
18000 stream, a working directory, or a last link to a file that is being
18001 executed.
18003 @acronym{DOS} variants cannot rename or remove open files, and do not
18004 support commands like @samp{rm foo >foo}, even though this is
18005 perfectly portable among Posix hosts.
18007 @item @command{rmdir}
18008 @c ------------------
18009 @prindex @command{rmdir}
18010 Just as with @command{rm}, some platforms refuse to remove a working
18011 directory.
18013 @anchor{sed}
18014 @item @command{sed}
18015 @c ----------------
18016 @prindex @command{sed}
18017 Patterns should not include the separator (unless escaped), even as part
18018 of a character class.  In conformance with Posix, the Cray
18019 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
18020 Even when escaped, patterns should not include separators that are also
18021 used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
18022 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
18023 before evaluating the basic regular expression.
18025 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
18026 not require support for empty patterns, and Unicos 9 @command{sed} rejects
18027 them.
18029 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
18031 Sed scripts should not use branch labels longer than 7 characters and
18032 should not contain comments.  @acronym{HP-UX} sed has a limit of 99 commands
18033 (not counting @samp{:} commands) and
18034 48 labels, which can not be circumvented by using more than one script
18035 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
18036 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
18037 about 6000 bytes for the internal representation of commands.
18039 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
18040 Net@acronym{BSD} 1.4.2's, incorrectly try to interpret the second
18041 @samp{;} as a command:
18043 @example
18044 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
18045 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
18046 @end example
18048 Input should not have unreasonably long lines, since some @command{sed}
18049 implementations have an input buffer limited to 4000 bytes.  Likewise,
18050 not all @command{sed} implementations can handle embedded @code{NUL} or
18051 a missing trailing newline.
18053 Portable @command{sed} regular expressions should use @samp{\} only to escape
18054 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
18055 alternation, @samp{\|}, is common but Posix does not require its
18056 support, so it should be avoided in portable scripts.  Solaris
18057 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
18058 deletes only lines that contain the literal string @samp{a|b}.
18059 Similarly, @samp{\+} and @samp{\?} should be avoided.
18061 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
18063 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
18064 quite portable to current hosts, but was not supported by some ancient
18065 @command{sed} implementations like SVR3.
18067 Some @command{sed} implementations, e.g., Solaris, restrict the special
18068 role of the asterisk @samp{*} to one-character regular expressions and
18069 back-references, and the special role of interval expressions
18070 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
18071 to one-character regular expressions.  This may lead to unexpected behavior:
18073 @example
18074 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
18075 x2x4
18076 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
18078 @end example
18080 The @option{-e} option is mostly portable.
18081 However, its argument
18082 cannot start with @samp{a}, @samp{c}, or @samp{i},
18083 as this runs afoul of a Tru64 5.1 bug.
18084 Also, its argument cannot be empty, as this fails on @acronym{AIX} 5.3.
18085 Some people prefer to use @samp{-e}:
18087 @example
18088 sed -e '@var{command-1}' \
18089     -e '@var{command-2}'
18090 @end example
18092 @noindent
18093 as opposed to the equivalent:
18095 @example
18096 sed '
18097   @var{command-1}
18098   @var{command-2}
18100 @end example
18102 @noindent
18103 The following usage is sometimes equivalent:
18105 @example
18106 sed '@var{command-1};@var{command-2}'
18107 @end example
18109 but Posix says that this use of a semicolon has undefined effect if
18110 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
18111 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
18112 should use semicolon only with simple scripts that do not use these
18113 verbs.
18115 Commands inside @{ @} brackets are further restricted.  Posix says that
18116 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
18117 each command must be followed immediately by a newline, without any
18118 intervening blanks or semicolons.  The closing bracket must be alone on
18119 a line, other than white space preceding or following it.
18121 Contrary to yet another urban legend, you may portably use @samp{&} in
18122 the replacement part of the @code{s} command to mean ``what was
18123 matched''.  All descendants of Unix version 7 @command{sed}
18124 (at least; we
18125 don't have first hand experience with older @command{sed} implementations) have
18126 supported it.
18128 Posix requires that you must not have any white space between
18129 @samp{!} and the following command.  It is OK to have blanks between
18130 the address and the @samp{!}.  For instance, on Solaris:
18132 @example
18133 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
18134 @error{}Unrecognized command: /bar/ ! p
18135 $ @kbd{echo "foo" | sed -n '/bar/! p'}
18136 @error{}Unrecognized command: /bar/! p
18137 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
18139 @end example
18141 Posix also says that you should not combine @samp{!} and @samp{;}.  If
18142 you use @samp{!}, it is best to put it on a command that is delimited by
18143 newlines rather than @samp{;}.
18145 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
18146 @samp{w} commands be followed by exactly one space before their argument.
18147 On the other hand, no white space is allowed between @samp{:} and the
18148 subsequent label name.
18150 If a sed script is specified on the command line and ends in an
18151 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
18152 should be followed by a newline.  Otherwise some @command{sed}
18153 implementations (e.g., Open@acronym{BSD} 3.9) do not append a newline to the
18154 inserted text.
18156 Many @command{sed} implementations (e.g., MacOS X 10.4,
18157 Open@acronym{BSD} 3.9, Solaris 10
18158 @command{/usr/ucb/sed}) strip leading white space from the text of
18159 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
18160 work around this incompatibility with Posix:
18162 @example
18163 $ @kbd{echo flushleft | sed 'a\}
18164 > @kbd{   indented}
18165 > @kbd{'}
18166 flushleft
18167 indented
18168 $ @kbd{echo foo | sed 'a\}
18169 > @kbd{\   indented}
18170 > @kbd{'}
18171 flushleft
18172    indented
18173 @end example
18175 Posix requires that with an empty regular expression, the last non-empty
18176 regular expression from either an address specification or substitution
18177 command is applied.  However, busybox 1.6.1 complains when using a
18178 substitution command with a replacement containing a back-reference to
18179 an empty regular expression; the workaround is repeating the regular
18180 expression.
18182 @example
18183 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
18184 sed: No previous regexp.
18185 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
18187 @end example
18190 @item @command{sed} (@samp{t})
18191 @c ---------------------------
18192 @prindex @command{sed} (@samp{t})
18193 Some old systems have @command{sed} that ``forget'' to reset their
18194 @samp{t} flag when starting a new cycle.  For instance on @acronym{MIPS
18195 RISC/OS}, and on @sc{irix} 5.3, if you run the following @command{sed}
18196 script (the line numbers are not actual part of the texts):
18198 @example
18199 s/keep me/kept/g  # a
18200 t end             # b
18201 s/.*/deleted/g    # c
18202 :end              # d
18203 @end example
18205 @noindent
18208 @example
18209 delete me         # 1
18210 delete me         # 2
18211 keep me           # 3
18212 delete me         # 4
18213 @end example
18215 @noindent
18216 you get
18218 @example
18219 deleted
18220 delete me
18221 kept
18222 deleted
18223 @end example
18225 @noindent
18226 instead of
18228 @example
18229 deleted
18230 deleted
18231 kept
18232 deleted
18233 @end example
18235 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
18236 flag, and the output is produced.  When processing
18237 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
18238 fails to match, but @command{sed} is not supposed to clear the @samp{t}
18239 flag when a substitution fails.  Command (b) sees that the flag is set,
18240 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
18241 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
18242 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
18243 Finally, since the flag is clear, line 4 is processed properly.
18245 There are two things one should remember about @samp{t} in @command{sed}.
18246 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
18247 succeeded, not only the immediately preceding substitution.  Therefore,
18248 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
18249 line, to reset the @samp{t} flag where needed.
18251 Secondly, you cannot rely on @command{sed} to clear the flag at each new
18252 cycle.
18254 One portable implementation of the script above is:
18256 @example
18257 t clear
18258 :clear
18259 s/keep me/kept/g
18260 t end
18261 s/.*/deleted/g
18262 :end
18263 @end example
18265 @item @command{sleep}
18266 @c ------------------
18267 @prindex @command{sleep}
18268 Using @command{sleep} is generally portable.  However, remember that
18269 adding a @command{sleep} to work around timestamp issues, with a minimum
18270 granularity of one second, doesn't scale well for parallel builds on
18271 modern machines with sub-second process completion.
18273 @item @command{sort}
18274 @c -----------------
18275 @prindex @command{sort}
18276 Remember that sort order is influenced by the current locale.  Inside
18277 @file{configure}, the C locale is in effect, but in Makefile snippets,
18278 you may need to specify @code{LC_ALL=C sort}.
18280 @item @command{tar}
18281 @c ----------------
18282 @prindex @command{tar}
18283 There are multiple file formats for @command{tar}; if you use Automake,
18284 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
18285 level of portability to use.
18287 @anchor{touch}
18288 @item @command{touch}
18289 @c ------------------
18290 @prindex @command{touch}
18291 @cindex timestamp resolution
18292 If you specify the desired timestamp (e.g., with the @option{-r}
18293 option), @command{touch} typically uses the @code{utime} or
18294 @code{utimes} system call, which can result in the same kind of
18295 timestamp truncation problems that @samp{cp -p} has.
18297 On ancient @acronym{BSD} systems, @command{touch} or any command that
18298 results in an empty file does not update the timestamps, so use a
18299 command like @command{echo} as a workaround.
18300 Also,
18301 @acronym{GNU} @command{touch} 3.16r (and presumably all before that)
18302 fails to work on SunOS 4.1.3 when the empty file is on an
18303 @acronym{NFS}-mounted 4.2 volume.
18304 However, these problems are no longer of practical concern.
18306 @item @command{tr}
18307 @c ---------------
18308 @prindex @command{tr}
18309 @cindex carriage return, deleting
18310 @cindex deleting carriage return
18311 Not all versions of @command{tr} handle all backslash character escapes.
18312 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
18313 Solaris contains more modern @command{tr} in other locations.
18314 Therefore, it is more portable to use octal escapes, even though this
18315 ties the result to @acronym{ASCII}, when using @command{tr} to delete
18316 newlines or carriage returns.
18318 @example
18319 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
18321 light
18322 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
18323 moonlight
18324 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
18325 moonlight
18326 @end example
18328 Not all versions of @command{tr} recognize ranges of characters: at
18329 least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
18330 use @command{/usr/xpg4/bin/tr} instead.
18332 @example
18333 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
18334 HAZy FAntAZy
18335 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
18336 HAZY FANTAZY
18337 @end example
18339 When providing two arguments, be sure the second string is at least as
18340 long as the first.
18342 @example
18343 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
18345 $ @kbd{echo abc | coreutils/tr bc d}
18347 @end example
18349 Posix requires @command{tr} to operate on binary files.  But at least
18350 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
18351 @code{NUL} in the input prior to doing any translation.  When using
18352 @command{tr} to process a binary file that may contain @code{NUL} bytes,
18353 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
18354 @command{/usr/xpg6/bin/tr} if that is available.
18356 @example
18357 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
18358  61 62
18359 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
18360  61 62
18361 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
18362  61 00 62
18363 @end example
18365 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
18366 octal escape for @code{NUL}.
18368 @example
18369 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
18370  61 62 63
18371 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
18372  61 00 64
18373 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
18374  61 00 64
18375 @end example
18377 @end table
18380 @node Portable Make
18381 @chapter Portable Make Programming
18382 @prindex @command{make}
18383 @cindex Limitations of @command{make}
18385 Writing portable makefiles is an art.  Since a makefile's commands are
18386 executed by the shell, you must consider the shell portability issues
18387 already mentioned.  However, other issues are specific to @command{make}
18388 itself.
18390 @menu
18391 * $< in Ordinary Make Rules::   $< in ordinary rules
18392 * Failure in Make Rules::       Failing portably in rules
18393 * Special Chars in Names::      Special Characters in Macro Names
18394 * Backslash-Newline-Newline::   Empty last lines in macro definitions
18395 * Backslash-Newline Comments::  Spanning comments across line boundaries
18396 * Long Lines in Makefiles::     Line length limitations
18397 * Macros and Submakes::         @code{make macro=value} and submakes
18398 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
18399 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
18400 * Parallel Make::               Parallel @command{make} quirks
18401 * Comments in Make Rules::      Other problems with Make comments
18402 * obj/ and Make::               Don't name a subdirectory @file{obj}
18403 * make -k Status::              Exit status of @samp{make -k}
18404 * VPATH and Make::              @code{VPATH} woes
18405 * Single Suffix Rules::         Single suffix rules and separated dependencies
18406 * Timestamps and Make::         Subsecond timestamp resolution
18407 @end menu
18409 @node $< in Ordinary Make Rules
18410 @section @code{$<} in Ordinary Make Rules
18412 Posix says that the @samp{$<} construct in makefiles can be
18413 used only in inference rules and in the @samp{.DEFAULT} rule; its
18414 meaning in ordinary rules is unspecified.  Solaris @command{make}
18415 for instance replaces it with the empty string.  Open@acronym{BSD} (3.0 and
18416 later) @command{make} diagnoses these uses and errors out.
18418 @node Failure in Make Rules
18419 @section Failure in Make Rules
18421 Posix 2008 requires that @command{make} must invoke each command with
18422 the equivalent of a @samp{sh -e -c} subshell, which causes the
18423 subshell to exit immediately if a subsidiary simple-command fails,
18424 although not all @command{make} implementations have historically
18425 followed this rule.  For
18426 example, the command @samp{touch T; rm -f U} may attempt to
18427 remove @file{U} even if the @command{touch} fails, although this is not
18428 permitted with Posix make.  One way to work around failures in simple
18429 commands is to reword them so that they always succeed, e.g., @samp{touch
18430 T || :; rm -f U}.
18431 However, even this approach can run into common bugs in @acronym{BSD}
18432 implementations of the @option{-e} option of @command{sh} and
18433 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
18434 are worried
18435 about porting to buggy @acronym{BSD} shells it may be simpler to migrate
18436 complicated @command{make} actions into separate scripts.
18438 @node Special Chars in Names
18439 @section Special Characters in Make Macro Names
18441 Posix limits macro names to nonempty strings containing only
18442 @acronym{ASCII} letters and digits, @samp{.}, and @samp{_}.  Many
18443 @command{make} implementations allow a wider variety of characters, but
18444 portable makefiles should avoid them.  It is portable to start a name
18445 with a special character, e.g., @samp{$(.FOO)}.
18447 Some ancient @command{make} implementations don't support leading
18448 underscores in macro names.  An example is @acronym{NEWS-OS} 4.2R.
18450 @example
18451 $ @kbd{cat Makefile}
18452 _am_include = #
18453 _am_quote =
18454 all:; @@echo this is test
18455 $ @kbd{make}
18456 Make: Must be a separator on rules line 2.  Stop.
18457 $ @kbd{cat Makefile2}
18458 am_include = #
18459 am_quote =
18460 all:; @@echo this is test
18461 $ @kbd{make -f Makefile2}
18462 this is test
18463 @end example
18465 @noindent
18466 However, this problem is no longer of practical concern.
18468 @node Backslash-Newline-Newline
18469 @section Backslash-Newline-Newline in Make Macro Values
18471 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
18472 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
18473 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
18474 On some versions of @acronym{HP-UX}, @command{make} reads multiple newlines
18475 following a backslash, continuing to the next non-empty line.  For
18476 example,
18478 @example
18479 FOO = one \
18481 BAR = two
18483 test:
18484         : FOO is "$(FOO)"
18485         : BAR is "$(BAR)"
18486 @end example
18488 @noindent
18489 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
18490 sensibly let a backslash continue only to the immediately following
18491 line.
18493 @node Backslash-Newline Comments
18494 @section Backslash-Newline in Make Comments
18496 According to Posix, Make comments start with @code{#}
18497 and continue until an unescaped newline is reached.
18499 @example
18500 $ @kbd{cat Makefile}
18501 # A = foo \
18502       bar \
18503       baz
18505 all:
18506         @@echo ok
18507 $ @kbd{make}   # GNU make
18509 @end example
18511 @noindent
18512 However this is not always the case.  Some implementations
18513 discard everything from @code{#} through the end of the line, ignoring any
18514 trailing backslash.
18516 @example
18517 $ @kbd{pmake}  # BSD make
18518 "Makefile", line 3: Need an operator
18519 Fatal errors encountered -- cannot continue
18520 @end example
18522 @noindent
18523 Therefore, if you want to comment out a multi-line definition, prefix each
18524 line with @code{#}, not only the first.
18526 @example
18527 # A = foo \
18528 #     bar \
18529 #     baz
18530 @end example
18532 @node Long Lines in Makefiles
18533 @section Long Lines in Makefiles
18535 Tru64 5.1's @command{make} has been reported to crash when given a
18536 makefile with lines longer than around 20 kB.  Earlier versions are
18537 reported to exit with @code{Line too long} diagnostics.
18539 @node Macros and Submakes
18540 @section @code{make macro=value} and Submakes
18542 A command-line variable definition such as @code{foo=bar} overrides any
18543 definition of @code{foo} in a makefile.  Some @command{make}
18544 implementations (such as @acronym{GNU} @command{make}) propagate this
18545 override to subsidiary invocations of @command{make}.  Some other
18546 implementations do not pass the substitution along to submakes.
18548 @example
18549 $ @kbd{cat Makefile}
18550 foo = foo
18551 one:
18552         @@echo $(foo)
18553         $(MAKE) two
18554 two:
18555         @@echo $(foo)
18556 $ @kbd{make foo=bar}            # GNU make 3.79.1
18558 make two
18559 make[1]: Entering directory `/home/adl'
18561 make[1]: Leaving directory `/home/adl'
18562 $ @kbd{pmake foo=bar}           # BSD make
18564 pmake two
18566 @end example
18568 You have a few possibilities if you do want the @code{foo=bar} override
18569 to propagate to submakes.  One is to use the @option{-e}
18570 option, which causes all environment variables to have precedence over
18571 the makefile macro definitions, and declare foo as an environment
18572 variable:
18574 @example
18575 $ @kbd{env foo=bar make -e}
18576 @end example
18578 The @option{-e} option is propagated to submakes automatically,
18579 and since the environment is inherited between @command{make}
18580 invocations, the @code{foo} macro is overridden in
18581 submakes as expected.
18583 This syntax (@code{foo=bar make -e}) is portable only when used
18584 outside of a makefile, for instance from a script or from the
18585 command line.  When run inside a @command{make} rule, @acronym{GNU}
18586 @command{make} 3.80 and prior versions forget to propagate the
18587 @option{-e} option to submakes.
18589 Moreover, using @option{-e} could have unexpected side effects if your
18590 environment contains some other macros usually defined by the
18591 makefile.  (See also the note about @code{make -e} and @code{SHELL}
18592 below.)
18594 Another way to propagate overrides to submakes is to do it
18595 manually, from your makefile:
18597 @example
18598 foo = foo
18599 one:
18600         @@echo $(foo)
18601         $(MAKE) foo=$(foo) two
18602 two:
18603         @@echo $(foo)
18604 @end example
18606 You need to foresee all macros that a user might want to override if
18607 you do that.
18609 Makefiles generated by @command{automake} expand @code{$(AM_MAKEFLAGS)}
18610 on the command line of submakes, which can be used for propagated overrides
18611 (@pxref{Subdirectories, , Automake, automake, @acronym{GNU} Automake}).
18613 @node The Make Macro MAKEFLAGS
18614 @section The Make Macro MAKEFLAGS
18615 @cindex @code{MAKEFLAGS} and @command{make}
18616 @cindex @command{make} and @code{MAKEFLAGS}
18618 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
18619 current and recursive invocations of make, but allows implementations
18620 several formats for the variable.  It is tricky to parse
18621 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
18622 or @option{-k} for continued execution are in effect.  For example, you
18623 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
18624 contains single-letter options, since in the Cygwin version of
18625 @acronym{GNU} @command{make} it is either @option{--unix} or
18626 @option{--win32} with the second word containing single-letter options.
18628 @example
18629 $ @kbd{cat Makefile}
18630 all:
18631         @@echo MAKEFLAGS = $(MAKEFLAGS)
18632 $ @kbd{make}
18633 MAKEFLAGS = --unix
18634 $ @kbd{make -k}
18635 MAKEFLAGS = --unix -k
18636 @end example
18638 @node The Make Macro SHELL
18639 @section The Make Macro @code{SHELL}
18640 @cindex @code{SHELL} and @command{make}
18641 @cindex @command{make} and @code{SHELL}
18643 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
18644 macro to spawn shell processes and execute Make rules.  This
18645 is a builtin macro supplied by @command{make}, but it can be modified
18646 by a makefile or by a command-line argument.
18648 Not all @command{make} implementations define this @code{SHELL} macro.
18649 Tru64
18650 @command{make} is an example; this implementation always uses
18651 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
18652 your makefiles.  If you use Autoconf, do
18654 @example
18655 SHELL = @@SHELL@@
18656 @end example
18658 @noindent
18659 If you use Automake, this is done for you.
18661 Do not force @code{SHELL = /bin/sh} because that is not correct
18662 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
18663 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
18664 Additionally, @acronym{DJGPP} lacks @code{/bin/sh}, and when its
18665 @acronym{GNU} @command{make} port sees such a setting it enters a
18666 special emulation mode where features like pipes and redirections are
18667 emulated on top of DOS's @command{command.com}.  Unfortunately this
18668 emulation is incomplete; for instance it does not handle command
18669 substitutions.  Using @code{@@SHELL@@} means that your makefile will
18670 benefit from the same improved shell, such as @command{bash} or
18671 @command{ksh}, that was discovered during @command{configure}, so that
18672 you aren't fighting two different sets of shell bugs between the two
18673 contexts.
18675 Posix-compliant @command{make} should never acquire the value of
18676 $(SHELL) from the environment, even when @code{make -e} is used
18677 (otherwise, think about what would happen to your rules if
18678 @code{SHELL=/bin/tcsh}).
18680 However not all @command{make} implementations have this exception.
18681 For instance it's not surprising that Tru64 @command{make} doesn't
18682 protect @code{SHELL}, since it doesn't use it.
18684 @example
18685 $ @kbd{cat Makefile}
18686 SHELL = /bin/sh
18687 FOO = foo
18688 all:
18689         @@echo $(SHELL)
18690         @@echo $(FOO)
18691 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
18692 /bin/tcsh
18694 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
18695 /bin/sh
18697 @end example
18699 Conversely, @command{make} is not supposed to export any changes to the
18700 macro @code{SHELL} to child processes.  Again, many implementations
18701 break this rule:
18703 @example
18704 $ @kbd{cat Makefile}
18705 all:
18706         @@echo $(SHELL)
18707         @@printenv SHELL
18708 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
18709 /bin/ksh
18710 /bin/ksh
18711 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
18712 /bin/ksh
18714 @end example
18716 @node Parallel Make
18717 @section Parallel Make
18718 @cindex Parallel @command{make}
18720 Support for parallel execution in @command{make} implementation varies.
18721 Generally, using @acronym{GNU} make is your best bet.  When NetBSD
18722 @command{make} is invoked with @option{-j@var{N}}, it will reuse the
18723 same shell for multiple commands within one recipe.  This can have
18724 unexpected consequences.@footnote{Note that @acronym{GNU} make has
18725 heuristics to avoid spawning a shell at all if the command is deemed
18726 safe to be executed directly.} For example, change of directories or
18727 variables persist between commands:
18729 @example
18730 all:
18731         @@var=value; cd /; pwd; echo $$var; echo $$$$
18732         @@pwd; echo $$var; echo $$$$
18733 @end example
18735 @noindent
18736 may output the following with @code{make -j1}:
18738 @example
18739 --- all ---
18741 value
18742 32235
18744 value
18745 32235
18746 @end example
18748 while without @option{-j1}, or with @option{-B}, the output looks less
18749 surprising:
18751 @example
18753 value
18754 32238
18755 /tmp
18757 32239
18758 @end example
18760 Another consequence of this is that, if one command in a recipe uses
18761 @code{exit 0} to indicate a successful exit, the shell will be gone
18762 and the remaining commands of this recipe will not be executed.
18764 The above example also shows additional status output NetBSD
18765 @command{make} produces in parallel mode for targets being updated.
18767 Furthermore, parallel NetBSD @command{make} will route standard error
18768 from commands that it spawns into its own standard output, and may
18769 remove leading whitespace from output lines.
18771 You can avoid these issues by using the @option{-B} option to enable
18772 compatibility semantics.  However, that will effectively also disable
18773 all parallelism as that will cause prerequisites to be updated in the
18774 order they are listed in a rule.
18776 @node Comments in Make Rules
18777 @section Comments in Make Rules
18778 @cindex Comments in @file{Makefile} rules
18779 @cindex @file{Makefile} rules and comments
18781 Never put comments in a rule.
18783 Some @command{make} treat anything starting with a tab as a command for
18784 the current rule, even if the tab is immediately followed by a @code{#}.
18785 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
18786 makefile runs @code{# foo} through the shell.
18788 @example
18789 all:
18790         # foo
18791 @end example
18793 @node obj/ and Make
18794 @section The @file{obj/} Subdirectory and Make
18795 @cindex @file{obj/}, subdirectory
18796 @cindex @acronym{BSD} @command{make} and @file{obj/}
18798 Never name one of your subdirectories @file{obj/} if you don't like
18799 surprises.
18801 If an @file{obj/} directory exists, @acronym{BSD} @command{make} enters it
18802 before reading the makefile.  Hence the makefile in the
18803 current directory is not read.
18805 @example
18806 $ @kbd{cat Makefile}
18807 all:
18808         echo Hello
18809 $ @kbd{cat obj/Makefile}
18810 all:
18811         echo World
18812 $ @kbd{make}      # GNU make
18813 echo Hello
18814 Hello
18815 $ @kbd{pmake}     # BSD make
18816 echo World
18817 World
18818 @end example
18820 @node make -k Status
18821 @section Exit Status of @code{make -k}
18822 @cindex @code{make -k}
18824 Do not rely on the exit status of @code{make -k}.  Some implementations
18825 reflect whether they encountered an error in their exit status; other
18826 implementations always succeed.
18828 @example
18829 $ @kbd{cat Makefile}
18830 all:
18831         false
18832 $ @kbd{make -k; echo exit status: $?}    # GNU make
18833 false
18834 make: *** [all] Error 1
18835 exit status: 2
18836 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
18837 false
18838 *** Error code 1 (continuing)
18839 exit status: 0
18840 @end example
18842 @node VPATH and Make
18843 @section @code{VPATH} and Make
18844 @cindex @code{VPATH}
18846 Posix does not specify the semantics of @code{VPATH}.  Typically,
18847 @command{make} supports @code{VPATH}, but its implementation is not
18848 consistent.
18850 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
18851 portable to recent-enough popular implementations of @command{make}, but
18852 to keep the resulting makefiles portable, a package's makefile
18853 prototypes must take the following issues into account.  These issues
18854 are complicated and are often poorly understood, and installers who use
18855 @code{VPATH} should expect to find many bugs in this area.  If you use
18856 @code{VPATH}, the simplest way to avoid these portability bugs is to
18857 stick with @acronym{GNU} @command{make}, since it is the most
18858 commonly-used @command{make} among Autoconf users.
18860 Here are some known issues with some @code{VPATH}
18861 implementations.
18863 @menu
18864 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
18865 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
18866 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
18867 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
18868 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
18869 * Make Target Lookup::          More details about @code{VPATH} lookup
18870 @end menu
18872 @node Variables listed in VPATH
18873 @subsection Variables listed in @code{VPATH}
18874 @cindex @code{VPATH} and variables
18875 @cindex variables and @code{VPATH}
18877 Do not set @code{VPATH} to the value of another variable, for example
18878 @samp{VPATH = $(srcdir)}, because some ancient versions of
18879 @command{make} do not do variable substitutions on the value of
18880 @code{VPATH}.  For example, use this
18882 @example
18883 srcdir = @@srcdir@@
18884 VPATH = @@srcdir@@
18885 @end example
18887 @noindent
18888 rather than @samp{VPATH = $(srcdir)}.  Note that with @acronym{GNU}
18889 Automake, there is no need to set this yourself.
18891 @node VPATH and Double-colon
18892 @subsection @code{VPATH} and Double-colon Rules
18893 @cindex @code{VPATH} and double-colon rules
18894 @cindex double-colon rules and @code{VPATH}
18896 With ancient versions of Sun @command{make},
18897 any assignment to @code{VPATH} causes @command{make} to execute only
18898 the first set of double-colon rules.
18899 However, this problem is no longer of practical concern.
18901 @node $< in Explicit Rules
18902 @subsection @code{$<} Not Supported in Explicit Rules
18903 @cindex explicit rules, @code{$<}, and @code{VPATH}
18904 @cindex @code{$<}, explicit rules, and @code{VPATH}
18905 @cindex @code{VPATH}, explicit rules, and @code{$<}
18907 Using @code{$<} in explicit rules is not portable.
18908 The prerequisite file must be named explicitly in the rule.  If you want
18909 to find the prerequisite via a @code{VPATH} search, you have to code the
18910 whole thing manually.  @xref{Build Directories}.
18912 @node Automatic Rule Rewriting
18913 @subsection Automatic Rule Rewriting
18914 @cindex @code{VPATH} and automatic rule rewriting
18915 @cindex automatic rule rewriting and @code{VPATH}
18917 Some @command{make} implementations, such as Solaris and Tru64,
18918 search for prerequisites in @code{VPATH} and
18919 then rewrite each occurrence as a plain word in the rule.
18920 For instance:
18922 @example
18923 # This isn't portable to GNU make.
18924 VPATH = ../pkg/src
18925 f.c: if.c
18926         cp if.c f.c
18927 @end example
18929 @noindent
18930 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
18931 found in @file{../pkg/src}.
18933 However, this rule leads to real problems in practice.  For example, if
18934 the source directory contains an ordinary file named @file{test} that is
18935 used in a dependency, Solaris @command{make} rewrites commands like
18936 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
18937 @dots{}}, which is typically undesirable.  To avoid this problem,
18938 portable makefiles should never mention a source file whose name is that
18939 of a shell keyword like @file{until} or a shell command like
18940 @command{cat} or @command{gcc} or @command{test}.
18942 Because of these problems @acronym{GNU} @command{make} and many other
18943 @command{make} implementations do not rewrite commands, so portable
18944 makefiles should
18945 search @code{VPATH} manually.  It is tempting to write this:
18947 @smallexample
18948 # This isn't portable to Solaris make.
18949 VPATH = ../pkg/src
18950 f.c: if.c
18951         cp `test -f if.c || echo $(VPATH)/`if.c f.c
18952 @end smallexample
18954 @noindent
18955 However, the ``prerequisite rewriting'' still applies here.  So if
18956 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
18957 execute
18959 @smallexample
18960 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
18961 @end smallexample
18963 @noindent
18964 which reduces to
18966 @example
18967 cp if.c f.c
18968 @end example
18970 @noindent
18971 and thus fails.  Oops.
18973 A simple workaround, and good practice anyway, is to use @samp{$?} and
18974 @samp{$@@} when possible:
18976 @smallexample
18977 VPATH = ../pkg/src
18978 f.c: if.c
18979         cp $? $@@
18980 @end smallexample
18982 @noindent
18983 but this does not generalize well to commands with multiple
18984 prerequisites.  A more general workaround is to rewrite the rule so that
18985 the prerequisite @file{if.c} never appears as a plain word.  For
18986 example, these three rules would be safe, assuming @file{if.c} is in
18987 @file{../pkg/src} and the other files are in the working directory:
18989 @smallexample
18990 VPATH = ../pkg/src
18991 f.c: if.c f1.c
18992         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
18993 g.c: if.c g1.c
18994         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
18995 h.c: if.c h1.c
18996         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
18997 @end smallexample
18999 Things get worse when your prerequisites are in a macro.
19001 @example
19002 VPATH = ../pkg/src
19003 HEADERS = f.h g.h h.h
19004 install-HEADERS: $(HEADERS)
19005         for i in $(HEADERS); do \
19006           $(INSTALL) -m 644 \
19007             `test -f $$i || echo $(VPATH)/`$$i \
19008             $(DESTDIR)$(includedir)/$$i; \
19009         done
19010 @end example
19012 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
19013 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
19014 where @code{f.h} and @code{g.h} are plain words and are hence
19015 subject to @code{VPATH} adjustments.
19017 If the three files are in @file{../pkg/src}, the rule is run as:
19019 @example
19020 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
19021   install -m 644 \
19022      `test -f $i || echo ../pkg/src/`$i \
19023      /usr/local/include/$i; \
19024 done
19025 @end example
19027 where the two first @command{install} calls fail.  For instance,
19028 consider the @code{f.h} installation:
19030 @example
19031 install -m 644 \
19032   `test -f ../pkg/src/f.h || \
19033     echo ../pkg/src/ \
19034   `../pkg/src/f.h \
19035   /usr/local/include/../pkg/src/f.h;
19036 @end example
19038 @noindent
19039 It reduces to:
19041 @example
19042 install -m 644 \
19043   ../pkg/src/f.h \
19044   /usr/local/include/../pkg/src/f.h;
19045 @end example
19047 Note that the manual @code{VPATH} search did not cause any problems here;
19048 however this command installs @file{f.h} in an incorrect directory.
19050 Trying to quote @code{$(HEADERS)} in some way, as we did for
19051 @code{foo.c} a few makefiles ago, does not help:
19053 @example
19054 install-HEADERS: $(HEADERS)
19055         headers='$(HEADERS)'; \
19056         for i in $$headers; do \
19057           $(INSTALL) -m 644 \
19058             `test -f $$i || echo $(VPATH)/`$$i \
19059             $(DESTDIR)$(includedir)/$$i; \
19060         done
19061 @end example
19063 Now, @code{headers='$(HEADERS)'} macro-expands to:
19065 @example
19066 headers='f.h g.h h.h'
19067 @end example
19069 @noindent
19070 but @code{g.h} is still a plain word.  (As an aside, the idiom
19071 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
19072 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
19073 syntax error on @code{for i in;}.)
19075 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
19077 @example
19078 VPATH = ../pkg/src
19079 HEADERS = f.h g.h h.h
19080 install-HEADERS: $(HEADERS)
19081         headers='$(HEADERS)'; \
19082         for i in $$headers; do \
19083           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
19084           $(INSTALL) -m 644 \
19085             `test -f $$i || echo $(VPATH)/`$$i \
19086             $(DESTDIR)$(includedir)/$$i; \
19087         done
19088 @end example
19090 Automake does something similar.  However the above hack works only if
19091 the files listed in @code{HEADERS} are in the current directory or a
19092 subdirectory; they should not be in an enclosing directory.  If we had
19093 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
19094 build with Tru64 @command{make}.  The reason is that not only does
19095 Tru64 @command{make} rewrite dependencies, but it also simplifies
19096 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
19097 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
19098 a leading @file{../pkg/src/} component.
19100 The following example makes the behavior of Tru64 @command{make}
19101 more apparent.
19103 @example
19104 $ @kbd{cat Makefile}
19105 VPATH = sub
19106 all: ../foo
19107         echo ../foo
19108 $ @kbd{ls}
19109 Makefile foo
19110 $ @kbd{make}
19111 echo foo
19113 @end example
19115 @noindent
19116 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
19117 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
19118 directory does not even exist, this just means that the simplification
19119 occurred before the file was checked for.)
19121 For the record here is how SunOS 4 @command{make} behaves on this
19122 example.
19124 @smallexample
19125 $ @kbd{make}
19126 make: Fatal error: Don't know how to make target `../foo'
19127 $ @kbd{mkdir sub}
19128 $ @kbd{make}
19129 echo sub/../foo
19130 sub/../foo
19131 @end smallexample
19134 @node Tru64 Directory Magic
19135 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
19136 @cindex @code{VPATH} and prerequisite directories
19137 @cindex prerequisite directories and @code{VPATH}
19139 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
19140 @command{make} creates it in the current directory.
19142 @example
19143 $ @kbd{mkdir -p foo/bar build}
19144 $ @kbd{cd build}
19145 $ @kbd{cat >Makefile <<END
19146 VPATH = ..
19147 all: foo/bar
19148 END}
19149 $ @kbd{make}
19150 mkdir foo
19151 mkdir foo/bar
19152 @end example
19154 This can yield unexpected results if a rule uses a manual @code{VPATH}
19155 search as presented before.
19157 @example
19158 VPATH = ..
19159 all : foo/bar
19160         command `test -d foo/bar || echo ../`foo/bar
19161 @end example
19163 The above @command{command} is run on the empty @file{foo/bar}
19164 directory that was created in the current directory.
19166 @node Make Target Lookup
19167 @subsection Make Target Lookup
19168 @cindex @code{VPATH}, resolving target pathnames
19170 @acronym{GNU} @command{make} uses a complex algorithm to decide when it
19171 should use files found via a @code{VPATH} search.  @xref{Search
19172 Algorithm, , How Directory Searches are Performed, make, The @acronym{GNU} Make
19173 Manual}.
19175 If a target needs to be rebuilt, @acronym{GNU} @command{make} discards the
19176 file name found during the @code{VPATH} search for this target, and
19177 builds the file locally using the file name given in the makefile.
19178 If a target does not need to be rebuilt, @acronym{GNU} @command{make} uses the
19179 file name found during the @code{VPATH} search.
19181 Other @command{make} implementations, like Net@acronym{BSD} @command{make}, are
19182 easier to describe: the file name found during the @code{VPATH} search
19183 is used whether the target needs to be rebuilt or not.  Therefore
19184 new files are created locally, but existing files are updated at their
19185 @code{VPATH} location.
19187 Open@acronym{BSD} and Free@acronym{BSD} @command{make}, however,
19188 never perform a
19189 @code{VPATH} search for a dependency that has an explicit rule.
19190 This is extremely annoying.
19192 When attempting a @code{VPATH} build for an autoconfiscated package
19193 (e.g., @code{mkdir build && cd build && ../configure}), this means
19194 @acronym{GNU}
19195 @command{make} builds everything locally in the @file{build}
19196 directory, while @acronym{BSD} @command{make} builds new files locally and
19197 updates existing files in the source directory.
19199 @example
19200 $ @kbd{cat Makefile}
19201 VPATH = ..
19202 all: foo.x bar.x
19203 foo.x bar.x: newer.x
19204         @@echo Building $@@
19205 $ @kbd{touch ../bar.x}
19206 $ @kbd{touch ../newer.x}
19207 $ @kbd{make}        # GNU make
19208 Building foo.x
19209 Building bar.x
19210 $ @kbd{pmake}       # NetBSD make
19211 Building foo.x
19212 Building ../bar.x
19213 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
19214 Building foo.x
19215 Building bar.x
19216 $ @kbd{tmake}       # Tru64 make
19217 Building foo.x
19218 Building bar.x
19219 $ @kbd{touch ../bar.x}
19220 $ @kbd{make}        # GNU make
19221 Building foo.x
19222 $ @kbd{pmake}       # NetBSD make
19223 Building foo.x
19224 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
19225 Building foo.x
19226 Building bar.x
19227 $ @kbd{tmake}       # Tru64 make
19228 Building foo.x
19229 Building bar.x
19230 @end example
19232 Note how Net@acronym{BSD} @command{make} updates @file{../bar.x} in its
19233 VPATH location, and how Free@acronym{BSD}, Open@acronym{BSD}, and Tru64
19234 @command{make} always
19235 update @file{bar.x}, even when @file{../bar.x} is up to date.
19237 Another point worth mentioning is that once @acronym{GNU} @command{make} has
19238 decided to ignore a @code{VPATH} file name (e.g., it ignored
19239 @file{../bar.x} in the above example) it continues to ignore it when
19240 the target occurs as a prerequisite of another rule.
19242 The following example shows that @acronym{GNU} @command{make} does not look up
19243 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
19244 because it ignored the @code{VPATH} result of @file{bar.x} while running
19245 the @code{bar.x: newer.x} rule.
19247 @example
19248 $ @kbd{cat Makefile}
19249 VPATH = ..
19250 all: bar.y
19251 bar.x: newer.x
19252         @@echo Building $@@
19253 .SUFFIXES: .x .y
19254 .x.y:
19255         cp $< $@@
19256 $ @kbd{touch ../bar.x}
19257 $ @kbd{touch ../newer.x}
19258 $ @kbd{make}        # GNU make
19259 Building bar.x
19260 cp bar.x bar.y
19261 cp: cannot stat `bar.x': No such file or directory
19262 make: *** [bar.y] Error 1
19263 $ @kbd{pmake}       # NetBSD make
19264 Building ../bar.x
19265 cp ../bar.x bar.y
19266 $ @kbd{rm bar.y}
19267 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
19268 echo Building bar.x
19269 cp bar.x bar.y
19270 cp: cannot stat `bar.x': No such file or directory
19271 *** Error code 1
19272 $ @kbd{tmake}       # Tru64 make
19273 Building bar.x
19274 cp: bar.x: No such file or directory
19275 *** Exit 1
19276 @end example
19278 Note that if you drop away the command from the @code{bar.x: newer.x}
19279 rule, @acronym{GNU} @command{make} magically starts to work: it
19280 knows that @code{bar.x} hasn't been updated, therefore it doesn't
19281 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
19282 uses.  Tru64 also works, but Free@acronym{BSD} and Open@acronym{BSD}
19283 still don't.
19285 @example
19286 $ @kbd{cat Makefile}
19287 VPATH = ..
19288 all: bar.y
19289 bar.x: newer.x
19290 .SUFFIXES: .x .y
19291 .x.y:
19292         cp $< $@@
19293 $ @kbd{touch ../bar.x}
19294 $ @kbd{touch ../newer.x}
19295 $ @kbd{make}        # GNU make
19296 cp ../bar.x bar.y
19297 $ @kbd{rm bar.y}
19298 $ @kbd{pmake}       # NetBSD make
19299 cp ../bar.x bar.y
19300 $ @kbd{rm bar.y}
19301 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
19302 cp bar.x bar.y
19303 cp: cannot stat `bar.x': No such file or directory
19304 *** Error code 1
19305 $ @kbd{tmake}       # Tru64 make
19306 cp ../bar.x bar.y
19307 @end example
19309 It seems the sole solution that would please every @command{make}
19310 implementation is to never rely on @code{VPATH} searches for targets.
19311 In other words, @code{VPATH} should be reserved to unbuilt sources.
19314 @node Single Suffix Rules
19315 @section Single Suffix Rules and Separated Dependencies
19316 @cindex Single Suffix Inference Rule
19317 @cindex Rule, Single Suffix Inference
19318 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
19319 (@samp{.from.to:}), but which @emph{destination} suffix is empty
19320 (@samp{.from:}).
19322 @cindex Separated Dependencies
19323 @dfn{Separated dependencies} simply refers to listing the prerequisite
19324 of a target, without defining a rule.  Usually one can list on the one
19325 hand side, the rules, and on the other hand side, the dependencies.
19327 Solaris @command{make} does not support separated dependencies for
19328 targets defined by single suffix rules:
19330 @example
19331 $ @kbd{cat Makefile}
19332 .SUFFIXES: .in
19333 foo: foo.in
19334 .in:
19335         cp $< $@@
19336 $ @kbd{touch foo.in}
19337 $ @kbd{make}
19338 $ @kbd{ls}
19339 Makefile  foo.in
19340 @end example
19342 @noindent
19343 while @acronym{GNU} Make does:
19345 @example
19346 $ @kbd{gmake}
19347 cp foo.in foo
19348 $ @kbd{ls}
19349 Makefile  foo       foo.in
19350 @end example
19352 Note it works without the @samp{foo: foo.in} dependency.
19354 @example
19355 $ @kbd{cat Makefile}
19356 .SUFFIXES: .in
19357 .in:
19358         cp $< $@@
19359 $ @kbd{make foo}
19360 cp foo.in foo
19361 @end example
19363 @noindent
19364 and it works with double suffix inference rules:
19366 @example
19367 $ @kbd{cat Makefile}
19368 foo.out: foo.in
19369 .SUFFIXES: .in .out
19370 .in.out:
19371         cp $< $@@
19372 $ @kbd{make}
19373 cp foo.in foo.out
19374 @end example
19376 As a result, in such a case, you have to write target rules.
19378 @node Timestamps and Make
19379 @section Timestamp Resolution and Make
19380 @cindex timestamp resolution
19381 Traditionally, file timestamps had 1-second resolution, and
19382 @command{make} used those timestamps to determine whether one file was
19383 newer than the other.  However, many modern file systems have
19384 timestamps with 1-nanosecond resolution.  Some @command{make}
19385 implementations look at the entire timestamp; others ignore the
19386 fractional part, which can lead to incorrect results.  Normally this
19387 is not a problem, but in some extreme cases you may need to use tricks
19388 like @samp{sleep 1} to work around timestamp truncation bugs.
19390 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
19391 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
19392 Tools}).  Hence you should be wary of rules like this:
19394 @example
19395 dest: src
19396         cp -p src dest
19397 @end example
19399 as @file{dest} often appears to be older than @file{src} after the
19400 timestamp is truncated, and this can cause @command{make} to do
19401 needless rework the next time it is invoked.  To work around this
19402 problem, you can use a timestamp file, e.g.:
19404 @example
19405 dest-stamp: src
19406         cp -p src dest
19407         date >dest-stamp
19408 @end example
19413 @c ======================================== Portable C and C++ Programming
19415 @node Portable C and C++
19416 @chapter Portable C and C++ Programming
19417 @cindex Portable C and C++ programming
19419 C and C++ programs often use low-level features of the underlying
19420 system, and therefore are often more difficult to make portable to other
19421 platforms.
19423 Several standards have been developed to help make your programs more
19424 portable.  If you write programs with these standards in mind, you can
19425 have greater confidence that your programs work on a wide variety
19426 of systems.
19427 @ifhtml
19428 @uref{http://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
19429 Standards Supported by @acronym{GCC}}
19430 @end ifhtml
19431 @ifnothtml
19432 @xref{Standards, , Language Standards Supported by
19433 @acronym{GCC}, gcc, Using the @acronym{GNU} Compiler Collection
19434 (@acronym{GCC})},
19435 @end ifnothtml
19436 for a list of C-related standards.  Many programs also assume the
19437 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
19439 Some old code is written to be portable to K&R C, which predates any C
19440 standard.  K&R C compilers are no longer of practical interest, though,
19441 and the rest of section assumes at least C89, the first C standard.
19443 Program portability is a huge topic, and this section can only briefly
19444 introduce common pitfalls.  @xref{System Portability, , Portability
19445 between System Types, standards, @acronym{GNU} Coding Standards}, for
19446 more information.
19448 @menu
19449 * Varieties of Unportability::  How to make your programs unportable
19450 * Integer Overflow::            When integers get too large
19451 * Preprocessor Arithmetic::     @code{#if} expression problems
19452 * Null Pointers::               Properties of null pointers
19453 * Buffer Overruns::             Subscript errors and the like
19454 * Volatile Objects::            @code{volatile} and signals
19455 * Floating Point Portability::  Portable floating-point arithmetic
19456 * Exiting Portably::            Exiting and the exit status
19457 @end menu
19459 @node Varieties of Unportability
19460 @section Varieties of Unportability
19461 @cindex portability
19463 Autoconf tests and ordinary programs often need to test what is allowed
19464 on a system, and therefore they may need to deliberately exceed the
19465 boundaries of what the standards allow, if only to see whether an
19466 optional feature is present.  When you write such a program, you should
19467 keep in mind the difference between constraints, unspecified behavior,
19468 and undefined behavior.
19470 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
19471 example constraint is that C programs must not declare a bit-field with
19472 negative width.  Tests can therefore reliably assume that programs with
19473 negative-width bit-fields are rejected by a compiler that conforms
19474 to the standard.
19476 @dfn{Unspecified behavior} is valid behavior, where the standard allows
19477 multiple possibilities.  For example, the order of evaluation of
19478 function arguments is unspecified.  Some unspecified behavior is
19479 @dfn{implementation-defined}, i.e., documented by the implementation,
19480 but since Autoconf tests cannot read the documentation they cannot
19481 distinguish between implementation-defined and other unspecified
19482 behavior.  It is common for Autoconf tests to probe implementations to
19483 determine otherwise-unspecified behavior.
19485 @dfn{Undefined behavior} is invalid behavior, where the standard allows
19486 the implementation to do anything it pleases.  For example,
19487 dereferencing a null pointer leads to undefined behavior.  If possible,
19488 test programs should avoid undefined behavior, since a program with
19489 undefined behavior might succeed on a test that should fail.
19491 The above rules apply to programs that are intended to conform to the
19492 standard.  However, strictly-conforming programs are quite rare, since
19493 the standards are so limiting.  A major goal of Autoconf is to support
19494 programs that use implementation features not described by the standard,
19495 and it is fairly common for test programs to violate the above rules, if
19496 the programs work well enough in practice.
19498 @node Integer Overflow
19499 @section Integer Overflow
19500 @cindex integer overflow
19501 @cindex overflow, signed integer
19502 @cindex signed integer overflow
19503 @cindex wraparound arithmetic
19505 In practice many portable C programs assume that signed integer overflow wraps
19506 around reliably using two's complement arithmetic.  Yet the C standard
19507 says that program behavior is undefined on overflow, and in a few cases
19508 C programs do not work on some modern implementations because their
19509 overflows do not wrap around as their authors expected.  Conversely, in
19510 signed integer remainder, the C standard requires overflow
19511 behavior that is commonly not implemented.
19513 @menu
19514 * Integer Overflow Basics::      Why integer overflow is a problem
19515 * Signed Overflow Examples::     Examples of code assuming wraparound
19516 * Optimization and Wraparound::  Optimizations that break uses of wraparound
19517 * Signed Overflow Advice::       Practical advice for signed overflow issues
19518 * Signed Integer Division::      @code{INT_MIN / -1} and @code{INT_MIN % -1}
19519 @end menu
19521 @node Integer Overflow Basics
19522 @subsection Basics of Integer Overflow
19523 @cindex integer overflow
19524 @cindex overflow, signed integer
19525 @cindex signed integer overflow
19526 @cindex wraparound arithmetic
19528 In languages like C, unsigned integer overflow reliably wraps around;
19529 e.g., @code{UINT_MAX + 1} yields zero.
19530 This is guaranteed by the C standard and is
19531 portable in practice, unless you specify aggressive,
19532 nonstandard optimization options
19533 suitable only for special applications.
19535 In contrast, the C standard says that signed integer overflow leads to
19536 undefined behavior where a program can do anything, including dumping
19537 core or overrunning a buffer.  The misbehavior can even precede the
19538 overflow.  Such an overflow can occur during addition, subtraction,
19539 multiplication, division, and left shift.
19541 Despite this requirement of the standard, many C programs and Autoconf
19542 tests assume that signed integer overflow silently wraps around modulo a
19543 power of two, using two's complement arithmetic, so long as you cast the
19544 resulting value to a signed integer type or store it into a signed
19545 integer variable.  If you use conservative optimization flags, such
19546 programs are generally portable to the vast majority of modern
19547 platforms, with a few exceptions discussed later.
19549 For historical reasons the C standard also allows implementations with
19550 ones' complement or signed magnitude arithmetic, but it is safe to
19551 assume two's complement nowadays.
19553 Also, overflow can occur when converting an out-of-range value to a
19554 signed integer type.  Here a standard implementation must define what
19555 happens, but this might include raising an exception.  In practice all
19556 known implementations support silent wraparound in this case, so you need
19557 not worry about other possibilities.
19559 @node Signed Overflow Examples
19560 @subsection Examples of Code Assuming Wraparound Overflow
19561 @cindex integer overflow
19562 @cindex overflow, signed integer
19563 @cindex signed integer overflow
19564 @cindex wraparound arithmetic
19566 There has long been a tension between what the C standard requires for
19567 signed integer overflow, and what C programs commonly assume.  The
19568 standard allows aggressive optimizations based on assumptions that
19569 overflow never occurs, but many practical C programs rely on overflow
19570 wrapping around.  These programs do not conform to the standard, but
19571 they commonly work in practice because compiler writers are
19572 understandably reluctant to implement optimizations that would break
19573 many programs, unless perhaps a user specifies aggressive optimization.
19575 The C Standard says that if a program has signed integer overflow its
19576 behavior is undefined, and the undefined behavior can even precede the
19577 overflow.  To take an extreme example:
19579 @c Inspired by Robert Dewar's example in
19580 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
19581 @example
19582 if (password == expected_password)
19583   allow_superuser_privileges ();
19584 else if (counter++ == INT_MAX)
19585   abort ();
19586 else
19587   printf ("%d password mismatches\n", counter);
19588 @end example
19590 @noindent
19591 If the @code{int} variable @code{counter} equals @code{INT_MAX},
19592 @code{counter++} must overflow and the behavior is undefined, so the C
19593 standard allows the compiler to optimize away the test against
19594 @code{INT_MAX} and the @code{abort} call.
19595 Worse, if an earlier bug in the program lets the compiler deduce that
19596 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
19597 the C standard allows the compiler to optimize away the password test
19598 and generate code that allows superuser privileges unconditionally.
19600 Despite this requirement by the standard, it has long been common for C
19601 code to assume wraparound arithmetic after signed overflow, and all
19602 known practical C implementations support some C idioms that assume
19603 wraparound signed arithmetic, even if the idioms do not conform
19604 strictly to the standard.  If your code looks like the following
19605 examples it will almost surely work with real-world compilers.
19607 Here is an example derived from the 7th Edition Unix implementation of
19608 @code{atoi} (1979-01-10):
19610 @example
19611 char *p;
19612 int f, n;
19613 @dots{}
19614 while (*p >= '0' && *p <= '9')
19615   n = n * 10 + *p++ - '0';
19616 return (f ? -n : n);
19617 @end example
19619 @noindent
19620 Even if the input string is in range, on most modern machines this has
19621 signed overflow when computing the most negative integer (the @code{-n}
19622 overflows) or a value near an extreme integer (the first @code{+}
19623 overflows).
19625 Here is another example, derived from the 7th Edition implementation of
19626 @code{rand} (1979-01-10).  Here the programmer expects both
19627 multiplication and addition to wrap on overflow:
19629 @example
19630 static long int randx = 1;
19631 @dots{}
19632 randx = randx * 1103515245 + 12345;
19633 return (randx >> 16) & 077777;
19634 @end example
19636 In the following example, derived from the @acronym{GNU} C Library 2.5
19637 implementation of @code{mktime} (2006-09-09), the code assumes
19638 wraparound arithmetic in @code{+} to detect signed overflow:
19640 @example
19641 time_t t, t1, t2;
19642 int sec_requested, sec_adjustment;
19643 @dots{}
19644 t1 = t + sec_requested;
19645 t2 = t1 + sec_adjustment;
19646 if (((t1 < t) != (sec_requested < 0))
19647     | ((t2 < t1) != (sec_adjustment < 0)))
19648   return -1;
19649 @end example
19651 If your code looks like these examples, it is probably safe even though
19652 it does not strictly conform to the C standard.  This might lead one to
19653 believe that one can generally assume wraparound on overflow, but that
19654 is not always true, as can be seen in the next section.
19656 @node Optimization and Wraparound
19657 @subsection Optimizations That Break Wraparound Arithmetic
19658 @cindex loop induction
19660 Compilers sometimes generate code that is incompatible with wraparound
19661 integer arithmetic.  A simple example is an algebraic simplification: a
19662 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
19663 because it assumes that @code{i * 2000} does not overflow.  The
19664 translation is not equivalent to the original when overflow occurs:
19665 e.g., in the typical case of 32-bit signed two's complement wraparound
19666 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
19667 the original expression returns @minus{}2147483 but the optimized
19668 version returns the mathematically correct value 2147484.
19670 More subtly, loop induction optimizations often exploit the undefined
19671 behavior of signed overflow.  Consider the following contrived function
19672 @code{sumc}:
19674 @example
19676 sumc (int lo, int hi)
19678   int sum = 0;
19679   int i;
19680   for (i = lo; i <= hi; i++)
19681     sum ^= i * 53;
19682   return sum;
19684 @end example
19686 @noindent
19687 To avoid multiplying by 53 each time through the loop, an optimizing
19688 compiler might internally transform @code{sumc} to the equivalent of the
19689 following:
19691 @example
19693 transformed_sumc (int lo, int hi)
19695   int sum = 0;
19696   int hic = hi * 53;
19697   int ic;
19698   for (ic = lo * 53; ic <= hic; ic += 53)
19699     sum ^= ic;
19700   return sum;
19702 @end example
19704 @noindent
19705 This transformation is allowed by the C standard, but it is invalid for
19706 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
19707 overflow in computing expressions like @code{hi * 53} can cause the
19708 expression @code{i <= hi} to yield a different value from the
19709 transformed expression @code{ic <= hic}.
19711 For this reason, compilers that use loop induction and similar
19712 techniques often do not support reliable wraparound arithmetic when a
19713 loop induction variable like @code{ic} is involved.  Since loop
19714 induction variables are generated by the compiler, and are not visible
19715 in the source code, it is not always trivial to say whether the problem
19716 affects your code.
19718 Hardly any code actually depends on wraparound arithmetic in cases like
19719 these, so in practice these loop induction optimizations are almost
19720 always useful.  However, edge cases in this area can cause problems.
19721 For example:
19723 @example
19724 int j;
19725 for (j = 1; 0 < j; j *= 2)
19726   test (j);
19727 @end example
19729 @noindent
19730 Here, the loop attempts to iterate through all powers of 2 that
19731 @code{int} can represent, but the C standard allows a compiler to
19732 optimize away the comparison and generate an infinite loop,
19733 under the argument that behavior is undefined on overflow.  As of this
19734 writing this optimization is not done by any production version of
19735 @acronym{GCC} with @option{-O2}, but it might be performed by other
19736 compilers, or by more aggressive @acronym{GCC} optimization options,
19737 and the @acronym{GCC} developers have not decided whether it will
19738 continue to work with @acronym{GCC} and @option{-O2}.
19740 @node Signed Overflow Advice
19741 @subsection Practical Advice for Signed Overflow Issues
19742 @cindex integer overflow
19743 @cindex overflow, signed integer
19744 @cindex signed integer overflow
19745 @cindex wraparound arithmetic
19747 Ideally the safest approach is to avoid signed integer overflow
19748 entirely.  For example, instead of multiplying two signed integers, you
19749 can convert them to unsigned integers, multiply the unsigned values,
19750 then test whether the result is in signed range.
19752 Rewriting code in this way will be inconvenient, though, particularly if
19753 the signed values might be negative.  Also, it may hurt
19754 performance.  Using unsigned arithmetic to check for overflow is
19755 particularly painful to do portably and efficiently when dealing with an
19756 integer type like @code{uid_t} whose width and signedness vary from
19757 platform to platform.
19759 Furthermore, many C applications pervasively assume wraparound behavior
19760 and typically it is not easy to find and remove all these assumptions.
19761 Hence it is often useful to maintain nonstandard code that assumes
19762 wraparound on overflow, instead of rewriting the code.  The rest of this
19763 section attempts to give practical advice for this situation.
19765 If your code wants to detect signed integer overflow in @code{sum = a +
19766 b}, it is generally safe to use an expression like @code{(sum < a) != (b
19767 < 0)}.
19769 If your code uses a signed loop index, make sure that the index cannot
19770 overflow, along with all signed expressions derived from the index.
19771 Here is a contrived example of problematic code with two instances of
19772 overflow.
19774 @example
19775 for (i = INT_MAX - 10; i <= INT_MAX; i++)
19776   if (i + 1 < 0)
19777     @{
19778       report_overflow ();
19779       break;
19780     @}
19781 @end example
19783 @noindent
19784 Because of the two overflows, a compiler might optimize away or
19785 transform the two comparisons in a way that is incompatible with the
19786 wraparound assumption.
19788 If your code uses an expression like @code{(i * 2000) / 1000} and you
19789 actually want the multiplication to wrap around on overflow, use
19790 unsigned arithmetic
19791 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
19793 If your code assumes wraparound behavior and you want to insulate it
19794 against any @acronym{GCC} optimizations that would fail to support that
19795 behavior, you should use @acronym{GCC}'s @option{-fwrapv} option, which
19796 causes signed overflow to wrap around reliably (except for division and
19797 remainder, as discussed in the next section).
19799 If you need to port to platforms where signed integer overflow does not
19800 reliably wrap around (e.g., due to hardware overflow checking, or to
19801 highly aggressive optimizations), you should consider debugging with
19802 @acronym{GCC}'s @option{-ftrapv} option, which causes signed overflow to
19803 raise an exception.
19805 @node Signed Integer Division
19806 @subsection Signed Integer Division and Integer Overflow
19807 @cindex division, integer
19809 Overflow in signed
19810 integer division is not always harmless: for example, on CPUs of the
19811 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
19812 which by default terminates the program.  Worse, taking the remainder
19813 of these two values typically yields the same signal on these CPUs,
19814 even though the C standard requires @code{INT_MIN % -1} to yield zero
19815 because the expression does not overflow.
19817 @node Preprocessor Arithmetic
19818 @section Preprocessor Arithmetic
19819 @cindex preprocessor arithmetic
19821 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
19822 be evaluated as if all signed values are of type @code{intmax_t} and all
19823 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
19824 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
19825 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
19826 @code{long long int}.  Also, some older preprocessors mishandle
19827 constants ending in @code{LL}.  To work around these problems, you can
19828 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
19829 @code{configure}-time rather than at @code{#if}-time.
19831 @node Null Pointers
19832 @section Properties of Null Pointers
19833 @cindex null pointers
19835 Most modern hosts reliably fail when you attempt to dereference a null
19836 pointer.
19838 On almost all modern hosts, null pointers use an all-bits-zero internal
19839 representation, so you can reliably use @code{memset} with 0 to set all
19840 the pointers in an array to null values.
19842 If @code{p} is a null pointer to an object type, the C expression
19843 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
19844 the standard says that it has undefined behavior.
19846 @node Buffer Overruns
19847 @section Buffer Overruns and Subscript Errors
19848 @cindex buffer overruns
19850 Buffer overruns and subscript errors are the most common dangerous
19851 errors in C programs.  They result in undefined behavior because storing
19852 outside an array typically modifies storage that is used by some other
19853 object, and most modern systems lack runtime checks to catch these
19854 errors.  Programs should not rely on buffer overruns being caught.
19856 There is one exception to the usual rule that a portable program cannot
19857 address outside an array.  In C, it is valid to compute the address just
19858 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
19859 so long as you do not dereference the resulting pointer.  But it is not
19860 valid to compute the address just before an object, e.g., @code{&a[-1]};
19861 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
19862 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
19863 reliable in general, and it is usually easy enough to avoid the
19864 potential portability problem, e.g., by allocating an extra unused array
19865 element at the start or end.
19867 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
19868 @acronym{GCC}
19869 users might also consider using the @option{-fmudflap} option to catch
19870 overruns.
19872 Buffer overruns are usually caused by off-by-one errors, but there are
19873 more subtle ways to get them.
19875 Using @code{int} values to index into an array or compute array sizes
19876 causes problems on typical 64-bit hosts where an array index might
19877 be @math{2^31} or larger.  Index values of type @code{size_t} avoid this
19878 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
19879 are signed, and are wide enough in practice.
19881 If you add or multiply two numbers to calculate an array size, e.g.,
19882 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
19883 multiplication overflows.
19885 Many implementations of the @code{alloca} function silently misbehave
19886 and can generate buffer overflows if given sizes that are too large.
19887 The size limits are implementation dependent, but are at least 4000
19888 bytes on all platforms that we know about.
19890 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
19891 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
19892 portable code should not use them unless the inputs are known to be
19893 within certain limits.  The time-related functions can overflow their
19894 buffers if given timestamps out of range (e.g., a year less than -999
19895 or greater than 9999).  Time-related buffer overflows cannot happen with
19896 recent-enough versions of the @acronym{GNU} C library, but are possible
19897 with other
19898 implementations.  The @code{gets} function is the worst, since it almost
19899 invariably overflows its buffer when presented with an input line larger
19900 than the buffer.
19902 @node Volatile Objects
19903 @section Volatile Objects
19904 @cindex volatile objects
19906 The keyword @code{volatile} is often misunderstood in portable code.
19907 Its use inhibits some memory-access optimizations, but programmers often
19908 wish that it had a different meaning than it actually does.
19910 @code{volatile} was designed for code that accesses special objects like
19911 memory-mapped device registers whose contents spontaneously change.
19912 Such code is inherently low-level, and it is difficult to specify
19913 portably what @code{volatile} means in these cases.  The C standard
19914 says, ``What constitutes an access to an object that has
19915 volatile-qualified type is implementation-defined,'' so in theory each
19916 implementation is supposed to fill in the gap by documenting what
19917 @code{volatile} means for that implementation.  In practice, though,
19918 this documentation is usually absent or incomplete.
19920 One area of confusion is the distinction between objects defined with
19921 volatile types, and volatile lvalues.  From the C standard's point of
19922 view, an object defined with a volatile type has externally visible
19923 behavior.  You can think of such objects as having little oscilloscope
19924 probes attached to them, so that the user can observe some properties of
19925 accesses to them, just as the user can observe data written to output
19926 files.  However, the standard does not make it clear whether users can
19927 observe accesses by volatile lvalues to ordinary objects.  For example:
19929 @example
19930 /* Declare and access a volatile object.
19931    Accesses to X are "visible" to users.  */
19932 static int volatile x;
19933 x = 1;
19935 /* Access two ordinary objects via a volatile lvalue.
19936    It's not clear whether accesses to *P are "visible".  */
19937 int y;
19938 int *z = malloc (sizeof (int));
19939 int volatile *p;
19940 p = &y;
19941 *p = 1;
19942 p = z;
19943 *p = 1;
19944 @end example
19946 Programmers often wish that @code{volatile} meant ``Perform the memory
19947 access here and now, without merging several memory accesses, without
19948 changing the memory word size, and without reordering.''  But the C
19949 standard does not require this.  For objects defined with a volatile
19950 type, accesses must be done before the next sequence point; but
19951 otherwise merging, reordering, and word-size change is allowed.  Worse,
19952 it is not clear from the standard whether volatile lvalues provide more
19953 guarantees in general than nonvolatile lvalues, if the underlying
19954 objects are ordinary.
19956 Even when accessing objects defined with a volatile type,
19957 the C standard allows only
19958 extremely limited signal handlers: the behavior is undefined if a signal
19959 handler reads any nonlocal object, or writes to any nonlocal object
19960 whose type is not @code{sig_atomic_t volatile}, or calls any standard
19961 library function other than @code{abort}, @code{signal}, and (if C99)
19962 @code{_Exit}.  Hence C compilers need not worry about a signal handler
19963 disturbing ordinary computation, unless the computation accesses a
19964 @code{sig_atomic_t volatile} lvalue that is not a local variable.
19965 (There is an obscure exception for accesses via a pointer to a volatile
19966 character, since it may point into part of a @code{sig_atomic_t
19967 volatile} object.)  Posix
19968 adds to the list of library functions callable from a portable signal
19969 handler, but otherwise is like the C standard in this area.
19971 Some C implementations allow memory-access optimizations within each
19972 translation unit, such that actual behavior agrees with the behavior
19973 required by the standard only when calling a function in some other
19974 translation unit, and a signal handler acts like it was called from a
19975 different translation unit.  The C standard hints that in these
19976 implementations, objects referred to by signal handlers ``would require
19977 explicit specification of @code{volatile} storage, as well as other
19978 implementation-defined restrictions.''  But unfortunately even for this
19979 special case these other restrictions are often not documented well.
19980 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
19981 @acronym{GNU} Compiler Collection (@acronym{GCC})}, for some
19982 restrictions imposed by @acronym{GCC}.  @xref{Defining Handlers, ,
19983 Defining Signal Handlers, libc, The @acronym{GNU} C Library}, for some
19984 restrictions imposed by the @acronym{GNU} C library.  Restrictions
19985 differ on other platforms.
19987 If possible, it is best to use a signal handler that fits within the
19988 limits imposed by the C and Posix standards.
19990 If this is not practical, you can try the following rules of thumb.  A
19991 signal handler should access only volatile lvalues, preferably lvalues
19992 that refer to objects defined with a volatile type, and should not
19993 assume that the accessed objects have an internally consistent state
19994 if they are larger than a machine word.  Furthermore, installers
19995 should employ compilers and compiler options that are commonly used
19996 for building operating system kernels, because kernels often need more
19997 from @code{volatile} than the C Standard requires, and installers who
19998 compile an application in a similar environment can sometimes benefit
19999 from the extra constraints imposed by kernels on compilers.
20000 Admittedly we are handwaving somewhat here, as there are few
20001 guarantees in this area; the rules of thumb may help to fix some bugs
20002 but there is a good chance that they will not fix them all.
20004 For @code{volatile}, C++ has the same problems that C does.
20005 Multithreaded applications have even more problems with @code{volatile},
20006 but they are beyond the scope of this section.
20008 The bottom line is that using @code{volatile} typically hurts
20009 performance but should not hurt correctness.  In some cases its use
20010 does help correctness, but these cases are often so poorly understood
20011 that all too often adding @code{volatile} to a data structure merely
20012 alleviates some symptoms of a bug while not fixing the bug in general.
20014 @node Floating Point Portability
20015 @section Floating Point Portability
20016 @cindex floating point
20018 Almost all modern systems use IEEE-754 floating point, and it is safe to
20019 assume IEEE-754 in most portable code these days.  For more information,
20020 please see David Goldberg's classic paper
20021 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
20022 Scientist Should Know About Floating-Point Arithmetic}.
20024 @node Exiting Portably
20025 @section Exiting Portably
20026 @cindex exiting portably
20028 A C or C++ program can exit with status @var{N} by returning
20029 @var{N} from the @code{main} function.  Portable programs are supposed
20030 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
20031 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
20032 fail by exiting with status 1, and test programs that assume Posix can
20033 fail by exiting with status values from 1 through 255.  Programs on
20034 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
20035 status when @code{main} returned nonzero, but ancient systems like these
20036 are no longer of practical concern.
20038 A program can also exit with status @var{N} by passing @var{N} to the
20039 @code{exit} function, and a program can fail by calling the @code{abort}
20040 function.  If a program is specialized to just some platforms, it can fail
20041 by calling functions specific to those platforms, e.g., @code{_exit}
20042 (Posix) and @code{_Exit} (C99).  However, like other functions, an exit
20043 function should be declared, typically by including a header.  For
20044 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
20045 either directly or via the default includes (@pxref{Default Includes}).
20047 A program can fail due to undefined behavior such as dereferencing a null
20048 pointer, but this is not recommended as undefined behavior allows an
20049 implementation to do whatever it pleases and this includes exiting
20050 successfully.
20053 @c ================================================== Manual Configuration
20055 @node Manual Configuration
20056 @chapter Manual Configuration
20058 A few kinds of features can't be guessed automatically by running test
20059 programs.  For example, the details of the object-file format, or
20060 special options that need to be passed to the compiler or linker.  You
20061 can check for such features using ad-hoc means, such as having
20062 @command{configure} check the output of the @code{uname} program, or
20063 looking for libraries that are unique to particular systems.  However,
20064 Autoconf provides a uniform method for handling unguessable features.
20066 @menu
20067 * Specifying Target Triplets::  Specifying target triplets
20068 * Canonicalizing::              Getting the canonical system type
20069 * Using System Type::           What to do with the system type
20070 @end menu
20072 @node Specifying Target Triplets
20073 @section Specifying target triplets
20074 @cindex System type
20075 @cindex Target triplet
20076 @c This node used to be named Specifying Names.  The @anchor allows old
20077 @c links to still work.
20078 @anchor{Specifying Names}
20080 Autoconf-generated
20081 @command{configure} scripts can make decisions based on a canonical name
20082 for the system type, or @dfn{target triplet}, which has the form:
20083 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
20084 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
20086 @command{configure} can usually guess the canonical name for the type of
20087 system it's running on.  To do so it runs a script called
20088 @command{config.guess}, which infers the name using the @code{uname}
20089 command or symbols predefined by the C preprocessor.
20091 Alternately, the user can specify the system type with command line
20092 arguments to @command{configure} (@pxref{System Type}.  Doing so is
20093 necessary when
20094 cross-compiling.  In the most complex case of cross-compiling, three
20095 system types are involved.  The options to specify them are:
20097 @table @option
20098 @item --build=@var{build-type}
20099 the type of system on which the package is being configured and
20100 compiled.  It defaults to the result of running @command{config.guess}.
20102 @item --host=@var{host-type}
20103 the type of system on which the package runs.  By default it is the
20104 same as the build machine.  Specifying it enables the cross-compilation
20105 mode.
20107 @item --target=@var{target-type}
20108 the type of system for which any compiler tools in the package
20109 produce code (rarely needed).  By default, it is the same as host.
20110 @end table
20112 If you mean to override the result of @command{config.guess}, use
20113 @option{--build}, not @option{--host}, since the latter enables
20114 cross-compilation.  For historical reasons,
20115 whenever you specify @option{--host},
20116 be sure to specify @option{--build} too; this will be fixed in the
20117 future.  So, to enter cross-compilation mode, use a command like this
20119 @example
20120 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
20121 @end example
20123 @noindent
20124 Note that if you do not specify @option{--host}, @command{configure}
20125 fails if it can't run the code generated by the specified compiler.  For
20126 example, configuring as follows fails:
20128 @example
20129 ./configure CC=m68k-coff-gcc
20130 @end example
20132 When cross-compiling, @command{configure} will warn about any tools
20133 (compilers, linkers, assemblers) whose name is not prefixed with the
20134 host type.  This is an aid to users performing cross-compilation.
20135 Continuing the example above, if a cross-compiler named @command{cc} is
20136 used with a native @command{pkg-config}, then libraries found by
20137 @command{pkg-config} will likely cause subtle build failures; but using
20138 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
20139 avoids any confusion.  Avoiding the warning is as simple as creating the
20140 correct symlinks naming the cross tools.
20142 @cindex @command{config.sub}
20143 @command{configure} recognizes short aliases for many system types; for
20144 example, @samp{decstation} can be used instead of
20145 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
20146 @command{config.sub} to canonicalize system type aliases.
20148 This section deliberately omits the description of the obsolete
20149 interface; see @ref{Hosts and Cross-Compilation}.
20152 @node Canonicalizing
20153 @section Getting the Canonical System Type
20154 @cindex System type
20155 @cindex Canonical system type
20157 The following macros make the system type available to @command{configure}
20158 scripts.
20160 @ovindex build_alias
20161 @ovindex host_alias
20162 @ovindex target_alias
20164 The variables @samp{build_alias}, @samp{host_alias}, and
20165 @samp{target_alias} are always exactly the arguments of @option{--build},
20166 @option{--host}, and @option{--target}; in particular, they are left empty
20167 if the user did not use them, even if the corresponding
20168 @code{AC_CANONICAL} macro was run.  Any configure script may use these
20169 variables anywhere.  These are the variables that should be used when in
20170 interaction with the user.
20172 If you need to recognize some special environments based on their system
20173 type, run the following macros to get canonical system names.  These
20174 variables are not set before the macro call.
20176 If you use these macros, you must distribute @command{config.guess} and
20177 @command{config.sub} along with your source code.  @xref{Output}, for
20178 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
20179 to control in which directory @command{configure} looks for those scripts.
20182 @defmac AC_CANONICAL_BUILD
20183 @acindex{CANONICAL_BUILD}
20184 @ovindex build
20185 @ovindex build_cpu
20186 @ovindex build_vendor
20187 @ovindex build_os
20188 Compute the canonical build-system type variable, @code{build}, and its
20189 three individual parts @code{build_cpu}, @code{build_vendor}, and
20190 @code{build_os}.
20192 If @option{--build} was specified, then @code{build} is the
20193 canonicalization of @code{build_alias} by @command{config.sub},
20194 otherwise it is determined by the shell script @command{config.guess}.
20195 @end defmac
20197 @defmac AC_CANONICAL_HOST
20198 @acindex{CANONICAL_HOST}
20199 @ovindex host
20200 @ovindex host_cpu
20201 @ovindex host_vendor
20202 @ovindex host_os
20203 Compute the canonical host-system type variable, @code{host}, and its
20204 three individual parts @code{host_cpu}, @code{host_vendor}, and
20205 @code{host_os}.
20207 If @option{--host} was specified, then @code{host} is the
20208 canonicalization of @code{host_alias} by @command{config.sub},
20209 otherwise it defaults to @code{build}.
20210 @end defmac
20212 @defmac AC_CANONICAL_TARGET
20213 @acindex{CANONICAL_TARGET}
20214 @ovindex target
20215 @ovindex target_cpu
20216 @ovindex target_vendor
20217 @ovindex target_os
20218 Compute the canonical target-system type variable, @code{target}, and its
20219 three individual parts @code{target_cpu}, @code{target_vendor}, and
20220 @code{target_os}.
20222 If @option{--target} was specified, then @code{target} is the
20223 canonicalization of @code{target_alias} by @command{config.sub},
20224 otherwise it defaults to @code{host}.
20225 @end defmac
20227 Note that there can be artifacts due to the backward compatibility
20228 code.  See @xref{Hosts and Cross-Compilation}, for more.
20230 @node Using System Type
20231 @section Using the System Type
20233 In @file{configure.ac} the system type is generally used by one or more
20234 @code{case} statements to select system-specifics.  Shell wildcards can
20235 be used to match a group of system types.
20237 For example, an extra assembler code object file could be chosen, giving
20238 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
20239 following would be used in a makefile to add the object to a
20240 program or library.
20242 @example
20243 AS_CASE([$host],
20244   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
20245   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
20246   [CYCLE_OBJ=""]
20248 AC_SUBST([CYCLE_OBJ])
20249 @end example
20251 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
20252 to select variant source files, for example optimized code for some
20253 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
20254 so some runtime capability checks may be necessary too.
20256 @example
20257 case $host in
20258   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
20259   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
20260   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
20261 esac
20262 @end example
20264 The host system type can also be used to find cross-compilation tools
20265 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
20267 The above examples all show @samp{$host}, since this is where the code
20268 is going to run.  Only rarely is it necessary to test @samp{$build}
20269 (which is where the build is being done).
20271 Whenever you're tempted to use @samp{$host} it's worth considering
20272 whether some sort of probe would be better.  New system types come along
20273 periodically or previously missing features are added.  Well-written
20274 probes can adapt themselves to such things, but hard-coded lists of
20275 names can't.  Here are some guidelines,
20277 @itemize @bullet
20278 @item
20279 Availability of libraries and library functions should always be checked
20280 by probing.
20281 @item
20282 Variant behavior of system calls is best identified with runtime tests
20283 if possible, but bug workarounds or obscure difficulties might have to
20284 be driven from @samp{$host}.
20285 @item
20286 Assembler code is inevitably highly CPU-specific and is best selected
20287 according to @samp{$host_cpu}.
20288 @item
20289 Assembler variations like underscore prefix on globals or ELF versus
20290 COFF type directives are however best determined by probing, perhaps
20291 even examining the compiler output.
20292 @end itemize
20294 @samp{$target} is for use by a package creating a compiler or similar.
20295 For ordinary packages it's meaningless and should not be used.  It
20296 indicates what the created compiler should generate code for, if it can
20297 cross-compile.  @samp{$target} generally selects various hard-coded CPU
20298 and system conventions, since usually the compiler or tools under
20299 construction themselves determine how the target works.
20302 @c ===================================================== Site Configuration.
20304 @node Site Configuration
20305 @chapter Site Configuration
20307 @command{configure} scripts support several kinds of local configuration
20308 decisions.  There are ways for users to specify where external software
20309 packages are, include or exclude optional features, install programs
20310 under modified names, and set default values for @command{configure}
20311 options.
20313 @menu
20314 * Help Formatting::             Customizing @samp{configure --help}
20315 * External Software::           Working with other optional software
20316 * Package Options::             Selecting optional features
20317 * Pretty Help Strings::         Formatting help string
20318 * Option Checking::             Controlling checking of @command{configure} options
20319 * Site Details::                Configuring site details
20320 * Transforming Names::          Changing program names when installing
20321 * Site Defaults::               Giving @command{configure} local defaults
20322 @end menu
20324 @node Help Formatting
20325 @section Controlling Help Output
20327 Users consult @samp{configure --help} to learn of configuration
20328 decisions specific to your package.  By default, @command{configure}
20329 breaks this output into sections for each type of option; within each
20330 section, help strings appear in the order @file{configure.ac} defines
20331 them:
20333 @example
20334 Optional Features:
20335   @dots{}
20336   --enable-bar            include bar
20338 Optional Packages:
20339   @dots{}
20340   --with-foo              use foo
20341 @end example
20343 @defmac AC_PRESERVE_HELP_ORDER
20344 @acindex{PRESERVE_HELP_ORDER}
20346 Request an alternate @option{--help} format, in which options of all
20347 types appear together, in the order defined.  Call this macro before any
20348 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
20350 @example
20351 Optional Features and Packages:
20352   @dots{}
20353   --enable-bar            include bar
20354   --with-foo              use foo
20355 @end example
20357 @end defmac
20359 @node External Software
20360 @section Working With External Software
20361 @cindex External software
20363 Some packages require, or can optionally use, other software packages
20364 that are already installed.  The user can give @command{configure}
20365 command line options to specify which such external software to use.
20366 The options have one of these forms:
20368 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
20369 @c awful.
20370 @example
20371 --with-@var{package}[=@var{arg}]
20372 --without-@var{package}
20373 @end example
20375 For example, @option{--with-gnu-ld} means work with the @acronym{GNU} linker
20376 instead of some other linker.  @option{--with-x} means work with The X
20377 Window System.
20379 The user can give an argument by following the package name with
20380 @samp{=} and the argument.  Giving an argument of @samp{no} is for
20381 packages that are used by default; it says to @emph{not} use the
20382 package.  An argument that is neither @samp{yes} nor @samp{no} could
20383 include a name or number of a version of the other package, to specify
20384 more precisely which other package this program is supposed to work
20385 with.  If no argument is given, it defaults to @samp{yes}.
20386 @option{--without-@var{package}} is equivalent to
20387 @option{--with-@var{package}=no}.
20389 Normally @command{configure} scripts complain about
20390 @option{--with-@var{package}} options that they do not support.
20391 @xref{Option Checking}, for details, and for how to override the
20392 defaults.
20394 For each external software package that may be used, @file{configure.ac}
20395 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
20396 user asked to use it.  Whether each package is used or not by default,
20397 and which arguments are valid, is up to you.
20399 @anchor{AC_ARG_WITH}
20400 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
20401   @ovar{action-if-given}, @ovar{action-if-not-given})
20402 @acindex{ARG_WITH}
20403 If the user gave @command{configure} the option @option{--with-@var{package}}
20404 or @option{--without-@var{package}}, run shell commands
20405 @var{action-if-given}.  If neither option was given, run shell commands
20406 @var{action-if-not-given}.  The name @var{package} indicates another
20407 software package that this program should work with.  It should consist
20408 only of alphanumeric characters, dashes, and dots.
20410 The option's argument is available to the shell commands
20411 @var{action-if-given} in the shell variable @code{withval}, which is
20412 actually just the value of the shell variable named
20413 @code{with_@var{package}}, with any non-alphanumeric characters in
20414 @var{package} changed into @samp{_}.  You may use that variable instead,
20415 if you wish.
20417 The argument @var{help-string} is a description of the option that
20418 looks like this:
20419 @example
20420   --with-readline         support fancy command line editing
20421 @end example
20423 @noindent
20424 @var{help-string} may be more than one line long, if more detail is
20425 needed.  Just make sure the columns line up in @samp{configure
20426 --help}.  Avoid tabs in the help string.  The easiest way to provide the
20427 proper leading whitespace is to format your @var{help-string} with the macro
20428 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
20430 The following example shows how to use the @code{AC_ARG_WITH} macro in
20431 a common situation.  You want to let the user decide whether to enable
20432 support for an external library (e.g., the readline library); if the user
20433 specified neither @option{--with-readline} nor @option{--without-readline},
20434 you want to enable support for readline only if the library is available
20435 on the system.
20437 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
20438 @example
20439 AC_ARG_WITH([readline],
20440   [AS_HELP_STRING([--with-readline],
20441     [support fancy command line editing @@<:@@default=check@@:>@@])],
20442   [],
20443   [with_readline=check])
20445 LIBREADLINE=
20446 AS_IF([test "x$with_readline" != xno],
20447   [AC_CHECK_LIB([readline], [main],
20448     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
20449      AC_DEFINE([HAVE_LIBREADLINE], [1],
20450                [Define if you have libreadline])
20451     ],
20452     [if test "x$with_readline" != xcheck; then
20453        AC_MSG_FAILURE(
20454          [--with-readline was given, but test for readline failed])
20455      fi
20456     ], -lncurses)])
20457 @end example
20459 The next example shows how to use @code{AC_ARG_WITH} to give the user the
20460 possibility to enable support for the readline library, in case it is still
20461 experimental and not well tested, and is therefore disabled by default.
20463 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
20464 @example
20465 AC_ARG_WITH([readline],
20466   [AS_HELP_STRING([--with-readline],
20467     [enable experimental support for readline])],
20468   [],
20469   [with_readline=no])
20471 LIBREADLINE=
20472 AS_IF([test "x$with_readline" != xno],
20473   [AC_CHECK_LIB([readline], [main],
20474     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
20475      AC_DEFINE([HAVE_LIBREADLINE], [1],
20476                [Define if you have libreadline])
20477     ],
20478     [AC_MSG_FAILURE(
20479        [--with-readline was given, but test for readline failed])],
20480     [-lncurses])])
20481 @end example
20483 The last example shows how to use @code{AC_ARG_WITH} to give the user the
20484 possibility to disable support for the readline library, given that it is
20485 an important feature and that it should be enabled by default.
20487 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
20488 @example
20489 AC_ARG_WITH([readline],
20490   [AS_HELP_STRING([--without-readline],
20491     [disable support for readline])],
20492   [],
20493   [with_readline=yes])
20495 LIBREADLINE=
20496 AS_IF([test "x$with_readline" != xno],
20497   [AC_CHECK_LIB([readline], [main],
20498     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
20499      AC_DEFINE([HAVE_LIBREADLINE], [1],
20500                [Define if you have libreadline])
20501     ],
20502     [AC_MSG_FAILURE(
20503        [readline test failed (--without-readline to disable)])],
20504     [-lncurses])])
20505 @end example
20507 These three examples can be easily adapted to the case where
20508 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
20509 @ref{Package Options}).
20510 @end defmac
20512 @node Package Options
20513 @section Choosing Package Options
20514 @cindex Package options
20515 @cindex Options, package
20517 If a software package has optional compile-time features, the user can
20518 give @command{configure} command line options to specify whether to
20519 compile them.  The options have one of these forms:
20521 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
20522 @c awful.
20523 @example
20524 --enable-@var{feature}[=@var{arg}]
20525 --disable-@var{feature}
20526 @end example
20528 These options allow users to choose which optional features to build and
20529 install.  @option{--enable-@var{feature}} options should never make a
20530 feature behave differently or cause one feature to replace another.
20531 They should only cause parts of the program to be built rather than left
20532 out.
20534 The user can give an argument by following the feature name with
20535 @samp{=} and the argument.  Giving an argument of @samp{no} requests
20536 that the feature @emph{not} be made available.  A feature with an
20537 argument looks like @option{--enable-debug=stabs}.  If no argument is
20538 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
20539 equivalent to @option{--enable-@var{feature}=no}.
20541 Normally @command{configure} scripts complain about
20542 @option{--enable-@var{package}} options that they do not support.
20543 @xref{Option Checking}, for details, and for how to override the
20544 defaults.
20546 For each optional feature, @file{configure.ac} should call
20547 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
20548 to include it.  Whether each feature is included or not by default, and
20549 which arguments are valid, is up to you.
20551 @anchor{AC_ARG_ENABLE}
20552 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
20553   @ovar{action-if-given}, @ovar{action-if-not-given})
20554 @acindex{ARG_ENABLE}
20555 If the user gave @command{configure} the option
20556 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
20557 shell commands @var{action-if-given}.  If neither option was given, run
20558 shell commands @var{action-if-not-given}.  The name @var{feature}
20559 indicates an optional user-level facility.  It should consist only of
20560 alphanumeric characters, dashes, and dots.
20562 The option's argument is available to the shell commands
20563 @var{action-if-given} in the shell variable @code{enableval}, which is
20564 actually just the value of the shell variable named
20565 @code{enable_@var{feature}}, with any non-alphanumeric characters in
20566 @var{feature} changed into @samp{_}.  You may use that variable instead,
20567 if you wish.  The @var{help-string} argument is like that of
20568 @code{AC_ARG_WITH} (@pxref{External Software}).
20570 You should format your @var{help-string} with the macro
20571 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
20573 See the examples suggested with the definition of @code{AC_ARG_WITH}
20574 (@pxref{External Software}) to get an idea of possible applications of
20575 @code{AC_ARG_ENABLE}.
20576 @end defmac
20578 @node Pretty Help Strings
20579 @section Making Your Help Strings Look Pretty
20580 @cindex Help strings
20582 Properly formatting the @samp{help strings} which are used in
20583 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
20584 (@pxref{Package Options}) can be challenging.  Specifically, you want
20585 your own @samp{help strings} to line up in the appropriate columns of
20586 @samp{configure --help} just like the standard Autoconf @samp{help
20587 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
20589 @anchor{AS_HELP_STRING}
20590 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
20591   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
20592 @asindex{HELP_STRING}
20594 Expands into a help string that looks pretty when the user executes
20595 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
20596 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
20597 Options}).  The following example makes this clearer.
20599 @example
20600 AC_ARG_WITH([foo],
20601   [AS_HELP_STRING([--with-foo],
20602      [use foo (default is no)])],
20603   [use_foo=$withval],
20604   [use_foo=no])
20605 @end example
20607 Then the last few lines of @samp{configure --help} appear like
20608 this:
20610 @example
20611 --enable and --with options recognized:
20612   --with-foo              use foo (default is no)
20613 @end example
20615 Macro expansion is performed on the first argument.  However, the second
20616 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
20617 list of text to be reformatted, and is not subject to macro expansion.
20618 Since it is not expanded, it should not be double quoted.
20619 @xref{Autoconf Language}, for a more detailed explanation.
20621 The @code{AS_HELP_STRING} macro is particularly helpful when the
20622 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
20623 arguments, as shown in the following example.  Be aware that
20624 @var{left-hand-side} may not expand to unbalanced quotes,
20625 although quadrigraphs can be used.
20627 @example
20628 AC_DEFUN([MY_ARG_WITH],
20629   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
20630      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
20631                      [use $1 (default is $2)])],
20632      [use_[]$1=$withval],
20633      [use_[]$1=$2])])
20634 MY_ARG_WITH([a_b], [no])
20635 @end example
20636 @noindent
20637 Here, the last few lines of @samp{configure --help} will include:
20639 @example
20640 --enable and --with options recognized:
20641   --with-a-b              use a_b (default is no)
20642 @end example
20644 The parameters @var{indent-column} and @var{wrap-column} were introduced
20645 in Autoconf 2.62.  Generally, they should not be specified; they exist
20646 for fine-tuning of the wrapping.
20647 @example
20648 AS_HELP_STRING([--option], [description of option])
20649 @result{}  --option                description of option
20650 AS_HELP_STRING([--option], [description of option], [15], [30])
20651 @result{}  --option     description of
20652 @result{}               option
20653 @end example
20654 @end defmac
20657 @node Option Checking
20658 @section Controlling Checking of @command{configure} Options
20659 @cindex Options, Package
20661 The @command{configure} script checks its command-line options against a
20662 list of known options, like @option{--help} or @option{--config-cache}.
20663 An unknown option ordinarily indicates a mistake by the user and
20664 @command{configure} halts with an error.  However, by default unknown
20665 @option{--with-@var{package}} and @option{--enable-@var{feature}}
20666 options elicit only a warning, to support configuring entire source
20667 trees.
20669 Source trees often contain multiple packages with a top-level
20670 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
20671 (@pxref{Subdirectories}).  Because the packages generally support
20672 different @option{--with-@var{package}} and
20673 @option{--enable-@var{feature}} options, the @acronym{GNU} Coding
20674 Standards say they must accept unrecognized options without halting.
20675 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
20676 automatically disables the warnings.
20678 This default behavior may be modified in two ways.  First, the installer
20679 can invoke @code{configure --disable-option-checking} to disable
20680 these warnings, or invoke @code{configure --enable-option-checking=fatal}
20681 options to turn them into fatal errors, respectively.  Second, the
20682 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
20684 @defmac AC_DISABLE_OPTION_CHECKING
20685 @acindex{DISABLE_OPTION_CHECKING}
20687 By default, disable warnings related to any unrecognized
20688 @option{--with-@var{package}} or @option{--enable-@var{feature}}
20689 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
20691 The installer can override this behavior by passing
20692 @option{--enable-option-checking} (enable warnings) or
20693 @option{--enable-option-checking=fatal} (enable errors) to
20694 @command{configure}.
20695 @end defmac
20698 @node Site Details
20699 @section Configuring Site Details
20700 @cindex Site details
20702 Some software packages require complex site-specific information.  Some
20703 examples are host names to use for certain services, company names, and
20704 email addresses to contact.  Since some configuration scripts generated
20705 by Metaconfig ask for such information interactively, people sometimes
20706 wonder how to get that information in Autoconf-generated configuration
20707 scripts, which aren't interactive.
20709 Such site configuration information should be put in a file that is
20710 edited @emph{only by users}, not by programs.  The location of the file
20711 can either be based on the @code{prefix} variable, or be a standard
20712 location such as the user's home directory.  It could even be specified
20713 by an environment variable.  The programs should examine that file at
20714 runtime, rather than at compile time.  Runtime configuration is more
20715 convenient for users and makes the configuration process simpler than
20716 getting the information while configuring.  @xref{Directory Variables, ,
20717 Variables for Installation Directories, standards, @acronym{GNU} Coding
20718 Standards}, for more information on where to put data files.
20720 @node Transforming Names
20721 @section Transforming Program Names When Installing
20722 @cindex Transforming program names
20723 @cindex Program names, transforming
20725 Autoconf supports changing the names of programs when installing them.
20726 In order to use these transformations, @file{configure.ac} must call the
20727 macro @code{AC_ARG_PROGRAM}.
20729 @defmac AC_ARG_PROGRAM
20730 @acindex{ARG_PROGRAM}
20731 @ovindex program_transform_name
20732 Place in output variable @code{program_transform_name} a sequence of
20733 @code{sed} commands for changing the names of installed programs.
20735 If any of the options described below are given to @command{configure},
20736 program names are transformed accordingly.  Otherwise, if
20737 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
20738 is given, the target type followed by a dash is used as a prefix.
20739 Otherwise, no program name transformation is done.
20740 @end defmac
20742 @menu
20743 * Transformation Options::      @command{configure} options to transform names
20744 * Transformation Examples::     Sample uses of transforming names
20745 * Transformation Rules::        Makefile uses of transforming names
20746 @end menu
20748 @node Transformation Options
20749 @subsection Transformation Options
20751 You can specify name transformations by giving @command{configure} these
20752 command line options:
20754 @table @option
20755 @item --program-prefix=@var{prefix}
20756 prepend @var{prefix} to the names;
20758 @item --program-suffix=@var{suffix}
20759 append @var{suffix} to the names;
20761 @item --program-transform-name=@var{expression}
20762 perform @code{sed} substitution @var{expression} on the names.
20763 @end table
20765 @node Transformation Examples
20766 @subsection Transformation Examples
20768 These transformations are useful with programs that can be part of a
20769 cross-compilation development environment.  For example, a
20770 cross-assembler running on a Sun 4 configured with
20771 @option{--target=i960-vxworks} is normally installed as
20772 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
20773 with a native Sun 4 assembler.
20775 You can force a program name to begin with @file{g}, if you don't want
20776 @acronym{GNU} programs installed on your system to shadow other programs with
20777 the same name.  For example, if you configure @acronym{GNU} @code{diff} with
20778 @option{--program-prefix=g}, then when you run @samp{make install} it is
20779 installed as @file{/usr/local/bin/gdiff}.
20781 As a more sophisticated example, you could use
20783 @example
20784 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
20785 @end example
20786 @noindent
20788 to prepend @samp{g} to most of the program names in a source tree,
20789 excepting those like @code{gdb} that already have one and those like
20790 @code{less} and @code{lesskey} that aren't @acronym{GNU} programs.  (That is
20791 assuming that you have a source tree containing those programs that is
20792 set up to use this feature.)
20794 One way to install multiple versions of some programs simultaneously is
20795 to append a version number to the name of one or both.  For example, if
20796 you want to keep Autoconf version 1 around for awhile, you can configure
20797 Autoconf version 2 using @option{--program-suffix=2} to install the
20798 programs as @file{/usr/local/bin/autoconf2},
20799 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
20800 that only the binaries are renamed, therefore you'd have problems with
20801 the library files which might overlap.
20803 @node Transformation Rules
20804 @subsection Transformation Rules
20806 Here is how to use the variable @code{program_transform_name} in a
20807 @file{Makefile.in}:
20809 @example
20810 PROGRAMS = cp ls rm
20811 transform = @@program_transform_name@@
20812 install:
20813         for p in $(PROGRAMS); do \
20814           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
20815                                               sed '$(transform)'`; \
20816         done
20818 uninstall:
20819         for p in $(PROGRAMS); do \
20820           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
20821         done
20822 @end example
20824 It is guaranteed that @code{program_transform_name} is never empty, and
20825 that there are no useless separators.  Therefore you may safely embed
20826 @code{program_transform_name} within a sed program using @samp{;}:
20828 @example
20829 transform = @@program_transform_name@@
20830 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
20831 @end example
20833 Whether to do the transformations on documentation files (Texinfo or
20834 @code{man}) is a tricky question; there seems to be no perfect answer,
20835 due to the several reasons for name transforming.  Documentation is not
20836 usually particular to a specific architecture, and Texinfo files do not
20837 conflict with system documentation.  But they might conflict with
20838 earlier versions of the same files, and @code{man} pages sometimes do
20839 conflict with system documentation.  As a compromise, it is probably
20840 best to do name transformations on @code{man} pages but not on Texinfo
20841 manuals.
20843 @node Site Defaults
20844 @section Setting Site Defaults
20845 @cindex Site defaults
20846 @cindex config.site
20848 Autoconf-generated @command{configure} scripts allow your site to provide
20849 default values for some configuration values.  You do this by creating
20850 site- and system-wide initialization files.
20852 @evindex CONFIG_SITE
20853 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
20854 uses its value as the name of a shell script to read.  Otherwise, it
20855 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
20856 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
20857 settings in machine-specific files override those in machine-independent
20858 ones in case of conflict.
20860 Site files can be arbitrary shell scripts, but only certain kinds of
20861 code are really appropriate to be in them.  Because @command{configure}
20862 reads any cache file after it has read any site files, a site file can
20863 define a default cache file to be shared between all Autoconf-generated
20864 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
20865 you set a default cache file in a site file, it is a good idea to also
20866 set the output variable @code{CC} in that site file, because the cache
20867 file is only valid for a particular compiler, but many systems have
20868 several available.
20870 You can examine or override the value set by a command line option to
20871 @command{configure} in a site file; options set shell variables that have
20872 the same names as the options, with any dashes turned into underscores.
20873 The exceptions are that @option{--without-} and @option{--disable-} options
20874 are like giving the corresponding @option{--with-} or @option{--enable-}
20875 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
20876 sets the variable @code{cache_file} to the value @samp{localcache};
20877 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
20878 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
20879 variable @code{prefix} to the value @samp{/usr}; etc.
20881 Site files are also good places to set default values for other output
20882 variables, such as @code{CFLAGS}, if you need to give them non-default
20883 values: anything you would normally do, repetitively, on the command
20884 line.  If you use non-default values for @var{prefix} or
20885 @var{exec_prefix} (wherever you locate the site file), you can set them
20886 in the site file if you specify it with the @code{CONFIG_SITE}
20887 environment variable.
20889 You can set some cache values in the site file itself.  Doing this is
20890 useful if you are cross-compiling, where it is impossible to check features
20891 that require running a test program.  You could ``prime the cache'' by
20892 setting those values correctly for that system in
20893 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
20894 variables you need to set, see the documentation of the respective
20895 Autoconf macro.  If the variables or their semantics are undocumented,
20896 you may need to look for shell variables with @samp{_cv_} in their names
20897 in the affected @command{configure} scripts, or in the Autoconf M4
20898 source code for those macros; but in that case, their name or semantics
20899 may change in a future Autoconf version.
20901 The cache file is careful to not override any variables set in the site
20902 files.  Similarly, you should not override command-line options in the
20903 site files.  Your code should check that variables such as @code{prefix}
20904 and @code{cache_file} have their default values (as set near the top of
20905 @command{configure}) before changing them.
20907 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
20908 command @samp{configure --prefix=/usr/share/local/gnu} would read this
20909 file (if @code{CONFIG_SITE} is not set to a different file).
20911 @example
20912 # /usr/share/local/gnu/share/config.site for configure
20914 # Change some defaults.
20915 test "$prefix" = NONE && prefix=/usr/share/local/gnu
20916 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
20917 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
20918 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
20920 # Give Autoconf 2.x generated configure scripts a shared default
20921 # cache file for feature test results, architecture-specific.
20922 if test "$cache_file" = /dev/null; then
20923   cache_file="$prefix/var/config.cache"
20924   # A cache file is only valid for one C compiler.
20925   CC=gcc
20927 @end example
20929 @cindex Filesystem Hierarchy Standard
20930 @cindex FHS
20932 Another use of @file{config.site} is for priming the directory variables
20933 in a manner consistent with the Filesystem Hierarchy Standard
20934 (@acronym{FHS}).  Once the following file is installed at
20935 @file{/usr/share/config.site}, a user can execute simply
20936 @code{./configure --prefix=/usr} to get all the directories chosen in
20937 the locations recommended by @acronym{FHS}.
20939 @example
20940 # /usr/share/config.site for FHS defaults when installing below /usr,
20941 # and the respective settings were not changed on the command line.
20942 if test "$prefix" = /usr; then
20943   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
20944   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
20945   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
20947 @end example
20949 @cindex lib64
20950 @cindex 64-bit libraries
20951 Likewise, on platforms where 64-bit libraries are built by default, then
20952 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
20953 it is appropriate to install @file{/usr/local/@/share/config.site}:
20955 @example
20956 # /usr/local/share/config.site for platforms that prefer
20957 # the directory /usr/local/lib64 over /usr/local/lib.
20958 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
20959 @end example
20962 @c ============================================== Running configure Scripts.
20964 @node Running configure Scripts
20965 @chapter Running @command{configure} Scripts
20966 @cindex @command{configure}
20968 Below are instructions on how to configure a package that uses a
20969 @command{configure} script, suitable for inclusion as an @file{INSTALL}
20970 file in the package.  A plain-text version of @file{INSTALL} which you
20971 may use comes with Autoconf.
20973 @menu
20974 * Basic Installation::          Instructions for typical cases
20975 * Compilers and Options::       Selecting compilers and optimization
20976 * Multiple Architectures::      Compiling for multiple architectures at once
20977 * Installation Names::          Installing in different directories
20978 * Optional Features::           Selecting optional features
20979 * Particular Systems::          Particular systems
20980 * System Type::                 Specifying the system type
20981 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
20982 * Defining Variables::          Specifying the compiler etc.
20983 * configure Invocation::        Changing how @command{configure} runs
20984 @end menu
20986 @set autoconf
20987 @include install.texi
20990 @c ============================================== config.status Invocation
20992 @node config.status Invocation
20993 @chapter config.status Invocation
20994 @cindex @command{config.status}
20996 The @command{configure} script creates a file named @file{config.status},
20997 which actually configures, @dfn{instantiates}, the template files.  It
20998 also records the configuration options that were specified when the
20999 package was last configured in case reconfiguring is needed.
21001 Synopsis:
21002 @example
21003 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
21004 @end example
21006 It configures each @var{tag}; if none are specified, all the templates
21007 are instantiated.  A @var{tag} refers to a file or other tag associated
21008 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
21009 macro (@pxref{Configuration Actions}).  The files must be specified
21010 without their dependencies, as in
21012 @example
21013 ./config.status foobar
21014 @end example
21016 @noindent
21019 @example
21020 ./config.status foobar:foo.in:bar.in
21021 @end example
21023 The supported options are:
21025 @table @option
21026 @item --help
21027 @itemx -h
21028 Print a summary of the command line options, the list of the template
21029 files, and exit.
21031 @item --version
21032 @itemx -V
21033 Print the version number of Autoconf and the configuration settings,
21034 and exit.
21036 @item --config
21037 Print the configuration settings in reusable way, quoted for the shell,
21038 and exit.  For example, for a debugging build that otherwise reuses the
21039 configuration from a different build directory @var{build-dir} of a
21040 package in @var{src-dir}, you could use the following:
21042 @example
21043 args=`@var{build-dir}/config.status --config`
21044 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
21045 @end example
21047 @noindent
21048 Note that it may be necessary to override a @option{--srcdir} setting
21049 that was saved in the configuration, if the arguments are used in a
21050 different build directory.
21052 @item --silent
21053 @itemx --quiet
21054 @itemx -q
21055 Do not print progress messages.
21057 @item --debug
21058 @itemx -d
21059 Don't remove the temporary files.
21061 @item --file=@var{file}[:@var{template}]
21062 Require that @var{file} be instantiated as if
21063 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
21064 @var{file} and @var{template} may be @samp{-} in which case the standard
21065 output and/or standard input, respectively, is used.  If a
21066 @var{template} file name is relative, it is first looked for in the build
21067 tree, and then in the source tree.  @xref{Configuration Actions}, for
21068 more details.
21070 This option and the following ones provide one way for separately
21071 distributed packages to share the values computed by @command{configure}.
21072 Doing so can be useful if some of the packages need a superset of the
21073 features that one of them, perhaps a common library, does.  These
21074 options allow a @file{config.status} file to create files other than the
21075 ones that its @file{configure.ac} specifies, so it can be used for a
21076 different package, or for extracting a subset of values.  For example,
21078 @example
21079 echo '@@CC@@' | ./config.status --file=-
21080 @end example
21082 @noindent
21083 provides the value of @code{@@CC@@} on standard output.
21085 @item --header=@var{file}[:@var{template}]
21086 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
21088 @item --recheck
21089 Ask @file{config.status} to update itself and exit (no instantiation).
21090 This option is useful if you change @command{configure}, so that the
21091 results of some tests might be different from the previous run.  The
21092 @option{--recheck} option reruns @command{configure} with the same arguments
21093 you used before, plus the @option{--no-create} option, which prevents
21094 @command{configure} from running @file{config.status} and creating
21095 @file{Makefile} and other files, and the @option{--no-recursion} option,
21096 which prevents @command{configure} from running other @command{configure}
21097 scripts in subdirectories.  (This is so other Make rules can
21098 run @file{config.status} when it changes; @pxref{Automatic Remaking},
21099 for an example).
21100 @end table
21102 @file{config.status} checks several optional environment variables that
21103 can alter its behavior:
21105 @anchor{CONFIG_SHELL}
21106 @defvar CONFIG_SHELL
21107 @evindex CONFIG_SHELL
21108 The shell with which to run @command{configure} for the @option{--recheck}
21109 option.  It must be Bourne-compatible.  The default is a shell that
21110 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
21111 Invoking @command{configure} by hand bypasses this setting, so you may
21112 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
21113 to insure that the same shell is used everywhere.  The absolute name of the
21114 shell should be passed.
21115 @end defvar
21117 @defvar CONFIG_STATUS
21118 @evindex CONFIG_STATUS
21119 The file name to use for the shell script that records the
21120 configuration.  The default is @file{./config.status}.  This variable is
21121 useful when one package uses parts of another and the @command{configure}
21122 scripts shouldn't be merged because they are maintained separately.
21123 @end defvar
21125 You can use @file{./config.status} in your makefiles.  For example, in
21126 the dependencies given above (@pxref{Automatic Remaking}),
21127 @file{config.status} is run twice when @file{configure.ac} has changed.
21128 If that bothers you, you can make each run only regenerate the files for
21129 that rule:
21130 @example
21131 @group
21132 config.h: stamp-h
21133 stamp-h: config.h.in config.status
21134         ./config.status config.h
21135         echo > stamp-h
21137 Makefile: Makefile.in config.status
21138         ./config.status Makefile
21139 @end group
21140 @end example
21142 The calling convention of @file{config.status} has changed; see
21143 @ref{Obsolete config.status Use}, for details.
21146 @c =================================================== Obsolete Constructs
21148 @node Obsolete Constructs
21149 @chapter Obsolete Constructs
21150 @cindex Obsolete constructs
21152 Autoconf changes, and throughout the years some constructs have been
21153 obsoleted.  Most of the changes involve the macros, but in some cases
21154 the tools themselves, or even some concepts, are now considered
21155 obsolete.
21157 You may completely skip this chapter if you are new to Autoconf.  Its
21158 intention is mainly to help maintainers updating their packages by
21159 understanding how to move to more modern constructs.
21161 @menu
21162 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
21163 * acconfig Header::             Additional entries in @file{config.h.in}
21164 * autoupdate Invocation::       Automatic update of @file{configure.ac}
21165 * Obsolete Macros::             Backward compatibility macros
21166 * Autoconf 1::                  Tips for upgrading your files
21167 * Autoconf 2.13::               Some fresher tips
21168 @end menu
21170 @node Obsolete config.status Use
21171 @section Obsolete @file{config.status} Invocation
21173 @file{config.status} now supports arguments to specify the files to
21174 instantiate; see @ref{config.status Invocation}, for more details.
21175 Before, environment variables had to be used.
21177 @defvar CONFIG_COMMANDS
21178 @evindex CONFIG_COMMANDS
21179 The tags of the commands to execute.  The default is the arguments given
21180 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
21181 @file{configure.ac}.
21182 @end defvar
21184 @defvar CONFIG_FILES
21185 @evindex CONFIG_FILES
21186 The files in which to perform @samp{@@@var{variable}@@} substitutions.
21187 The default is the arguments given to @code{AC_OUTPUT} and
21188 @code{AC_CONFIG_FILES} in @file{configure.ac}.
21189 @end defvar
21191 @defvar CONFIG_HEADERS
21192 @evindex CONFIG_HEADERS
21193 The files in which to substitute C @code{#define} statements.  The
21194 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
21195 macro was not called, @file{config.status} ignores this variable.
21196 @end defvar
21198 @defvar CONFIG_LINKS
21199 @evindex CONFIG_LINKS
21200 The symbolic links to establish.  The default is the arguments given to
21201 @code{AC_CONFIG_LINKS}; if that macro was not called,
21202 @file{config.status} ignores this variable.
21203 @end defvar
21205 In @ref{config.status Invocation}, using this old interface, the example
21206 would be:
21208 @example
21209 @group
21210 config.h: stamp-h
21211 stamp-h: config.h.in config.status
21212         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
21213           CONFIG_HEADERS=config.h ./config.status
21214         echo > stamp-h
21216 Makefile: Makefile.in config.status
21217         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
21218           CONFIG_FILES=Makefile ./config.status
21219 @end group
21220 @end example
21222 @noindent
21223 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
21224 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
21225 for @code{CONFIG_COMMANDS}, etc.)
21228 @node acconfig Header
21229 @section @file{acconfig.h}
21231 @cindex @file{acconfig.h}
21232 @cindex @file{config.h.top}
21233 @cindex @file{config.h.bot}
21235 In order to produce @file{config.h.in}, @command{autoheader} needs to
21236 build or to find templates for each symbol.  Modern releases of Autoconf
21237 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
21238 Macros}), but in older releases a file, @file{acconfig.h}, contained the
21239 list of needed templates.  @command{autoheader} copied comments and
21240 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
21241 the current directory, if present.  This file used to be mandatory if
21242 you @code{AC_DEFINE} any additional symbols.
21244 Modern releases of Autoconf also provide @code{AH_TOP} and
21245 @code{AH_BOTTOM} if you need to prepend/append some information to
21246 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
21247 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
21248 @command{autoheader} copies the lines before the line containing
21249 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
21250 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
21251 @command{autoheader} copies the lines after that line to the end of the
21252 file it generates.  Either or both of those strings may be omitted.  An
21253 even older alternate way to produce the same effect in ancient versions
21254 of Autoconf is to create the files @file{@var{file}.top} (typically
21255 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
21256 directory.  If they exist, @command{autoheader} copies them to the
21257 beginning and end, respectively, of its output.
21259 In former versions of Autoconf, the files used in preparing a software
21260 package for distribution were:
21261 @example
21262 @group
21263 configure.ac --.   .------> autoconf* -----> configure
21264                +---+
21265 [aclocal.m4] --+   `---.
21266 [acsite.m4] ---'       |
21267                        +--> [autoheader*] -> [config.h.in]
21268 [acconfig.h] ----.     |
21269                  +-----'
21270 [config.h.top] --+
21271 [config.h.bot] --'
21272 @end group
21273 @end example
21275 Using only the @code{AH_} macros, @file{configure.ac} should be
21276 self-contained, and should not depend upon @file{acconfig.h} etc.
21279 @node autoupdate Invocation
21280 @section Using @command{autoupdate} to Modernize @file{configure.ac}
21281 @cindex @command{autoupdate}
21283 The @command{autoupdate} program updates a @file{configure.ac} file that
21284 calls Autoconf macros by their old names to use the current macro names.
21285 In version 2 of Autoconf, most of the macros were renamed to use a more
21286 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
21287 description of the new scheme.  Although the old names still work
21288 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
21289 new names), you can make your @file{configure.ac} files more readable
21290 and make it easier to use the current Autoconf documentation if you
21291 update them to use the new macro names.
21293 @evindex SIMPLE_BACKUP_SUFFIX
21294 If given no arguments, @command{autoupdate} updates @file{configure.ac},
21295 backing up the original version with the suffix @file{~} (or the value
21296 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
21297 set).  If you give @command{autoupdate} an argument, it reads that file
21298 instead of @file{configure.ac} and writes the updated file to the
21299 standard output.
21301 @noindent
21302 @command{autoupdate} accepts the following options:
21304 @table @option
21305 @item --help
21306 @itemx -h
21307 Print a summary of the command line options and exit.
21309 @item --version
21310 @itemx -V
21311 Print the version number of Autoconf and exit.
21313 @item --verbose
21314 @itemx -v
21315 Report processing steps.
21317 @item --debug
21318 @itemx -d
21319 Don't remove the temporary files.
21321 @item --force
21322 @itemx -f
21323 Force the update even if the file has not changed.  Disregard the cache.
21325 @item --include=@var{dir}
21326 @itemx -I @var{dir}
21327 Also look for input files in @var{dir}.  Multiple invocations accumulate.
21328 Directories are browsed from last to first.
21330 @item --prepend-include=@var{dir}
21331 @itemx -B @var{dir}
21332 Prepend directory @var{dir} to the search path.  This is used to include
21333 the language-specific files before any third-party macros.
21334 @end table
21336 @node Obsolete Macros
21337 @section Obsolete Macros
21339 Several macros are obsoleted in Autoconf, for various reasons (typically
21340 they failed to quote properly, couldn't be extended for more recent
21341 issues, etc.).  They are still supported, but deprecated: their use
21342 should be avoided.
21344 During the jump from Autoconf version 1 to version 2, most of the
21345 macros were renamed to use a more uniform and descriptive naming scheme,
21346 but their signature did not change.  @xref{Macro Names}, for a
21347 description of the new naming scheme.  Below, if there is just the mapping
21348 from old names to new names for these macros, the reader is invited to
21349 refer to the definition of the new macro for the signature and the
21350 description.
21352 @defmac AC_AIX
21353 @acindex{AIX}
21354 @cvindex _ALL_SOURCE
21355 This macro is a platform-specific subset of
21356 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
21357 @end defmac
21359 @defmac AC_ALLOCA
21360 @acindex{ALLOCA}
21361 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
21362 @end defmac
21364 @defmac AC_ARG_ARRAY
21365 @acindex{ARG_ARRAY}
21366 Removed because of limited usefulness.
21367 @end defmac
21369 @defmac AC_C_CROSS
21370 @acindex{C_CROSS}
21371 This macro is obsolete; it does nothing.
21372 @end defmac
21374 @defmac AC_C_LONG_DOUBLE
21375 @acindex{C_LONG_DOUBLE}
21376 @cvindex HAVE_LONG_DOUBLE
21377 If the C compiler supports a working @code{long double} type with more
21378 range or precision than the @code{double} type, define
21379 @code{HAVE_LONG_DOUBLE}.
21381 You should use @code{AC_TYPE_LONG_DOUBLE} or
21382 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
21383 @end defmac
21385 @defmac AC_CANONICAL_SYSTEM
21386 @acindex{CANONICAL_SYSTEM}
21387 Determine the system type and set output variables to the names of the
21388 canonical system types.  @xref{Canonicalizing}, for details about the
21389 variables this macro sets.
21391 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
21392 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
21393 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
21394 other macros (@pxref{Canonicalizing}).
21395 @end defmac
21397 @defmac AC_CHAR_UNSIGNED
21398 @acindex{CHAR_UNSIGNED}
21399 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
21400 @end defmac
21402 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
21403 @acindex{CHECK_TYPE}
21404 Autoconf, up to 2.13, used to provide this version of
21405 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
21406 it is a member of the @code{CHECK} clan, it does
21407 more than just checking.  Secondly, missing types are defined
21408 using @code{#define}, not @code{typedef}, and this can lead to
21409 problems in the case of pointer types.
21411 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
21412 @ref{Generic Types}, for the description of the current macro.
21414 If the type @var{type} is not defined, define it to be the C (or C++)
21415 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
21417 This macro is equivalent to:
21419 @example
21420 AC_CHECK_TYPE([@var{type}], [],
21421   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
21422      [Define to `@var{default}'
21423       if <sys/types.h> does not define.])])
21424 @end example
21426 In order to keep backward compatibility, the two versions of
21427 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
21429 @enumerate
21430 @item
21431 If there are three or four arguments, the modern version is used.
21433 @item
21434 If the second argument appears to be a C or C++ type, then the
21435 obsolete version is used.  This happens if the argument is a C or C++
21436 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
21437 followed by one of @samp{[(* } and then by a string of zero or more
21438 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
21440 @item
21441 If the second argument is spelled with the alphabet of valid C and C++
21442 types, the user is warned and the modern version is used.
21444 @item
21445 Otherwise, the modern version is used.
21446 @end enumerate
21448 @noindent
21449 You are encouraged either to use a valid builtin type, or to use the
21450 equivalent modern code (see above), or better yet, to use
21451 @code{AC_CHECK_TYPES} together with
21453 @example
21454 #ifndef HAVE_LOFF_T
21455 typedef loff_t off_t;
21456 #endif
21457 @end example
21458 @end defmac
21459 @c end of AC_CHECK_TYPE
21461 @defmac AC_CHECKING (@var{feature-description})
21462 @acindex{CHECKING}
21463 Same as
21465 @example
21466 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
21467 @end example
21469 @noindent
21470 @xref{AC_MSG_NOTICE}.
21471 @end defmac
21473 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
21474   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
21475 @acindex{COMPILE_CHECK}
21476 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
21477 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
21478 addition that it prints @samp{checking for @var{echo-text}} to the
21479 standard output first, if @var{echo-text} is non-empty.  Use
21480 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
21481 messages (@pxref{Printing Messages}).
21482 @end defmac
21484 @defmac AC_CONST
21485 @acindex{CONST}
21486 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
21487 @end defmac
21489 @defmac AC_CROSS_CHECK
21490 @acindex{CROSS_CHECK}
21491 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
21492 @code{:-)}.
21493 @end defmac
21495 @defmac AC_CYGWIN
21496 @acindex{CYGWIN}
21497 @evindex CYGWIN
21498 Check for the Cygwin environment in which case the shell variable
21499 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
21500 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
21501 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
21503 @example
21504 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
21505 case $host_os in
21506   *cygwin* ) CYGWIN=yes;;
21507          * ) CYGWIN=no;;
21508 esac
21509 @end example
21511 Beware that the variable @env{CYGWIN} has a special meaning when
21512 running Cygwin, and should not be changed.  That's yet another reason
21513 not to use this macro.
21514 @end defmac
21516 @defmac AC_DECL_SYS_SIGLIST
21517 @acindex{DECL_SYS_SIGLIST}
21518 @cvindex SYS_SIGLIST_DECLARED
21519 Same as:
21521 @example
21522 AC_CHECK_DECLS([sys_siglist], [], [],
21523 [#include <signal.h>
21524 /* NetBSD declares sys_siglist in unistd.h.  */
21525 #ifdef HAVE_UNISTD_H
21526 # include <unistd.h>
21527 #endif
21529 @end example
21531 @noindent
21532 @xref{AC_CHECK_DECLS}.
21533 @end defmac
21535 @defmac AC_DECL_YYTEXT
21536 @acindex{DECL_YYTEXT}
21537 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
21538 @end defmac
21540 @defmac AC_DIR_HEADER
21541 @acindex{DIR_HEADER}
21542 @cvindex DIRENT
21543 @cvindex SYSNDIR
21544 @cvindex SYSDIR
21545 @cvindex NDIR
21546 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
21547 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
21548 (@pxref{AC_HEADER_DIRENT}),
21549 but defines a different set of C preprocessor macros to indicate which
21550 header file is found:
21552 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
21553 @item Header            @tab Old Symbol     @tab New Symbol
21554 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
21555 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
21556 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
21557 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
21558 @end multitable
21559 @end defmac
21561 @defmac AC_DYNIX_SEQ
21562 @acindex{DYNIX_SEQ}
21563 If on DYNIX/ptx, add @option{-lseq} to output variable
21564 @code{LIBS}.  This macro used to be defined as
21566 @example
21567 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
21568 @end example
21570 @noindent
21571 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
21572 @end defmac
21574 @defmac AC_EXEEXT
21575 @acindex{EXEEXT}
21576 @ovindex EXEEXT
21577 Defined the output variable @code{EXEEXT} based on the output of the
21578 compiler, which is now done automatically.  Typically set to empty
21579 string if Posix and @samp{.exe} if a @acronym{DOS} variant.
21580 @end defmac
21582 @defmac AC_EMXOS2
21583 @acindex{EMXOS2}
21584 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
21585 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
21586 check the nature of the host is using @code{AC_CANONICAL_HOST}
21587 (@pxref{Canonicalizing}).
21588 @end defmac
21590 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
21591   @ovar{action-if-not-given})
21592 @acindex{ENABLE}
21593 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
21594 support providing a help string (@pxref{AC_ARG_ENABLE}).
21595 @end defmac
21597 @defmac AC_ERROR
21598 @acindex{ERROR}
21599 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
21600 @end defmac
21602 @defmac AC_FIND_X
21603 @acindex{FIND_X}
21604 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
21605 @end defmac
21607 @defmac AC_FIND_XTRA
21608 @acindex{FIND_XTRA}
21609 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
21610 @end defmac
21612 @defmac AC_FOREACH
21613 @acindex{FOREACH}
21614 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
21615 @end defmac
21617 @defmac AC_FUNC_CHECK
21618 @acindex{FUNC_CHECK}
21619 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
21620 @end defmac
21622 @anchor{AC_FUNC_SETVBUF_REVERSED}
21623 @defmac AC_FUNC_SETVBUF_REVERSED
21624 @acindex{FUNC_SETVBUF_REVERSED}
21625 @cvindex SETVBUF_REVERSED
21626 @c @fuindex setvbuf
21627 @prindex @code{setvbuf}
21628 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
21629 the buffering type as its second argument and the buffer pointer as the
21630 third, instead of the other way around, and defined
21631 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
21632 were those based on SVR2, which became obsolete in 1987, and the macro
21633 is no longer needed.
21634 @end defmac
21636 @defmac AC_FUNC_WAIT3
21637 @acindex{FUNC_WAIT3}
21638 @cvindex HAVE_WAIT3
21639 @c @fuindex wait3
21640 @prindex @code{wait3}
21641 If @code{wait3} is found and fills in the contents of its third argument
21642 (a @samp{struct rusage *}), which @acronym{HP-UX} does not do, define
21643 @code{HAVE_WAIT3}.
21645 These days portable programs should use @code{waitpid}, not
21646 @code{wait3}, as @code{wait3} has been removed from Posix.
21647 @end defmac
21649 @defmac AC_GCC_TRADITIONAL
21650 @acindex{GCC_TRADITIONAL}
21651 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
21652 @end defmac
21654 @defmac AC_GETGROUPS_T
21655 @acindex{GETGROUPS_T}
21656 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
21657 @end defmac
21659 @defmac AC_GETLOADAVG
21660 @acindex{GETLOADAVG}
21661 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
21662 @end defmac
21664 @defmac AC_GNU_SOURCE
21665 @acindex{GNU_SOURCE}
21666 @cvindex _GNU_SOURCE
21667 This macro is a platform-specific subset of
21668 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
21669 @end defmac
21671 @defmac AC_HAVE_FUNCS
21672 @acindex{HAVE_FUNCS}
21673 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
21674 @end defmac
21676 @defmac AC_HAVE_HEADERS
21677 @acindex{HAVE_HEADERS}
21678 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
21679 @end defmac
21681 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
21682   @ovar{action-if-not-found}, @ovar{other-libraries})
21683 @acindex{HAVE_LIBRARY}
21684 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
21685 @var{function} argument of @code{main}.  In addition, @var{library} can
21686 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
21687 all of those cases, the compiler is passed @option{-lfoo}.  However,
21688 @var{library} cannot be a shell variable; it must be a literal name.
21689 @xref{AC_CHECK_LIB}.
21690 @end defmac
21692 @defmac AC_HAVE_POUNDBANG
21693 @acindex{HAVE_POUNDBANG}
21694 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
21695 @end defmac
21697 @defmac AC_HEADER_CHECK
21698 @acindex{HEADER_CHECK}
21699 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
21700 @end defmac
21702 @defmac AC_HEADER_EGREP
21703 @acindex{HEADER_EGREP}
21704 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
21705 @end defmac
21707 @defmac AC_HELP_STRING
21708 @acindex{HELP_STRING}
21709 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
21710 @end defmac
21712 @defmac AC_INIT (@var{unique-file-in-source-dir})
21713 @acindex{INIT}
21714 Formerly @code{AC_INIT} used to have a single argument, and was
21715 equivalent to:
21717 @example
21718 AC_INIT
21719 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
21720 @end example
21721 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
21722 @end defmac
21724 @defmac AC_INLINE
21725 @acindex{INLINE}
21726 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
21727 @end defmac
21729 @defmac AC_INT_16_BITS
21730 @acindex{INT_16_BITS}
21731 @cvindex INT_16_BITS
21732 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
21733 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
21734 @end defmac
21736 @defmac AC_IRIX_SUN
21737 @acindex{IRIX_SUN}
21738 If on @sc{irix} (Silicon Graphics Unix), add @option{-lsun} to output
21739 @code{LIBS}.  If you were using it to get @code{getmntent}, use
21740 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
21741 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
21742 getpwnam)}.  Up to Autoconf 2.13, it used to be
21744 @example
21745 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
21746 @end example
21748 @noindent
21749 now it is defined as
21751 @example
21752 AC_FUNC_GETMNTENT
21753 AC_CHECK_LIB([sun], [getpwnam])
21754 @end example
21756 @noindent
21757 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
21758 @end defmac
21760 @defmac AC_ISC_POSIX
21761 @acindex{ISC_POSIX}
21762 @ovindex LIBS
21763 This macro adds @option{-lcposix} to output variable @code{LIBS} if
21764 necessary for Posix facilities.  Sun dropped support for the obsolete
21765 @sc{interactive} Systems Corporation Unix on 2006-07-23.  New programs
21766 need not use this macro.  It is implemented as
21767 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
21768 @end defmac
21770 @defmac AC_LANG_C
21771 @acindex{LANG_C}
21772 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
21773 @end defmac
21775 @defmac AC_LANG_CPLUSPLUS
21776 @acindex{LANG_CPLUSPLUS}
21777 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
21778 @end defmac
21780 @defmac AC_LANG_FORTRAN77
21781 @acindex{LANG_FORTRAN77}
21782 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
21783 @end defmac
21785 @defmac AC_LANG_RESTORE
21786 @acindex{LANG_RESTORE}
21787 Select the @var{language} that is saved on the top of the stack, as set
21788 by @code{AC_LANG_SAVE}, remove it from the stack, and call
21789 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
21790 preferred way to change languages.
21791 @end defmac
21793 @defmac AC_LANG_SAVE
21794 @acindex{LANG_SAVE}
21795 Remember the current language (as set by @code{AC_LANG}) on a stack.
21796 The current language does not change.  @code{AC_LANG_PUSH} is preferred
21797 (@pxref{AC_LANG_PUSH}).
21798 @end defmac
21800 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
21801 @acindex{LINK_FILES}
21802 This is an obsolete version of @code{AC_CONFIG_LINKS}
21803 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
21805 @example
21806 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
21807               host.h            object.h)
21808 @end example
21810 @noindent
21813 @example
21814 AC_CONFIG_LINKS([host.h:config/$machine.h
21815                 object.h:config/$obj_format.h])
21816 @end example
21817 @end defmac
21819 @defmac AC_LN_S
21820 @acindex{LN_S}
21821 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
21822 @end defmac
21824 @defmac AC_LONG_64_BITS
21825 @acindex{LONG_64_BITS}
21826 @cvindex LONG_64_BITS
21827 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
21828 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
21829 (@pxref{AC_CHECK_SIZEOF}).
21830 @end defmac
21832 @defmac AC_LONG_DOUBLE
21833 @acindex{LONG_DOUBLE}
21834 If the C compiler supports a working @code{long double} type with more
21835 range or precision than the @code{double} type, define
21836 @code{HAVE_LONG_DOUBLE}.
21838 You should use @code{AC_TYPE_LONG_DOUBLE} or
21839 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
21840 @end defmac
21842 @defmac AC_LONG_FILE_NAMES
21843 @acindex{LONG_FILE_NAMES}
21844 Replaced by
21845 @example
21846 AC_SYS_LONG_FILE_NAMES
21847 @end example
21848 @noindent
21849 @xref{AC_SYS_LONG_FILE_NAMES}.
21850 @end defmac
21852 @defmac AC_MAJOR_HEADER
21853 @acindex{MAJOR_HEADER}
21854 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
21855 @end defmac
21857 @defmac AC_MEMORY_H
21858 @acindex{MEMORY_H}
21859 @cvindex NEED_MEMORY_H
21860 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
21861 defined in @file{memory.h}.  Today it is equivalent to
21862 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
21863 your code to depend upon
21864 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
21865 Symbols}.
21866 @end defmac
21868 @defmac AC_MINGW32
21869 @acindex{MINGW32}
21870 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
21871 environment and sets @code{MINGW32}.  Don't use this macro, the
21872 dignified means to check the nature of the host is using
21873 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
21874 @end defmac
21876 @defmac AC_MINIX
21877 @acindex{MINIX}
21878 @cvindex _MINIX
21879 @cvindex _POSIX_SOURCE
21880 @cvindex _POSIX_1_SOURCE
21881 This macro is a platform-specific subset of
21882 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
21883 @end defmac
21885 @defmac AC_MINUS_C_MINUS_O
21886 @acindex{MINUS_C_MINUS_O}
21887 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
21888 @end defmac
21890 @defmac AC_MMAP
21891 @acindex{MMAP}
21892 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
21893 @end defmac
21895 @defmac AC_MODE_T
21896 @acindex{MODE_T}
21897 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
21898 @end defmac
21900 @defmac AC_OBJEXT
21901 @acindex{OBJEXT}
21902 @ovindex OBJEXT
21903 Defined the output variable @code{OBJEXT} based on the output of the
21904 compiler, after .c files have been excluded.  Typically set to @samp{o}
21905 if Posix, @samp{obj} if a @acronym{DOS} variant.
21906 Now the compiler checking macros handle
21907 this automatically.
21908 @end defmac
21910 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
21911 @acindex{OBSOLETE}
21912 Make M4 print a message to the standard error output warning that
21913 @var{this-macro-name} is obsolete, and giving the file and line number
21914 where it was called.  @var{this-macro-name} should be the name of the
21915 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
21916 it is printed at the end of the warning message; for example, it can be
21917 a suggestion for what to use instead of @var{this-macro-name}.
21919 For instance
21921 @example
21922 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
21923 @end example
21925 @noindent
21926 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
21927 services to the user (@pxref{AU_DEFUN}).
21928 @end defmac
21930 @defmac AC_OFF_T
21931 @acindex{OFF_T}
21932 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
21933 @end defmac
21935 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
21936 @acindex{OUTPUT}
21937 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
21938 interface is equivalent to:
21940 @example
21941 @group
21942 AC_CONFIG_FILES(@var{file}@dots{})
21943 AC_CONFIG_COMMANDS([default],
21944                    @var{extra-cmds}, @var{init-cmds})
21945 AC_OUTPUT
21946 @end group
21947 @end example
21949 @noindent
21950 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
21951 @end defmac
21953 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
21954 @acindex{OUTPUT_COMMANDS}
21955 Specify additional shell commands to run at the end of
21956 @file{config.status}, and shell commands to initialize any variables
21957 from @command{configure}.  This macro may be called multiple times.  It is
21958 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
21960 Here is an unrealistic example:
21962 @example
21963 fubar=27
21964 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
21965                    [fubar=$fubar])
21966 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
21967                    [echo init bit])
21968 @end example
21970 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
21971 additional key, an important difference is that
21972 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
21973 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
21974 can safely be given macro calls as arguments:
21976 @example
21977 AC_CONFIG_COMMANDS(foo, [my_FOO()])
21978 @end example
21980 @noindent
21981 Conversely, where one level of quoting was enough for literal strings
21982 with @code{AC_OUTPUT_COMMANDS}, you need two with
21983 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
21985 @example
21986 @group
21987 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
21988 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
21989 @end group
21990 @end example
21991 @end defmac
21993 @defmac AC_PID_T
21994 @acindex{PID_T}
21995 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
21996 @end defmac
21998 @defmac AC_PREFIX
21999 @acindex{PREFIX}
22000 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
22001 @end defmac
22003 @defmac AC_PROGRAMS_CHECK
22004 @acindex{PROGRAMS_CHECK}
22005 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
22006 @end defmac
22008 @defmac AC_PROGRAMS_PATH
22009 @acindex{PROGRAMS_PATH}
22010 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
22011 @end defmac
22013 @defmac AC_PROGRAM_CHECK
22014 @acindex{PROGRAM_CHECK}
22015 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
22016 @end defmac
22018 @defmac AC_PROGRAM_EGREP
22019 @acindex{PROGRAM_EGREP}
22020 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
22021 @end defmac
22023 @defmac AC_PROGRAM_PATH
22024 @acindex{PROGRAM_PATH}
22025 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
22026 @end defmac
22028 @defmac AC_REMOTE_TAPE
22029 @acindex{REMOTE_TAPE}
22030 Removed because of limited usefulness.
22031 @end defmac
22033 @defmac AC_RESTARTABLE_SYSCALLS
22034 @acindex{RESTARTABLE_SYSCALLS}
22035 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
22036 these days portable programs should use @code{sigaction} with
22037 @code{SA_RESTART} if they want restartable system calls.  They should
22038 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
22039 system call is restartable is a dynamic issue, not a configuration-time
22040 issue.
22041 @end defmac
22043 @defmac AC_RETSIGTYPE
22044 @acindex{RETSIGTYPE}
22045 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
22046 is obsolete when assuming C89 or better.
22047 @end defmac
22049 @defmac AC_RSH
22050 @acindex{RSH}
22051 Removed because of limited usefulness.
22052 @end defmac
22054 @defmac AC_SCO_INTL
22055 @acindex{SCO_INTL}
22056 @ovindex LIBS
22057 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
22058 macro used to do this:
22060 @example
22061 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
22062 @end example
22064 @noindent
22065 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
22066 @end defmac
22068 @defmac AC_SETVBUF_REVERSED
22069 @acindex{SETVBUF_REVERSED}
22070 Replaced by
22071 @example
22072 AC_FUNC_SETVBUF_REVERSED
22073 @end example
22074 @noindent
22075 @xref{AC_FUNC_SETVBUF_REVERSED}.
22076 @end defmac
22078 @defmac AC_SET_MAKE
22079 @acindex{SET_MAKE}
22080 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
22081 @end defmac
22083 @defmac AC_SIZEOF_TYPE
22084 @acindex{SIZEOF_TYPE}
22085 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
22086 @end defmac
22088 @defmac AC_SIZE_T
22089 @acindex{SIZE_T}
22090 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
22091 @end defmac
22093 @defmac AC_STAT_MACROS_BROKEN
22094 @acindex{STAT_MACROS_BROKEN}
22095 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
22096 @end defmac
22098 @defmac AC_STDC_HEADERS
22099 @acindex{STDC_HEADERS}
22100 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
22101 @end defmac
22103 @defmac AC_STRCOLL
22104 @acindex{STRCOLL}
22105 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
22106 @end defmac
22108 @defmac AC_STRUCT_ST_BLKSIZE
22109 @acindex{STRUCT_ST_BLKSIZE}
22110 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
22111 @cvindex HAVE_ST_BLKSIZE
22112 If @code{struct stat} contains an @code{st_blksize} member, define
22113 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
22114 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
22115 the future.  This macro is obsoleted, and should be replaced by
22117 @example
22118 AC_CHECK_MEMBERS([struct stat.st_blksize])
22119 @end example
22120 @noindent
22121 @xref{AC_CHECK_MEMBERS}.
22122 @end defmac
22124 @defmac AC_STRUCT_ST_RDEV
22125 @acindex{STRUCT_ST_RDEV}
22126 @cvindex HAVE_ST_RDEV
22127 @cvindex HAVE_STRUCT_STAT_ST_RDEV
22128 If @code{struct stat} contains an @code{st_rdev} member, define
22129 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
22130 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
22131 in the future.  Actually, even the new macro is obsolete and should be
22132 replaced by:
22133 @example
22134 AC_CHECK_MEMBERS([struct stat.st_rdev])
22135 @end example
22136 @noindent
22137 @xref{AC_CHECK_MEMBERS}.
22138 @end defmac
22140 @defmac AC_ST_BLKSIZE
22141 @acindex{ST_BLKSIZE}
22142 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
22143 @end defmac
22145 @defmac AC_ST_BLOCKS
22146 @acindex{ST_BLOCKS}
22147 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
22148 @end defmac
22150 @defmac AC_ST_RDEV
22151 @acindex{ST_RDEV}
22152 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
22153 @end defmac
22155 @defmac AC_SYS_RESTARTABLE_SYSCALLS
22156 @acindex{SYS_RESTARTABLE_SYSCALLS}
22157 @cvindex HAVE_RESTARTABLE_SYSCALLS
22158 If the system automatically restarts a system call that is interrupted
22159 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
22160 not check whether system calls are restarted in general---it checks whether a
22161 signal handler installed with @code{signal} (but not @code{sigaction})
22162 causes system calls to be restarted.  It does not check whether system calls
22163 can be restarted when interrupted by signals that have no handler.
22165 These days portable programs should use @code{sigaction} with
22166 @code{SA_RESTART} if they want restartable system calls.  They should
22167 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
22168 system call is restartable is a dynamic issue, not a configuration-time
22169 issue.
22170 @end defmac
22172 @defmac AC_SYS_SIGLIST_DECLARED
22173 @acindex{SYS_SIGLIST_DECLARED}
22174 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
22175 name is obsolete, as the same functionality is now acheived via
22176 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
22177 @end defmac
22179 @defmac AC_TEST_CPP
22180 @acindex{TEST_CPP}
22181 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
22182 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
22183 @end defmac
22185 @defmac AC_TEST_PROGRAM
22186 @acindex{TEST_PROGRAM}
22187 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
22188 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
22189 @end defmac
22191 @defmac AC_TIMEZONE
22192 @acindex{TIMEZONE}
22193 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
22194 @end defmac
22196 @defmac AC_TIME_WITH_SYS_TIME
22197 @acindex{TIME_WITH_SYS_TIME}
22198 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
22199 @end defmac
22201 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
22202   @ovar{action-if-true}, @ovar{action-if-false})
22203 @acindex{TRY_COMPILE}
22204 Same as:
22206 @example
22207 AC_COMPILE_IFELSE(
22208   [AC_LANG_PROGRAM([[@var{includes}]],
22209      [[@var{function-body}]])],
22210   [@var{action-if-true}],
22211   [@var{action-if-false}])
22212 @end example
22214 @noindent
22215 @xref{Running the Compiler}.
22217 This macro double quotes both @var{includes} and @var{function-body}.
22219 For C and C++, @var{includes} is any @code{#include} statements needed
22220 by the code in @var{function-body} (@var{includes} is ignored if
22221 the currently selected language is Fortran or Fortran 77).  The compiler
22222 and compilation flags are determined by the current language
22223 (@pxref{Language Choice}).
22224 @end defmac
22226 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
22227 @acindex{TRY_CPP}
22228 Same as:
22230 @example
22231 AC_PREPROC_IFELSE(
22232   [AC_LANG_SOURCE([[@var{input}]])],
22233   [@var{action-if-true}],
22234   [@var{action-if-false}])
22235 @end example
22237 @noindent
22238 @xref{Running the Preprocessor}.
22240 This macro double quotes the @var{input}.
22241 @end defmac
22243 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
22244   @ovar{action-if-true}, @ovar{action-if-false})
22245 @acindex{TRY_LINK}
22246 Same as:
22248 @example
22249 AC_LINK_IFELSE(
22250   [AC_LANG_PROGRAM([[@var{includes}]],
22251      [[@var{function-body}]])],
22252   [@var{action-if-true}],
22253   [@var{action-if-false}])
22254 @end example
22256 @noindent
22257 @xref{Running the Compiler}.
22259 This macro double quotes both @var{includes} and @var{function-body}.
22261 Depending on the current language (@pxref{Language Choice}), create a
22262 test program to see whether a function whose body consists of
22263 @var{function-body} can be compiled and linked.  If the file compiles
22264 and links successfully, run shell commands @var{action-if-found},
22265 otherwise run @var{action-if-not-found}.
22267 This macro double quotes both @var{includes} and @var{function-body}.
22269 For C and C++, @var{includes} is any @code{#include} statements needed
22270 by the code in @var{function-body} (@var{includes} is ignored if
22271 the currently selected language is Fortran or Fortran 77).  The compiler
22272 and compilation flags are determined by the current language
22273 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
22274 @code{LIBS} are used for linking.
22275 @end defmac
22277 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
22278   @ovar{action-if-not-found})
22279 @acindex{TRY_LINK_FUNC}
22280 This macro is equivalent to
22281 @example
22282 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
22283   [@var{action-if-found}], [@var{action-if-not-found}])
22284 @end example
22285 @noindent
22286 @xref{AC_LINK_IFELSE}.
22287 @end defmac
22289 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
22290   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
22291 @acindex{TRY_RUN}
22292 Same as:
22294 @example
22295 AC_RUN_IFELSE(
22296   [AC_LANG_SOURCE([[@var{program}]])],
22297   [@var{action-if-true}],
22298   [@var{action-if-false}],
22299   [@var{action-if-cross-compiling}])
22300 @end example
22302 @noindent
22303 @xref{Runtime}.
22304 @end defmac
22306 @anchor{AC_TYPE_SIGNAL}
22307 @defmac AC_TYPE_SIGNAL
22308 @acindex{TYPE_SIGNAL}
22309 @cvindex RETSIGTYPE
22310 @hdrindex{signal.h}
22311 If @file{signal.h} declares @code{signal} as returning a pointer to a
22312 function returning @code{void}, define @code{RETSIGTYPE} to be
22313 @code{void}; otherwise, define it to be @code{int}.  These days, it is
22314 portable to assume C89, and that signal handlers return @code{void},
22315 without needing to use this macro or @code{RETSIGTYPE}.
22317 When targetting older K&R C, it is possible to define signal handlers as
22318 returning type @code{RETSIGTYPE}, and omit a return statement:
22320 @example
22321 @group
22322 RETSIGTYPE
22323 hup_handler ()
22325 @dots{}
22327 @end group
22328 @end example
22329 @end defmac
22331 @defmac AC_UID_T
22332 @acindex{UID_T}
22333 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
22334 @end defmac
22336 @defmac AC_UNISTD_H
22337 @acindex{UNISTD_H}
22338 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
22339 @end defmac
22341 @defmac AC_USG
22342 @acindex{USG}
22343 @cvindex USG
22344 Define @code{USG} if the @acronym{BSD} string functions are defined in
22345 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
22346 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
22347 @end defmac
22349 @defmac AC_UTIME_NULL
22350 @acindex{UTIME_NULL}
22351 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
22352 @end defmac
22354 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
22355 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
22356 If the cache file is inconsistent with the current host, target and
22357 build system types, it used to execute @var{cmd} or print a default
22358 error message.  This is now handled by default.
22359 @end defmac
22361 @defmac AC_VERBOSE (@var{result-description})
22362 @acindex{VERBOSE}
22363 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
22364 @end defmac
22366 @defmac AC_VFORK
22367 @acindex{VFORK}
22368 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
22369 @end defmac
22371 @defmac AC_VPRINTF
22372 @acindex{VPRINTF}
22373 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
22374 @end defmac
22376 @defmac AC_WAIT3
22377 @acindex{WAIT3}
22378 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
22379 portable programs should use @code{waitpid}, not @code{wait3}, as
22380 @code{wait3} has been removed from Posix.
22381 @end defmac
22383 @defmac AC_WARN
22384 @acindex{WARN}
22385 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
22386 @end defmac
22388 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
22389   @ovar{action-if-not-given})
22390 @acindex{WITH}
22391 This is an obsolete version of @code{AC_ARG_WITH} that does not
22392 support providing a help string (@pxref{AC_ARG_WITH}).
22393 @end defmac
22395 @defmac AC_WORDS_BIGENDIAN
22396 @acindex{WORDS_BIGENDIAN}
22397 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
22398 @end defmac
22400 @defmac AC_XENIX_DIR
22401 @acindex{XENIX_DIR}
22402 @ovindex LIBS
22403 This macro used to add @option{-lx} to output variable @code{LIBS} if on
22404 Xenix.  Also, if @file{dirent.h} is being checked for, added
22405 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
22406 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
22407 running @sc{xenix} on which you should not depend:
22409 @example
22410 AC_MSG_CHECKING([for Xenix])
22411 AC_EGREP_CPP([yes],
22412 [#if defined M_XENIX && !defined M_UNIX
22413   yes
22414 #endif],
22415              [AC_MSG_RESULT([yes]); XENIX=yes],
22416              [AC_MSG_RESULT([no]); XENIX=])
22417 @end example
22418 @noindent
22419 Don't use this macro, the dignified means to check the nature of the
22420 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
22421 @end defmac
22423 @defmac AC_YYTEXT_POINTER
22424 @acindex{YYTEXT_POINTER}
22425 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
22426 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
22427 @end defmac
22429 @node Autoconf 1
22430 @section Upgrading From Version 1
22431 @cindex Upgrading autoconf
22432 @cindex Autoconf upgrading
22434 Autoconf version 2 is mostly backward compatible with version 1.
22435 However, it introduces better ways to do some things, and doesn't
22436 support some of the ugly things in version 1.  So, depending on how
22437 sophisticated your @file{configure.ac} files are, you might have to do
22438 some manual work in order to upgrade to version 2.  This chapter points
22439 out some problems to watch for when upgrading.  Also, perhaps your
22440 @command{configure} scripts could benefit from some of the new features in
22441 version 2; the changes are summarized in the file @file{NEWS} in the
22442 Autoconf distribution.
22444 @menu
22445 * Changed File Names::          Files you might rename
22446 * Changed Makefiles::           New things to put in @file{Makefile.in}
22447 * Changed Macros::              Macro calls you might replace
22448 * Changed Results::             Changes in how to check test results
22449 * Changed Macro Writing::       Better ways to write your own macros
22450 @end menu
22452 @node Changed File Names
22453 @subsection Changed File Names
22455 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
22456 in a particular package's source directory), you must rename it to
22457 @file{acsite.m4}.  @xref{autoconf Invocation}.
22459 If you distribute @file{install.sh} with your package, rename it to
22460 @file{install-sh} so @command{make} builtin rules don't inadvertently
22461 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
22462 looks for the script under both names, but it is best to use the new name.
22464 If you were using @file{config.h.top}, @file{config.h.bot}, or
22465 @file{acconfig.h}, you still can, but you have less clutter if you
22466 use the @code{AH_} macros.  @xref{Autoheader Macros}.
22468 @node Changed Makefiles
22469 @subsection Changed Makefiles
22471 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
22472 your @file{Makefile.in} files, so they can take advantage of the values
22473 of those variables in the environment when @command{configure} is run.
22474 Doing this isn't necessary, but it's a convenience for users.
22476 Also add @samp{@@configure_input@@} in a comment to each input file for
22477 @code{AC_OUTPUT}, so that the output files contain a comment saying
22478 they were produced by @command{configure}.  Automatically selecting the
22479 right comment syntax for all the kinds of files that people call
22480 @code{AC_OUTPUT} on became too much work.
22482 Add @file{config.log} and @file{config.cache} to the list of files you
22483 remove in @code{distclean} targets.
22485 If you have the following in @file{Makefile.in}:
22487 @example
22488 prefix = /usr/local
22489 exec_prefix = $(prefix)
22490 @end example
22492 @noindent
22493 you must change it to:
22495 @example
22496 prefix = @@prefix@@
22497 exec_prefix = @@exec_prefix@@
22498 @end example
22500 @noindent
22501 The old behavior of replacing those variables without @samp{@@}
22502 characters around them has been removed.
22504 @node Changed Macros
22505 @subsection Changed Macros
22507 Many of the macros were renamed in Autoconf version 2.  You can still
22508 use the old names, but the new ones are clearer, and it's easier to find
22509 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
22510 new names for the old macros.  Use the @command{autoupdate} program to
22511 convert your @file{configure.ac} to using the new macro names.
22512 @xref{autoupdate Invocation}.
22514 Some macros have been superseded by similar ones that do the job better,
22515 but are not call-compatible.  If you get warnings about calling obsolete
22516 macros while running @command{autoconf}, you may safely ignore them, but
22517 your @command{configure} script generally works better if you follow
22518 the advice that is printed about what to replace the obsolete macros with.  In
22519 particular, the mechanism for reporting the results of tests has
22520 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
22521 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
22522 looks better if you switch to @code{AC_MSG_CHECKING} and
22523 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
22524 in conjunction with cache variables.  @xref{Caching Results}.
22528 @node Changed Results
22529 @subsection Changed Results
22531 If you were checking the results of previous tests by examining the
22532 shell variable @code{DEFS}, you need to switch to checking the values of
22533 the cache variables for those tests.  @code{DEFS} no longer exists while
22534 @command{configure} is running; it is only created when generating output
22535 files.  This difference from version 1 is because properly quoting the
22536 contents of that variable turned out to be too cumbersome and
22537 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
22538 Variable Names}.
22540 For example, here is a @file{configure.ac} fragment written for Autoconf
22541 version 1:
22543 @example
22544 AC_HAVE_FUNCS(syslog)
22545 case "$DEFS" in
22546 *-DHAVE_SYSLOG*) ;;
22547 *) # syslog is not in the default libraries.  See if it's in some other.
22548   saved_LIBS="$LIBS"
22549   for lib in bsd socket inet; do
22550     AC_CHECKING(for syslog in -l$lib)
22551     LIBS="-l$lib $saved_LIBS"
22552     AC_HAVE_FUNCS(syslog)
22553     case "$DEFS" in
22554     *-DHAVE_SYSLOG*) break ;;
22555     *) ;;
22556     esac
22557     LIBS="$saved_LIBS"
22558   done ;;
22559 esac
22560 @end example
22562 Here is a way to write it for version 2:
22564 @example
22565 AC_CHECK_FUNCS([syslog])
22566 if test "x$ac_cv_func_syslog" = xno; then
22567   # syslog is not in the default libraries.  See if it's in some other.
22568   for lib in bsd socket inet; do
22569     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
22570       LIBS="-l$lib $LIBS"; break])
22571   done
22573 @end example
22575 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
22576 backslashes before quotes, you need to remove them.  It now works
22577 predictably, and does not treat quotes (except back quotes) specially.
22578 @xref{Setting Output Variables}.
22580 All of the Boolean shell variables set by Autoconf macros now use
22581 @samp{yes} for the true value.  Most of them use @samp{no} for false,
22582 though for backward compatibility some use the empty string instead.  If
22583 you were relying on a shell variable being set to something like 1 or
22584 @samp{t} for true, you need to change your tests.
22586 @node Changed Macro Writing
22587 @subsection Changed Macro Writing
22589 When defining your own macros, you should now use @code{AC_DEFUN}
22590 instead of @code{define}.  @code{AC_DEFUN} automatically calls
22591 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
22592 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
22593 messages on the screen.  There's no actual harm in continuing to use the
22594 older way, but it's less convenient and attractive.  @xref{Macro
22595 Definitions}.
22597 You probably looked at the macros that came with Autoconf as a guide for
22598 how to do things.  It would be a good idea to take a look at the new
22599 versions of them, as the style is somewhat improved and they take
22600 advantage of some new features.
22602 If you were doing tricky things with undocumented Autoconf internals
22603 (macros, variables, diversions), check whether you need to change
22604 anything to account for changes that have been made.  Perhaps you can
22605 even use an officially supported technique in version 2 instead of
22606 kludging.  Or perhaps not.
22608 To speed up your locally written feature tests, add caching to them.
22609 See whether any of your tests are of general enough usefulness to
22610 encapsulate them into macros that you can share.
22613 @node Autoconf 2.13
22614 @section Upgrading From Version 2.13
22615 @cindex Upgrading autoconf
22616 @cindex Autoconf upgrading
22618 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
22619 suits this section@enddots{}
22621 @quotation
22622 Autoconf version 2.50 is mostly backward compatible with version 2.13.
22623 However, it introduces better ways to do some things, and doesn't
22624 support some of the ugly things in version 2.13.  So, depending on how
22625 sophisticated your @file{configure.ac} files are, you might have to do
22626 some manual work in order to upgrade to version 2.50.  This chapter
22627 points out some problems to watch for when upgrading.  Also, perhaps
22628 your @command{configure} scripts could benefit from some of the new
22629 features in version 2.50; the changes are summarized in the file
22630 @file{NEWS} in the Autoconf distribution.
22631 @end quotation
22633 @menu
22634 * Changed Quotation::           Broken code which used to work
22635 * New Macros::                  Interaction with foreign macros
22636 * Hosts and Cross-Compilation::  Bugward compatibility kludges
22637 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
22638 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
22639 @end menu
22641 @node Changed Quotation
22642 @subsection Changed Quotation
22644 The most important changes are invisible to you: the implementation of
22645 most macros have completely changed.  This allowed more factorization of
22646 the code, better error messages, a higher uniformity of the user's
22647 interface etc.  Unfortunately, as a side effect, some construct which
22648 used to (miraculously) work might break starting with Autoconf 2.50.
22649 The most common culprit is bad quotation.
22651 For instance, in the following example, the message is not properly
22652 quoted:
22654 @example
22655 AC_INIT
22656 AC_CHECK_HEADERS(foo.h, ,
22657   AC_MSG_ERROR(cannot find foo.h, bailing out))
22658 AC_OUTPUT
22659 @end example
22661 @noindent
22662 Autoconf 2.13 simply ignores it:
22664 @example
22665 $ @kbd{autoconf-2.13; ./configure --silent}
22666 creating cache ./config.cache
22667 configure: error: cannot find foo.h
22669 @end example
22671 @noindent
22672 while Autoconf 2.50 produces a broken @file{configure}:
22674 @example
22675 $ @kbd{autoconf-2.50; ./configure --silent}
22676 configure: error: cannot find foo.h
22677 ./configure: exit: bad non-numeric arg `bailing'
22678 ./configure: exit: bad non-numeric arg `bailing'
22680 @end example
22682 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
22683 too!
22685 @example
22686 AC_INIT([Example], [1.0], [bug-example@@example.org])
22687 AC_CHECK_HEADERS([foo.h], [],
22688   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
22689 AC_OUTPUT
22690 @end example
22692 Many many (and many more) Autoconf macros were lacking proper quotation,
22693 including no less than@dots{} @code{AC_DEFUN} itself!
22695 @example
22696 $ @kbd{cat configure.in}
22697 AC_DEFUN([AC_PROG_INSTALL],
22698 [# My own much better version
22700 AC_INIT
22701 AC_PROG_INSTALL
22702 AC_OUTPUT
22703 $ @kbd{autoconf-2.13}
22704 autoconf: Undefined macros:
22705 ***BUG in Autoconf--please report*** AC_FD_MSG
22706 ***BUG in Autoconf--please report*** AC_EPI
22707 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
22708 configure.in:5:AC_PROG_INSTALL
22709 $ @kbd{autoconf-2.50}
22711 @end example
22714 @node New Macros
22715 @subsection New Macros
22717 @cindex undefined macro
22718 @cindex @code{_m4_divert_diversion}
22720 While Autoconf was relatively dormant in the late 1990s, Automake
22721 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
22722 in 2001, Autoconf provided
22723 versions of these macros, integrated in the @code{AC_} namespace,
22724 instead of @code{AM_}.  But in order to ease the upgrading via
22725 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
22727 Unfortunately older versions of Automake (e.g., Automake 1.4)
22728 did not quote the names of these macros.
22729 Therefore, when @command{m4} finds something like
22730 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
22731 @code{AM_TYPE_PTRDIFF_T} is
22732 expanded, replaced with its Autoconf definition.
22734 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
22735 complains, in its own words:
22737 @example
22738 $ @kbd{cat configure.ac}
22739 AC_INIT([Example], [1.0], [bug-example@@example.org])
22740 AM_TYPE_PTRDIFF_T
22741 $ @kbd{aclocal-1.4}
22742 $ @kbd{autoconf}
22743 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
22744 aclocal.m4:17: the top level
22745 autom4te: m4 failed with exit status: 1
22747 @end example
22749 Modern versions of Automake no longer define most of these
22750 macros, and properly quote the names of the remaining macros.
22751 If you must use an old Automake, do not depend upon macros from Automake
22752 as it is simply not its job
22753 to provide macros (but the one it requires itself):
22755 @example
22756 $ @kbd{cat configure.ac}
22757 AC_INIT([Example], [1.0], [bug-example@@example.org])
22758 AM_TYPE_PTRDIFF_T
22759 $ @kbd{rm aclocal.m4}
22760 $ @kbd{autoupdate}
22761 autoupdate: `configure.ac' is updated
22762 $ @kbd{cat configure.ac}
22763 AC_INIT([Example], [1.0], [bug-example@@example.org])
22764 AC_CHECK_TYPES([ptrdiff_t])
22765 $ @kbd{aclocal-1.4}
22766 $ @kbd{autoconf}
22768 @end example
22771 @node Hosts and Cross-Compilation
22772 @subsection Hosts and Cross-Compilation
22773 @cindex Cross compilation
22775 Based on the experience of compiler writers, and after long public
22776 debates, many aspects of the cross-compilation chain have changed:
22778 @itemize @minus
22779 @item
22780 the relationship between the build, host, and target architecture types,
22782 @item
22783 the command line interface for specifying them to @command{configure},
22785 @item
22786 the variables defined in @command{configure},
22788 @item
22789 the enabling of cross-compilation mode.
22790 @end itemize
22792 @sp 1
22794 The relationship between build, host, and target have been cleaned up:
22795 the chain of default is now simply: target defaults to host, host to
22796 build, and build to the result of @command{config.guess}.  Nevertheless,
22797 in order to ease the transition from 2.13 to 2.50, the following
22798 transition scheme is implemented.  @emph{Do not rely on it}, as it will
22799 be completely disabled in a couple of releases (we cannot keep it, as it
22800 proves to cause more problems than it cures).
22802 They all default to the result of running @command{config.guess}, unless
22803 you specify either @option{--build} or @option{--host}.  In this case,
22804 the default becomes the system type you specified.  If you specify both,
22805 and they're different, @command{configure} enters cross compilation
22806 mode, so it doesn't run any tests that require execution.
22808 Hint: if you mean to override the result of @command{config.guess},
22809 prefer @option{--build} over @option{--host}.  In the future,
22810 @option{--host} will not override the name of the build system type.
22811 Whenever you specify @option{--host}, be sure to specify @option{--build}
22812 too.
22814 @sp 1
22816 For backward compatibility, @command{configure} accepts a system
22817 type as an option by itself.  Such an option overrides the
22818 defaults for build, host, and target system types.  The following
22819 configure statement configures a cross toolchain that runs on
22820 Net@acronym{BSD}/alpha but generates code for @acronym{GNU} Hurd/sparc,
22821 which is also the build platform.
22823 @example
22824 ./configure --host=alpha-netbsd sparc-gnu
22825 @end example
22827 @sp 1
22829 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
22830 and @code{target} had a different semantics before and after the
22831 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
22832 @option{--build} is strictly copied into @code{build_alias}, and is left
22833 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
22834 set to the canonicalized build type.  To ease the transition, before,
22835 its contents is the same as that of @code{build_alias}.  Do @emph{not}
22836 rely on this broken feature.
22838 For consistency with the backward compatibility scheme exposed above,
22839 when @option{--host} is specified but @option{--build} isn't, the build
22840 system is assumed to be the same as @option{--host}, and
22841 @samp{build_alias} is set to that value.  Eventually, this
22842 historically incorrect behavior will go away.
22844 @sp 1
22846 The former scheme to enable cross-compilation proved to cause more harm
22847 than good, in particular, it used to be triggered too easily, leaving
22848 regular end users puzzled in front of cryptic error messages.
22849 @command{configure} could even enter cross-compilation mode only
22850 because the compiler was not functional.  This is mainly because
22851 @command{configure} used to try to detect cross-compilation, instead of
22852 waiting for an explicit flag from the user.
22854 Now, @command{configure} enters cross-compilation mode if and only if
22855 @option{--host} is passed.
22857 That's the short documentation.  To ease the transition between 2.13 and
22858 its successors, a more complicated scheme is implemented.  @emph{Do not
22859 rely on the following}, as it will be removed in the near future.
22861 If you specify @option{--host}, but not @option{--build}, when
22862 @command{configure} performs the first compiler test it tries to run
22863 an executable produced by the compiler.  If the execution fails, it
22864 enters cross-compilation mode.  This is fragile.  Moreover, by the time
22865 the compiler test is performed, it may be too late to modify the
22866 build-system type: other tests may have already been performed.
22867 Therefore, whenever you specify @option{--host}, be sure to specify
22868 @option{--build} too.
22870 @example
22871 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
22872 @end example
22874 @noindent
22875 enters cross-compilation mode.  The former interface, which
22876 consisted in setting the compiler to a cross-compiler without informing
22877 @command{configure} is obsolete.  For instance, @command{configure}
22878 fails if it can't run the code generated by the specified compiler if you
22879 configure as follows:
22881 @example
22882 ./configure CC=m68k-coff-gcc
22883 @end example
22886 @node AC_LIBOBJ vs LIBOBJS
22887 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
22889 Up to Autoconf 2.13, the replacement of functions was triggered via the
22890 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
22891 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
22892 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
22894 This change is mandated by the unification of the @acronym{GNU} Build System
22895 components.  In particular, the various fragile techniques used to parse
22896 a @file{configure.ac} are all replaced with the use of traces.  As a
22897 consequence, any action must be traceable, which obsoletes critical
22898 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
22899 and it can even be handled gracefully (read, ``without your having to
22900 change something'').
22902 There were two typical uses of @code{LIBOBJS}: asking for a replacement
22903 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
22905 @sp 1
22907 As for function replacement, the fix is immediate: use
22908 @code{AC_LIBOBJ}.  For instance:
22910 @example
22911 LIBOBJS="$LIBOBJS fnmatch.o"
22912 LIBOBJS="$LIBOBJS malloc.$ac_objext"
22913 @end example
22915 @noindent
22916 should be replaced with:
22918 @example
22919 AC_LIBOBJ([fnmatch])
22920 AC_LIBOBJ([malloc])
22921 @end example
22923 @sp 1
22925 @ovindex LIBOBJDIR
22926 When used with Automake 1.10 or newer, a suitable value for
22927 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
22928 can be referenced from any @file{Makefile.am}.  Even without Automake,
22929 arranging for @code{LIBOBJDIR} to be set correctly enables
22930 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
22931 The @code{LIBOBJDIR} feature is experimental.
22934 @node AC_ACT_IFELSE vs AC_TRY_ACT
22935 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
22936 @c the anchor keeps the old node name, to try to avoid breaking links
22937 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
22939 @acindex{@var{ACT}_IFELSE}
22940 @acindex{TRY_@var{ACT}}
22941 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
22942 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
22943 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCES},
22944 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
22945 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
22946 @code{AC_TRY_RUN}.  The motivations where:
22947 @itemize @minus
22948 @item
22949 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
22950 quoting their arguments;
22952 @item
22953 the combinatoric explosion is solved by decomposing on the one hand the
22954 generation of sources, and on the other hand executing the program;
22956 @item
22957 this scheme helps supporting more languages than plain C and C++.
22958 @end itemize
22960 In addition to the change of syntax, the philosophy has changed too:
22961 while emphasis was put on speed at the expense of accuracy, today's
22962 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
22963 expense of speed.
22966 As a perfect example of what is @emph{not} to be done, here is how to
22967 find out whether a header file contains a particular declaration, such
22968 as a typedef, a structure, a structure member, or a function.  Use
22969 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
22970 header file; on some systems the symbol might be defined in another
22971 header file that the file you are checking includes.
22973 As a (bad) example, here is how you should not check for C preprocessor
22974 symbols, either defined by header files or predefined by the C
22975 preprocessor: using @code{AC_EGREP_CPP}:
22977 @example
22978 @group
22979 AC_EGREP_CPP(yes,
22980 [#ifdef _AIX
22981   yes
22982 #endif
22983 ], is_aix=yes, is_aix=no)
22984 @end group
22985 @end example
22987 The above example, properly written would (i) use
22988 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
22990 @example
22991 @group
22992 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
22993 [[#ifndef _AIX
22994  error: This isn't AIX!
22995 #endif
22996 ]])],
22997                    [is_aix=yes],
22998                    [is_aix=no])
22999 @end group
23000 @end example
23003 @c ============================= Generating Test Suites with Autotest
23005 @node Using Autotest
23006 @chapter Generating Test Suites with Autotest
23008 @cindex Autotest
23010 @display
23011 @strong{N.B.: This section describes a feature which is still
23012 stabilizing.  Although we believe that Autotest is useful as-is, this
23013 documentation describes an interface which might change in the future:
23014 do not depend upon Autotest without subscribing to the Autoconf mailing
23015 lists.}
23016 @end display
23018 It is paradoxical that portable projects depend on nonportable tools
23019 to run their test suite.  Autoconf by itself is the paragon of this
23020 problem: although it aims at perfectly portability, up to 2.13 its
23021 test suite was using Deja@acronym{GNU}, a rich and complex testing
23022 framework, but which is far from being standard on Posix systems.
23023 Worse yet, it was likely to be missing on the most fragile platforms,
23024 the very platforms that are most likely to torture Autoconf and
23025 exhibit deficiencies.
23027 To circumvent this problem, many package maintainers have developed their
23028 own testing framework, based on simple shell scripts whose sole outputs
23029 are exit status values describing whether the test succeeded.  Most of
23030 these tests share common patterns, and this can result in lots of
23031 duplicated code and tedious maintenance.
23033 Following exactly the same reasoning that yielded to the inception of
23034 Autoconf, Autotest provides a test suite generation framework, based on
23035 M4 macros building a portable shell script.  The suite itself is
23036 equipped with automatic logging and tracing facilities which greatly
23037 diminish the interaction with bug reporters, and simple timing reports.
23039 Autoconf itself has been using Autotest for years, and we do attest that
23040 it has considerably improved the strength of the test suite and the
23041 quality of bug reports.  Other projects are known to use some generation
23042 of Autotest, such as Bison, Free Recode, Free Wdiff, @acronym{GNU} Tar, each of
23043 them with different needs, and this usage has validated Autotest as a general
23044 testing framework.
23046 Nonetheless, compared to Deja@acronym{GNU}, Autotest is inadequate for
23047 interactive tool testing, which is probably its main limitation.
23049 @menu
23050 * Using an Autotest Test Suite::  Autotest and the user
23051 * Writing Testsuites::          Autotest macros
23052 * testsuite Invocation::        Running @command{testsuite} scripts
23053 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
23054 @end menu
23056 @node Using an Autotest Test Suite
23057 @section Using an Autotest Test Suite
23059 @menu
23060 * testsuite Scripts::           The concepts of Autotest
23061 * Autotest Logs::               Their contents
23062 @end menu
23064 @node testsuite Scripts
23065 @subsection @command{testsuite} Scripts
23067 @cindex @command{testsuite}
23069 Generating testing or validation suites using Autotest is rather easy.
23070 The whole validation suite is held in a file to be processed through
23071 @command{autom4te}, itself using @acronym{GNU} M4 under the scene, to
23072 produce a stand-alone Bourne shell script which then gets distributed.
23073 Neither @command{autom4te} nor @acronym{GNU} M4 are needed at
23074 the installer's end.
23076 @cindex test group
23077 Each test of the validation suite should be part of some test group.  A
23078 @dfn{test group} is a sequence of interwoven tests that ought to be
23079 executed together, usually because one test in the group creates data
23080 files than a later test in the same group needs to read.  Complex test
23081 groups make later debugging more tedious.  It is much better to
23082 keep only a few tests per test group.  Ideally there is only one test
23083 per test group.
23085 For all but the simplest packages, some file such as @file{testsuite.at}
23086 does not fully hold all test sources, as these are often easier to
23087 maintain in separate files.  Each of these separate files holds a single
23088 test group, or a sequence of test groups all addressing some common
23089 functionality in the package.  In such cases, @file{testsuite.at}
23090 merely initializes the validation suite, and sometimes does elementary
23091 health checking, before listing include statements for all other test
23092 files.  The special file @file{package.m4}, containing the
23093 identification of the package, is automatically included if found.
23095 A convenient alternative consists in moving all the global issues
23096 (local Autotest macros, elementary health checking, and @code{AT_INIT}
23097 invocation) into the file @code{local.at}, and making
23098 @file{testsuite.at} be a simple list of @code{m4_include} of sub test
23099 suites.  In such case, generating the whole test suite or pieces of it
23100 is only a matter of choosing the @command{autom4te} command line
23101 arguments.
23103 The validation scripts that Autotest produces are by convention called
23104 @command{testsuite}.  When run, @command{testsuite} executes each test
23105 group in turn, producing only one summary line per test to say if that
23106 particular test succeeded or failed.  At end of all tests, summarizing
23107 counters get printed.  One debugging directory is left for each test
23108 group which failed, if any: such directories are named
23109 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
23110 the test group, and they include:
23112 @itemize @bullet
23113 @item a debugging script named @file{run} which reruns the test in
23114 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
23115 of debugging scripts has the purpose of easing the chase for bugs.
23117 @item all the files created with @code{AT_DATA}
23119 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
23121 @item a log of the run, named @file{testsuite.log}
23122 @end itemize
23124 In the ideal situation, none of the tests fail, and consequently no
23125 debugging directory is left behind for validation.
23127 It often happens in practice that individual tests in the validation
23128 suite need to get information coming out of the configuration process.
23129 Some of this information, common for all validation suites, is provided
23130 through the file @file{atconfig}, automatically created by
23131 @code{AC_CONFIG_TESTDIR}.  For configuration informations which your
23132 testing environment specifically needs, you might prepare an optional
23133 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
23134 The configuration process produces @file{atconfig} and @file{atlocal}
23135 out of these two input files, and these two produced files are
23136 automatically read by the @file{testsuite} script.
23138 Here is a diagram showing the relationship between files.
23140 @noindent
23141 Files used in preparing a software package for distribution:
23143 @example
23144                 [package.m4] -->.
23145                                  \
23146 subfile-1.at ->.  [local.at] ---->+
23147     ...         \                  \
23148 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
23149     ...         /
23150 subfile-n.at ->'
23151 @end example
23153 @noindent
23154 Files used in configuring a software package:
23156 @example
23157                                      .--> atconfig
23158                                     /
23159 [atlocal.in] -->  config.status* --<
23160                                     \
23161                                      `--> [atlocal]
23162 @end example
23164 @noindent
23165 Files created during the test suite execution:
23167 @example
23168 atconfig -->.                    .--> testsuite.log
23169              \                  /
23170               >-- testsuite* --<
23171              /                  \
23172 [atlocal] ->'                    `--> [testsuite.dir]
23173 @end example
23176 @node Autotest Logs
23177 @subsection Autotest Logs
23179 When run, the test suite creates a log file named after itself, e.g., a
23180 test suite named @command{testsuite} creates @file{testsuite.log}.  It
23181 contains a lot of information, usually more than maintainers actually
23182 need, but therefore most of the time it contains all that is needed:
23184 @table @asis
23185 @item command line arguments
23186 @c akim s/to consist in/to consist of/
23187 A bad but unfortunately widespread habit consists of
23188 setting environment variables before the command, such as in
23189 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
23190 know this change, hence (i) it cannot report it to you, and (ii)
23191 it cannot preserve the value of @code{CC} for subsequent runs.
23192 Autoconf faced exactly the same problem, and solved it by asking
23193 users to pass the variable definitions as command line arguments.
23194 Autotest requires this rule, too, but has no means to enforce it; the log
23195 then contains a trace of the variables that were changed by the user.
23197 @item @file{ChangeLog} excerpts
23198 The topmost lines of all the @file{ChangeLog} files found in the source
23199 hierarchy.  This is especially useful when bugs are reported against
23200 development versions of the package, since the version string does not
23201 provide sufficient information to know the exact state of the sources
23202 the user compiled.  Of course, this relies on the use of a
23203 @file{ChangeLog}.
23205 @item build machine
23206 Running a test suite in a cross-compile environment is not an easy task,
23207 since it would mean having the test suite run on a machine @var{build},
23208 while running programs on a machine @var{host}.  It is much simpler to
23209 run both the test suite and the programs on @var{host}, but then, from
23210 the point of view of the test suite, there remains a single environment,
23211 @var{host} = @var{build}.  The log contains relevant information on the
23212 state of the build machine, including some important environment
23213 variables.
23214 @c FIXME: How about having an M4sh macro to say `hey, log the value
23215 @c of `@dots{}'?  This would help both Autoconf and Autotest.
23217 @item tested programs
23218 The absolute file name and answers to @option{--version} of the tested
23219 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
23221 @item configuration log
23222 The contents of @file{config.log}, as created by @command{configure},
23223 are appended.  It contains the configuration flags and a detailed report
23224 on the configuration itself.
23225 @end table
23228 @node Writing Testsuites
23229 @section Writing @file{testsuite.at}
23231 The @file{testsuite.at} is a Bourne shell script making use of special
23232 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
23233 its beginning followed by one call to @code{m4_include} per source file
23234 for tests.  Each such included file, or the remainder of
23235 @file{testsuite.at} if include files are not used, contain a sequence of
23236 test groups.  Each test group begins with a call to @code{AT_SETUP},
23237 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
23238 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
23239 groups can be categorized by a call to @code{AT_BANNER}.
23241 All of the public Autotest macros have all-uppercase names in the
23242 namespace @samp{^AT_} to prevent them from accidentally conflicting with
23243 other text; Autoconf also reserves the namespace @samp{^_AT_} for
23244 internal macros.  All shell variables used in the testsuite for internal
23245 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
23246 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
23247 makes use of the file system namespace @samp{^at-}.
23249 Since Autoconf is built on top of M4sugar (@pxref{Programming in
23250 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
23251 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
23252 @emph{should not use} the namespace of a package that does not own the
23253 macro or shell code you are writing.
23255 @defmac AT_INIT (@ovar{name})
23256 @atindex{INIT}
23257 @c FIXME: Not clear, plus duplication of the information.
23258 Initialize Autotest.  Giving a @var{name} to the test suite is
23259 encouraged if your package includes several test suites.  Before this
23260 macro is called, @code{AT_PACKAGE_STRING} and
23261 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
23262 information about the testsuite to the user.  Typically, these macros
23263 are provided by a file @file{package.m4} built by @command{make}
23264 (@pxref{Making testsuite Scripts}), in order to inherit the package
23265 name, version, and bug reporting address from @file{configure.ac}.
23266 @end defmac
23268 @defmac AT_COPYRIGHT (@var{copyright-notice})
23269 @atindex{COPYRIGHT}
23270 @cindex Copyright Notice
23271 State that, in addition to the Free Software Foundation's copyright on
23272 the Autotest macros, parts of your test suite are covered by
23273 @var{copyright-notice}.
23275 The @var{copyright-notice} shows up in both the head of
23276 @command{testsuite} and in @samp{testsuite --version}.
23277 @end defmac
23279 @defmac AT_TESTED (@var{executables})
23280 @atindex{TESTED}
23281 Log the file name and answer to @option{--version} of each program in
23282 space-separated list @var{executables}.  Several invocations register
23283 new executables, in other words, don't fear registering one program
23284 several times.
23285 @end defmac
23287 Autotest test suites rely on @env{PATH} to find the tested program.
23288 This avoids the need to generate absolute names of the various tools, and
23289 makes it possible to test installed programs.  Therefore, knowing which
23290 programs are being exercised is crucial to understanding problems in
23291 the test suite itself, or its occasional misuses.  It is a good idea to
23292 also subscribe foreign programs you depend upon, to avoid incompatible
23293 diagnostics.
23295 @sp 1
23297 @defmac AT_BANNER (@var{test-category-name})
23298 @atindex{BANNER}
23299 This macro identifies the start of a category of related test groups.
23300 When the resulting @file{testsuite} is invoked with more than one test
23301 group to run, its output will include a banner containing
23302 @var{test-category-name} prior to any tests run from that category.  The
23303 banner should be no more than about 40 or 50 characters.  A blank banner
23304 will not print, effectively ending a category and letting subsequent
23305 test groups behave as though they are uncategorized when run in
23306 isolation.
23307 @end defmac
23309 @defmac AT_SETUP (@var{test-group-name})
23310 @atindex{SETUP}
23311 This macro starts a group of related tests, all to be executed in the
23312 same subshell.  It accepts a single argument, which holds a few words
23313 (no more than about 30 or 40 characters) quickly describing the purpose
23314 of the test group being started.  @var{test-group-name} must not expand
23315 to unbalanced quotes, although quadrigraphs can be used.
23316 @end defmac
23318 @defmac AT_KEYWORDS (@var{keywords})
23319 @atindex{KEYWORDS}
23320 Associate the space-separated list of @var{keywords} to the enclosing
23321 test group.  This makes it possible to run ``slices'' of the test suite.
23322 For instance, if some of your test groups exercise some @samp{foo}
23323 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
23324 @samp{./testsuite -k foo} to run exclusively these test groups.  The
23325 @var{title} of the test group is automatically recorded to
23326 @code{AT_KEYWORDS}.
23328 Several invocations within a test group accumulate new keywords.  In
23329 other words, don't fear registering the same keyword several times in a
23330 test group.
23331 @end defmac
23333 @defmac AT_CAPTURE_FILE (@var{file})
23334 @atindex{CAPTURE_FILE}
23335 If the current test group fails, log the contents of @var{file}.
23336 Several identical calls within one test group have no additional effect.
23337 @end defmac
23339 @defmac AT_FAIL_IF (@var{shell-condition})
23340 @atindex{FAIL_IF}
23341 Make the test group fail and skip the rest of its execution, if
23342 @var{shell-condition} is true.  @var{shell-condition} is a shell expression
23343 such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
23344 will be executed and may still cause the test group to be skipped.
23345 You can instantiate this macro many times from within the same test group.
23347 You should use this macro only for very simple failure conditions.  If the
23348 @var{shell-condition} could emit any kind of output you should instead
23349 use @command{AT_CHECK} like
23350 @example
23351 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
23352 @end example
23353 @noindent
23354 so that such output is properly recorded in the @file{testsuite.log}
23355 file.
23356 @end defmac
23358 @defmac AT_SKIP_IF (@var{shell-condition})
23359 @atindex{SKIP_IF}
23360 Determine whether the test should be skipped because it requires
23361 features that are unsupported on the machine under test.
23362 @var{shell-condition} is a shell expression such as a @code{test}
23363 command.  Tests before @command{AT_SKIP_IF} will be executed
23364 and may still cause the test group to fail.  You can instantiate this
23365 macro many times from within the same test group.
23367 You should use this macro only for very simple skip conditions.  If the
23368 @var{shell-condition} could emit any kind of output you should instead
23369 use @command{AT_CHECK} like
23370 @example
23371 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
23372 @end example
23373 @noindent
23374 so that such output is properly recorded in the @file{testsuite.log}
23375 file.
23376 @end defmac
23378 @defmac AT_XFAIL_IF (@var{shell-condition})
23379 @atindex{XFAIL_IF}
23380 Determine whether the test is expected to fail because it is a known
23381 bug (for unsupported features, you should skip the test).
23382 @var{shell-condition} is a shell expression such as a @code{test}
23383 command; you can instantiate this macro many times from within the
23384 same test group, and one of the conditions is enough to turn
23385 the test into an expected failure.
23386 @end defmac
23388 @defmac AT_CLEANUP
23389 @atindex{CLEANUP}
23390 End the current test group.
23391 @end defmac
23393 @sp 1
23395 @defmac AT_DATA (@var{file}, @var{contents})
23396 @atindex{DATA}
23397 Initialize an input data @var{file} with given @var{contents}.  Of
23398 course, the @var{contents} have to be properly quoted between square
23399 brackets to protect against included commas or spurious M4
23400 expansion.  The contents must end with an end of line.  @var{file} must
23401 be a single shell word that expands into a single file name.
23402 @end defmac
23404 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
23405   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
23406 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
23407   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
23408 @atindex{CHECK}
23409 @atindex{CHECK_UNQUOTED}
23410 Execute a test by performing given shell @var{commands}.  @var{commands}
23411 is output as-is, so shell expansions are honored.  These commands
23412 should normally exit with @var{status}, while producing expected
23413 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
23414 unexpected status 77, then the rest of the test group is skipped.  If
23415 @var{commands} exit with unexpected status 99, then the test group is
23416 immediately failed.  Otherwise, if this test
23417 fails, run shell commands @var{run-if-fail} or, if this test passes, run shell
23418 commands @var{run-if-pass}.
23420 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
23422 If @var{status} is the literal @samp{ignore}, then the corresponding
23423 exit status is not checked, except for the special cases of 77 (skip)
23424 and 99 (hard failure).  The existence of hard failures allows one to
23425 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
23426 feature has not yet been implemented, but to still distinguish between
23427 gracefully handling the missing feature and dumping core.  A hard
23428 failure also inhibits post-test actions in @var{run-if-fail}.
23430 If the value of the @var{stdout} or @var{stderr} parameter is one of the
23431 literals in the following table, then the test treats the output
23432 according to the rules of that literal.  Otherwise, the value of the
23433 parameter is treated as text that must exactly match the output given by
23434 @var{commands} on standard out and standard error (including an empty
23435 parameter for no output); any differences are captured in the testsuite
23436 log and the test is failed (unless an unexpected exit status of 77
23437 skipped the test instead).  The difference between @code{AT_CHECK} and
23438 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
23439 expansion (@samp{$}), command substitution (@samp{`}), and backslash
23440 escaping (@samp{\}) on comparison text given in the @var{stdout} and
23441 @var{stderr} arguments; if the text includes a trailing newline, this
23442 would be the same as if it were specified via an unquoted
23443 here-document.  (However, there is no difference in the interpretation
23444 of @var{commands}).
23446 @table @samp
23447 @item ignore
23448 The content of the output is ignored, but still captured in the test
23449 group log (if the testsuite is run with option @option{-v}, the test
23450 group log is displayed as the test is run; if the test group later
23451 fails, the test group log is also copied into the overall testsuite
23452 log).  This action is valid for both @var{stdout} and @var{stderr}.
23454 @item ignore-nolog
23455 The content of the output is ignored, and nothing is captured in the log
23456 files.  If @var{commands} are likely to produce binary output (including
23457 long lines) or large amounts of output, then logging the output can make
23458 it harder to locate details related to subsequent tests within the
23459 group, and could potentially corrupt terminal display of a user running
23460 @command{testsuite -v}.
23462 @item stdout
23463 For the @var{stdout} parameter, capture the content of standard output
23464 to both the file @file{stdout} and the test group log.  Subsequent
23465 commands in the test group can then post-process the file.  This action
23466 is often used when it is desired to use @command{grep} to look for a
23467 substring in the output, or when the output must be post-processed to
23468 normalize error messages into a common form.
23470 @item stderr
23471 Like @samp{stdout}, except that it only works for the @var{stderr}
23472 parameter, and the standard error capture file will be named
23473 @file{stderr}.
23475 @item stdout-nolog
23476 @itemx stderr-nolog
23477 Like @samp{stdout} or @samp{stderr}, except that the captured output is
23478 not duplicated into the test group log.  This action is particularly
23479 useful for an intermediate check that produces large amounts of data,
23480 which will be followed by another check that filters down to the
23481 relevant data, as it makes it easier to locate details in the log.
23483 @item expout
23484 For the @var{stdout} parameter, compare standard output contents with
23485 the previously created file @file{expout}, and list any differences in
23486 the testsuite log.
23488 @item experr
23489 Like @samp{expout}, except that it only works for the @var{stderr}
23490 parameter, and the standard error contents are compared with
23491 @file{experr}.
23492 @end table
23493 @end defmac
23495 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
23496   @ovar{run-if-fail}, @ovar{run-if-pass})
23497 @atindex{CHECK_EUNIT}
23498 Initialize and execute an Erlang module named @var{module} that performs
23499 tests following the @var{test-spec} EUnit test specification.
23500 @var{test-spec} must be a valid EUnit test specification, as defined in
23501 the @uref{http://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
23502 Reference Manual}.  @var{erlflags} are optional command-line options
23503 passed to the Erlang interpreter to execute the test Erlang module.
23504 Typically, @var{erlflags} defines at least the paths to directories
23505 containing the compiled Erlang modules under test, as @samp{-pa path1
23506 path2 ...}.
23508 For example, the unit tests associated with Erlang module @samp{testme},
23509 which compiled code is in subdirectory @file{src}, can be performed
23510 with:
23512 @example
23513 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
23514                [-pa "$@{abs_top_builddir@}/src"])
23515 @end example
23517 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
23519 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
23520 must be defined as the path of the Erlang interpreter, the path of the
23521 Erlang compiler, and the command-line flags to pass to the compiler,
23522 respectively.  Those variables should be configured in
23523 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
23524 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
23525 variables are automatically defined in the testsuite.  If @code{ERL} or
23526 @code{ERLC} is not defined, the test group is skipped.
23528 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
23529 be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
23530 an invalid EUnit test specification, the test group fails.  Otherwise,
23531 if the EUnit test passes, shell commands @var{run-if-pass} are executed
23532 or, if the EUnit test fails, shell commands @var{run-if-fail} are
23533 executed and the test group fails.
23535 Only the generated test Erlang module is automatically compiled and
23536 executed.  If @var{test-spec} involves testing other Erlang modules,
23537 e.g. module @samp{testme} in the example above, those modules must be
23538 already compiled.
23540 If the testsuite is run in verbose mode, with option @option{--verbose},
23541 EUnit is also run in verbose mode to output more details about
23542 individual unit tests.
23543 @end defmac
23546 @node testsuite Invocation
23547 @section Running @command{testsuite} Scripts
23548 @cindex @command{testsuite}
23550 Autotest test suites support the following arguments:
23552 @table @option
23553 @item --help
23554 @itemx -h
23555 Display the list of options and exit successfully.
23557 @item --version
23558 @itemx -V
23559 Display the version of the test suite and exit successfully.
23561 @item --directory=@var{dir}
23562 @itemx -C @var{dir}
23563 Change the current directory to @var{dir} before creating any files.
23564 Useful for running the testsuite in a subdirectory from a top-level
23565 Makefile.
23567 @item --jobs@r{[}=@var{n}@r{]}
23568 @itemx -j@ovar{n}
23569 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
23570 run all given tests in parallel.  Note that there should be no space
23571 before the argument to @option{-j}, as @option{-j @var{number}} denotes
23572 the separate arguments @option{-j} and @option{@var{number}}, see below.
23574 In parallel mode, the standard input device of the testsuite script is
23575 not available to commands inside a test group.  Furthermore, banner
23576 lines are not printed, and the summary line for each test group is
23577 output after the test group completes.  Summary lines may appear
23578 unordered.  If verbose and trace output are enabled (see below), they
23579 may appear intermixed from concurrently running tests.
23581 Parallel mode requires the @command{mkfifo} command to work, and will be
23582 silently disabled otherwise.
23584 @item --clean
23585 @itemx -c
23586 Remove all the files the test suite might have created and exit.  Meant
23587 for @code{clean} Make targets.
23589 @item --list
23590 @itemx -l
23591 List all the tests (or only the selection), including their possible
23592 keywords.
23593 @end table
23595 @sp 1
23597 By default all tests are performed (or described with
23598 @option{--list}) in the default environment first silently, then
23599 verbosely, but the environment, set of tests, and verbosity level can be
23600 tuned:
23602 @table @samp
23603 @item @var{variable}=@var{value}
23604 Set the environment @var{variable} to @var{value}.  Use this rather
23605 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
23606 different environment.
23608 @cindex @code{AUTOTEST_PATH}
23609 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
23610 to @env{PATH}.  Relative directory names (not starting with
23611 @samp{/}) are considered to be relative to the top level of the
23612 package being built.  All directories are made absolute, first
23613 starting from the top level @emph{build} tree, then from the
23614 @emph{source} tree.  For instance @samp{./testsuite
23615 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
23616 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
23617 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
23618 @env{PATH}.
23620 @item @var{number}
23621 @itemx @var{number}-@var{number}
23622 @itemx @var{number}-
23623 @itemx -@var{number}
23624 Add the corresponding test groups, with obvious semantics, to the
23625 selection.
23627 @item --keywords=@var{keywords}
23628 @itemx -k @var{keywords}
23629 Add to the selection the test groups with title or keywords (arguments
23630 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
23631 of the comma separated list @var{keywords}, case-insensitively.  Use
23632 @samp{!} immediately before the keyword to invert the selection for this
23633 keyword.  By default, the keywords match whole words; enclose them in
23634 @samp{.*} to also match parts of words.
23636 For example, running
23638 @example
23639 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
23640 @end example
23642 @noindent
23643 selects all tests tagged @samp{autoupdate} @emph{and} with tags
23644 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
23645 etc.), while
23647 @example
23648 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
23649 @end example
23651 @noindent
23652 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
23653 containing @samp{FUNC}.
23655 @item --errexit
23656 @itemx -e
23657 If any test fails, immediately abort testing.  It implies
23658 @option{--debug}: post test group clean up, and top-level logging
23659 are inhibited.  This option is meant for the full test
23660 suite, it is not really useful for generated debugging scripts.
23661 If the testsuite is run in parallel mode using @option{--jobs},
23662 then concurrently running tests will finish before exiting.
23664 @item --verbose
23665 @itemx -v
23666 Force more verbosity in the detailed output of what is being done.  This
23667 is the default for debugging scripts.
23669 @item --debug
23670 @itemx -d
23671 Do not remove the files after a test group was performed ---but they are
23672 still removed @emph{before}, therefore using this option is sane when
23673 running several test groups.  Create debugging scripts.  Do not
23674 overwrite the top-level
23675 log (in order to preserve supposedly existing full log file).  This is
23676 the default for debugging scripts, but it can also be useful to debug
23677 the testsuite itself.
23679 @item --trace
23680 @itemx -x
23681 Trigger shell tracing of the test groups.
23682 @end table
23685 @node Making testsuite Scripts
23686 @section Making @command{testsuite} Scripts
23688 For putting Autotest into movement, you need some configuration and
23689 makefile machinery.  We recommend, at least if your package uses deep or
23690 shallow hierarchies, that you use @file{tests/} as the name of the
23691 directory holding all your tests and their makefile.  Here is a
23692 check list of things to do.
23694 @itemize @minus
23696 @item
23697 @cindex @file{package.m4}
23698 @atindex{PACKAGE_STRING}
23699 @atindex{PACKAGE_BUGREPORT}
23700 @atindex{PACKAGE_NAME}
23701 @atindex{PACKAGE_TARNAME}
23702 @atindex{PACKAGE_VERSION}
23703 @atindex{PACKAGE_URL}
23704 Make sure to create the file @file{package.m4}, which defines the
23705 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
23706 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
23707 address to which bug reports should be sent.  For sake of completeness,
23708 we suggest that you also define @code{AT_PACKAGE_NAME},
23709 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
23710 @code{AT_PACKAGE_URL}.
23711 @xref{Initializing configure}, for a description of these variables.
23712 Be sure to distribute @file{package.m4} and to put it into the source
23713 hierarchy: the test suite ought to be shipped!  See below for an example
23714 @file{Makefile} excerpt.
23716 @item
23717 Invoke @code{AC_CONFIG_TESTDIR}.
23719 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
23720 @acindex{CONFIG_TESTDIR}
23721 An Autotest test suite is to be configured in @var{directory}.  This
23722 macro requires the instantiation of @file{@var{directory}/atconfig} from
23723 @file{@var{directory}/atconfig.in}, and sets the default
23724 @code{AUTOTEST_PATH} to @var{test-path} (@pxref{testsuite Invocation}).
23725 @end defmac
23727 @item
23728 Still within @file{configure.ac}, as appropriate, ensure that some
23729 @code{AC_CONFIG_FILES} command includes substitution for
23730 @file{tests/atlocal}.
23732 @item
23733 The appropriate @file{Makefile} should be modified so the validation in
23734 your package is triggered by @samp{make check}.  An example is provided
23735 below.
23736 @end itemize
23738 With Automake, here is a minimal example for inclusion in
23739 @file{tests/Makefile.am}, in order to link @samp{make check} with a
23740 validation suite.
23742 @example
23743 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
23744 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
23745         :;@{ \
23746           echo '# Signature of the current package.' && \
23747           echo 'm4_define([AT_PACKAGE_NAME],' && \
23748           echo '  [@@PACKAGE_NAME@@])' && \
23749           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
23750           echo '  [@@PACKAGE_TARNAME@@])' && \
23751           echo 'm4_define([AT_PACKAGE_VERSION],' && \
23752           echo '  [@@PACKAGE_VERSION@@])' && \
23753           echo 'm4_define([AT_PACKAGE_STRING],' && \
23754           echo '  [@@PACKAGE_STRING@@])' && \
23755           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
23756           echo '  [@@PACKAGE_BUGREPORT@@])'; \
23757           echo 'm4_define([AT_PACKAGE_URL],' && \
23758           echo '  [@@PACKAGE_URL@@])'; \
23759         @} >'$(srcdir)/package.m4'
23761 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
23762 TESTSUITE = $(srcdir)/testsuite
23764 check-local: atconfig atlocal $(TESTSUITE)
23765         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
23767 installcheck-local: atconfig atlocal $(TESTSUITE)
23768         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
23769           $(TESTSUITEFLAGS)
23771 clean-local:
23772         test ! -f '$(TESTSUITE)' || \
23773          $(SHELL) '$(TESTSUITE)' --clean
23775 AUTOM4TE = $(SHELL) $(srcdir)/build-aux/missing --run autom4te
23776 AUTOTEST = $(AUTOM4TE) --language=autotest
23777 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
23778         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
23779         mv $@@.tmp $@@
23780 @end example
23782 Note that the built testsuite is distributed; this is necessary because
23783 users might not have Autoconf installed, and thus would not be able to
23784 rebuild it.  Likewise, the use of @file{missing} provides the user with
23785 a nicer error message if they modify a source file to the testsuite, and
23786 accidentally trigger the rebuild rules.
23788 You might want to list explicitly the dependencies, i.e., the list of
23789 the files @file{testsuite.at} includes.
23791 If you don't use Automake, you should include the above example in
23792 @file{tests/@/Makefile.in}, along with additional lines inspired from
23793 the following:
23795 @example
23796 subdir = tests
23798 atconfig: $(top_builddir)/config.status
23799         cd $(top_builddir) && \
23800            $(SHELL) ./config.status $(subdir)/$@@
23802 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
23803         cd $(top_builddir) && \
23804            $(SHELL) ./config.status $(subdir)/$@@
23805 @end example
23807 @noindent
23808 and manage to have @code{$(EXTRA_DIST)} distributed.  You will also want
23809 to distribute the file @file{build-aux/@/missing} from the Automake
23810 project; a copy of this file resides in the Autoconf source.
23812 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
23813 within your makefile, you can fine-tune test suite execution with this
23814 variable, for example:
23816 @example
23817 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
23818 @end example
23822 @c =============================== Frequent Autoconf Questions, with answers
23824 @node FAQ
23825 @chapter Frequent Autoconf Questions, with answers
23827 Several questions about Autoconf come up occasionally.  Here some of them
23828 are addressed.
23830 @menu
23831 * Distributing::                Distributing @command{configure} scripts
23832 * Why GNU M4::                  Why not use the standard M4?
23833 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
23834 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
23835 * Defining Directories::        Passing @code{datadir} to program
23836 * Autom4te Cache::              What is it?  Can I remove it?
23837 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
23838 * Expanded Before Required::    Expanded Before Required
23839 * Debugging::                   Debugging @command{configure} scripts
23840 @end menu
23842 @node Distributing
23843 @section Distributing @command{configure} Scripts
23844 @cindex License
23846 @display
23847 What are the restrictions on distributing @command{configure}
23848 scripts that Autoconf generates?  How does that affect my
23849 programs that use them?
23850 @end display
23852 There are no restrictions on how the configuration scripts that Autoconf
23853 produces may be distributed or used.  In Autoconf version 1, they were
23854 covered by the @acronym{GNU} General Public License.  We still encourage
23855 software authors to distribute their work under terms like those of the
23856 @acronym{GPL}, but doing so is not required to use Autoconf.
23858 Of the other files that might be used with @command{configure},
23859 @file{config.h.in} is under whatever copyright you use for your
23860 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
23861 exception to the @acronym{GPL} when they are used with an Autoconf-generated
23862 @command{configure} script, which permits you to distribute them under the
23863 same terms as the rest of your package.  @file{install-sh} is from the X
23864 Consortium and is not copyrighted.
23866 @node Why GNU M4
23867 @section Why Require @acronym{GNU} M4?
23869 @display
23870 Why does Autoconf require @acronym{GNU} M4?
23871 @end display
23873 Many M4 implementations have hard-coded limitations on the size and
23874 number of macros that Autoconf exceeds.  They also lack several
23875 builtin macros that it would be difficult to get along without in a
23876 sophisticated application like Autoconf, including:
23878 @example
23879 m4_builtin
23880 m4_indir
23881 m4_bpatsubst
23882 __file__
23883 __line__
23884 @end example
23886 Autoconf requires version 1.4.6 or later of @acronym{GNU} M4.
23888 Since only software maintainers need to use Autoconf, and since @acronym{GNU}
23889 M4 is simple to configure and install, it seems reasonable to require
23890 @acronym{GNU} M4 to be installed also.  Many maintainers of @acronym{GNU} and
23891 other free software already have most of the @acronym{GNU} utilities
23892 installed, since they prefer them.
23894 @node Bootstrapping
23895 @section How Can I Bootstrap?
23896 @cindex Bootstrap
23898 @display
23899 If Autoconf requires @acronym{GNU} M4 and @acronym{GNU} M4 has an Autoconf
23900 @command{configure} script, how do I bootstrap?  It seems like a chicken
23901 and egg problem!
23902 @end display
23904 This is a misunderstanding.  Although @acronym{GNU} M4 does come with a
23905 @command{configure} script produced by Autoconf, Autoconf is not required
23906 in order to run the script and install @acronym{GNU} M4.  Autoconf is only
23907 required if you want to change the M4 @command{configure} script, which few
23908 people have to do (mainly its maintainer).
23910 @node Why Not Imake
23911 @section Why Not Imake?
23912 @cindex Imake
23914 @display
23915 Why not use Imake instead of @command{configure} scripts?
23916 @end display
23918 Several people have written addressing this question, so I include
23919 adaptations of their explanations here.
23921 The following answer is based on one written by Richard Pixley:
23923 @quotation
23924 Autoconf generated scripts frequently work on machines that it has
23925 never been set up to handle before.  That is, it does a good job of
23926 inferring a configuration for a new system.  Imake cannot do this.
23928 Imake uses a common database of host specific data.  For X11, this makes
23929 sense because the distribution is made as a collection of tools, by one
23930 central authority who has control over the database.
23932 @acronym{GNU} tools are not released this way.  Each @acronym{GNU} tool has a
23933 maintainer; these maintainers are scattered across the world.  Using a
23934 common database would be a maintenance nightmare.  Autoconf may appear
23935 to be this kind of database, but in fact it is not.  Instead of listing
23936 host dependencies, it lists program requirements.
23938 If you view the @acronym{GNU} suite as a collection of native tools, then the
23939 problems are similar.  But the @acronym{GNU} development tools can be
23940 configured as cross tools in almost any host+target permutation.  All of
23941 these configurations can be installed concurrently.  They can even be
23942 configured to share host independent files across hosts.  Imake doesn't
23943 address these issues.
23945 Imake templates are a form of standardization.  The @acronym{GNU} coding
23946 standards address the same issues without necessarily imposing the same
23947 restrictions.
23948 @end quotation
23951 Here is some further explanation, written by Per Bothner:
23953 @quotation
23954 One of the advantages of Imake is that it easy to generate large
23955 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
23956 However, @code{cpp} is not programmable: it has limited conditional
23957 facilities, and no looping.  And @code{cpp} cannot inspect its
23958 environment.
23960 All of these problems are solved by using @code{sh} instead of
23961 @code{cpp}.  The shell is fully programmable, has macro substitution,
23962 can execute (or source) other shell scripts, and can inspect its
23963 environment.
23964 @end quotation
23967 Paul Eggert elaborates more:
23969 @quotation
23970 With Autoconf, installers need not assume that Imake itself is already
23971 installed and working well.  This may not seem like much of an advantage
23972 to people who are accustomed to Imake.  But on many hosts Imake is not
23973 installed or the default installation is not working well, and requiring
23974 Imake to install a package hinders the acceptance of that package on
23975 those hosts.  For example, the Imake template and configuration files
23976 might not be installed properly on a host, or the Imake build procedure
23977 might wrongly assume that all source files are in one big directory
23978 tree, or the Imake configuration might assume one compiler whereas the
23979 package or the installer needs to use another, or there might be a
23980 version mismatch between the Imake expected by the package and the Imake
23981 supported by the host.  These problems are much rarer with Autoconf,
23982 where each package comes with its own independent configuration
23983 processor.
23985 Also, Imake often suffers from unexpected interactions between
23986 @command{make} and the installer's C preprocessor.  The fundamental problem
23987 here is that the C preprocessor was designed to preprocess C programs,
23988 not makefiles.  This is much less of a problem with Autoconf,
23989 which uses the general-purpose preprocessor M4, and where the
23990 package's author (rather than the installer) does the preprocessing in a
23991 standard way.
23992 @end quotation
23995 Finally, Mark Eichin notes:
23997 @quotation
23998 Imake isn't all that extensible, either.  In order to add new features to
23999 Imake, you need to provide your own project template, and duplicate most
24000 of the features of the existing one.  This means that for a sophisticated
24001 project, using the vendor-provided Imake templates fails to provide any
24002 leverage---since they don't cover anything that your own project needs
24003 (unless it is an X11 program).
24005 On the other side, though:
24007 The one advantage that Imake has over @command{configure}:
24008 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
24009 than @file{Makefile.in} files.  There is a fix to this, however---at least
24010 for the Kerberos V5 tree, we've modified things to call in common
24011 @file{post.in} and @file{pre.in} makefile fragments for the
24012 entire tree.  This means that a lot of common things don't have to be
24013 duplicated, even though they normally are in @command{configure} setups.
24014 @end quotation
24017 @node Defining Directories
24018 @section How Do I @code{#define} Installation Directories?
24020 @display
24021 My program needs library files, installed in @code{datadir} and
24022 similar.  If I use
24024 @example
24025 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
24026   [Define to the read-only architecture-independent
24027    data directory.])
24028 @end example
24030 @noindent
24031 I get
24033 @example
24034 #define DATADIR "$@{prefix@}/share"
24035 @end example
24036 @end display
24038 As already explained, this behavior is on purpose, mandated by the
24039 @acronym{GNU} Coding Standards, see @ref{Installation Directory
24040 Variables}.  There are several means to achieve a similar goal:
24042 @itemize @minus
24043 @item
24044 Do not use @code{AC_DEFINE} but use your makefile to pass the
24045 actual value of @code{datadir} via compilation flags.
24046 @xref{Installation Directory Variables}, for the details.
24048 @item
24049 This solution can be simplified when compiling a program: you may either
24050 extend the @code{CPPFLAGS}:
24052 @example
24053 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
24054 @end example
24056 @noindent
24057 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
24059 @example
24060 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
24061 @end example
24063 @noindent
24064 Alternatively, create a dedicated header file:
24066 @example
24067 DISTCLEANFILES = myprog-paths.h
24068 myprog-paths.h: Makefile
24069         echo '#define DATADIR "$(datadir)"' >$@@
24070 @end example
24072 @item
24073 Use @code{AC_DEFINE} but have @command{configure} compute the literal
24074 value of @code{datadir} and others.  Many people have wrapped macros to
24075 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
24076 the @uref{http://@/autoconf-archive@/.cryp.to/, Autoconf Macro
24077 Archive}.
24079 This solution does not conform to the @acronym{GNU} Coding Standards.
24081 @item
24082 Note that all the previous solutions hard wire the absolute name of
24083 these directories in the executables, which is not a good property.  You
24084 may try to compute the names relative to @code{prefix}, and try to
24085 find @code{prefix} at runtime, this way your package is relocatable.
24086 @end itemize
24089 @node Autom4te Cache
24090 @section What is @file{autom4te.cache}?
24092 @display
24093 What is this directory @file{autom4te.cache}?  Can I safely remove it?
24094 @end display
24096 In the @acronym{GNU} Build System, @file{configure.ac} plays a central
24097 role and is read by many tools: @command{autoconf} to create
24098 @file{configure}, @command{autoheader} to create @file{config.h.in},
24099 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
24100 check the completeness of @file{configure.ac}, @command{autoreconf} to
24101 check the @acronym{GNU} Build System components that are used.  To
24102 ``read @file{configure.ac}'' actually means to compile it with M4,
24103 which can be a long process for complex @file{configure.ac}.
24105 This is why all these tools, instead of running directly M4, invoke
24106 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
24107 a specific demand, stores additional information in
24108 @file{autom4te.cache} for future runs.  For instance, if you run
24109 @command{autoconf}, behind the scenes, @command{autom4te} also
24110 stores information for the other tools, so that when you invoke
24111 @command{autoheader} or @command{automake} etc., reprocessing
24112 @file{configure.ac} is not needed.  The speed up is frequently 30%,
24113 and is increasing with the size of @file{configure.ac}.
24115 But it is and remains being simply a cache: you can safely remove it.
24117 @sp 1
24119 @display
24120 Can I permanently get rid of it?
24121 @end display
24123 The creation of this cache can be disabled from
24124 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
24125 details.  You should be aware that disabling the cache slows down the
24126 Autoconf test suite by 40%.  The more @acronym{GNU} Build System
24127 components are used, the more the cache is useful; for instance
24128 running @samp{autoreconf -f} on the Core Utilities is twice slower without
24129 the cache @emph{although @option{--force} implies that the cache is
24130 not fully exploited}, and eight times slower than without
24131 @option{--force}.
24134 @node Present But Cannot Be Compiled
24135 @section Header Present But Cannot Be Compiled
24137 The most important guideline to bear in mind when checking for
24138 features is to mimic as much as possible the intended use.
24139 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
24140 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
24141 the preprocessor, instead of the compiler, to check for headers.  As a
24142 result, incompatibilities between headers went unnoticed during
24143 configuration, and maintainers finally had to deal with this issue
24144 elsewhere.
24146 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
24147 checks are performed, and @command{configure} complains loudly if the
24148 compiler and the preprocessor do not agree.  However, only the compiler
24149 result is considered.
24151 Consider the following example:
24153 @smallexample
24154 $ @kbd{cat number.h}
24155 typedef int number;
24156 $ @kbd{cat pi.h}
24157 const number pi = 3;
24158 $ @kbd{cat configure.ac}
24159 AC_INIT([Example], [1.0], [bug-example@@example.org])
24160 AC_CHECK_HEADERS([pi.h])
24161 $ @kbd{autoconf -Wall}
24162 $ @kbd{./configure}
24163 checking for gcc... gcc
24164 checking for C compiler default output file name... a.out
24165 checking whether the C compiler works... yes
24166 checking whether we are cross compiling... no
24167 checking for suffix of executables...
24168 checking for suffix of object files... o
24169 checking whether we are using the GNU C compiler... yes
24170 checking whether gcc accepts -g... yes
24171 checking for gcc option to accept ISO C89... none needed
24172 checking how to run the C preprocessor... gcc -E
24173 checking for grep that handles long lines and -e... grep
24174 checking for egrep... grep -E
24175 checking for ANSI C header files... yes
24176 checking for sys/types.h... yes
24177 checking for sys/stat.h... yes
24178 checking for stdlib.h... yes
24179 checking for string.h... yes
24180 checking for memory.h... yes
24181 checking for strings.h... yes
24182 checking for inttypes.h... yes
24183 checking for stdint.h... yes
24184 checking for unistd.h... yes
24185 checking pi.h usability... no
24186 checking pi.h presence... yes
24187 configure: WARNING: pi.h: present but cannot be compiled
24188 configure: WARNING: pi.h:     check for missing prerequisite headers?
24189 configure: WARNING: pi.h: see the Autoconf documentation
24190 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
24191 configure: WARNING: pi.h: proceeding with the compiler's result
24192 configure: WARNING:     ## -------------------------------------- ##
24193 configure: WARNING:     ## Report this to bug-example@@example.org ##
24194 configure: WARNING:     ## -------------------------------------- ##
24195 checking for pi.h... yes
24196 @end smallexample
24198 @noindent
24199 The proper way the handle this case is using the fourth argument
24200 (@pxref{Generic Headers}):
24202 @example
24203 $ @kbd{cat configure.ac}
24204 AC_INIT([Example], [1.0], [bug-example@@example.org])
24205 AC_CHECK_HEADERS([number.h pi.h], [], [],
24206 [[#ifdef HAVE_NUMBER_H
24207 # include <number.h>
24208 #endif
24210 $ @kbd{autoconf -Wall}
24211 $ @kbd{./configure}
24212 checking for gcc... gcc
24213 checking for C compiler default output... a.out
24214 checking whether the C compiler works... yes
24215 checking whether we are cross compiling... no
24216 checking for suffix of executables...
24217 checking for suffix of object files... o
24218 checking whether we are using the GNU C compiler... yes
24219 checking whether gcc accepts -g... yes
24220 checking for gcc option to accept ANSI C... none needed
24221 checking for number.h... yes
24222 checking for pi.h... yes
24223 @end example
24225 See @ref{Particular Headers}, for a list of headers with their
24226 prerequisites.
24228 @node Expanded Before Required
24229 @section Expanded Before Required
24231 @cindex expanded before required
24232 Older versions of Autoconf silently built files with incorrect ordering
24233 between dependent macros if an outer macro first expanded, then later
24234 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
24235 situation no longer generates out-of-order code, but results in
24236 duplicate output and a syntax warning:
24238 @example
24239 $ @kbd{cat configure.ac}
24240 @result{}AC_DEFUN([TESTA], [[echo in A
24241 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
24242 @result{}SEEN_A=:]])
24243 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
24244 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
24245 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
24246 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
24247 @result{}TESTA
24248 @result{}TESTC])
24249 @result{}AC_INIT
24250 @result{}OUTER
24251 @result{}AC_OUTPUT
24252 $ @kbd{autoconf}
24253 @result{}configure.ac:11: warning: AC_REQUIRE:
24254 @result{} `TESTA' was expanded before it was required
24255 @result{}configure.ac:4: TESTB is expanded from...
24256 @result{}configure.ac:6: TESTC is expanded from...
24257 @result{}configure.ac:7: OUTER is expanded from...
24258 @result{}configure.ac:11: the top level
24259 @end example
24261 @noindent
24262 To avoid this warning, decide what purpose the macro in question serves.
24263 If it only needs to be expanded once (for example, if it provides
24264 initialization text used by later macros), then the simplest fix is to
24265 change the macro to be declared with @code{AC_DEFUN_ONCE}
24266 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
24267 newer.  A more portable fix is to change all
24268 instances of direct calls to instead go through @code{AC_REQUIRE}
24269 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
24270 by arguments or by the current definition of other macros in the m4
24271 environment, then the macro should always be directly expanded instead
24272 of required.
24274 For another case study, consider this example trimmed down from an
24275 actual package.  Originally, the package contained shell code and
24276 multiple macro invocations at the top level of @file{configure.ac}:
24278 @example
24279 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
24280 foobar=
24281 AC_PROG_CC
24283 @end example
24285 @noindent
24286 but that was getting complex, so the author wanted to offload some of
24287 the text into a new macro in another file included via
24288 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
24289 macro:
24291 @example
24292 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
24293 AC_DEFUN([BAR], [
24294 foobar=
24295 AC_PROG_CC
24299 @end example
24301 @noindent
24302 With older versions of Autoconf, the setting of @samp{foobar=} occurs
24303 before the single compiler check, as the author intended.  But with
24304 Autoconf 2.64, this issues the ``expanded before it was required''
24305 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
24306 check, one before @samp{foobar=}, and one after.  To understand why this
24307 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
24308 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
24309 the documented semantics of @code{AC_REQUIRE}, this means that
24310 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
24311 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceeding the
24312 use of @samp{foobar=}.  The older versions of Autoconf were broken with
24313 regards to the rules of @code{AC_REQUIRE}, which explains why the code
24314 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
24315 autoconf.  In other words, the author was unknowingly relying on a bug
24316 exploit to get the desired results, and that exploit broke once the bug
24317 was fixed.
24319 So, what recourse does the author have, to restore their intended
24320 semantics of setting @samp{foobar=} prior to a single compiler check,
24321 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
24322 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
24323 there is always the possibility of using the lower-level
24324 @code{m4_define}:
24326 @example
24327 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
24328 m4_define([BAR], [
24329 foobar=
24330 AC_PROG_CC
24334 @end example
24336 @noindent
24337 This works great if everything is in the same file.  However, it does
24338 not help in the case where the author wants to have @command{aclocal}
24339 find the definition of @code{BAR} from its own file, since
24340 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
24341 better fix is to recognize that if @code{BAR} also uses
24342 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
24343 to a subsequent require.  Then, by creating yet another helper macro,
24344 the author can once again guarantee a single invocation of
24345 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
24346 author can also use @code{AC_BEFORE} to make sure no other macro
24347 appearing before @code{BAR} has triggered an unwanted expansion of
24348 @code{AC_PROG_CC}.
24350 @example
24351 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
24352 AC_DEFUN([BEFORE_CC], [
24353 foobar=
24355 AC_DEFUN([BAR], [
24356 AC_BEFORE([$0], [AC_PROG_CC])dnl
24357 AC_REQUIRE([BEFORE_CC])dnl
24358 AC_REQUIRE([AC_PROG_CC])dnl
24362 @end example
24365 @node Debugging
24366 @section Debugging @command{configure} scripts
24368 While in general, @command{configure} scripts generated by Autoconf
24369 strive to be fairly portable to various systems, compilers, shells, and
24370 other tools, it may still be necessary to debug a failing test, broken
24371 script or makefile, or fix or override an incomplete, faulty, or erroneous
24372 test, especially during macro development.  Failures can occur at all levels,
24373 in M4 syntax or semantics, shell script issues, or due to bugs in the
24374 test or the tools invoked by @command{configure}.  Together with the
24375 rather arcane error message that @command{m4} and @command{make} may
24376 produce when their input contains syntax errors, this can make debugging
24377 rather painful.
24379 Nevertheless, here is a list of hints and strategies that may help:
24381 @itemize
24382 @item
24383 When @command{autoconf} fails, common causes for error include:
24385 @itemize
24386 @item
24387 mismatched or unbalanced parentheses or braces (@pxref{Balancing
24388 Parentheses}),
24390 @item under- or overquoted macro arguments (@pxref{Autoconf
24391 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
24392 Macros}),
24394 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
24395 Language}).
24396 @end itemize
24398 Typically, it helps to go back to the last working version of the input
24399 and compare the differences for each of these errors.  Another
24400 possibility is to sprinkle pairs of @code{m4_traceon} and
24401 @code{m4_traceoff} judiciously in the code, either without a parameter
24402 or listing some macro names and watch @command{m4} expand its input
24403 verbosely (@pxref{Debugging via autom4te}).
24405 @item
24406 Sometimes @command{autoconf} succeeds but the generated
24407 @command{configure} script has invalid shell syntax.  You can detect this
24408 case by running @samp{bash -n configure} or @samp{sh -n configure}.
24409 If this command fails, the same tips apply, as if @command{autoconf} had
24410 failed.
24412 @item
24413 Debugging @command{configure} script execution may be done by sprinkling
24414 pairs of @code{set -x} and @code{set +x} into the shell script before
24415 and after the region that contains a bug.  Running the whole script with
24416 @samp{@var{shell} ./configure -vx 2>&1 | tee @var{log-file}} with a decent
24417 @var{shell} may work, but produces lots of output.  Here, it can help to
24418 search for markers like @samp{checking for} a particular test in the
24419 @var{log-file}.
24421 @item
24422 When @command{configure} tests produce invalid results for your system,
24423 it may be necessary to override them:
24425 @itemize
24426 @item
24427 For programs, tools or libraries variables, preprocessor, compiler, or
24428 linker flags, it is often sufficient to override them at @command{make}
24429 run time with some care (@pxref{Macros and Submakes}).  Since this
24430 normally won't cause @command{configure} to be run again with these
24431 changed settings, it may fail if the changed variable would have caused
24432 different test results from @command{configure}, so this may work only
24433 for simple differences.
24435 @item
24436 Most tests which produce their result in a substituted variable allow to
24437 override the test by setting the variable on the @command{configure}
24438 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
24439 @pxref{Particular Systems}).
24441 @item
24442 Many tests store their result in a cache variable (@pxref{Caching
24443 Results}).  This lets you override them either on the
24444 @command{configure} command line as above, or through a primed cache or
24445 site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
24446 cache variable is documented with a test macro or may be inferred from
24447 @ref{Cache Variable Names}; the precise semantics of undocumented
24448 variables are often internal details, subject to change.
24449 @end itemize
24450 @end itemize
24452 Conversely, as macro author, you can make it easier for users of your
24453 macro:
24455 @itemize
24456 @item
24457 by minimizing dependencies between tests and between test results as far
24458 as possible,
24460 @item
24461 by using @command{make} variables to factorize and allow
24462 override of settings at @command{make} run time,
24464 @item
24465 by honoring the @acronym{GNU} Coding Standards and not overriding flags
24466 reserved for the user except temporarily during @command{configure}
24467 tests,
24469 @item
24470 by not requiring users of your macro to use the cache variables.
24471 Instead, expose the result of the test via @var{run-if-true} and
24472 @var{run-if-false} parameters.  If the result is not a boolean,
24473 then provide it through documented shell variables.
24474 @end itemize
24477 @c ===================================================== History of Autoconf.
24479 @node History
24480 @chapter History of Autoconf
24481 @cindex History of autoconf
24483 You may be wondering, Why was Autoconf originally written?  How did it
24484 get into its present form?  (Why does it look like gorilla spit?)  If
24485 you're not wondering, then this chapter contains no information useful
24486 to you, and you might as well skip it.  If you @emph{are} wondering,
24487 then let there be light@enddots{}
24489 @menu
24490 * Genesis::                     Prehistory and naming of @command{configure}
24491 * Exodus::                      The plagues of M4 and Perl
24492 * Leviticus::                   The priestly code of portability arrives
24493 * Numbers::                     Growth and contributors
24494 * Deuteronomy::                 Approaching the promises of easy configuration
24495 @end menu
24497 @node Genesis
24498 @section Genesis
24500 In June 1991 I was maintaining many of the @acronym{GNU} utilities for the
24501 Free Software Foundation.  As they were ported to more platforms and
24502 more programs were added, the number of @option{-D} options that users
24503 had to select in the makefile (around 20) became burdensome.
24504 Especially for me---I had to test each new release on a bunch of
24505 different systems.  So I wrote a little shell script to guess some of
24506 the correct settings for the fileutils package, and released it as part
24507 of fileutils 2.0.  That @command{configure} script worked well enough that
24508 the next month I adapted it (by hand) to create similar @command{configure}
24509 scripts for several other @acronym{GNU} utilities packages.  Brian Berliner
24510 also adapted one of my scripts for his @acronym{CVS} revision control system.
24512 Later that summer, I learned that Richard Stallman and Richard Pixley
24513 were developing similar scripts to use in the @acronym{GNU} compiler tools;
24514 so I adapted my @command{configure} scripts to support their evolving
24515 interface: using the file name @file{Makefile.in} as the templates;
24516 adding @samp{+srcdir}, the first option (of many); and creating
24517 @file{config.status} files.
24519 @node Exodus
24520 @section Exodus
24522 As I got feedback from users, I incorporated many improvements, using
24523 Emacs to search and replace, cut and paste, similar changes in each of
24524 the scripts.  As I adapted more @acronym{GNU} utilities packages to use
24525 @command{configure} scripts, updating them all by hand became impractical.
24526 Rich Murphey, the maintainer of the @acronym{GNU} graphics utilities, sent me
24527 mail saying that the @command{configure} scripts were great, and asking if
24528 I had a tool for generating them that I could send him.  No, I thought,
24529 but I should!  So I started to work out how to generate them.  And the
24530 journey from the slavery of hand-written @command{configure} scripts to the
24531 abundance and ease of Autoconf began.
24533 Cygnus @command{configure}, which was being developed at around that time,
24534 is table driven; it is meant to deal mainly with a discrete number of
24535 system types with a small number of mainly unguessable features (such as
24536 details of the object file format).  The automatic configuration system
24537 that Brian Fox had developed for Bash takes a similar approach.  For
24538 general use, it seems to me a hopeless cause to try to maintain an
24539 up-to-date database of which features each variant of each operating
24540 system has.  It's easier and more reliable to check for most features on
24541 the fly---especially on hybrid systems that people have hacked on
24542 locally or that have patches from vendors installed.
24544 I considered using an architecture similar to that of Cygnus
24545 @command{configure}, where there is a single @command{configure} script that
24546 reads pieces of @file{configure.in} when run.  But I didn't want to have
24547 to distribute all of the feature tests with every package, so I settled
24548 on having a different @command{configure} made from each
24549 @file{configure.in} by a preprocessor.  That approach also offered more
24550 control and flexibility.
24552 I looked briefly into using the Metaconfig package, by Larry Wall,
24553 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
24554 reasons.  The @command{Configure} scripts it produces are interactive,
24555 which I find quite inconvenient; I didn't like the ways it checked for
24556 some features (such as library functions); I didn't know that it was
24557 still being maintained, and the @command{Configure} scripts I had
24558 seen didn't work on many modern systems (such as System V R4 and NeXT);
24559 it wasn't flexible in what it could do in response to a feature's
24560 presence or absence; I found it confusing to learn; and it was too big
24561 and complex for my needs (I didn't realize then how much Autoconf would
24562 eventually have to grow).
24564 I considered using Perl to generate my style of @command{configure}
24565 scripts, but decided that M4 was better suited to the job of simple
24566 textual substitutions: it gets in the way less, because output is
24567 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
24568 the @acronym{GNU} extensions to M4.)  Also, some of my friends at the
24569 University of Maryland had recently been putting M4 front ends on
24570 several programs, including @code{tvtwm}, and I was interested in trying
24571 out a new language.
24573 @node Leviticus
24574 @section Leviticus
24576 Since my @command{configure} scripts determine the system's capabilities
24577 automatically, with no interactive user intervention, I decided to call
24578 the program that generates them Autoconfig.  But with a version number
24579 tacked on, that name would be too long for old Unix file systems,
24580 so I shortened it to Autoconf.
24582 In the fall of 1991 I called together a group of fellow questers after
24583 the Holy Grail of portability (er, that is, alpha testers) to give me
24584 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
24585 and continued to add features and improve the techniques used in the
24586 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
24587 with the idea of making an Autoconf shell script to run M4
24588 and check for unresolved macro calls; Richard Pixley, who suggested
24589 running the compiler instead of searching the file system to find
24590 include files and symbols, for more accurate results; Karl Berry, who
24591 got Autoconf to configure @TeX{} and added the macro index to the
24592 documentation; and Ian Lance Taylor, who added support for creating a C
24593 header file as an alternative to putting @option{-D} options in a
24594 makefile, so he could use Autoconf for his @acronym{UUCP} package.
24595 The alpha testers cheerfully adjusted their files again and again as the
24596 names and calling conventions of the Autoconf macros changed from
24597 release to release.  They all contributed many specific checks, great
24598 ideas, and bug fixes.
24600 @node Numbers
24601 @section Numbers
24603 In July 1992, after months of alpha testing, I released Autoconf 1.0,
24604 and converted many @acronym{GNU} packages to use it.  I was surprised by how
24605 positive the reaction to it was.  More people started using it than I
24606 could keep track of, including people working on software that wasn't
24607 part of the @acronym{GNU} Project (such as TCL, FSP, and Kerberos V5).
24608 Autoconf continued to improve rapidly, as many people using the
24609 @command{configure} scripts reported problems they encountered.
24611 Autoconf turned out to be a good torture test for M4 implementations.
24612 Unix M4 started to dump core because of the length of the
24613 macros that Autoconf defined, and several bugs showed up in @acronym{GNU}
24614 M4 as well.  Eventually, we realized that we needed to use some
24615 features that only @acronym{GNU} M4 has.  4.3@acronym{BSD} M4, in
24616 particular, has an impoverished set of builtin macros; the System V
24617 version is better, but still doesn't provide everything we need.
24619 More development occurred as people put Autoconf under more stresses
24620 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
24621 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
24622 invalid arguments.  Jim Blandy bravely coerced it into configuring
24623 @acronym{GNU} Emacs, laying the groundwork for several later improvements.
24624 Roland McGrath got it to configure the @acronym{GNU} C Library, wrote the
24625 @command{autoheader} script to automate the creation of C header file
24626 templates, and added a @option{--verbose} option to @command{configure}.
24627 Noah Friedman added the @option{--autoconf-dir} option and
24628 @code{AC_MACRODIR} environment variable.  (He also coined the term
24629 @dfn{autoconfiscate} to mean ``adapt a software package to use
24630 Autoconf''.)  Roland and Noah improved the quoting protection in
24631 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
24632 dealing with portability problems from February through June, 1993.
24634 @node Deuteronomy
24635 @section Deuteronomy
24637 A long wish list for major features had accumulated, and the effect of
24638 several years of patching by various people had left some residual
24639 cruft.  In April 1994, while working for Cygnus Support, I began a major
24640 revision of Autoconf.  I added most of the features of the Cygnus
24641 @command{configure} that Autoconf had lacked, largely by adapting the
24642 relevant parts of Cygnus @command{configure} with the help of david zuhn
24643 and Ken Raeburn.  These features include support for using
24644 @file{config.sub}, @file{config.guess}, @option{--host}, and
24645 @option{--target}; making links to files; and running @command{configure}
24646 scripts in subdirectories.  Adding these features enabled Ken to convert
24647 @acronym{GNU} @code{as}, and Rob Savoye to convert Deja@acronym{GNU}, to using
24648 Autoconf.
24650 I added more features in response to other peoples' requests.  Many
24651 people had asked for @command{configure} scripts to share the results of
24652 the checks between runs, because (particularly when configuring a large
24653 source tree, like Cygnus does) they were frustratingly slow.  Mike
24654 Haertel suggested adding site-specific initialization scripts.  People
24655 distributing software that had to unpack on MS-DOS asked for a way to
24656 override the @file{.in} extension on the file names, which produced file
24657 names like @file{config.h.in} containing two dots.  Jim Avera did an
24658 extensive examination of the problems with quoting in @code{AC_DEFINE}
24659 and @code{AC_SUBST}; his insights led to significant improvements.
24660 Richard Stallman asked that compiler output be sent to @file{config.log}
24661 instead of @file{/dev/null}, to help people debug the Emacs
24662 @command{configure} script.
24664 I made some other changes because of my dissatisfaction with the quality
24665 of the program.  I made the messages showing results of the checks less
24666 ambiguous, always printing a result.  I regularized the names of the
24667 macros and cleaned up coding style inconsistencies.  I added some
24668 auxiliary utilities that I had developed to help convert source code
24669 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
24670 the macros not interrupt each others' messages.  (That feature revealed
24671 some performance bottlenecks in @acronym{GNU} M4, which he hastily
24672 corrected!)  I reorganized the documentation around problems people want
24673 to solve.  And I began a test suite, because experience had shown that
24674 Autoconf has a pronounced tendency to regress when we change it.
24676 Again, several alpha testers gave invaluable feedback, especially
24677 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
24678 and Mark Eichin.
24680 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
24681 have free time again.  I think.  Yeah, right.)
24684 @c ========================================================== Appendices
24687 @node GNU Free Documentation License
24688 @appendix GNU Free Documentation License
24690 @include fdl.texi
24692 @node Indices
24693 @appendix Indices
24695 @menu
24696 * Environment Variable Index::  Index of environment variables used
24697 * Output Variable Index::       Index of variables set in output files
24698 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
24699 * Cache Variable Index::        Index of documented cache variables
24700 * Autoconf Macro Index::        Index of Autoconf macros
24701 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
24702 * Autotest Macro Index::        Index of Autotest macros
24703 * Program & Function Index::    Index of those with portability problems
24704 * Concept Index::               General index
24705 @end menu
24707 @node Environment Variable Index
24708 @appendixsec Environment Variable Index
24710 This is an alphabetical list of the environment variables that might
24711 influence Autoconf checks.
24713 @printindex ev
24715 @node Output Variable Index
24716 @appendixsec Output Variable Index
24718 This is an alphabetical list of the variables that Autoconf can
24719 substitute into files that it creates, typically one or more
24720 makefiles.  @xref{Setting Output Variables}, for more information
24721 on how this is done.
24723 @printindex ov
24725 @node Preprocessor Symbol Index
24726 @appendixsec Preprocessor Symbol Index
24728 This is an alphabetical list of the C preprocessor symbols that the
24729 Autoconf macros define.  To work with Autoconf, C source code needs to
24730 use these names in @code{#if} or @code{#ifdef} directives.
24732 @printindex cv
24734 @node Cache Variable Index
24735 @appendixsec Cache Variable Index
24737 This is an alphabetical list of documented cache variables used
24738 by macros defined in Autoconf.  Autoconf macros may use additional cache
24739 variables internally.
24740 @ifset shortindexflag
24741 To make the list easier to use, the variables are listed without their
24742 preceding @samp{ac_cv_}.
24743 @end ifset
24745 @printindex CA
24747 @node Autoconf Macro Index
24748 @appendixsec Autoconf Macro Index
24750 This is an alphabetical list of the Autoconf macros.
24751 @ifset shortindexflag
24752 To make the list easier to use, the macros are listed without their
24753 preceding @samp{AC_}.
24754 @end ifset
24756 @printindex AC
24758 @node M4 Macro Index
24759 @appendixsec M4 Macro Index
24761 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
24762 @ifset shortindexflag
24763 To make the list easier to use, the macros are listed without their
24764 preceding @samp{m4_} or @samp{AS_}.
24765 @end ifset
24767 @printindex MS
24769 @node Autotest Macro Index
24770 @appendixsec Autotest Macro Index
24772 This is an alphabetical list of the Autotest macros.
24773 @ifset shortindexflag
24774 To make the list easier to use, the macros are listed without their
24775 preceding @samp{AT_}.
24776 @end ifset
24778 @printindex AT
24780 @node Program & Function Index
24781 @appendixsec Program and Function Index
24783 This is an alphabetical list of the programs and functions whose
24784 portability is discussed in this document.
24786 @printindex pr
24788 @node Concept Index
24789 @appendixsec Concept Index
24791 This is an alphabetical list of the files, tools, and concepts
24792 introduced in this document.
24794 @printindex cp
24796 @bye
24798 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
24799 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
24800 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
24801 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
24802 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
24803 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
24804 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
24805 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
24806 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
24807 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
24808 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
24809 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
24810 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
24811 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
24812 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
24813 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
24814 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
24815 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
24816 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
24817 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
24818 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
24819 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
24820 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
24821 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
24822 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
24823 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
24824 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
24825 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
24826 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
24827 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
24828 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
24829 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
24830 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
24831 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
24832 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
24833 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
24834 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
24835 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
24836 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
24837 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
24838 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
24839 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
24840 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
24841 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
24842 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
24843 @c  LocalWords:  STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
24844 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
24845 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
24846 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
24847 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
24848 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
24849 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
24850 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
24851 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
24852 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
24853 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
24854 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
24855 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
24856 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
24857 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
24858 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
24859 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
24860 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
24861 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
24862 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
24863 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
24864 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
24865 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
24866 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
24867 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
24868 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
24869 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
24870 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
24871 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
24872 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
24873 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
24874 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
24875 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
24876 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
24877 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
24878 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
24879 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
24880 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
24881 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
24882 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
24883 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
24884 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
24885 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
24886 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
24887 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
24888 @c  LocalWords:  Dynix descrips basename aname cname macroexpands xno xcheck
24889 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
24891 @c Local Variables:
24892 @c fill-column: 72
24893 @c ispell-local-dictionary: "american"
24894 @c indent-tabs-mode: nil
24895 @c whitespace-check-buffer-indent: nil
24896 @c End: