maint: update copyright year
[autoconf.git] / doc / autoconf.texi
blob1e9fb422beba2df868d1337ebbd3cd15de2aed8f
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, for variables users may set
50 @c in their environment or on the configure command line.
51 @defcodeindex ev
52 @c Define an output variable index, for commonly AC_SUBST'ed variables.
53 @defcodeindex ov
54 @c Define a cache variable index, for variables matching *_cv_*.
55 @defcodeindex CA
56 @c Other shell variables not fitting the above categories should be
57 @c listed in the predefined vrindex, which we merge in the concept index.
58 @syncodeindex vr cp
59 @c Define a CPP preprocessor macro index, for #define'd strings.
60 @defcodeindex cv
61 @c Define an Autoconf macro index that @defmac doesn't write to.
62 @defcodeindex AC
63 @c Define an Autotest macro index that @defmac doesn't write to.
64 @defcodeindex AT
65 @c Define an M4sugar macro index that @defmac doesn't write to.
66 @defcodeindex MS
67 @c Define an index for *foreign* programs: `mv' etc.  Used for the
68 @c portability sections and so on.
69 @defindex pr
71 @c shortindexflag
72 @c --------------
73 @c Shall we factor AC_ out of the Autoconf macro index etc.?
74 @iftex
75 @set shortindexflag
76 @end iftex
78 @c @acindex{MACRO}
79 @c ---------------
80 @c Registering an AC_\MACRO\.
81 @ifset shortindexflag
82 @macro acindex{macro}
83 @ACindex \macro\
85 @end macro
86 @end ifset
87 @ifclear shortindexflag
88 @macro acindex{macro}
89 @ACindex AC_\macro\
90 @end macro
91 @end ifclear
93 @c @ahindex{MACRO}
94 @c ---------------
95 @c Registering an AH_\MACRO\.
96 @macro ahindex{macro}
97 @ACindex AH_\macro\
99 @end macro
101 @c @asindex{MACRO}
102 @c ---------------
103 @c Registering an AS_\MACRO\.
104 @ifset shortindexflag
105 @macro asindex{macro}
106 @MSindex \macro\
108 @end macro
109 @end ifset
110 @ifclear shortindexflag
111 @macro asindex{macro}
112 @MSindex AS_\macro\
113 @end macro
114 @end ifclear
116 @c @atindex{MACRO}
117 @c ---------------
118 @c Registering an AT_\MACRO\.
119 @ifset shortindexflag
120 @macro atindex{macro}
121 @ATindex \macro\
123 @end macro
124 @end ifset
125 @ifclear shortindexflag
126 @macro atindex{macro}
127 @ATindex AT_\macro\
128 @end macro
129 @end ifclear
131 @c @auindex{MACRO}
132 @c ---------------
133 @c Registering an AU_\MACRO\.
134 @macro auindex{macro}
135 @ACindex AU_\macro\
137 @end macro
139 @c @hdrindex{MACRO}
140 @c ----------------
141 @c Indexing a header.
142 @macro hdrindex{macro}
143 @prindex @file{\macro\}
145 @end macro
147 @c @msindex{MACRO}
148 @c ---------------
149 @c Registering an m4_\MACRO\.
150 @ifset shortindexflag
151 @macro msindex{macro}
152 @MSindex \macro\
154 @end macro
155 @end ifset
156 @ifclear shortindexflag
157 @macro msindex{macro}
158 @MSindex m4_\macro\
159 @end macro
160 @end ifclear
163 @c @caindex{VARIABLE}
164 @c ------------------
165 @c Registering an ac_cv_\VARIABLE\ cache variable.
166 @ifset shortindexflag
167 @macro caindex{macro}
168 @CAindex \macro\
169 @end macro
170 @end ifset
171 @ifclear shortindexflag
172 @macro caindex{macro}
173 @CAindex ac_cv_\macro\
174 @end macro
175 @end ifclear
177 @c Define an index for functions: `alloca' etc.  Used for the
178 @c portability sections and so on.  We can't use `fn' (aka `fnindex),
179 @c since `@defmac' goes into it => we'd get all the macros too.
181 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
183 @c   ! No room for a new @write .
184 @c   l.112 @defcodeindex fu
186 @c   so don't define yet another one :(  Just put some tags before each
187 @c   @prindex which is actually a @funindex.
189 @c   @defcodeindex fu
192 @c   @c Put the programs and functions into their own index.
193 @c   @syncodeindex fu pr
195 @comment %**end of header
196 @comment ========================================================
198 @copying
200 This manual (@value{UPDATED}) is for GNU Autoconf
201 (version @value{VERSION}),
202 a package for creating scripts to configure source code packages using
203 templates and an M4 macro package.
205 Copyright @copyright{} 1992-1996, 1998-2011 Free Software Foundation,
206 Inc.
208 @quotation
209 Permission is granted to copy, distribute and/or modify this document
210 under the terms of the GNU Free Documentation License,
211 Version 1.3 or any later version published by the Free Software
212 Foundation; with no Invariant Sections, with the Front-Cover texts
213 being ``A GNU Manual,'' and with the Back-Cover Texts as in
214 (a) below.  A copy of the license is included in the section entitled
215 ``GNU Free Documentation License.''
217 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
218 modify this GNU manual.  Buying copies from the FSF
219 supports it in developing GNU and promoting software
220 freedom.''
221 @end quotation
222 @end copying
226 @dircategory Software development
227 @direntry
228 * Autoconf: (autoconf).         Create source code configuration scripts.
229 @end direntry
231 @dircategory Individual utilities
232 @direntry
233 * autoscan: (autoconf)autoscan Invocation.
234                                 Semi-automatic @file{configure.ac} writing
235 * ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
236 * autoconf-invocation: (autoconf)autoconf Invocation.
237                                 How to create configuration scripts
238 * autoreconf: (autoconf)autoreconf Invocation.
239                                 Remaking multiple @command{configure} scripts
240 * autoheader: (autoconf)autoheader Invocation.
241                                 How to create configuration templates
242 * autom4te: (autoconf)autom4te Invocation.
243                                 The Autoconf executables backbone
244 * configure: (autoconf)configure Invocation.    Configuring a package.
245 * autoupdate: (autoconf)autoupdate Invocation.
246                                 Automatic update of @file{configure.ac}
247 * config.status: (autoconf)config.status Invocation. Recreating configurations.
248 * testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
249 @end direntry
251 @titlepage
252 @title Autoconf
253 @subtitle Creating Automatic Configuration Scripts
254 @subtitle for version @value{VERSION}, @value{UPDATED}
255 @author David MacKenzie
256 @author Ben Elliston
257 @author Akim Demaille
258 @page
259 @vskip 0pt plus 1filll
260 @insertcopying
261 @end titlepage
263 @contents
266 @ifnottex
267 @node Top
268 @top Autoconf
269 @insertcopying
270 @end ifnottex
272 @c The master menu, created with texinfo-master-menu, goes here.
274 @menu
275 * Introduction::                Autoconf's purpose, strengths, and weaknesses
276 * The GNU Build System::        A set of tools for portable software packages
277 * Making configure Scripts::    How to organize and produce Autoconf scripts
278 * Setup::                       Initialization and output
279 * Existing Tests::              Macros that check for particular features
280 * Writing Tests::               How to write new feature checks
281 * Results::                     What to do with results from feature checks
282 * Programming in M4::           Layers on top of which Autoconf is written
283 * Programming in M4sh::         Shell portability layer
284 * Writing Autoconf Macros::     Adding new macros to Autoconf
285 * Portable Shell::              Shell script portability pitfalls
286 * Portable Make::               Makefile portability pitfalls
287 * Portable C and C++::          C and C++ portability pitfalls
288 * Manual Configuration::        Selecting features that can't be guessed
289 * Site Configuration::          Local defaults for @command{configure}
290 * Running configure Scripts::   How to use the Autoconf output
291 * config.status Invocation::    Recreating a configuration
292 * Obsolete Constructs::         Kept for backward compatibility
293 * Using Autotest::              Creating portable test suites
294 * FAQ::                         Frequent Autoconf Questions, with answers
295 * History::                     History of Autoconf
296 * GNU Free Documentation License::  License for copying this manual
297 * Indices::                     Indices of symbols, concepts, etc.
299 @detailmenu
300  --- The Detailed Node Listing ---
302 The GNU Build System
304 * Automake::                    Escaping makefile hell
305 * Gnulib::                      The GNU portability library
306 * Libtool::                     Building libraries portably
307 * Pointers::                    More info on the GNU build system
309 Making @command{configure} Scripts
311 * Writing Autoconf Input::      What to put in an Autoconf input file
312 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
313 * ifnames Invocation::          Listing the conditionals in source code
314 * autoconf Invocation::         How to create configuration scripts
315 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
317 Writing @file{configure.ac}
319 * Shell Script Compiler::       Autoconf as solution of a problem
320 * Autoconf Language::           Programming in Autoconf
321 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
323 Initialization and Output Files
325 * Initializing configure::      Option processing etc.
326 * Versioning::                  Dealing with Autoconf versions
327 * Notices::                     Copyright, version numbers in @command{configure}
328 * Input::                       Where Autoconf should find files
329 * Output::                      Outputting results from the configuration
330 * Configuration Actions::       Preparing the output based on results
331 * Configuration Files::         Creating output files
332 * Makefile Substitutions::      Using output variables in makefiles
333 * Configuration Headers::       Creating a configuration header file
334 * Configuration Commands::      Running arbitrary instantiation commands
335 * Configuration Links::         Links depending on the configuration
336 * Subdirectories::              Configuring independent packages together
337 * Default Prefix::              Changing the default installation prefix
339 Substitutions in Makefiles
341 * Preset Output Variables::     Output variables that are always set
342 * Installation Directory Variables::  Other preset output variables
343 * Changed Directory Variables:: Warnings about @file{datarootdir}
344 * Build Directories::           Supporting multiple concurrent compiles
345 * Automatic Remaking::          Makefile rules for configuring
347 Configuration Header Files
349 * Header Templates::            Input for the configuration headers
350 * autoheader Invocation::       How to create configuration templates
351 * Autoheader Macros::           How to specify CPP templates
353 Existing Tests
355 * Common Behavior::             Macros' standard schemes
356 * Alternative Programs::        Selecting between alternative programs
357 * Files::                       Checking for the existence of files
358 * Libraries::                   Library archives that might be missing
359 * Library Functions::           C library functions that might be missing
360 * Header Files::                Header files that might be missing
361 * Declarations::                Declarations that may be missing
362 * Structures::                  Structures or members that might be missing
363 * Types::                       Types that might be missing
364 * Compilers and Preprocessors::  Checking for compiling programs
365 * System Services::             Operating system services
366 * Posix Variants::              Special kludges for specific Posix variants
367 * Erlang Libraries::            Checking for the existence of Erlang libraries
369 Common Behavior
371 * Standard Symbols::            Symbols defined by the macros
372 * Default Includes::            Includes used by the generic macros
374 Alternative Programs
376 * Particular Programs::         Special handling to find certain programs
377 * Generic Programs::            How to find other programs
379 Library Functions
381 * Function Portability::        Pitfalls with usual functions
382 * Particular Functions::        Special handling to find certain functions
383 * Generic Functions::           How to find other functions
385 Header Files
387 * Header Portability::          Collected knowledge on common headers
388 * Particular Headers::          Special handling to find certain headers
389 * Generic Headers::             How to find other headers
391 Declarations
393 * Particular Declarations::     Macros to check for certain declarations
394 * Generic Declarations::        How to find other declarations
396 Structures
398 * Particular Structures::       Macros to check for certain structure members
399 * Generic Structures::          How to find other structure members
401 Types
403 * Particular Types::            Special handling to find certain types
404 * Generic Types::               How to find other types
406 Compilers and Preprocessors
408 * Specific Compiler Characteristics::  Some portability issues
409 * Generic Compiler Characteristics::  Language independent tests and features
410 * C Compiler::                  Checking its characteristics
411 * C++ Compiler::                Likewise
412 * Objective C Compiler::        Likewise
413 * Objective C++ Compiler::      Likewise
414 * Erlang Compiler and Interpreter::  Likewise
415 * Fortran Compiler::            Likewise
417 Writing Tests
419 * Language Choice::             Selecting which language to use for testing
420 * Writing Test Programs::       Forging source files for compilers
421 * Running the Preprocessor::    Detecting preprocessor symbols
422 * Running the Compiler::        Detecting language or header features
423 * Running the Linker::          Detecting library features
424 * Runtime::                     Testing for runtime features
425 * Systemology::                 A zoology of operating systems
426 * Multiple Cases::              Tests for several possible values
428 Writing Test Programs
430 * Guidelines::                  General rules for writing test programs
431 * Test Functions::              Avoiding pitfalls in test programs
432 * Generating Sources::          Source program boilerplate
434 Results of Tests
436 * Defining Symbols::            Defining C preprocessor symbols
437 * Setting Output Variables::    Replacing variables in output files
438 * Special Chars in Variables::  Characters to beware of in variables
439 * Caching Results::             Speeding up subsequent @command{configure} runs
440 * Printing Messages::           Notifying @command{configure} users
442 Caching Results
444 * Cache Variable Names::        Shell variables used in caches
445 * Cache Files::                 Files @command{configure} uses for caching
446 * Cache Checkpointing::         Loading and saving the cache file
448 Programming in M4
450 * M4 Quotation::                Protecting macros from unwanted expansion
451 * Using autom4te::              The Autoconf executables backbone
452 * Programming in M4sugar::      Convenient pure M4 macros
453 * Debugging via autom4te::      Figuring out what M4 was doing
455 Programming in M4sh
457 * Common Shell Constructs::     Portability layer for common shell constructs
458 * Polymorphic Variables::       Support for indirect variable names
459 * Initialization Macros::       Macros to establish a sane shell environment
460 * File Descriptor Macros::      File descriptor macros for input and output
462 M4 Quotation
464 * Active Characters::           Characters that change the behavior of M4
465 * One Macro Call::              Quotation and one macro call
466 * Quoting and Parameters::      M4 vs. shell parameters
467 * Quotation and Nested Macros::  Macros calling macros
468 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
469 * Quadrigraphs::                Another way to escape special characters
470 * Balancing Parentheses::       Dealing with unbalanced parentheses
471 * Quotation Rule Of Thumb::     One parenthesis, one quote
473 Using @command{autom4te}
475 * autom4te Invocation::         A GNU M4 wrapper
476 * Customizing autom4te::        Customizing the Autoconf package
478 Programming in M4sugar
480 * Redefined M4 Macros::         M4 builtins changed in M4sugar
481 * Diagnostic Macros::           Diagnostic messages from M4sugar
482 * Diversion support::           Diversions in M4sugar
483 * Conditional constructs::      Conditions in M4
484 * Looping constructs::          Iteration in M4
485 * Evaluation Macros::           More quotation and evaluation control
486 * Text processing Macros::      String manipulation in M4
487 * Number processing Macros::    Arithmetic computation in M4
488 * Set manipulation Macros::     Set manipulation in M4
489 * Forbidden Patterns::          Catching unexpanded macros
491 Writing Autoconf Macros
493 * Macro Definitions::           Basic format of an Autoconf macro
494 * Macro Names::                 What to call your new macros
495 * Reporting Messages::          Notifying @command{autoconf} users
496 * Dependencies Between Macros::  What to do when macros depend on other macros
497 * Obsoleting Macros::           Warning about old ways of doing things
498 * Coding Style::                Writing Autoconf macros @`a la Autoconf
500 Dependencies Between Macros
502 * Prerequisite Macros::         Ensuring required information
503 * Suggested Ordering::          Warning about possible ordering problems
504 * One-Shot Macros::             Ensuring a macro is called only once
506 Portable Shell Programming
508 * Shellology::                  A zoology of shells
509 * Here-Documents::              Quirks and tricks
510 * File Descriptors::            FDs and redirections
511 * File System Conventions::     File names
512 * Shell Pattern Matching::      Pattern matching
513 * Shell Substitutions::         Variable and command expansions
514 * Assignments::                 Varying side effects of assignments
515 * Parentheses::                 Parentheses in shell scripts
516 * Slashes::                     Slashes in shell scripts
517 * Special Shell Variables::     Variables you should not change
518 * Shell Functions::             What to look out for if you use them
519 * Limitations of Builtins::     Portable use of not so portable /bin/sh
520 * Limitations of Usual Tools::  Portable use of portable tools
522 Portable Make Programming
524 * $< in Ordinary Make Rules::   $< in ordinary rules
525 * Failure in Make Rules::       Failing portably in rules
526 * Special Chars in Names::      Special Characters in Macro Names
527 * Backslash-Newline-Newline::   Empty last lines in macro definitions
528 * Backslash-Newline Comments::  Spanning comments across line boundaries
529 * Long Lines in Makefiles::     Line length limitations
530 * Macros and Submakes::         @code{make macro=value} and submakes
531 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
532 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
533 * Parallel Make::               Parallel @command{make} quirks
534 * Comments in Make Rules::      Other problems with Make comments
535 * Newlines in Make Rules::      Using literal newlines in rules
536 * obj/ and Make::               Don't name a subdirectory @file{obj}
537 * make -k Status::              Exit status of @samp{make -k}
538 * VPATH and Make::              @code{VPATH} woes
539 * Single Suffix Rules::         Single suffix rules and separated dependencies
540 * Timestamps and Make::         Subsecond timestamp resolution
542 @code{VPATH} and Make
544 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
545 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
546 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
547 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
548 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
549 * Make Target Lookup::          More details about @code{VPATH} lookup
551 Portable C and C++ Programming
553 * Varieties of Unportability::  How to make your programs unportable
554 * Integer Overflow::            When integers get too large
555 * Preprocessor Arithmetic::     @code{#if} expression problems
556 * Null Pointers::               Properties of null pointers
557 * Buffer Overruns::             Subscript errors and the like
558 * Volatile Objects::            @code{volatile} and signals
559 * Floating Point Portability::  Portable floating-point arithmetic
560 * Exiting Portably::            Exiting and the exit status
562 Manual Configuration
564 * Specifying Target Triplets::  Specifying target triplets
565 * Canonicalizing::              Getting the canonical system type
566 * Using System Type::           What to do with the system type
568 Site Configuration
570 * Help Formatting::             Customizing @samp{configure --help}
571 * External Software::           Working with other optional software
572 * Package Options::             Selecting optional features
573 * Pretty Help Strings::         Formatting help string
574 * Option Checking::             Controlling checking of @command{configure} options
575 * Site Details::                Configuring site details
576 * Transforming Names::          Changing program names when installing
577 * Site Defaults::               Giving @command{configure} local defaults
579 Transforming Program Names When Installing
581 * Transformation Options::      @command{configure} options to transform names
582 * Transformation Examples::     Sample uses of transforming names
583 * Transformation Rules::        Makefile uses of transforming names
585 Running @command{configure} Scripts
587 * Basic Installation::          Instructions for typical cases
588 * Compilers and Options::       Selecting compilers and optimization
589 * Multiple Architectures::      Compiling for multiple architectures at once
590 * Installation Names::          Installing in different directories
591 * Optional Features::           Selecting optional features
592 * Particular Systems::          Particular systems
593 * System Type::                 Specifying the system type
594 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
595 * Defining Variables::          Specifying the compiler etc.
596 * configure Invocation::        Changing how @command{configure} runs
598 Obsolete Constructs
600 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
601 * acconfig Header::             Additional entries in @file{config.h.in}
602 * autoupdate Invocation::       Automatic update of @file{configure.ac}
603 * Obsolete Macros::             Backward compatibility macros
604 * Autoconf 1::                  Tips for upgrading your files
605 * Autoconf 2.13::               Some fresher tips
607 Upgrading From Version 1
609 * Changed File Names::          Files you might rename
610 * Changed Makefiles::           New things to put in @file{Makefile.in}
611 * Changed Macros::              Macro calls you might replace
612 * Changed Results::             Changes in how to check test results
613 * Changed Macro Writing::       Better ways to write your own macros
615 Upgrading From Version 2.13
617 * Changed Quotation::           Broken code which used to work
618 * New Macros::                  Interaction with foreign macros
619 * Hosts and Cross-Compilation::  Bugward compatibility kludges
620 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
621 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
623 Generating Test Suites with Autotest
625 * Using an Autotest Test Suite::  Autotest and the user
626 * Writing Testsuites::          Autotest macros
627 * testsuite Invocation::        Running @command{testsuite} scripts
628 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
630 Using an Autotest Test Suite
632 * testsuite Scripts::           The concepts of Autotest
633 * Autotest Logs::               Their contents
635 Frequent Autoconf Questions, with answers
637 * Distributing::                Distributing @command{configure} scripts
638 * Why GNU M4::                  Why not use the standard M4?
639 * Bootstrapping::               Autoconf and GNU M4 require each other?
640 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
641 * Defining Directories::        Passing @code{datadir} to program
642 * Autom4te Cache::              What is it?  Can I remove it?
643 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
644 * Expanded Before Required::    Expanded Before Required
645 * Debugging::                   Debugging @command{configure} scripts
647 History of Autoconf
649 * Genesis::                     Prehistory and naming of @command{configure}
650 * Exodus::                      The plagues of M4 and Perl
651 * Leviticus::                   The priestly code of portability arrives
652 * Numbers::                     Growth and contributors
653 * Deuteronomy::                 Approaching the promises of easy configuration
655 Indices
657 * Environment Variable Index::  Index of environment variables used
658 * Output Variable Index::       Index of variables set in output files
659 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
660 * Cache Variable Index::        Index of documented cache variables
661 * Autoconf Macro Index::        Index of Autoconf macros
662 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
663 * Autotest Macro Index::        Index of Autotest macros
664 * Program & Function Index::    Index of those with portability problems
665 * Concept Index::               General index
667 @end detailmenu
668 @end menu
670 @c ============================================================= Introduction.
672 @node Introduction
673 @chapter Introduction
674 @cindex Introduction
676 @flushright
677 A physicist, an engineer, and a computer scientist were discussing the
678 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
679 early in the Creation, God made Light; and you know, Maxwell's
680 equations, the dual nature of electromagnetic waves, the relativistic
681 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
682 before making Light, God split the Chaos into Land and Water; it takes a
683 hell of an engineer to handle that big amount of mud, and orderly
684 separation of solids from liquids@enddots{}'' The computer scientist
685 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
687 ---Anonymous
688 @end flushright
689 @c (via Franc,ois Pinard)
691 Autoconf is a tool for producing shell scripts that automatically
692 configure software source code packages to adapt to many kinds of
693 Posix-like systems.  The configuration scripts produced by Autoconf
694 are independent of Autoconf when they are run, so their users do not
695 need to have Autoconf.
697 The configuration scripts produced by Autoconf require no manual user
698 intervention when run; they do not normally even need an argument
699 specifying the system type.  Instead, they individually test for the
700 presence of each feature that the software package they are for might need.
701 (Before each check, they print a one-line message stating what they are
702 checking for, so the user doesn't get too bored while waiting for the
703 script to finish.)  As a result, they deal well with systems that are
704 hybrids or customized from the more common Posix variants.  There is
705 no need to maintain files that list the features supported by each
706 release of each variant of Posix.
708 For each software package that Autoconf is used with, it creates a
709 configuration script from a template file that lists the system features
710 that the package needs or can use.  After the shell code to recognize
711 and respond to a system feature has been written, Autoconf allows it to
712 be shared by many software packages that can use (or need) that feature.
713 If it later turns out that the shell code needs adjustment for some
714 reason, it needs to be changed in only one place; all of the
715 configuration scripts can be regenerated automatically to take advantage
716 of the updated code.
718 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
719 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
720 Those who do not understand Autoconf are condemned to reinvent it, poorly.
721 The primary goal of Autoconf is making the @emph{user's} life easier;
722 making the @emph{maintainer's} life easier is only a secondary goal.
723 Put another way, the primary goal is not to make the generation of
724 @file{configure} automatic for package maintainers (although patches
725 along that front are welcome, since package maintainers form the user
726 base of Autoconf); rather, the goal is to make @file{configure}
727 painless, portable, and predictable for the end user of each
728 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
729 successful at its goal --- most complaints to the Autoconf list are
730 about difficulties in writing Autoconf input, and not in the behavior of
731 the resulting @file{configure}.  Even packages that don't use Autoconf
732 will generally provide a @file{configure} script, and the most common
733 complaint about these alternative home-grown scripts is that they fail
734 to meet one or more of the GNU Coding Standars (@pxref{Configuration, , ,
735 standards, The GNU Coding Standards}) that users
736 have come to expect from Autoconf-generated @file{configure} scripts.
738 The Metaconfig package is similar in purpose to Autoconf, but the
739 scripts it produces require manual user intervention, which is quite
740 inconvenient when configuring large source trees.  Unlike Metaconfig
741 scripts, Autoconf scripts can support cross-compiling, if some care is
742 taken in writing them.
744 Autoconf does not solve all problems related to making portable
745 software packages---for a more complete solution, it should be used in
746 concert with other GNU build tools like Automake and
747 Libtool.  These other tools take on jobs like the creation of a
748 portable, recursive makefile with all of the standard targets,
749 linking of shared libraries, and so on.  @xref{The GNU Build System},
750 for more information.
752 Autoconf imposes some restrictions on the names of macros used with
753 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
755 Autoconf requires GNU M4 version 1.4.6 or later in order to
756 generate the scripts.  It uses features that some versions of M4,
757 including GNU M4 1.3, do not have.  Autoconf works better
758 with GNU M4 version 1.4.14 or later, though this is not
759 required.
761 @xref{Autoconf 1}, for information about upgrading from version 1.
762 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
763 for answers to some common questions about Autoconf.
765 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
766 Autoconf web page} for up-to-date information, details on the mailing
767 lists, pointers to a list of known bugs, etc.
769 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
770 list}.  Past suggestions are
771 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
773 Mail bug reports to @email{bug-autoconf@@gnu.org, the
774 Autoconf Bugs mailing list}.  Past bug reports are
775 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
777 If possible, first check that your bug is
778 not already solved in current development versions, and that it has not
779 been reported yet.  Be sure to include all the needed information and a
780 short @file{configure.ac} that demonstrates the problem.
782 Autoconf's development tree is accessible via @command{git}; see the
783 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
784 Summary} for details, or view
785 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
786 repository}.  Anonymous CVS access is also available, see
787 @file{README} for more details.  Patches relative to the
788 current @command{git} version can be sent for review to the
789 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
790 discussion on prior patches
791 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
792 archived}; and all commits are posted in the read-only
793 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
794 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
795 archived}.
797 Because of its mission, the Autoconf package itself
798 includes only a set of often-used
799 macros that have already demonstrated their usefulness.  Nevertheless,
800 if you wish to share your macros, or find existing ones, see the
801 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
802 Archive}, which is kindly run by @email{simons@@cryp.to,
803 Peter Simons}.
806 @c ================================================= The GNU Build System
808 @node The GNU Build System
809 @chapter The GNU Build System
810 @cindex GNU build system
812 Autoconf solves an important problem---reliable discovery of
813 system-specific build and runtime information---but this is only one
814 piece of the puzzle for the development of portable software.  To this
815 end, the GNU project has developed a suite of integrated
816 utilities to finish the job Autoconf started: the GNU build
817 system, whose most important components are Autoconf, Automake, and
818 Libtool.  In this chapter, we introduce you to those tools, point you
819 to sources of more information, and try to convince you to use the
820 entire GNU build system for your software.
822 @menu
823 * Automake::                    Escaping makefile hell
824 * Gnulib::                      The GNU portability library
825 * Libtool::                     Building libraries portably
826 * Pointers::                    More info on the GNU build system
827 @end menu
829 @node Automake
830 @section Automake
832 The ubiquity of @command{make} means that a makefile is almost the
833 only viable way to distribute automatic build rules for software, but
834 one quickly runs into its numerous limitations.  Its lack of
835 support for automatic dependency tracking, recursive builds in
836 subdirectories, reliable timestamps (e.g., for network file systems), and
837 so on, mean that developers must painfully (and often incorrectly)
838 reinvent the wheel for each project.  Portability is non-trivial, thanks
839 to the quirks of @command{make} on many systems.  On top of all this is the
840 manual labor required to implement the many standard targets that users
841 have come to expect (@code{make install}, @code{make distclean},
842 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
843 you also have to insert repetitive code in your @file{Makefile.in} to
844 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
845 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
846 @cindex Automake
848 Automake allows you to specify your build needs in a @file{Makefile.am}
849 file with a vastly simpler and more powerful syntax than that of a plain
850 makefile, and then generates a portable @file{Makefile.in} for
851 use with Autoconf.  For example, the @file{Makefile.am} to build and
852 install a simple ``Hello world'' program might look like:
854 @example
855 bin_PROGRAMS = hello
856 hello_SOURCES = hello.c
857 @end example
859 @noindent
860 The resulting @file{Makefile.in} (~400 lines) automatically supports all
861 the standard targets, the substitutions provided by Autoconf, automatic
862 dependency tracking, @code{VPATH} building, and so on.  @command{make}
863 builds the @code{hello} program, and @code{make install} installs it
864 in @file{/usr/local/bin} (or whatever prefix was given to
865 @command{configure}, if not @file{/usr/local}).
867 The benefits of Automake increase for larger packages (especially ones
868 with subdirectories), but even for small programs the added convenience
869 and portability can be substantial.  And that's not all@enddots{}
871 @node Gnulib
872 @section Gnulib
874 GNU software has a well-deserved reputation for running on
875 many different types of systems.  While our primary goal is to write
876 software for the GNU system, many users and developers have
877 been introduced to us through the systems that they were already using.
879 @cindex Gnulib
880 Gnulib is a central location for common GNU code, intended to
881 be shared among free software packages.  Its components are typically
882 shared at the source level, rather than being a library that gets built,
883 installed, and linked against.  The idea is to copy files from Gnulib
884 into your own source tree.  There is no distribution tarball; developers
885 should just grab source modules from the repository.  The source files
886 are available online, under various licenses, mostly GNU
887 GPL or GNU LGPL.
889 Gnulib modules typically contain C source code along with Autoconf
890 macros used to configure the source code.  For example, the Gnulib
891 @code{stdbool} module implements a @file{stdbool.h} header that nearly
892 conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
893 This module contains a source file for the replacement header, along
894 with an Autoconf macro that arranges to use the replacement header on
895 old-fashioned systems.
897 @node Libtool
898 @section Libtool
900 Often, one wants to build not only programs, but libraries, so that
901 other programs can benefit from the fruits of your labor.  Ideally, one
902 would like to produce @emph{shared} (dynamically linked) libraries,
903 which can be used by multiple programs without duplication on disk or in
904 memory and can be updated independently of the linked programs.
905 Producing shared libraries portably, however, is the stuff of
906 nightmares---each system has its own incompatible tools, compiler flags,
907 and magic incantations.  Fortunately, GNU provides a solution:
908 @dfn{Libtool}.
909 @cindex Libtool
911 Libtool handles all the requirements of building shared libraries for
912 you, and at this time seems to be the @emph{only} way to do so with any
913 portability.  It also handles many other headaches, such as: the
914 interaction of Make rules with the variable suffixes of
915 shared libraries, linking reliably with shared libraries before they are
916 installed by the superuser, and supplying a consistent versioning system
917 (so that different versions of a library can be installed or upgraded
918 without breaking binary compatibility).  Although Libtool, like
919 Autoconf, can be used without Automake, it is most simply utilized in
920 conjunction with Automake---there, Libtool is used automatically
921 whenever shared libraries are needed, and you need not know its syntax.
923 @node Pointers
924 @section Pointers
926 Developers who are used to the simplicity of @command{make} for small
927 projects on a single system might be daunted at the prospect of
928 learning to use Automake and Autoconf.  As your software is
929 distributed to more and more users, however, you otherwise
930 quickly find yourself putting lots of effort into reinventing the
931 services that the GNU build tools provide, and making the
932 same mistakes that they once made and overcame.  (Besides, since
933 you're already learning Autoconf, Automake is a piece of cake.)
935 There are a number of places that you can go to for more information on
936 the GNU build tools.
938 @itemize @minus
940 @item Web
942 The project home pages for
943 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
944 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
945 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
946 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
948 @item Automake Manual
950 @xref{Top, , Automake, automake, GNU Automake}, for more
951 information on Automake.
953 @item Books
955 The book @cite{GNU Autoconf, Automake and
956 Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
957 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
958 New Riders), 2000, ISBN 1578701902.} describes the complete GNU
959 build environment.  You can also find
960 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
962 @end itemize
964 @c ================================================= Making configure Scripts.
966 @node Making configure Scripts
967 @chapter Making @command{configure} Scripts
968 @cindex @file{aclocal.m4}
969 @cindex @command{configure}
971 The configuration scripts that Autoconf produces are by convention
972 called @command{configure}.  When run, @command{configure} creates several
973 files, replacing configuration parameters in them with appropriate
974 values.  The files that @command{configure} creates are:
976 @itemize @minus
977 @item
978 one or more @file{Makefile} files, usually one in each subdirectory of the
979 package (@pxref{Makefile Substitutions});
981 @item
982 optionally, a C header file, the name of which is configurable,
983 containing @code{#define} directives (@pxref{Configuration Headers});
985 @item
986 a shell script called @file{config.status} that, when run, recreates
987 the files listed above (@pxref{config.status Invocation});
989 @item
990 an optional shell script normally called @file{config.cache}
991 (created when using @samp{configure --config-cache}) that
992 saves the results of running many of the tests (@pxref{Cache Files});
994 @item
995 a file called @file{config.log} containing any messages produced by
996 compilers, to help debugging if @command{configure} makes a mistake.
997 @end itemize
999 @cindex @file{configure.in}
1000 @cindex @file{configure.ac}
1001 To create a @command{configure} script with Autoconf, you need to write an
1002 Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
1003 @command{autoconf} on it.  If you write your own feature tests to
1004 supplement those that come with Autoconf, you might also write files
1005 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
1006 file to contain @code{#define} directives, you might also run
1007 @command{autoheader}, and you can distribute the generated file
1008 @file{config.h.in} with the package.
1010 Here is a diagram showing how the files that can be used in
1011 configuration are produced.  Programs that are executed are suffixed by
1012 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
1013 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1014 macro files (by reading @file{autoconf.m4}).
1016 @noindent
1017 Files used in preparing a software package for distribution, when using
1018 just Autoconf:
1019 @example
1020 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1022 @group
1023 configure.ac --.
1024                |   .------> autoconf* -----> configure
1025 [aclocal.m4] --+---+
1026                |   `-----> [autoheader*] --> [config.h.in]
1027 [acsite.m4] ---'
1028 @end group
1030 Makefile.in
1031 @end example
1033 @noindent
1034 Additionally, if you use Automake, the following additional productions
1035 come into play:
1037 @example
1038 @group
1039 [acinclude.m4] --.
1040                  |
1041 [local macros] --+--> aclocal* --> aclocal.m4
1042                  |
1043 configure.ac ----'
1044 @end group
1046 @group
1047 configure.ac --.
1048                +--> automake* --> Makefile.in
1049 Makefile.am ---'
1050 @end group
1051 @end example
1053 @noindent
1054 Files used in configuring a software package:
1055 @example
1056 @group
1057                        .-------------> [config.cache]
1058 configure* ------------+-------------> config.log
1059                        |
1060 [config.h.in] -.       v            .-> [config.h] -.
1061                +--> config.status* -+               +--> make*
1062 Makefile.in ---'                    `-> Makefile ---'
1063 @end group
1064 @end example
1066 @menu
1067 * Writing Autoconf Input::      What to put in an Autoconf input file
1068 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1069 * ifnames Invocation::          Listing the conditionals in source code
1070 * autoconf Invocation::         How to create configuration scripts
1071 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1072 @end menu
1074 @node Writing Autoconf Input
1075 @section Writing @file{configure.ac}
1077 To produce a @command{configure} script for a software package, create a
1078 file called @file{configure.ac} that contains invocations of the
1079 Autoconf macros that test the system features your package needs or can
1080 use.  Autoconf macros already exist to check for many features; see
1081 @ref{Existing Tests}, for their descriptions.  For most other features,
1082 you can use Autoconf template macros to produce custom checks; see
1083 @ref{Writing Tests}, for information about them.  For especially tricky
1084 or specialized features, @file{configure.ac} might need to contain some
1085 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1086 Programming}.  The @command{autoscan} program can give you a good start
1087 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1088 information).
1090 Previous versions of Autoconf promoted the name @file{configure.in},
1091 which is somewhat ambiguous (the tool needed to process this file is not
1092 described by its extension), and introduces a slight confusion with
1093 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1094 processed by @command{configure}'').  Using @file{configure.ac} is now
1095 preferred.
1097 @menu
1098 * Shell Script Compiler::       Autoconf as solution of a problem
1099 * Autoconf Language::           Programming in Autoconf
1100 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1101 @end menu
1103 @node Shell Script Compiler
1104 @subsection A Shell Script Compiler
1106 Just as for any other computer language, in order to properly program
1107 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1108 the language tries to address and @emph{how} it does so.
1110 The problem Autoconf addresses is that the world is a mess.  After all,
1111 you are using Autoconf in order to have your package compile easily on
1112 all sorts of different systems, some of them being extremely hostile.
1113 Autoconf itself bears the price for these differences: @command{configure}
1114 must run on all those systems, and thus @command{configure} must limit itself
1115 to their lowest common denominator of features.
1117 Naturally, you might then think of shell scripts; who needs
1118 @command{autoconf}?  A set of properly written shell functions is enough to
1119 make it easy to write @command{configure} scripts by hand.  Sigh!
1120 Unfortunately, even in 2008, where shells without any function support are
1121 far and few between, there are pitfalls to avoid when making use of them.
1122 Also, finding a Bourne shell that accepts shell functions is not trivial,
1123 even though there is almost always one on interesting porting targets.
1125 So, what is really needed is some kind of compiler, @command{autoconf},
1126 that takes an Autoconf program, @file{configure.ac}, and transforms it
1127 into a portable shell script, @command{configure}.
1129 How does @command{autoconf} perform this task?
1131 There are two obvious possibilities: creating a brand new language or
1132 extending an existing one.  The former option is attractive: all
1133 sorts of optimizations could easily be implemented in the compiler and
1134 many rigorous checks could be performed on the Autoconf program
1135 (e.g., rejecting any non-portable construct).  Alternatively, you can
1136 extend an existing language, such as the @code{sh} (Bourne shell)
1137 language.
1139 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1140 therefore most convenient to implement @command{autoconf} as a macro
1141 expander: a program that repeatedly performs @dfn{macro expansions} on
1142 text input, replacing macro calls with macro bodies and producing a pure
1143 @code{sh} script in the end.  Instead of implementing a dedicated
1144 Autoconf macro expander, it is natural to use an existing
1145 general-purpose macro language, such as M4, and implement the extensions
1146 as a set of M4 macros.
1149 @node Autoconf Language
1150 @subsection The Autoconf Language
1151 @cindex quotation
1153 The Autoconf language differs from many other computer
1154 languages because it treats actual code the same as plain text.  Whereas
1155 in C, for instance, data and instructions have different syntactic
1156 status, in Autoconf their status is rigorously the same.  Therefore, we
1157 need a means to distinguish literal strings from text to be expanded:
1158 quotation.
1160 When calling macros that take arguments, there must not be any white
1161 space between the macro name and the open parenthesis.
1163 @example
1164 AC_INIT ([oops], [1.0]) # incorrect
1165 AC_INIT([hello], [1.0]) # good
1166 @end example
1168 Arguments should
1169 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1170 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1171 unless they are quoted.  You should always quote an argument that
1172 might contain a macro name, comma, parenthesis, or a leading blank or
1173 newline.  This rule applies recursively for every macro
1174 call, including macros called from other macros.  For more details on
1175 quoting rules, see @ref{Programming in M4}.
1177 For instance:
1179 @example
1180 AC_CHECK_HEADER([stdio.h],
1181                 [AC_DEFINE([HAVE_STDIO_H], [1],
1182                    [Define to 1 if you have <stdio.h>.])],
1183                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1184 @end example
1186 @noindent
1187 is quoted properly.  You may safely simplify its quotation to:
1189 @example
1190 AC_CHECK_HEADER([stdio.h],
1191                 [AC_DEFINE([HAVE_STDIO_H], 1,
1192                    [Define to 1 if you have <stdio.h>.])],
1193                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1194 @end example
1196 @noindent
1197 because @samp{1} cannot contain a macro call.  Here, the argument of
1198 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1199 interpreted as an argument separator.  Also, the second and third arguments
1200 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1201 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1202 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1203 if you unwisely defined a macro with a name like @samp{Define} or
1204 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1205 would keep the quotes, but many Autoconf users find such precautions
1206 annoying, and would rewrite the example as follows:
1208 @example
1209 AC_CHECK_HEADER(stdio.h,
1210                 [AC_DEFINE(HAVE_STDIO_H, 1,
1211                    [Define to 1 if you have <stdio.h>.])],
1212                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1213 @end example
1215 @noindent
1216 This is safe, so long as you adopt good naming conventions and do not
1217 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1218 @samp{h}.  Though it is also safe here to omit the quotes around
1219 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1220 message strings are more likely to inadvertently contain commas.
1222 The following example is wrong and dangerous, as it is underquoted:
1224 @example
1225 AC_CHECK_HEADER(stdio.h,
1226                 AC_DEFINE(HAVE_STDIO_H, 1,
1227                    Define to 1 if you have <stdio.h>.),
1228                 AC_MSG_ERROR([sorry, can't do anything for you]))
1229 @end example
1231 In other cases, you may have to use text that also resembles a macro
1232 call.  You must quote that text even when it is not passed as a macro
1233 argument.  For example, these two approaches in @file{configure.ac}
1234 (quoting just the potential problems, or quoting the entire line) will
1235 protect your script in case autoconf ever adds a macro @code{AC_DC}:
1237 @example
1238 echo "Hard rock was here!  --[AC_DC]"
1239 [echo "Hard rock was here!  --AC_DC"]
1240 @end example
1242 @noindent
1243 which results in this text in @file{configure}:
1245 @example
1246 echo "Hard rock was here!  --AC_DC"
1247 echo "Hard rock was here!  --AC_DC"
1248 @end example
1250 @noindent
1251 When you use the same text in a macro argument, you must therefore have
1252 an extra quotation level (since one is stripped away by the macro
1253 substitution).  In general, then, it is a good idea to @emph{use double
1254 quoting for all literal string arguments}, either around just the
1255 problematic portions, or over the entire argument:
1257 @example
1258 AC_MSG_WARN([[AC_DC] stinks  --Iron Maiden])
1259 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1260 @end example
1262 However, the above example triggers a warning about a possibly
1263 unexpanded macro when running @command{autoconf}, because it collides
1264 with the namespace of macros reserved for the Autoconf language.  To be
1265 really safe, you can use additional escaping (either a quadrigraph, or
1266 creative shell constructs) to silence that particular warning:
1268 @example
1269 echo "Hard rock was here!  --AC""_DC"
1270 AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1271 @end example
1273 You are now able to understand one of the constructs of Autoconf that
1274 has been continually misunderstood@enddots{}  The rule of thumb is that
1275 @emph{whenever you expect macro expansion, expect quote expansion};
1276 i.e., expect one level of quotes to be lost.  For instance:
1278 @example
1279 AC_COMPILE_IFELSE([char b[10];], [], [AC_MSG_ERROR([you lose])])
1280 @end example
1282 @noindent
1283 is incorrect: here, the first argument of @code{AC_COMPILE_IFELSE} is
1284 @samp{char b[10];} and is expanded once, which results in
1285 @samp{char b10;}.  (There was an idiom common in Autoconf's past to
1286 address this issue via the M4 @code{changequote} primitive, but do not
1287 use it!)  Let's take a closer look: the author meant the first argument
1288 to be understood as a literal, and therefore it must be quoted twice:
1290 @example
1291 AC_COMPILE_IFELSE([[char b[10];]], [], [AC_MSG_ERROR([you lose])])
1292 @end example
1294 @noindent
1295 Voil@`a, you actually produce @samp{char b[10];} this time!
1297 On the other hand, descriptions (e.g., the last parameter of
1298 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1299 are subject to line breaking, for example---and should not be double quoted.
1300 Even if these descriptions are short and are not actually broken, double
1301 quoting them yields weird results.
1303 Some macros take optional arguments, which this documentation represents
1304 as @ovar{arg} (not to be confused with the quote characters).  You may
1305 just leave them empty, or use @samp{[]} to make the emptiness of the
1306 argument explicit, or you may simply omit the trailing commas.  The
1307 three lines below are equivalent:
1309 @example
1310 AC_CHECK_HEADERS([stdio.h], [], [], [])
1311 AC_CHECK_HEADERS([stdio.h],,,)
1312 AC_CHECK_HEADERS([stdio.h])
1313 @end example
1315 It is best to put each macro call on its own line in
1316 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1317 rely on the newline after the macro call to terminate the commands.
1318 This approach makes the generated @command{configure} script a little
1319 easier to read by not inserting lots of blank lines.  It is generally
1320 safe to set shell variables on the same line as a macro call, because
1321 the shell allows assignments without intervening newlines.
1323 You can include comments in @file{configure.ac} files by starting them
1324 with the @samp{#}.  For example, it is helpful to begin
1325 @file{configure.ac} files with a line like this:
1327 @example
1328 # Process this file with autoconf to produce a configure script.
1329 @end example
1331 @node Autoconf Input Layout
1332 @subsection Standard @file{configure.ac} Layout
1334 The order in which @file{configure.ac} calls the Autoconf macros is not
1335 important, with a few exceptions.  Every @file{configure.ac} must
1336 contain a call to @code{AC_INIT} before the checks, and a call to
1337 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1338 rely on other macros having been called first, because they check
1339 previously set values of some variables to decide what to do.  These
1340 macros are noted in the individual descriptions (@pxref{Existing
1341 Tests}), and they also warn you when @command{configure} is created if they
1342 are called out of order.
1344 To encourage consistency, here is a suggested order for calling the
1345 Autoconf macros.  Generally speaking, the things near the end of this
1346 list are those that could depend on things earlier in it.  For example,
1347 library functions could be affected by types and libraries.
1349 @display
1350 @group
1351 Autoconf requirements
1352 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1353 information on the package
1354 checks for programs
1355 checks for libraries
1356 checks for header files
1357 checks for types
1358 checks for structures
1359 checks for compiler characteristics
1360 checks for library functions
1361 checks for system services
1362 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1363 @code{AC_OUTPUT}
1364 @end group
1365 @end display
1368 @node autoscan Invocation
1369 @section Using @command{autoscan} to Create @file{configure.ac}
1370 @cindex @command{autoscan}
1372 The @command{autoscan} program can help you create and/or maintain a
1373 @file{configure.ac} file for a software package.  @command{autoscan}
1374 examines source files in the directory tree rooted at a directory given
1375 as a command line argument, or the current directory if none is given.
1376 It searches the source files for common portability problems and creates
1377 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1378 for that package, and checks a possibly existing @file{configure.ac} for
1379 completeness.
1381 When using @command{autoscan} to create a @file{configure.ac}, you
1382 should manually examine @file{configure.scan} before renaming it to
1383 @file{configure.ac}; it probably needs some adjustments.
1384 Occasionally, @command{autoscan} outputs a macro in the wrong order
1385 relative to another macro, so that @command{autoconf} produces a warning;
1386 you need to move such macros manually.  Also, if you want the package to
1387 use a configuration header file, you must add a call to
1388 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1389 also have to change or add some @code{#if} directives to your program in
1390 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1391 information about a program that can help with that job).
1393 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1394 consider adding its suggestions.  The file @file{autoscan.log}
1395 contains detailed information on why a macro is requested.
1397 @command{autoscan} uses several data files (installed along with Autoconf)
1398 to determine which macros to output when it finds particular symbols in
1399 a package's source files.  These data files all have the same format:
1400 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1401 output if that symbol is encountered.  Lines starting with @samp{#} are
1402 comments.
1404 @command{autoscan} accepts the following options:
1406 @table @option
1407 @item --help
1408 @itemx -h
1409 Print a summary of the command line options and exit.
1411 @item --version
1412 @itemx -V
1413 Print the version number of Autoconf and exit.
1415 @item --verbose
1416 @itemx -v
1417 Print the names of the files it examines and the potentially interesting
1418 symbols it finds in them.  This output can be voluminous.
1420 @item --debug
1421 @itemx -d
1422 Don't remove temporary files.
1424 @item --include=@var{dir}
1425 @itemx -I @var{dir}
1426 Append @var{dir} to the include path.  Multiple invocations accumulate.
1428 @item --prepend-include=@var{dir}
1429 @itemx -B @var{dir}
1430 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1431 @end table
1433 @node ifnames Invocation
1434 @section Using @command{ifnames} to List Conditionals
1435 @cindex @command{ifnames}
1437 @command{ifnames} can help you write @file{configure.ac} for a software
1438 package.  It prints the identifiers that the package already uses in C
1439 preprocessor conditionals.  If a package has already been set up to have
1440 some portability, @command{ifnames} can thus help you figure out what its
1441 @command{configure} needs to check for.  It may help fill in some gaps in a
1442 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1443 Invocation}).
1445 @command{ifnames} scans all of the C source files named on the command line
1446 (or the standard input, if none are given) and writes to the standard
1447 output a sorted list of all the identifiers that appear in those files
1448 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1449 directives.  It prints each identifier on a line, followed by a
1450 space-separated list of the files in which that identifier occurs.
1452 @noindent
1453 @command{ifnames} accepts the following options:
1455 @table @option
1456 @item --help
1457 @itemx -h
1458 Print a summary of the command line options and exit.
1460 @item --version
1461 @itemx -V
1462 Print the version number of Autoconf and exit.
1463 @end table
1465 @node autoconf Invocation
1466 @section Using @command{autoconf} to Create @command{configure}
1467 @cindex @command{autoconf}
1469 To create @command{configure} from @file{configure.ac}, run the
1470 @command{autoconf} program with no arguments.  @command{autoconf} processes
1471 @file{configure.ac} with the M4 macro processor, using the
1472 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1473 file instead of @file{configure.ac} and writes the configuration script
1474 to the standard output instead of to @command{configure}.  If you give
1475 @command{autoconf} the argument @option{-}, it reads from the standard
1476 input instead of @file{configure.ac} and writes the configuration script
1477 to the standard output.
1479 The Autoconf macros are defined in several files.  Some of the files are
1480 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1481 looks for the optional file @file{acsite.m4} in the directory that
1482 contains the distributed Autoconf macro files, and for the optional file
1483 @file{aclocal.m4} in the current directory.  Those files can contain
1484 your site's or the package's own Autoconf macro definitions
1485 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1486 defined in more than one of the files that @command{autoconf} reads, the
1487 last definition it reads overrides the earlier ones.
1489 @command{autoconf} accepts the following options:
1491 @table @option
1492 @item --help
1493 @itemx -h
1494 Print a summary of the command line options and exit.
1496 @item --version
1497 @itemx -V
1498 Print the version number of Autoconf and exit.
1500 @item --verbose
1501 @itemx -v
1502 Report processing steps.
1504 @item --debug
1505 @itemx -d
1506 Don't remove the temporary files.
1508 @item --force
1509 @itemx -f
1510 Remake @file{configure} even if newer than its input files.
1512 @item --include=@var{dir}
1513 @itemx -I @var{dir}
1514 Append @var{dir} to the include path.  Multiple invocations accumulate.
1516 @item --prepend-include=@var{dir}
1517 @itemx -B @var{dir}
1518 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1520 @item --output=@var{file}
1521 @itemx -o @var{file}
1522 Save output (script or trace) to @var{file}.  The file @option{-} stands
1523 for the standard output.
1525 @item --warnings=@var{category}
1526 @itemx -W @var{category}
1527 @evindex WARNINGS
1528 Report the warnings related to @var{category} (which can actually be a
1529 comma separated list).  @xref{Reporting Messages}, macro
1530 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1531 values include:
1533 @table @samp
1534 @item all
1535 report all the warnings
1537 @item none
1538 report none
1540 @item error
1541 treats warnings as errors
1543 @item no-@var{category}
1544 disable warnings falling into @var{category}
1545 @end table
1547 Warnings about @samp{syntax} are enabled by default, and the environment
1548 variable @env{WARNINGS}, a comma separated list of categories, is
1549 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1550 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1551 disable the defaults and @env{WARNINGS}, and then
1552 enable warnings about obsolete constructs, use @option{-W
1553 none,obsolete}.
1555 @cindex Back trace
1556 @cindex Macro invocation stack
1557 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1558 displays a back trace for errors, but not for warnings; if you want
1559 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1560 examples.
1562 @item --trace=@var{macro}[:@var{format}]
1563 @itemx -t @var{macro}[:@var{format}]
1564 Do not create the @command{configure} script, but list the calls to
1565 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1566 arguments can be used to list several macros.  Multiple @option{--trace}
1567 arguments for a single macro are not cumulative; instead, you should
1568 just make @var{format} as long as needed.
1570 The @var{format} is a regular string, with newlines if desired, and
1571 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1572 @ref{autom4te Invocation}, for details on the @var{format}.
1574 @item --initialization
1575 @itemx -i
1576 By default, @option{--trace} does not trace the initialization of the
1577 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1578 results in a noticeable speedup, but can be disabled by this option.
1579 @end table
1582 It is often necessary to check the content of a @file{configure.ac}
1583 file, but parsing it yourself is extremely fragile and error-prone.  It
1584 is suggested that you rely upon @option{--trace} to scan
1585 @file{configure.ac}.  For instance, to find the list of variables that
1586 are substituted, use:
1588 @example
1589 @group
1590 $ @kbd{autoconf -t AC_SUBST}
1591 configure.ac:2:AC_SUBST:ECHO_C
1592 configure.ac:2:AC_SUBST:ECHO_N
1593 configure.ac:2:AC_SUBST:ECHO_T
1594 @i{More traces deleted}
1595 @end group
1596 @end example
1598 @noindent
1599 The example below highlights the difference between @samp{$@@},
1600 @samp{$*}, and @samp{$%}.
1602 @example
1603 @group
1604 $ @kbd{cat configure.ac}
1605 AC_DEFINE(This, is, [an
1606 [example]])
1607 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1608 *: $*
1609 %: $%'
1610 @@: [This],[is],[an
1611 [example]]
1612 *: This,is,an
1613 [example]
1614 %: This:is:an [example]
1615 @end group
1616 @end example
1618 @noindent
1619 The @var{format} gives you a lot of freedom:
1621 @example
1622 @group
1623 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1624 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1625 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1626 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1627 @i{More traces deleted}
1628 @end group
1629 @end example
1631 @noindent
1632 A long @var{separator} can be used to improve the readability of complex
1633 structures, and to ease their parsing (for instance when no single
1634 character is suitable as a separator):
1636 @example
1637 @group
1638 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1639 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1640 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1641 AUTOMAKE|:::::|automake|:::::|$missing_dir
1642 @i{More traces deleted}
1643 @end group
1644 @end example
1646 @node autoreconf Invocation
1647 @section Using @command{autoreconf} to Update @command{configure} Scripts
1648 @cindex @command{autoreconf}
1650 Installing the various components of the GNU Build System can be
1651 tedious: running @command{autopoint} for Gettext, @command{automake} for
1652 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1653 because some tools such as @command{automake} have been updated on your
1654 system, or because some of the sources such as @file{configure.ac} have
1655 been updated, or finally, simply in order to install the GNU Build
1656 System in a fresh tree.
1658 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1659 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1660 @command{autopoint} (when appropriate) repeatedly to update the
1661 GNU Build System in the specified directories and their
1662 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1663 those files that are older than their sources.  The environment variables
1664 @env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE},
1665 @env{ACLOCAL}, @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE}
1666 may be used to override the invocation of the respective tools.
1668 If you install a new version of some tool, you can make
1669 @command{autoreconf} remake @emph{all} of the files by giving it the
1670 @option{--force} option.
1672 @xref{Automatic Remaking}, for Make rules to automatically
1673 rebuild @command{configure} scripts when their source files change.  That
1674 method handles the timestamps of configuration header templates
1675 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1676 @option{--localdir=@var{dir}}.
1678 @cindex Gettext
1679 @cindex @command{autopoint}
1680 Gettext supplies the @command{autopoint} command to add translation
1681 infrastructure to a source package.  If you use @command{autopoint},
1682 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1683 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1684 Invocation, , Invoking the @code{autopoint} Program, gettext,
1685 GNU @code{gettext} utilities}, for further details.
1687 @noindent
1688 @command{autoreconf} accepts the following options:
1690 @table @option
1691 @item --help
1692 @itemx -h
1693 Print a summary of the command line options and exit.
1695 @item --version
1696 @itemx -V
1697 Print the version number of Autoconf and exit.
1699 @item --verbose
1700 @itemx -V
1701 Print the name of each directory @command{autoreconf} examines and the
1702 commands it runs.  If given two or more times, pass @option{--verbose}
1703 to subordinate tools that support it.
1705 @item --debug
1706 @itemx -d
1707 Don't remove the temporary files.
1709 @item --force
1710 @itemx -f
1711 Remake even @file{configure} scripts and configuration headers that are
1712 newer than their input files (@file{configure.ac} and, if present,
1713 @file{aclocal.m4}).
1715 @item --install
1716 @itemx -i
1717 Install the missing auxiliary files in the package.  By default, files
1718 are copied; this can be changed with @option{--symlink}.
1720 If deemed appropriate, this option triggers calls to
1721 @samp{automake --add-missing},
1722 @samp{libtoolize}, @samp{autopoint}, etc.
1724 @item --no-recursive
1725 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1726 macro @code{AC_CONFIG_SUBDIRS}).
1728 @item --symlink
1729 @itemx -s
1730 When used with @option{--install}, install symbolic links to the missing
1731 auxiliary files instead of copying them.
1733 @item --make
1734 @itemx -m
1735 When the directories were configured, update the configuration by
1736 running @samp{./config.status --recheck && ./config.status}, and then
1737 run @samp{make}.
1739 @item --include=@var{dir}
1740 @itemx -I @var{dir}
1741 Append @var{dir} to the include path.  Multiple invocations accumulate.
1742 Passed on to @command{aclocal}, @command{autoconf} and
1743 @command{autoheader} internally.
1745 @item --prepend-include=@var{dir}
1746 @itemx -B @var{dir}
1747 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1748 Passed on to @command{autoconf} and @command{autoheader} internally.
1750 @item --warnings=@var{category}
1751 @itemx -W @var{category}
1752 @evindex WARNINGS
1753 Report the warnings related to @var{category} (which can actually be a
1754 comma separated list).
1756 @table @samp
1757 @item cross
1758 related to cross compilation issues.
1760 @item obsolete
1761 report the uses of obsolete constructs.
1763 @item portability
1764 portability issues
1766 @item syntax
1767 dubious syntactic constructs.
1769 @item all
1770 report all the warnings
1772 @item none
1773 report none
1775 @item error
1776 treats warnings as errors
1778 @item no-@var{category}
1779 disable warnings falling into @var{category}
1780 @end table
1782 Warnings about @samp{syntax} are enabled by default, and the environment
1783 variable @env{WARNINGS}, a comma separated list of categories, is
1784 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1785 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1786 disable the defaults and @env{WARNINGS}, and then
1787 enable warnings about obsolete constructs, use @option{-W
1788 none,obsolete}.
1789 @end table
1791 If you want @command{autoreconf} to pass flags that are not listed here
1792 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1793 Due to a limitation in the Autoconf implementation these flags currently
1794 must be set on a single line in @file{Makefile.am}, without any
1795 backslash-newlines.
1797 @c ========================================= Initialization and Output Files.
1799 @node Setup
1800 @chapter Initialization and Output Files
1802 Autoconf-generated @command{configure} scripts need some information about
1803 how to initialize, such as how to find the package's source files and
1804 about the output files to produce.  The following sections describe the
1805 initialization and the creation of output files.
1807 @menu
1808 * Initializing configure::      Option processing etc.
1809 * Versioning::                  Dealing with Autoconf versions
1810 * Notices::                     Copyright, version numbers in @command{configure}
1811 * Input::                       Where Autoconf should find files
1812 * Output::                      Outputting results from the configuration
1813 * Configuration Actions::       Preparing the output based on results
1814 * Configuration Files::         Creating output files
1815 * Makefile Substitutions::      Using output variables in makefiles
1816 * Configuration Headers::       Creating a configuration header file
1817 * Configuration Commands::      Running arbitrary instantiation commands
1818 * Configuration Links::         Links depending on the configuration
1819 * Subdirectories::              Configuring independent packages together
1820 * Default Prefix::              Changing the default installation prefix
1821 @end menu
1823 @node Initializing configure
1824 @section Initializing @command{configure}
1826 Every @command{configure} script must call @code{AC_INIT} before doing
1827 anything else that produces output.  Calls to silent macros, such as
1828 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1829 are generally used via @file{aclocal.m4}, since that is implicitly
1830 included before the start of @file{configure.ac}.  The only other
1831 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1833 @anchor{AC_INIT}
1834 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1835   @ovar{tarname}, @ovar{url})
1836 @acindex{INIT}
1837 Process any command-line arguments and perform various initializations
1838 and verifications.
1840 Set the name of the @var{package} and its @var{version}.  These are
1841 typically used in @option{--version} support, including that of
1842 @command{configure}.  The optional argument @var{bug-report} should be
1843 the email to which users should send bug reports.  The package
1844 @var{tarname} differs from @var{package}: the latter designates the full
1845 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1846 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1847 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1848 other than alphanumerics and underscores are changed to @samp{-}.  If
1849 provided, @var{url} should be the home page for the package.
1851 The arguments of @code{AC_INIT} must be static, i.e., there should not
1852 be any shell computation, quotes, or newlines, but they can be computed
1853 by M4.  This is because the package information strings are expanded at
1854 M4 time into several contexts, and must give the same text at shell time
1855 whether used in single-quoted strings, double-quoted strings, quoted
1856 here-documents, or unquoted here-documents.  It is permissible to use
1857 @code{m4_esyscmd} or @code{m4_esyscmd_s} for computing a version string
1858 that changes with every commit to a version control system (in fact,
1859 Autoconf does just that, for all builds of the development tree made
1860 between releases).
1862 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1863 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1864 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1866 @table @asis
1867 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1868 @acindex{PACKAGE_NAME}
1869 @ovindex PACKAGE_NAME
1870 @cvindex PACKAGE_NAME
1871 Exactly @var{package}.
1873 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1874 @acindex{PACKAGE_TARNAME}
1875 @ovindex PACKAGE_TARNAME
1876 @cvindex PACKAGE_TARNAME
1877 Exactly @var{tarname}, possibly generated from @var{package}.
1879 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1880 @acindex{PACKAGE_VERSION}
1881 @ovindex PACKAGE_VERSION
1882 @cvindex PACKAGE_VERSION
1883 Exactly @var{version}.
1885 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1886 @acindex{PACKAGE_STRING}
1887 @ovindex PACKAGE_STRING
1888 @cvindex PACKAGE_STRING
1889 Exactly @samp{@var{package} @var{version}}.
1891 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1892 @acindex{PACKAGE_BUGREPORT}
1893 @ovindex PACKAGE_BUGREPORT
1894 @cvindex PACKAGE_BUGREPORT
1895 Exactly @var{bug-report}, if one was provided.  Typically an email
1896 address, or URL to a bug management web page.
1898 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1899 @acindex{PACKAGE_URL}
1900 @ovindex PACKAGE_URL
1901 @cvindex PACKAGE_URL
1902 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1903 @var{package} begins with @samp{GNU }, then this defaults to
1904 @samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1905 assumed.
1906 @end table
1907 @end defmac
1909 If your @command{configure} script does its own option processing, it
1910 should inspect @samp{$@@} or @samp{$*} immediately after calling
1911 @code{AC_INIT}, because other Autoconf macros liberally use the
1912 @command{set} command to process strings, and this has the side effect
1913 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1914 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1915 implement your own option processing.  @xref{Site Configuration}.
1917 @node Versioning
1918 @section Dealing with Autoconf versions
1919 @cindex Autoconf version
1920 @cindex version, Autoconf
1922 The following optional macros can be used to help choose the minimum
1923 version of Autoconf that can successfully compile a given
1924 @file{configure.ac}.
1926 @defmac AC_PREREQ (@var{version})
1927 @acindex{PREREQ}
1928 @cindex Version
1929 Ensure that a recent enough version of Autoconf is being used.  If the
1930 version of Autoconf being used to create @command{configure} is
1931 earlier than @var{version}, print an error message to the standard
1932 error output and exit with failure (exit status is 63).  For example:
1934 @example
1935 AC_PREREQ([@value{VERSION}])
1936 @end example
1938 This macro may be used before @code{AC_INIT}.
1939 @end defmac
1941 @defmac AC_AUTOCONF_VERSION
1942 @acindex{AUTOCONF_VERSION}
1943 This macro was introduced in Autoconf 2.62.  It identifies the version
1944 of Autoconf that is currently parsing the input file, in a format
1945 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1946 other words, for this release of Autoconf, its value is
1947 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1948 conditional fallbacks based on when a feature was added to Autoconf,
1949 rather than using @code{AC_PREREQ} to require the newer version of
1950 Autoconf.  However, remember that the Autoconf philosophy favors feature
1951 checks over version checks.
1953 You should not expand this macro directly; use
1954 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1955 users might
1956 have a beta version of Autoconf installed, with arbitrary letters
1957 included in its version string.  This means it is possible for the
1958 version string to contain the name of a defined macro, such that
1959 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1960 macro during rescanning, and change the version string to be different
1961 than what you intended to check.
1962 @end defmac
1964 @node Notices
1965 @section Notices in @command{configure}
1966 @cindex Notices in @command{configure}
1968 The following macros manage version numbers for @command{configure}
1969 scripts.  Using them is optional.
1971 @defmac AC_COPYRIGHT (@var{copyright-notice})
1972 @acindex{COPYRIGHT}
1973 @cindex Copyright Notice
1974 State that, in addition to the Free Software Foundation's copyright on
1975 the Autoconf macros, parts of your @command{configure} are covered by the
1976 @var{copyright-notice}.
1978 The @var{copyright-notice} shows up in both the head of
1979 @command{configure} and in @samp{configure --version}.
1980 @end defmac
1983 @defmac AC_REVISION (@var{revision-info})
1984 @acindex{REVISION}
1985 @cindex Revision
1986 Copy revision stamp @var{revision-info} into the @command{configure}
1987 script, with any dollar signs or double-quotes removed.  This macro lets
1988 you put a revision stamp from @file{configure.ac} into @command{configure}
1989 without RCS or CVS changing it when you check in
1990 @command{configure}.  That way, you can determine easily which revision of
1991 @file{configure.ac} a particular @command{configure} corresponds to.
1993 For example, this line in @file{configure.ac}:
1995 @c The @w prevents RCS from changing the example in the manual.
1996 @example
1997 AC_REVISION([@w{$}Revision: 1.30 $])
1998 @end example
2000 @noindent
2001 produces this in @command{configure}:
2003 @example
2004 #!/bin/sh
2005 # From configure.ac Revision: 1.30
2006 @end example
2007 @end defmac
2010 @node Input
2011 @section Finding @command{configure} Input
2013 @anchor{AC_CONFIG_SRCDIR}
2014 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2015 @acindex{CONFIG_SRCDIR}
2016 @var{unique-file-in-source-dir} is some file that is in the package's
2017 source directory; @command{configure} checks for this file's existence to
2018 make sure that the directory that it is told contains the source code in
2019 fact does.  Occasionally people accidentally specify the wrong directory
2020 with @option{--srcdir}; this is a safety check.  @xref{configure
2021 Invocation}, for more information.
2022 @end defmac
2025 @c FIXME: Remove definitively once --install explained.
2027 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
2028 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
2029 @c to split the macros in several files.  In this case, Autoconf must be
2030 @c told which files to load, and in which order.
2032 @c @defmac AC_INCLUDE (@var{file}@dots{})
2033 @c @acindex{INCLUDE}
2034 @c @c FIXME: There is no longer shell globbing.
2035 @c Read the macro definitions that appear in the listed files.  A list of
2036 @c space-separated file names or shell globbing patterns is expected.  The
2037 @c files are read in the order they're listed.
2039 @c Because the order of definition of macros is important (only the last
2040 @c definition of a macro is used), beware that it is @code{AC_INIT} that
2041 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
2042 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
2043 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
2044 @c the latter case, non-macro lines from included files may end up in the
2045 @c @file{configure} script, whereas in the former case, they'd be discarded
2046 @c just like any text that appear before @code{AC_INIT}.
2047 @c @end defmac
2049 Packages that do manual configuration or use the @command{install} program
2050 might need to tell @command{configure} where to find some other shell
2051 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
2052 it looks are correct for most cases.
2054 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2055 @acindex{CONFIG_AUX_DIR}
2056 Use the auxiliary build tools (e.g., @file{install-sh},
2057 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
2058 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
2059 These are auxiliary files used in configuration.  @var{dir} can be
2060 either absolute or relative to @file{@var{srcdir}}.  The default is
2061 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
2062 @file{@var{srcdir}/../..}, whichever is the first that contains
2063 @file{install-sh}.  The other files are not checked for, so that using
2064 @code{AC_PROG_INSTALL} does not automatically require distributing the
2065 other auxiliary files.  It checks for @file{install.sh} also, but that
2066 name is obsolete because some @command{make} have a rule that creates
2067 @file{install} from it if there is no makefile.
2069 The auxiliary directory is commonly named @file{build-aux}.
2070 If you need portability to DOS variants, do not name the
2071 auxiliary directory @file{aux}.  @xref{File System Conventions}.
2072 @end defmac
2074 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2075 @acindex{REQUIRE_AUX_FILE}
2076 Declares that @var{file} is expected in the directory defined above.  In
2077 Autoconf proper, this macro does nothing: its sole purpose is to be
2078 traced by third-party tools to produce a list of expected auxiliary
2079 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
2080 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2081 (@pxref{Canonicalizing}) to register the auxiliary files they need.
2082 @end defmac
2084 Similarly, packages that use @command{aclocal} should declare where
2085 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
2087 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
2088 @acindex{CONFIG_MACRO_DIR}
2089 Specify @var{dir} as the location of additional local Autoconf macros.
2090 This macro is intended for use by future versions of commands like
2091 @command{autoreconf} that trace macro calls.  It should be called
2092 directly from @file{configure.ac} so that tools that install macros for
2093 @command{aclocal} can find the macros' declarations.
2095 Note that if you use @command{aclocal} from Automake to generate
2096 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
2097 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
2098 the Autoconf implementation of @command{autoreconf}, these include
2099 directives currently must be set on a single line in @file{Makefile.am},
2100 without any backslash-newlines.
2101 @end defmac
2104 @node Output
2105 @section Outputting Files
2106 @cindex Outputting files
2108 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2109 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2110 @file{config.status}, which in turn creates the makefiles and any
2111 other files resulting from configuration.  This is the only required
2112 macro besides @code{AC_INIT} (@pxref{Input}).
2114 @anchor{AC_OUTPUT}
2115 @defmac AC_OUTPUT
2116 @acindex{OUTPUT}
2117 @cindex Instantiation
2118 Generate @file{config.status} and launch it.  Call this macro once, at
2119 the end of @file{configure.ac}.
2121 @file{config.status} performs all the configuration actions: all the
2122 output files (see @ref{Configuration Files}, macro
2123 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2124 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2125 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2126 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2127 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2128 are honored.
2130 The location of your @code{AC_OUTPUT} invocation is the exact point
2131 where configuration actions are taken: any code afterwards is
2132 executed by @command{configure} once @command{config.status} was run.  If
2133 you want to bind actions to @command{config.status} itself
2134 (independently of whether @command{configure} is being run), see
2135 @ref{Configuration Commands, , Running Arbitrary Configuration
2136 Commands}.
2137 @end defmac
2139 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2140 @xref{Obsolete Macros}, for a description of the arguments that
2141 @code{AC_OUTPUT} used to support.
2144 If you run @command{make} in subdirectories, you should run it using the
2145 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2146 @code{MAKE} to the name of the @command{make} program plus any options it
2147 was given.  (But many do not include in it the values of any variables
2148 set on the command line, so those are not passed on automatically.)
2149 Some old versions of @command{make} do not set this variable.  The
2150 following macro allows you to use it even with those versions.
2152 @anchor{AC_PROG_MAKE_SET}
2153 @defmac AC_PROG_MAKE_SET
2154 @acindex{PROG_MAKE_SET}
2155 @ovindex SET_MAKE
2156 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2157 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2158 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2159 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2160 @code{SET_MAKE}.
2161 @end defmac
2163 If you use this macro, place a line like this in each @file{Makefile.in}
2164 that runs @command{MAKE} on other directories:
2166 @example
2167 @@SET_MAKE@@
2168 @end example
2172 @node Configuration Actions
2173 @section Performing Configuration Actions
2174 @cindex Configuration actions
2176 @file{configure} is designed so that it appears to do everything itself,
2177 but there is actually a hidden slave: @file{config.status}.
2178 @file{configure} is in charge of examining your system, but it is
2179 @file{config.status} that actually takes the proper actions based on the
2180 results of @file{configure}.  The most typical task of
2181 @file{config.status} is to @emph{instantiate} files.
2183 @acindex{CONFIG_@var{ITEMS}}
2184 This section describes the common behavior of the four standard
2185 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2186 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2187 have this prototype:
2189 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2190 @c awful.
2191 @example
2192 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2193 @end example
2195 @noindent
2196 where the arguments are:
2198 @table @var
2199 @item tag@dots{}
2200 A blank-or-newline-separated list of tags, which are typically the names of
2201 the files to instantiate.
2203 You are encouraged to use literals as @var{tags}.  In particular, you
2204 should avoid
2206 @example
2207 @dots{} && my_foos="$my_foos fooo"
2208 @dots{} && my_foos="$my_foos foooo"
2209 AC_CONFIG_@var{ITEMS}([$my_foos])
2210 @end example
2212 @noindent
2213 and use this instead:
2215 @example
2216 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2217 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2218 @end example
2220 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2221 special @var{tag} values: they may have the form @samp{@var{output}} or
2222 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2223 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2225 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2226 for example, asks for
2227 the creation of the file @file{Makefile} that contains the expansion of the
2228 output variables in the concatenation of @file{boiler/top.mk} and
2229 @file{boiler/bot.mk}.
2231 The special value @samp{-} might be used to denote the standard output
2232 when used in @var{output}, or the standard input when used in the
2233 @var{inputs}.  You most probably don't need to use this in
2234 @file{configure.ac}, but it is convenient when using the command line
2235 interface of @file{./config.status}, see @ref{config.status Invocation},
2236 for more details.
2238 The @var{inputs} may be absolute or relative file names.  In the latter
2239 case they are first looked for in the build tree, and then in the source
2240 tree.  Input files should be text files, and a line length below 2000
2241 bytes should be safe.
2243 @item commands
2244 Shell commands output literally into @file{config.status}, and
2245 associated with a tag that the user can use to tell @file{config.status}
2246 which commands to run.  The commands are run each time a @var{tag}
2247 request is given to @file{config.status}, typically each time the file
2248 @file{@var{tag}} is created.
2250 The variables set during the execution of @command{configure} are
2251 @emph{not} available here: you first need to set them via the
2252 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2254 @table @code
2255 @item srcdir
2256 @vrindex srcdir
2257 The name of the top source directory, assuming that the working
2258 directory is the top build directory.  This
2259 is what the @command{configure} option @option{--srcdir} sets.
2261 @item ac_top_srcdir
2262 @vrindex ac_top_srcdir
2263 The name of the top source directory, assuming that the working
2264 directory is the current build directory.
2266 @item ac_top_build_prefix
2267 @vrindex ac_top_build_prefix
2268 The name of the top build directory, assuming that the working
2269 directory is the current build directory.
2270 It can be empty, or else ends with a slash, so that you may concatenate
2273 @item ac_srcdir
2274 @vrindex ac_srcdir
2275 The name of the corresponding source directory, assuming that the
2276 working directory is the current build directory.
2278 @item tmp
2279 @vrindex tmp
2280 The name of a temporary directory within the build tree, which you
2281 can use if you need to create additional temporary files.  The
2282 directory is cleaned up when @command{config.status} is done or
2283 interrupted.  Please use package-specific file name prefixes to
2284 avoid clashing with files that @command{config.status} may use
2285 internally.
2286 @end table
2288 @noindent
2289 The @dfn{current} directory refers to the directory (or
2290 pseudo-directory) containing the input part of @var{tags}.  For
2291 instance, running
2293 @example
2294 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2295 @end example
2297 @noindent
2298  with @option{--srcdir=../package} produces the following values:
2300 @example
2301 # Argument of --srcdir
2302 srcdir='../package'
2303 # Reversing deep/dir
2304 ac_top_build_prefix='../../'
2305 # Concatenation of $ac_top_build_prefix and srcdir
2306 ac_top_srcdir='../../../package'
2307 # Concatenation of $ac_top_srcdir and deep/dir
2308 ac_srcdir='../../../package/deep/dir'
2309 @end example
2311 @noindent
2312 independently of @samp{in/in.in}.
2314 @item init-cmds
2315 Shell commands output @emph{unquoted} near the beginning of
2316 @file{config.status}, and executed each time @file{config.status} runs
2317 (regardless of the tag).  Because they are unquoted, for example,
2318 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2319 is typically used by @file{configure} to give @file{config.status} some
2320 variables it needs to run the @var{commands}.
2322 You should be extremely cautious in your variable names: all the
2323 @var{init-cmds} share the same name space and may overwrite each other
2324 in unpredictable ways.  Sorry@enddots{}
2325 @end table
2327 All these macros can be called multiple times, with different
2328 @var{tag} values, of course!
2331 @node Configuration Files
2332 @section Creating Configuration Files
2333 @cindex Creating configuration files
2334 @cindex Configuration file creation
2336 Be sure to read the previous section, @ref{Configuration Actions}.
2338 @anchor{AC_CONFIG_FILES}
2339 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2340 @acindex{CONFIG_FILES}
2341 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2342 file (by default @file{@var{file}.in}), substituting the output variable
2343 values.
2344 @c Before we used to have this feature, which was later rejected
2345 @c because it complicates the writing of makefiles:
2346 @c If the file would be unchanged, it is left untouched, to preserve
2347 @c timestamp.
2348 This macro is one of the instantiating macros; see @ref{Configuration
2349 Actions}.  @xref{Makefile Substitutions}, for more information on using
2350 output variables.  @xref{Setting Output Variables}, for more information
2351 on creating them.  This macro creates the directory that the file is in
2352 if it doesn't exist.  Usually, makefiles are created this way,
2353 but other files, such as @file{.gdbinit}, can be specified as well.
2355 Typical calls to @code{AC_CONFIG_FILES} look like this:
2357 @example
2358 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2359 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2360 @end example
2362 You can override an input file name by appending to @var{file} a
2363 colon-separated list of input files.  Examples:
2365 @example
2366 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2367                 [lib/Makefile:boiler/lib.mk])
2368 @end example
2370 @noindent
2371 Doing this allows you to keep your file names acceptable to
2372 DOS variants, or
2373 to prepend and/or append boilerplate to the file.
2374 @end defmac
2378 @node Makefile Substitutions
2379 @section Substitutions in Makefiles
2380 @cindex Substitutions in makefiles
2381 @cindex Makefile substitutions
2383 Each subdirectory in a distribution that contains something to be
2384 compiled or installed should come with a file @file{Makefile.in}, from
2385 which @command{configure} creates a file @file{Makefile} in that directory.
2386 To create @file{Makefile}, @command{configure} performs a simple variable
2387 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2388 @file{Makefile.in} with the value that @command{configure} has determined
2389 for that variable.  Variables that are substituted into output files in
2390 this way are called @dfn{output variables}.  They are ordinary shell
2391 variables that are set in @command{configure}.  To make @command{configure}
2392 substitute a particular variable into the output files, the macro
2393 @code{AC_SUBST} must be called with that variable name as an argument.
2394 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2395 left unchanged.  @xref{Setting Output Variables}, for more information
2396 on creating output variables with @code{AC_SUBST}.
2398 A software package that uses a @command{configure} script should be
2399 distributed with a file @file{Makefile.in}, but no makefile; that
2400 way, the user has to properly configure the package for the local system
2401 before compiling it.
2403 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2404 GNU Coding Standards}, for more information on what to put in
2405 makefiles.
2407 @menu
2408 * Preset Output Variables::     Output variables that are always set
2409 * Installation Directory Variables::  Other preset output variables
2410 * Changed Directory Variables:: Warnings about @file{datarootdir}
2411 * Build Directories::           Supporting multiple concurrent compiles
2412 * Automatic Remaking::          Makefile rules for configuring
2413 @end menu
2415 @node Preset Output Variables
2416 @subsection Preset Output Variables
2417 @cindex Output variables
2419 Some output variables are preset by the Autoconf macros.  Some of the
2420 Autoconf macros set additional output variables, which are mentioned in
2421 the descriptions for those macros.  @xref{Output Variable Index}, for a
2422 complete list of output variables.  @xref{Installation Directory
2423 Variables}, for the list of the preset ones related to installation
2424 directories.  Below are listed the other preset ones, many of which are
2425 precious variables (@pxref{Setting Output Variables},
2426 @code{AC_ARG_VAR}).
2428 The preset variables which are available during @file{config.status}
2429 (@pxref{Configuration Actions}) may also be used during
2430 @command{configure} tests.  For example, it is permissible to reference
2431 @samp{$srcdir} when constructing a list of directories to pass via
2432 option @option{-I} during a compiler feature check.  When used in this
2433 manner, coupled with the fact that @command{configure} is always run
2434 from the top build directory, it is sufficient to use just
2435 @samp{$srcdir} instead of @samp{$top_srcdir}.
2437 @c Just say no to ASCII sorting!  We're humans, not computers.
2438 @c These variables are listed as they would be in a dictionary:
2439 @c actor
2440 @c Actress
2441 @c actress
2443 @defvar CFLAGS
2444 @evindex CFLAGS
2445 @ovindex CFLAGS
2446 Debugging and optimization options for the C compiler.  If it is not set
2447 in the environment when @command{configure} runs, the default value is set
2448 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2449 uses this variable when compiling or linking programs to test for C features.
2451 If a compiler option affects only the behavior of the preprocessor
2452 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2453 instead.  If it affects only the linker (e.g., @option{-L@var{directory}}),
2454 it should be put into @code{LDFLAGS} instead.  If it
2455 affects only the compiler proper, @code{CFLAGS} is the natural home for
2456 it.  If an option affects multiple phases of the compiler, though,
2457 matters get tricky.  One approach to put such options directly into
2458 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2459 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2461 However, remember that some @file{Makefile} variables are reserved by
2462 the GNU Coding Standards for the use of the ``user''---the person
2463 building the package.  For instance, @code{CFLAGS} is one such variable.
2465 Sometimes package developers are tempted to set user variables such as
2466 @code{CFLAGS} because it appears to make their job easier.  However, the
2467 package itself should never set a user variable, particularly not to
2468 include switches that are required for proper compilation of the
2469 package.  Since these variables are documented as being for the package
2470 builder, that person rightfully expects to be able to override any of
2471 these variables at build time.  If the package developer needs to add
2472 switches without interfering with the user, the proper way to do that is
2473 to introduce an additional variable.  Automake makes this easy by
2474 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2475 automake, GNU Automake}), but the concept is the same even if
2476 Automake is not used.
2477 @end defvar
2479 @defvar configure_input
2480 @ovindex configure_input
2481 A comment saying that the file was generated automatically by
2482 @command{configure} and giving the name of the input file.
2483 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2484 of every makefile it creates.  For other files, you should
2485 reference this variable in a comment at the top of each input file.  For
2486 example, an input shell script should begin like this:
2488 @example
2489 #!/bin/sh
2490 # @@configure_input@@
2491 @end example
2493 @noindent
2494 The presence of that line also reminds people editing the file that it
2495 needs to be processed by @command{configure} in order to be used.
2496 @end defvar
2498 @defvar CPPFLAGS
2499 @evindex CPPFLAGS
2500 @ovindex CPPFLAGS
2501 Preprocessor options for the C, C++, Objective C, and Objective C++
2502 preprocessors and compilers.  If
2503 it is not set in the environment when @command{configure} runs, the default
2504 value is empty.  @command{configure} uses this variable when preprocessing
2505 or compiling programs to test for C, C++, Objective C, and Objective C++
2506 features.
2508 This variable's contents should contain options like @option{-I},
2509 @option{-D}, and @option{-U} that affect only the behavior of the
2510 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2511 can do if an option affects other phases of the compiler as well.
2513 Currently, @command{configure} always links as part of a single
2514 invocation of the compiler that also preprocesses and compiles, so it
2515 uses this variable also when linking programs.  However, it is unwise to
2516 depend on this behavior because the GNU Coding Standards do
2517 not require it and many packages do not use @code{CPPFLAGS} when linking
2518 programs.
2520 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2521 might run into.
2522 @end defvar
2524 @defvar CXXFLAGS
2525 @evindex CXXFLAGS
2526 @ovindex CXXFLAGS
2527 Debugging and optimization options for the C++ compiler.  It acts like
2528 @code{CFLAGS}, but for C++ instead of C.
2529 @end defvar
2531 @defvar DEFS
2532 @ovindex DEFS
2533 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2534 is called, @command{configure} replaces @samp{@@DEFS@@} with
2535 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2536 variable is not defined while @command{configure} is performing its tests,
2537 only when creating the output files.  @xref{Setting Output Variables}, for
2538 how to check the results of previous tests.
2539 @end defvar
2541 @defvar ECHO_C
2542 @defvarx ECHO_N
2543 @defvarx ECHO_T
2544 @ovindex ECHO_C
2545 @ovindex ECHO_N
2546 @ovindex ECHO_T
2547 How does one suppress the trailing newline from @command{echo} for
2548 question-answer message pairs?  These variables provide a way:
2550 @example
2551 echo $ECHO_N "And the winner is... $ECHO_C"
2552 sleep 100000000000
2553 echo "$@{ECHO_T@}dead."
2554 @end example
2556 @noindent
2557 Some old and uncommon @command{echo} implementations offer no means to
2558 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2559 want to use it.
2560 @end defvar
2562 @defvar ERLCFLAGS
2563 @evindex ERLCFLAGS
2564 @ovindex ERLCFLAGS
2565 Debugging and optimization options for the Erlang compiler.  If it is not set
2566 in the environment when @command{configure} runs, the default value is empty.
2567 @command{configure} uses this variable when compiling
2568 programs to test for Erlang features.
2569 @end defvar
2571 @defvar FCFLAGS
2572 @evindex FCFLAGS
2573 @ovindex FCFLAGS
2574 Debugging and optimization options for the Fortran compiler.  If it
2575 is not set in the environment when @command{configure} runs, the default
2576 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2577 @command{configure} uses this variable when compiling or linking
2578 programs to test for Fortran features.
2579 @end defvar
2581 @defvar FFLAGS
2582 @evindex FFLAGS
2583 @ovindex FFLAGS
2584 Debugging and optimization options for the Fortran 77 compiler.  If it
2585 is not set in the environment when @command{configure} runs, the default
2586 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2587 @command{configure} uses this variable when compiling or linking
2588 programs to test for Fortran 77 features.
2589 @end defvar
2591 @defvar LDFLAGS
2592 @evindex LDFLAGS
2593 @ovindex LDFLAGS
2594 Options for the linker.  If it is not set
2595 in the environment when @command{configure} runs, the default value is empty.
2596 @command{configure} uses this variable when linking programs to test for
2597 C, C++, Objective C, Objective C++, and Fortran features.
2599 This variable's contents should contain options like @option{-s} and
2600 @option{-L} that affect only the behavior of the linker.  Please see the
2601 explanation of @code{CFLAGS} for what you can do if an option also
2602 affects other phases of the compiler.
2604 Don't use this variable to pass library names
2605 (@option{-l}) to the linker; use @code{LIBS} instead.
2606 @end defvar
2608 @defvar LIBS
2609 @evindex LIBS
2610 @ovindex LIBS
2611 @option{-l} options to pass to the linker.  The default value is empty,
2612 but some Autoconf macros may prepend extra libraries to this variable if
2613 those libraries are found and provide necessary functions, see
2614 @ref{Libraries}.  @command{configure} uses this variable when linking
2615 programs to test for C, C++, Objective C, Objective C++, and Fortran
2616 features.
2617 @end defvar
2619 @defvar OBJCFLAGS
2620 @evindex OBJCFLAGS
2621 @ovindex OBJCFLAGS
2622 Debugging and optimization options for the Objective C compiler.  It
2623 acts like @code{CFLAGS}, but for Objective C instead of C.
2624 @end defvar
2626 @defvar OBJCXXFLAGS
2627 @evindex OBJCXXFLAGS
2628 @ovindex OBJCXXFLAGS
2629 Debugging and optimization options for the Objective C++ compiler.  It
2630 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2631 @end defvar
2633 @defvar builddir
2634 @ovindex builddir
2635 Rigorously equal to @samp{.}.  Added for symmetry only.
2636 @end defvar
2638 @defvar abs_builddir
2639 @ovindex abs_builddir
2640 Absolute name of @code{builddir}.
2641 @end defvar
2643 @defvar top_builddir
2644 @ovindex top_builddir
2645 The relative name of the top level of the current build tree.  In the
2646 top-level directory, this is the same as @code{builddir}.
2647 @end defvar
2649 @defvar top_build_prefix
2650 @ovindex top_build_prefix
2651 The relative name of the top level of the current build tree with final
2652 slash if nonemtpy.  This is the same as @code{top_builddir}, except that
2653 it contains zero or more runs of @code{../}, so it should not be
2654 appended with a slash for concatenation.  This helps for @command{make}
2655 implementations that otherwise do not treat @file{./file} and @file{file}
2656 as equal in the toplevel build directory.
2657 @end defvar
2659 @defvar abs_top_builddir
2660 @ovindex abs_top_builddir
2661 Absolute name of @code{top_builddir}.
2662 @end defvar
2664 @defvar srcdir
2665 @ovindex srcdir
2666 The name of the directory that contains the source code for
2667 that makefile.
2668 @end defvar
2670 @defvar abs_srcdir
2671 @ovindex abs_srcdir
2672 Absolute name of @code{srcdir}.
2673 @end defvar
2675 @defvar top_srcdir
2676 @ovindex top_srcdir
2677 The name of the top-level source code directory for the
2678 package.  In the top-level directory, this is the same as @code{srcdir}.
2679 @end defvar
2681 @defvar abs_top_srcdir
2682 @ovindex abs_top_srcdir
2683 Absolute name of @code{top_srcdir}.
2684 @end defvar
2686 @node Installation Directory Variables
2687 @subsection Installation Directory Variables
2688 @cindex Installation directories
2689 @cindex Directories, installation
2691 The following variables specify the directories for
2692 package installation, see @ref{Directory Variables, , Variables for
2693 Installation Directories, standards, The GNU Coding
2694 Standards}, for more information.  Each variable corresponds to an
2695 argument of @command{configure}; trailing slashes are stripped so that
2696 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2697 between directory names.  See the end of this section for
2698 details on when and how to use these variables.
2700 @defvar bindir
2701 @ovindex bindir
2702 The directory for installing executables that users run.
2703 @end defvar
2705 @defvar datadir
2706 @ovindex datadir
2707 The directory for installing idiosyncratic read-only
2708 architecture-independent data.
2709 @end defvar
2711 @defvar datarootdir
2712 @ovindex datarootdir
2713 The root of the directory tree for read-only architecture-independent
2714 data files.
2715 @end defvar
2717 @defvar docdir
2718 @ovindex docdir
2719 The directory for installing documentation files (other than Info and
2720 man).
2721 @end defvar
2723 @defvar dvidir
2724 @ovindex dvidir
2725 The directory for installing documentation files in DVI format.
2726 @end defvar
2728 @defvar exec_prefix
2729 @ovindex exec_prefix
2730 The installation prefix for architecture-dependent files.  By default
2731 it's the same as @code{prefix}.  You should avoid installing anything
2732 directly to @code{exec_prefix}.  However, the default value for
2733 directories containing architecture-dependent files should be relative
2734 to @code{exec_prefix}.
2735 @end defvar
2737 @defvar htmldir
2738 @ovindex htmldir
2739 The directory for installing HTML documentation.
2740 @end defvar
2742 @defvar includedir
2743 @ovindex includedir
2744 The directory for installing C header files.
2745 @end defvar
2747 @defvar infodir
2748 @ovindex infodir
2749 The directory for installing documentation in Info format.
2750 @end defvar
2752 @defvar libdir
2753 @ovindex libdir
2754 The directory for installing object code libraries.
2755 @end defvar
2757 @defvar libexecdir
2758 @ovindex libexecdir
2759 The directory for installing executables that other programs run.
2760 @end defvar
2762 @defvar localedir
2763 @ovindex localedir
2764 The directory for installing locale-dependent but
2765 architecture-independent data, such as message catalogs.  This directory
2766 usually has a subdirectory per locale.
2767 @end defvar
2769 @defvar localstatedir
2770 @ovindex localstatedir
2771 The directory for installing modifiable single-machine data.
2772 @end defvar
2774 @defvar mandir
2775 @ovindex mandir
2776 The top-level directory for installing documentation in man format.
2777 @end defvar
2779 @defvar oldincludedir
2780 @ovindex oldincludedir
2781 The directory for installing C header files for non-GCC compilers.
2782 @end defvar
2784 @defvar pdfdir
2785 @ovindex pdfdir
2786 The directory for installing PDF documentation.
2787 @end defvar
2789 @defvar prefix
2790 @ovindex prefix
2791 The common installation prefix for all files.  If @code{exec_prefix}
2792 is defined to a different value, @code{prefix} is used only for
2793 architecture-independent files.
2794 @end defvar
2796 @defvar psdir
2797 @ovindex psdir
2798 The directory for installing PostScript documentation.
2799 @end defvar
2801 @defvar sbindir
2802 @ovindex sbindir
2803 The directory for installing executables that system
2804 administrators run.
2805 @end defvar
2807 @defvar sharedstatedir
2808 @ovindex sharedstatedir
2809 The directory for installing modifiable architecture-independent data.
2810 @end defvar
2812 @defvar sysconfdir
2813 @ovindex sysconfdir
2814 The directory for installing read-only single-machine data.
2815 @end defvar
2818 Most of these variables have values that rely on @code{prefix} or
2819 @code{exec_prefix}.  It is deliberate that the directory output
2820 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2821 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2822 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2824 This behavior is mandated by the GNU Coding Standards, so that when
2825 the user runs:
2827 @table @samp
2828 @item make
2829 she can still specify a different prefix from the one specified to
2830 @command{configure}, in which case, if needed, the package should hard
2831 code dependencies corresponding to the make-specified prefix.
2833 @item make install
2834 she can specify a different installation location, in which case the
2835 package @emph{must} still depend on the location which was compiled in
2836 (i.e., never recompile when @samp{make install} is run).  This is an
2837 extremely important feature, as many people may decide to install all
2838 the files of a package grouped together, and then install links from
2839 the final locations to there.
2840 @end table
2842 In order to support these features, it is essential that
2843 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2844 so that its value can be expanded based
2845 on the current value of @code{prefix}.
2847 A corollary is that you should not use these variables except in
2848 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2849 in @file{configure} and hard-coding it in makefiles using
2850 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2851 you should add
2852 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2853 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2855 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2856 @code{bindir} and friends in your shell scripts and other files; instead,
2857 let @command{make} manage their replacement.  For instance Autoconf
2858 ships templates of its shell scripts ending with @samp{.in}, and uses a
2859 makefile snippet similar to the following to build scripts like
2860 @command{autoheader} and @command{autom4te}:
2862 @example
2863 @group
2864 edit = sed \
2865         -e 's|@@bindir[@@]|$(bindir)|g' \
2866         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2867         -e 's|@@prefix[@@]|$(prefix)|g'
2868 @end group
2870 @group
2871 autoheader autom4te: Makefile
2872         rm -f $@@ $@@.tmp
2873         srcdir=''; \
2874           test -f ./$@@.in || srcdir=$(srcdir)/; \
2875           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2876 @c $$ restore font-lock
2877         chmod +x $@@.tmp
2878         chmod a-w $@@.tmp
2879         mv $@@.tmp $@@
2880 @end group
2882 @group
2883 autoheader: $(srcdir)/autoheader.in
2884 autom4te: $(srcdir)/autom4te.in
2885 @end group
2886 @end example
2888 Some details are noteworthy:
2890 @table @asis
2891 @item @samp{@@bindir[@@]}
2892 The brackets prevent @command{configure} from replacing
2893 @samp{@@bindir@@} in the Sed expression itself.
2894 Brackets are preferable to a backslash here, since
2895 Posix says @samp{\@@} is not portable.
2897 @item @samp{$(bindir)}
2898 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2899 instead.
2901 @item @samp{$(pkgdatadir)}
2902 The example takes advantage of the variable @samp{$(pkgdatadir)}
2903 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2905 @item @samp{/}
2906 Don't use @samp{/} in the Sed expressions that replace file names since
2907 most likely the
2908 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2909 Use a shell metacharacter instead, such as @samp{|}.
2911 @item special characters
2912 File names, file name components, and the value of @code{VPATH} should
2913 not contain shell metacharacters or white
2914 space.  @xref{Special Chars in Variables}.
2916 @item dependency on @file{Makefile}
2917 Since @code{edit} uses values that depend on the configuration specific
2918 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2919 the output depends on @file{Makefile}, not @file{configure.ac}.
2921 @item @samp{$@@}
2922 The main rule is generic, and uses @samp{$@@} extensively to
2923 avoid the need for multiple copies of the rule.
2925 @item Separated dependencies and single suffix rules
2926 You can't use them!  The above snippet cannot be (portably) rewritten
2929 @example
2930 autoconf autoheader: Makefile
2931 @group
2932 .in:
2933         rm -f $@@ $@@.tmp
2934         $(edit) $< >$@@.tmp
2935         chmod +x $@@.tmp
2936         mv $@@.tmp $@@
2937 @end group
2938 @end example
2940 @xref{Single Suffix Rules}, for details.
2942 @item @samp{$(srcdir)}
2943 Be sure to specify the name of the source directory,
2944 otherwise the package won't support separated builds.
2945 @end table
2947 For the more specific installation of Erlang libraries, the following variables
2948 are defined:
2950 @defvar ERLANG_INSTALL_LIB_DIR
2951 @ovindex ERLANG_INSTALL_LIB_DIR
2952 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2953 The common parent directory of Erlang library installation directories.
2954 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2955 macro in @file{configure.ac}.
2956 @end defvar
2958 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2959 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2960 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2961 The installation directory for Erlang library @var{library}.
2962 This variable is set by using the
2963 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2964 macro in @file{configure.ac}.
2965 @end defvar
2967 @xref{Erlang Libraries}, for details.
2970 @node Changed Directory Variables
2971 @subsection Changed Directory Variables
2972 @cindex @file{datarootdir}
2974 In Autoconf 2.60, the set of directory variables has changed, and the
2975 defaults of some variables have been adjusted
2976 (@pxref{Installation Directory Variables}) to changes in the
2977 GNU Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
2978 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
2979 upgrading from an earlier Autoconf version, you may need to adjust your files
2980 to ensure that the directory variables are substituted correctly
2981 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
2982 in place.  For example, in a @file{Makefile.in}, adding
2984 @example
2985 datarootdir = @@datarootdir@@
2986 @end example
2988 @noindent
2989 is usually sufficient.  If you use Automake to create @file{Makefile.in},
2990 it will add this for you.
2992 To help with the transition, Autoconf warns about files that seem to use
2993 @code{datarootdir} without defining it.  In some cases, it then expands
2994 the value of @code{$datarootdir} in substitutions of the directory
2995 variables.  The following example shows such a warning:
2997 @example
2998 $ @kbd{cat configure.ac}
2999 AC_INIT
3000 AC_CONFIG_FILES([Makefile])
3001 AC_OUTPUT
3002 $ @kbd{cat Makefile.in}
3003 prefix = @@prefix@@
3004 datadir = @@datadir@@
3005 $ @kbd{autoconf}
3006 $ @kbd{configure}
3007 configure: creating ./config.status
3008 config.status: creating Makefile
3009 config.status: WARNING:
3010                Makefile.in seems to ignore the --datarootdir setting
3011 $ @kbd{cat Makefile}
3012 prefix = /usr/local
3013 datadir = $@{prefix@}/share
3014 @end example
3016 Usually one can easily change the file to accommodate both older and newer
3017 Autoconf releases:
3019 @example
3020 $ @kbd{cat Makefile.in}
3021 prefix = @@prefix@@
3022 datarootdir = @@datarootdir@@
3023 datadir = @@datadir@@
3024 $ @kbd{configure}
3025 configure: creating ./config.status
3026 config.status: creating Makefile
3027 $ @kbd{cat Makefile}
3028 prefix = /usr/local
3029 datarootdir = $@{prefix@}/share
3030 datadir = $@{datarootdir@}
3031 @end example
3033 @acindex{DATAROOTDIR_CHECKED}
3034 In some cases, however, the checks may not be able to detect that a suitable
3035 initialization of @code{datarootdir} is in place, or they may fail to detect
3036 that such an initialization is necessary in the output file.  If, after
3037 auditing your package, there are still spurious @file{configure} warnings about
3038 @code{datarootdir}, you may add the line
3040 @example
3041 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3042 @end example
3044 @noindent
3045 to your @file{configure.ac} to disable the warnings.  This is an exception
3046 to the usual rule that you should not define a macro whose name begins with
3047 @code{AC_} (@pxref{Macro Names}).
3051 @node Build Directories
3052 @subsection Build Directories
3053 @cindex Build directories
3054 @cindex Directories, build
3056 You can support compiling a software package for several architectures
3057 simultaneously from the same copy of the source code.  The object files
3058 for each architecture are kept in their own directory.
3060 To support doing this, @command{make} uses the @code{VPATH} variable to
3061 find the files that are in the source directory.  GNU Make
3062 can do this.  Most other recent @command{make} programs can do this as
3063 well, though they may have difficulties and it is often simpler to
3064 recommend GNU @command{make} (@pxref{VPATH and Make}).  Older
3065 @command{make} programs do not support @code{VPATH}; when using them, the
3066 source code must be in the same directory as the object files.
3068 If you are using GNU Automake, the remaining details in this
3069 section are already covered for you, based on the contents of your
3070 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
3071 supporting @code{VPATH} requires the following in your
3072 @file{Makefile.in}:
3074 @example
3075 srcdir = @@srcdir@@
3076 VPATH = @@srcdir@@
3077 @end example
3079 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3080 listed in VPATH}.
3082 @command{configure} substitutes the correct value for @code{srcdir} when
3083 it produces @file{Makefile}.
3085 Do not use the @command{make} variable @code{$<}, which expands to the
3086 file name of the file in the source directory (found with @code{VPATH}),
3087 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3088 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3089 versions of @command{make} do not set @code{$<} in explicit rules; they
3090 expand it to an empty value.
3092 Instead, Make command lines should always refer to source
3093 files by prefixing them with @samp{$(srcdir)/}.  For example:
3095 @example
3096 time.info: time.texinfo
3097         $(MAKEINFO) '$(srcdir)/time.texinfo'
3098 @end example
3100 @node Automatic Remaking
3101 @subsection Automatic Remaking
3102 @cindex Automatic remaking
3103 @cindex Remaking automatically
3105 You can put rules like the following in the top-level @file{Makefile.in}
3106 for a package to automatically update the configuration information when
3107 you change the configuration files.  This example includes all of the
3108 optional files, such as @file{aclocal.m4} and those related to
3109 configuration header files.  Omit from the @file{Makefile.in} rules for
3110 any of these files that your package does not use.
3112 The @samp{$(srcdir)/} prefix is included because of limitations in the
3113 @code{VPATH} mechanism.
3115 The @file{stamp-} files are necessary because the timestamps of
3116 @file{config.h.in} and @file{config.h} are not changed if remaking
3117 them does not change their contents.  This feature avoids unnecessary
3118 recompilation.  You should include the file @file{stamp-h.in} in your
3119 package's distribution, so that @command{make} considers
3120 @file{config.h.in} up to date.  Don't use @command{touch}
3121 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3122 @command{echo} (using
3123 @command{date} would cause needless differences, hence CVS
3124 conflicts, etc.).
3126 @example
3127 @group
3128 $(srcdir)/configure: configure.ac aclocal.m4
3129         cd '$(srcdir)' && autoconf
3131 # autoheader might not change config.h.in, so touch a stamp file.
3132 $(srcdir)/config.h.in: stamp-h.in
3133 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3134         cd '$(srcdir)' && autoheader
3135         echo timestamp > '$(srcdir)/stamp-h.in'
3137 config.h: stamp-h
3138 stamp-h: config.h.in config.status
3139         ./config.status
3141 Makefile: Makefile.in config.status
3142         ./config.status
3144 config.status: configure
3145         ./config.status --recheck
3146 @end group
3147 @end example
3149 @noindent
3150 (Be careful if you copy these lines directly into your makefile, as you
3151 need to convert the indented lines to start with the tab character.)
3153 In addition, you should use
3155 @example
3156 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3157 @end example
3159 @noindent
3160 so @file{config.status} ensures that @file{config.h} is considered up to
3161 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3163 @xref{config.status Invocation}, for more examples of handling
3164 configuration-related dependencies.
3166 @node Configuration Headers
3167 @section Configuration Header Files
3168 @cindex Configuration Header
3169 @cindex @file{config.h}
3171 When a package contains more than a few tests that define C preprocessor
3172 symbols, the command lines to pass @option{-D} options to the compiler
3173 can get quite long.  This causes two problems.  One is that the
3174 @command{make} output is hard to visually scan for errors.  More
3175 seriously, the command lines can exceed the length limits of some
3176 operating systems.  As an alternative to passing @option{-D} options to
3177 the compiler, @command{configure} scripts can create a C header file
3178 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3179 macro selects this kind of output.  Though it can be called anywhere
3180 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3181 it right after @code{AC_INIT}.
3183 The package should @samp{#include} the configuration header file before
3184 any other header files, to prevent inconsistencies in declarations (for
3185 example, if it redefines @code{const}).
3187 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3188 option (or @option{-I..}; whichever directory contains @file{config.h}).
3189 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3190 the directory of the currently read file, i.e., the source directory, not
3191 the build directory.
3193 With the appropriate @option{-I} option, you can use
3194 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3195 because in the rare case when the source directory contains another
3196 @file{config.h}, the build directory should be searched first.
3199 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3200 @acindex{CONFIG_HEADERS}
3201 @cvindex HAVE_CONFIG_H
3202 This macro is one of the instantiating macros; see @ref{Configuration
3203 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3204 blank-or-newline-separated list @var{header} containing C preprocessor
3205 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3206 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3207 The usual name for @var{header} is @file{config.h}.
3209 If @var{header} already exists and its contents are identical to what
3210 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3211 making some changes in the configuration without needlessly causing
3212 object files that depend on the header file to be recompiled.
3214 Usually the input file is named @file{@var{header}.in}; however, you can
3215 override the input file name by appending to @var{header} a
3216 colon-separated list of input files.  For example, you might need to make
3217 the input file name acceptable to DOS variants:
3219 @example
3220 AC_CONFIG_HEADERS([config.h:config.hin])
3221 @end example
3223 @end defmac
3225 @defmac AH_HEADER
3226 @ahindex{HEADER}
3227 This macro is defined as the name of the first declared config header
3228 and undefined if no config headers have been declared up to this point.
3229 A third-party macro may, for example, require use of a config header
3230 without invoking AC_CONFIG_HEADERS twice, like this:
3232 @example
3233 AC_CONFIG_COMMANDS_PRE(
3234         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3235 @end example
3237 @end defmac
3239 @xref{Configuration Actions}, for more details on @var{header}.
3241 @menu
3242 * Header Templates::            Input for the configuration headers
3243 * autoheader Invocation::       How to create configuration templates
3244 * Autoheader Macros::           How to specify CPP templates
3245 @end menu
3247 @node Header Templates
3248 @subsection Configuration Header Templates
3249 @cindex Configuration Header Template
3250 @cindex Header templates
3251 @cindex @file{config.h.in}
3253 Your distribution should contain a template file that looks as you want
3254 the final header file to look, including comments, with @code{#undef}
3255 statements which are used as hooks.  For example, suppose your
3256 @file{configure.ac} makes these calls:
3258 @example
3259 AC_CONFIG_HEADERS([conf.h])
3260 AC_CHECK_HEADERS([unistd.h])
3261 @end example
3263 @noindent
3264 Then you could have code like the following in @file{conf.h.in}.
3265 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3266 to 1, if and only if the system has @file{unistd.h}.
3268 @example
3269 @group
3270 /* Define as 1 if you have unistd.h.  */
3271 #undef HAVE_UNISTD_H
3272 @end group
3273 @end example
3275 The format of the template file is stricter than what the C preprocessor
3276 is required to accept.  A directive line should contain only whitespace,
3277 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3278 instead of @samp{#undef}, or of comments on the same line as
3279 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3280 once.  Other preprocessor lines, such as @samp{#ifdef} or
3281 @samp{#include}, are copied verbatim from the template into the
3282 generated header.
3284 Since it is a tedious task to keep a template header up to date, you may
3285 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3287 During the instantiation of the header, each @samp{#undef} line in the
3288 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3289 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3290 been executed during the @command{configure} run, the @samp{#undef} line is
3291 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3292 on many systems, it can be implicitly defined by the compiler, and
3293 undefining it in the header would then break compilation of subsequent
3294 headers.)
3296 Currently, @emph{all} remaining @samp{#undef} lines in the header
3297 template are commented out, whether or not there was a corresponding
3298 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3299 for future releases of Autoconf.
3301 Generally speaking, since you should not use @samp{#define}, and you
3302 cannot guarantee whether a @samp{#undef} directive in the header
3303 template will be converted to a @samp{#define} or commented out in the
3304 generated header file, the template file cannot be used for conditional
3305 definition effects.  Consequently, if you need to use the construct
3307 @example
3308 @group
3309 #ifdef THIS
3310 # define THAT
3311 #endif
3312 @end group
3313 @end example
3315 @noindent
3316 you must place it outside of the template.
3317 If you absolutely need to hook it to the config header itself, please put
3318 the directives to a separate file, and @samp{#include} that file from the
3319 config header template.  If you are using @command{autoheader}, you would
3320 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3323 @node autoheader Invocation
3324 @subsection Using @command{autoheader} to Create @file{config.h.in}
3325 @cindex @command{autoheader}
3327 The @command{autoheader} program can create a template file of C
3328 @samp{#define} statements for @command{configure} to use.
3329 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3330 @file{configure} sources to determine the name of the template.
3331 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3332 input file name, @command{autoheader} uses the first one.)
3334 It is recommended that only one input file is used.  If you want to append
3335 a boilerplate code, it is preferable to use
3336 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3337 File @file{conf_post.h} is not processed during the configuration then,
3338 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3339 prepend a boilerplate code.
3341 In order to do its job, @command{autoheader} needs you to document all
3342 of the symbols that you might use.  Typically this is done via an
3343 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3344 is a literal symbol and whose third argument describes the symbol
3345 (@pxref{Defining Symbols}).  Alternatively, you can use
3346 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3347 suitable input file for a subsequent configuration header file.
3348 Symbols defined by Autoconf's builtin tests are already documented properly;
3349 you need to document only those that you
3350 define yourself.
3352 You might wonder why @command{autoheader} is needed: after all, why
3353 would @command{configure} need to ``patch'' a @file{config.h.in} to
3354 produce a @file{config.h} instead of just creating @file{config.h} from
3355 scratch?  Well, when everything rocks, the answer is just that we are
3356 wasting our time maintaining @command{autoheader}: generating
3357 @file{config.h} directly is all that is needed.  When things go wrong,
3358 however, you'll be thankful for the existence of @command{autoheader}.
3360 The fact that the symbols are documented is important in order to
3361 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3362 well-defined list of symbols that should be defined (or not) is
3363 also important for people who are porting packages to environments where
3364 @command{configure} cannot be run: they just have to @emph{fill in the
3365 blanks}.
3367 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3369 If you give @command{autoheader} an argument, it uses that file instead
3370 of @file{configure.ac} and writes the header file to the standard output
3371 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3372 argument of @option{-}, it reads the standard input instead of
3373 @file{configure.ac} and writes the header file to the standard output.
3375 @command{autoheader} accepts the following options:
3377 @table @option
3378 @item --help
3379 @itemx -h
3380 Print a summary of the command line options and exit.
3382 @item --version
3383 @itemx -V
3384 Print the version number of Autoconf and exit.
3386 @item --verbose
3387 @itemx -v
3388 Report processing steps.
3390 @item --debug
3391 @itemx -d
3392 Don't remove the temporary files.
3394 @item --force
3395 @itemx -f
3396 Remake the template file even if newer than its input files.
3398 @item --include=@var{dir}
3399 @itemx -I @var{dir}
3400 Append @var{dir} to the include path.  Multiple invocations accumulate.
3402 @item --prepend-include=@var{dir}
3403 @itemx -B @var{dir}
3404 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3406 @item --warnings=@var{category}
3407 @itemx -W @var{category}
3408 @evindex WARNINGS
3409 Report the warnings related to @var{category} (which can actually be a
3410 comma separated list).  Current categories include:
3412 @table @samp
3413 @item obsolete
3414 report the uses of obsolete constructs
3416 @item all
3417 report all the warnings
3419 @item none
3420 report none
3422 @item error
3423 treats warnings as errors
3425 @item no-@var{category}
3426 disable warnings falling into @var{category}
3427 @end table
3429 @end table
3433 @node Autoheader Macros
3434 @subsection Autoheader Macros
3435 @cindex Autoheader macros
3437 @command{autoheader} scans @file{configure.ac} and figures out which C
3438 preprocessor symbols it might define.  It knows how to generate
3439 templates for symbols defined by @code{AC_CHECK_HEADERS},
3440 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3441 symbol, you must define a template for it.  If there are missing
3442 templates, @command{autoheader} fails with an error message.
3444 The template for a @var{symbol} is created
3445 by @command{autoheader} from
3446 the @var{description} argument to an @code{AC_DEFINE};
3447 see @ref{Defining Symbols}.
3449 For special needs, you can use the following macros.
3452 @defmac AH_TEMPLATE (@var{key}, @var{description})
3453 @ahindex{TEMPLATE}
3454 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3455 generates standard templates just like @code{AC_DEFINE} when a
3456 @var{description} is given.
3458 For example:
3460 @example
3461 AH_TEMPLATE([CRAY_STACKSEG_END],
3462             [Define to one of _getb67, GETB67, getb67
3463              for Cray-2 and Cray-YMP systems.  This
3464              function is required for alloca.c support
3465              on those systems.])
3466 @end example
3468 @noindent
3469 generates the following template, with the description properly
3470 justified.
3472 @example
3473 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3474    Cray-YMP systems.  This function is required for alloca.c
3475    support on those systems.  */
3476 #undef CRAY_STACKSEG_END
3477 @end example
3478 @end defmac
3481 @defmac AH_VERBATIM (@var{key}, @var{template})
3482 @ahindex{VERBATIM}
3483 Tell @command{autoheader} to include the @var{template} as-is in the header
3484 template file.  This @var{template} is associated with the @var{key},
3485 which is used to sort all the different templates and guarantee their
3486 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3487 @end defmac
3490 @defmac AH_TOP (@var{text})
3491 @ahindex{TOP}
3492 Include @var{text} at the top of the header template file.
3493 @end defmac
3496 @defmac AH_BOTTOM (@var{text})
3497 @ahindex{BOTTOM}
3498 Include @var{text} at the bottom of the header template file.
3499 @end defmac
3502 Please note that @var{text} gets included ``verbatim'' to the template file,
3503 not to the resulting config header, so it can easily get mangled when the
3504 template is processed.  There is rarely a need for something other than
3506 @example
3507 AH_BOTTOM([#include <custom.h>])
3508 @end example
3512 @node Configuration Commands
3513 @section Running Arbitrary Configuration Commands
3514 @cindex Configuration commands
3515 @cindex Commands for configuration
3517 You can execute arbitrary commands before, during, and after
3518 @file{config.status} is run.  The three following macros accumulate the
3519 commands to run when they are called multiple times.
3520 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3521 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3523 @anchor{AC_CONFIG_COMMANDS}
3524 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3525 @acindex{CONFIG_COMMANDS}
3526 Specify additional shell commands to run at the end of
3527 @file{config.status}, and shell commands to initialize any variables
3528 from @command{configure}.  Associate the commands with @var{tag}.
3529 Since typically the @var{cmds} create a file, @var{tag} should
3530 naturally be the name of that file.  If needed, the directory hosting
3531 @var{tag} is created.  This macro is one of the instantiating macros;
3532 see @ref{Configuration Actions}.
3534 Here is an unrealistic example:
3535 @example
3536 fubar=42
3537 AC_CONFIG_COMMANDS([fubar],
3538                    [echo this is extra $fubar, and so on.],
3539                    [fubar=$fubar])
3540 @end example
3542 Here is a better one:
3543 @example
3544 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3545 @end example
3546 @end defmac
3548 The following two macros look similar, but in fact they are not of the same
3549 breed: they are executed directly by @file{configure}, so you cannot use
3550 @file{config.status} to rerun them.
3552 @c Yet it is good to leave them here.  The user sees them together and
3553 @c decides which best fits their needs.
3555 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3556 @acindex{CONFIG_COMMANDS_PRE}
3557 Execute the @var{cmds} right before creating @file{config.status}.
3559 This macro presents the last opportunity to call @code{AC_SUBST},
3560 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3561 @end defmac
3563 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3564 @acindex{CONFIG_COMMANDS_POST}
3565 Execute the @var{cmds} right after creating @file{config.status}.
3566 @end defmac
3571 @node Configuration Links
3572 @section Creating Configuration Links
3573 @cindex Configuration links
3574 @cindex Links for configuration
3576 You may find it convenient to create links whose destinations depend upon
3577 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3578 creation of relative symbolic links can be delicate when the package is
3579 built in a directory different from the source directory.
3581 @anchor{AC_CONFIG_LINKS}
3582 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3583   @ovar{init-cmds})
3584 @acindex{CONFIG_LINKS}
3585 @cindex Links
3586 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3587 the corresponding link name @var{dest}.  Makes a symbolic link if
3588 possible, otherwise a hard link if possible, otherwise a copy.  The
3589 @var{dest} and @var{source} names should be relative to the top level
3590 source or build directory.  This macro is one of the instantiating
3591 macros; see @ref{Configuration Actions}.
3593 For example, this call:
3595 @example
3596 AC_CONFIG_LINKS([host.h:config/$machine.h
3597                 object.h:config/$obj_format.h])
3598 @end example
3600 @noindent
3601 creates in the current directory @file{host.h} as a link to
3602 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3603 link to @file{@var{srcdir}/config/$obj_format.h}.
3605 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3606 impossible for @samp{config.status} to guess the links to establish.
3608 One can then run:
3609 @example
3610 ./config.status host.h object.h
3611 @end example
3612 @noindent
3613 to create the links.
3614 @end defmac
3618 @node Subdirectories
3619 @section Configuring Other Packages in Subdirectories
3620 @cindex Configure subdirectories
3621 @cindex Subdirectory configure
3623 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3624 makefiles in subdirectories.  However, @command{configure} scripts
3625 that control more than one independent package can use
3626 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3627 packages in subdirectories.
3629 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3630 @acindex{CONFIG_SUBDIRS}
3631 @ovindex subdirs
3632 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3633 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3634 be a literal, i.e., please do not use:
3636 @example
3637 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3638 if test "x$package_foo_enabled" = xyes; then
3639   my_subdirs="$my_subdirs foo"
3641 AC_CONFIG_SUBDIRS([$my_subdirs])
3642 @end example
3644 @noindent
3645 because this prevents @samp{./configure --help=recursive} from
3646 displaying the options of the package @code{foo}.  Instead, you should
3647 write:
3649 @example
3650 if test "x$package_foo_enabled" = xyes; then
3651   AC_CONFIG_SUBDIRS([foo])
3653 @end example
3655 If a given @var{dir} is not found at @command{configure} run time, a
3656 warning is reported; if the subdirectory is optional, write:
3658 @example
3659 if test -d "$srcdir/foo"; then
3660   AC_CONFIG_SUBDIRS([foo])
3662 @end example
3664 @c NB: Yes, below we mean configure.in, not configure.ac.
3665 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3666 of @command{configure}.  This is for packages that might use a
3667 non-Autoconf script @command{Configure}, which can't be called through a
3668 wrapper @command{configure} since it would be the same file on
3669 case-insensitive file systems.  Likewise, if a @var{dir} contains
3670 @file{configure.in} but no @command{configure}, the Cygnus
3671 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3673 The subdirectory @command{configure} scripts are given the same command
3674 line options that were given to this @command{configure} script, with minor
3675 changes if needed, which include:
3677 @itemize @minus
3678 @item
3679 adjusting a relative name for the cache file;
3681 @item
3682 adjusting a relative name for the source directory;
3684 @item
3685 propagating the current value of @code{$prefix}, including if it was
3686 defaulted, and if the default values of the top level and of the subdirectory
3687 @file{configure} differ.
3688 @end itemize
3690 This macro also sets the output variable @code{subdirs} to the list of
3691 directories @samp{@var{dir} @dots{}}.  Make rules can use
3692 this variable to determine which subdirectories to recurse into.
3694 This macro may be called multiple times.
3695 @end defmac
3697 @node Default Prefix
3698 @section Default Prefix
3699 @cindex Install prefix
3700 @cindex Prefix for install
3702 By default, @command{configure} sets the prefix for files it installs to
3703 @file{/usr/local}.  The user of @command{configure} can select a different
3704 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3705 There are two ways to change the default: when creating
3706 @command{configure}, and when running it.
3708 Some software packages might want to install in a directory other than
3709 @file{/usr/local} by default.  To accomplish that, use the
3710 @code{AC_PREFIX_DEFAULT} macro.
3712 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3713 @acindex{PREFIX_DEFAULT}
3714 Set the default installation prefix to @var{prefix} instead of
3715 @file{/usr/local}.
3716 @end defmac
3718 It may be convenient for users to have @command{configure} guess the
3719 installation prefix from the location of a related program that they
3720 have already installed.  If you wish to do that, you can call
3721 @code{AC_PREFIX_PROGRAM}.
3723 @anchor{AC_PREFIX_PROGRAM}
3724 @defmac AC_PREFIX_PROGRAM (@var{program})
3725 @acindex{PREFIX_PROGRAM}
3726 If the user did not specify an installation prefix (using the
3727 @option{--prefix} option), guess a value for it by looking for
3728 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3729 is found, set the prefix to the parent of the directory containing
3730 @var{program}, else default the prefix as described above
3731 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3732 @var{program} is @code{gcc} and the @env{PATH} contains
3733 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3734 @end defmac
3738 @c ======================================================== Existing tests
3740 @node Existing Tests
3741 @chapter Existing Tests
3743 These macros test for particular system features that packages might
3744 need or want to use.  If you need to test for a kind of feature that
3745 none of these macros check for, you can probably do it by calling
3746 primitive test macros with appropriate arguments (@pxref{Writing
3747 Tests}).
3749 These tests print messages telling the user which feature they're
3750 checking for, and what they find.  They cache their results for future
3751 @command{configure} runs (@pxref{Caching Results}).
3753 Some of these macros set output variables.  @xref{Makefile
3754 Substitutions}, for how to get their values.  The phrase ``define
3755 @var{name}'' is used below as a shorthand to mean ``define the C
3756 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3757 Symbols}, for how to get those symbol definitions into your program.
3759 @menu
3760 * Common Behavior::             Macros' standard schemes
3761 * Alternative Programs::        Selecting between alternative programs
3762 * Files::                       Checking for the existence of files
3763 * Libraries::                   Library archives that might be missing
3764 * Library Functions::           C library functions that might be missing
3765 * Header Files::                Header files that might be missing
3766 * Declarations::                Declarations that may be missing
3767 * Structures::                  Structures or members that might be missing
3768 * Types::                       Types that might be missing
3769 * Compilers and Preprocessors::  Checking for compiling programs
3770 * System Services::             Operating system services
3771 * Posix Variants::              Special kludges for specific Posix variants
3772 * Erlang Libraries::            Checking for the existence of Erlang libraries
3773 @end menu
3775 @node Common Behavior
3776 @section Common Behavior
3777 @cindex Common autoconf behavior
3779 Much effort has been expended to make Autoconf easy to learn.  The most
3780 obvious way to reach this goal is simply to enforce standard interfaces
3781 and behaviors, avoiding exceptions as much as possible.  Because of
3782 history and inertia, unfortunately, there are still too many exceptions
3783 in Autoconf; nevertheless, this section describes some of the common
3784 rules.
3786 @menu
3787 * Standard Symbols::            Symbols defined by the macros
3788 * Default Includes::            Includes used by the generic macros
3789 @end menu
3791 @node Standard Symbols
3792 @subsection Standard Symbols
3793 @cindex Standard symbols
3795 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3796 their test transform their @var{argument} values to a standard alphabet.
3797 First, @var{argument} is converted to upper case and any asterisks
3798 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3799 that are not alphanumeric are converted to underscores.
3801 For instance,
3803 @example
3804 AC_CHECK_TYPES([struct $Expensive*])
3805 @end example
3807 @noindent
3808 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3809 succeeds.
3812 @node Default Includes
3813 @subsection Default Includes
3814 @cindex Default includes
3815 @cindex Includes, default
3817 Several tests depend upon a set of header files.  Since these headers
3818 are not universally available, tests actually have to provide a set of
3819 protected includes, such as:
3821 @example
3822 @group
3823 #ifdef TIME_WITH_SYS_TIME
3824 # include <sys/time.h>
3825 # include <time.h>
3826 #else
3827 # ifdef HAVE_SYS_TIME_H
3828 #  include <sys/time.h>
3829 # else
3830 #  include <time.h>
3831 # endif
3832 #endif
3833 @end group
3834 @end example
3836 @noindent
3837 Unless you know exactly what you are doing, you should avoid using
3838 unconditional includes, and check the existence of the headers you
3839 include beforehand (@pxref{Header Files}).
3841 Most generic macros use the following macro to provide the default set
3842 of includes:
3844 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3845 @acindex{INCLUDES_DEFAULT}
3846 Expand to @var{include-directives} if defined, otherwise to:
3848 @example
3849 @group
3850 #include <stdio.h>
3851 #ifdef HAVE_SYS_TYPES_H
3852 # include <sys/types.h>
3853 #endif
3854 #ifdef HAVE_SYS_STAT_H
3855 # include <sys/stat.h>
3856 #endif
3857 #ifdef STDC_HEADERS
3858 # include <stdlib.h>
3859 # include <stddef.h>
3860 #else
3861 # ifdef HAVE_STDLIB_H
3862 #  include <stdlib.h>
3863 # endif
3864 #endif
3865 #ifdef HAVE_STRING_H
3866 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3867 #  include <memory.h>
3868 # endif
3869 # include <string.h>
3870 #endif
3871 #ifdef HAVE_STRINGS_H
3872 # include <strings.h>
3873 #endif
3874 #ifdef HAVE_INTTYPES_H
3875 # include <inttypes.h>
3876 #endif
3877 #ifdef HAVE_STDINT_H
3878 # include <stdint.h>
3879 #endif
3880 #ifdef HAVE_UNISTD_H
3881 # include <unistd.h>
3882 #endif
3883 @end group
3884 @end example
3886 If the default includes are used, then check for the presence of these
3887 headers and their compatibility, i.e., you don't need to run
3888 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3890 These headers are checked for in the same order as they are included.
3891 For instance, on some systems @file{string.h} and @file{strings.h} both
3892 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3893 @code{HAVE_STRINGS_H}.
3894 @end defmac
3896 @node Alternative Programs
3897 @section Alternative Programs
3898 @cindex Programs, checking
3900 These macros check for the presence or behavior of particular programs.
3901 They are used to choose between several alternative programs and to
3902 decide what to do once one has been chosen.  If there is no macro
3903 specifically defined to check for a program you need, and you don't need
3904 to check for any special properties of it, then you can use one of the
3905 general program-check macros.
3907 @menu
3908 * Particular Programs::         Special handling to find certain programs
3909 * Generic Programs::            How to find other programs
3910 @end menu
3912 @node Particular Programs
3913 @subsection Particular Program Checks
3915 These macros check for particular programs---whether they exist, and
3916 in some cases whether they support certain features.
3918 @defmac AC_PROG_AWK
3919 @acindex{PROG_AWK}
3920 @ovindex AWK
3921 @caindex prog_AWK
3922 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3923 order, and set output variable @code{AWK} to the first one that is found.
3924 It tries @code{gawk} first because that is reported to be the
3925 best implementation.  The result can be overridden by setting the
3926 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
3928 Using this macro is sufficient to avoid the pitfalls of traditional
3929 @command{awk} (@pxref{awk, , Limitations of Usual Tools}).
3930 @end defmac
3932 @defmac AC_PROG_GREP
3933 @acindex{PROG_GREP}
3934 @ovindex GREP
3935 @caindex prog_GREP
3936 Look for the best available @code{grep} or @code{ggrep} that accepts the
3937 longest input lines possible, and that supports multiple @option{-e} options.
3938 Set the output variable @code{GREP} to whatever is chosen.
3939 @xref{grep, , Limitations of Usual Tools}, for more information about
3940 portability problems with the @command{grep} command family.  The result
3941 can be overridden by setting the @code{GREP} variable and is cached in the
3942 @code{ac_cv_path_GREP} variable.
3943 @end defmac
3945 @defmac AC_PROG_EGREP
3946 @acindex{PROG_EGREP}
3947 @ovindex EGREP
3948 @caindex prog_EGREP
3949 Check whether @code{$GREP -E} works, or else look for the best available
3950 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3951 Set the output variable @code{EGREP} to whatever is chosen.  The result
3952 can be overridden by setting the @code{EGREP} variable and is cached in the
3953 @code{ac_cv_path_EGREP} variable.
3954 @end defmac
3956 @defmac AC_PROG_FGREP
3957 @acindex{PROG_FGREP}
3958 @ovindex FGREP
3959 @caindex prog_FGREP
3960 Check whether @code{$GREP -F} works, or else look for the best available
3961 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3962 Set the output variable @code{FGREP} to whatever is chosen.  The result
3963 can be overridden by setting the @code{FGREP} variable and is cached in the
3964 @code{ac_cv_path_FGREP} variable.
3965 @end defmac
3967 @defmac AC_PROG_INSTALL
3968 @acindex{PROG_INSTALL}
3969 @ovindex INSTALL
3970 @ovindex INSTALL_PROGRAM
3971 @ovindex INSTALL_DATA
3972 @ovindex INSTALL_SCRIPT
3973 @caindex path_install
3974 Set output variable @code{INSTALL} to the name of a BSD-compatible
3975 @command{install} program, if one is found in the current @env{PATH}.
3976 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3977 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3978 default directories) to determine @var{dir} (@pxref{Output}).  Also set
3979 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
3980 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
3982 @samp{@@INSTALL@@} is special, as its value may vary for different
3983 configuration files.
3985 This macro screens out various instances of @command{install} known not to
3986 work.  It prefers to find a C program rather than a shell script, for
3987 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
3988 but that name is obsolete because some @command{make} programs have a rule
3989 that creates @file{install} from it if there is no makefile.  Further, this
3990 macro requires @command{install} to be able to install multiple files into a
3991 target directory in a single invocation.
3993 Autoconf comes with a copy of @file{install-sh} that you can use.  If
3994 you use @code{AC_PROG_INSTALL}, you must include either
3995 @file{install-sh} or @file{install.sh} in your distribution; otherwise
3996 @command{configure} produces an error message saying it can't find
3997 them---even if the system you're on has a good @command{install} program.
3998 This check is a safety measure to prevent you from accidentally leaving
3999 that file out, which would prevent your package from installing on
4000 systems that don't have a BSD-compatible @command{install} program.
4002 If you need to use your own installation program because it has features
4003 not found in standard @command{install} programs, there is no reason to use
4004 @code{AC_PROG_INSTALL}; just put the file name of your program into your
4005 @file{Makefile.in} files.
4007 The result of the test can be overridden by setting the variable
4008 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4009 @end defmac
4011 @defmac AC_PROG_MKDIR_P
4012 @acindex{PROG_MKDIR_P}
4013 @ovindex MKDIR_P
4014 @caindex path_mkdir
4015 Set output variable @code{MKDIR_P} to a program that ensures that for
4016 each argument, a directory named by this argument exists, creating it
4017 and its parent directories if needed, and without race conditions when
4018 two instances of the program attempt to make the same directory at
4019 nearly the same time.
4021 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
4022 falls back on invoking @command{install-sh} with the @option{-d} option,
4023 so your package should
4024 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4025 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4026 is vulnerable to race conditions, so if you want to support parallel
4027 installs from
4028 different packages into the same directory you need to make sure you
4029 have an up-to-date @file{install-sh}.  In particular, be careful about
4030 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4032 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4033 in M4sh}), but it sets an output variable intended for use in other
4034 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4035 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
4036 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4037 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4038 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4039 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4040 Finally, @code{AS_MKDIR_P} does not check for race condition
4041 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4043 @samp{@@MKDIR_P@@} is special, as its value may vary for different
4044 configuration files.
4046 The result of the test can be overridden by setting the variable
4047 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4048 @end defmac
4050 @anchor{AC_PROG_LEX}
4051 @defmac AC_PROG_LEX
4052 @acindex{PROG_LEX}
4053 @ovindex LEX
4054 @ovindex LEXLIB
4055 @cvindex YYTEXT_POINTER
4056 @ovindex LEX_OUTPUT_ROOT
4057 @caindex prog_LEX
4058 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
4059 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
4060 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
4061 @option{-ll}, if found.  If neither variant is available, set @code{LEX}
4062 to @samp{:}; for packages that ship the generated @file{file.yy.c}
4063 alongside the source @file{file.l}, this default allows users without a
4064 lexer generator to still build the package even if the timestamp for
4065 @file{file.l} is inadvertantly changed.
4067 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
4068 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
4069 the base of the file name that the lexer generates; usually
4070 @file{lex.yy}, but sometimes something else.  These results vary
4071 according to whether @code{lex} or @code{flex} is being used.
4073 You are encouraged to use Flex in your sources, since it is both more
4074 pleasant to use than plain Lex and the C source it produces is portable.
4075 In order to ensure portability, however, you must either provide a
4076 function @code{yywrap} or, if you don't use it (e.g., your scanner has
4077 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
4078 statement in the scanner's source.  Once this done, the scanner is
4079 portable (unless @emph{you} felt free to use nonportable constructs) and
4080 does not depend on any library.  In this case, and in this case only, it
4081 is suggested that you use this Autoconf snippet:
4083 @example
4084 AC_PROG_LEX
4085 if test "x$LEX" != xflex; then
4086   LEX="$SHELL $missing_dir/missing flex"
4087   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4088   AC_SUBST([LEXLIB], [''])
4090 @end example
4092 The shell script @command{missing} can be found in the Automake
4093 distribution.
4095 Remember that the user may have supplied an alternate location in
4096 @env{LEX}, so if Flex is required, it is better to check that the user
4097 provided something sufficient by parsing the output of @samp{$LEX
4098 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4100 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
4101 (indirectly) this macro twice, which causes an annoying but benign
4102 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
4103 of Automake will fix this issue; meanwhile, just ignore this message.
4105 As part of running the test, this macro may delete any file in the
4106 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
4108 The result of this test can be influenced by setting the variable
4109 @code{LEX} or the cache variable @code{ac_cv_prog_LEX}.
4110 @end defmac
4112 @anchor{AC_PROG_LN_S}
4113 @defmac AC_PROG_LN_S
4114 @acindex{PROG_LN_S}
4115 @ovindex LN_S
4116 If @samp{ln -s} works on the current file system (the operating system
4117 and file system support symbolic links), set the output variable
4118 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4119 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
4121 If you make a link in a directory other than the current directory, its
4122 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4123 create links using @samp{$(LN_S)}, either find out which form is used
4124 and adjust the arguments, or always invoke @code{ln} in the directory
4125 where the link is to be created.
4127 In other words, it does not work to do:
4128 @example
4129 $(LN_S) foo /x/bar
4130 @end example
4132 Instead, do:
4134 @example
4135 (cd /x && $(LN_S) foo bar)
4136 @end example
4137 @end defmac
4139 @defmac AC_PROG_RANLIB
4140 @acindex{PROG_RANLIB}
4141 @ovindex RANLIB
4142 @c @caindex prog_RANLIB
4143 @c @caindex prog_ac_ct_RANLIB
4144 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4145 is found, and otherwise to @samp{:} (do nothing).
4146 @end defmac
4148 @defmac AC_PROG_SED
4149 @acindex{PROG_SED}
4150 @ovindex SED
4151 @caindex path_SED
4152 Set output variable @code{SED} to a Sed implementation that conforms to
4153 Posix and does not have arbitrary length limits.  Report an error if no
4154 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4155 information about portability problems with Sed.
4157 The result of this test can be overridden by setting the @code{SED} variable
4158 and is cached in the @code{ac_cv_path_SED} variable.
4159 @end defmac
4161 @defmac AC_PROG_YACC
4162 @acindex{PROG_YACC}
4163 @evindex YACC
4164 @evindex YFLAGS
4165 @ovindex YACC
4166 @caindex prog_YACC
4167 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4168 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4169 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4170 The result of this test can be influenced by setting the variable
4171 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4172 @end defmac
4174 @node Generic Programs
4175 @subsection Generic Program and File Checks
4177 These macros are used to find programs not covered by the ``particular''
4178 test macros.  If you need to check the behavior of a program as well as
4179 find out whether it is present, you have to write your own test for it
4180 (@pxref{Writing Tests}).  By default, these macros use the environment
4181 variable @env{PATH}.  If you need to check for a program that might not
4182 be in the user's @env{PATH}, you can pass a modified path to use
4183 instead, like this:
4185 @example
4186 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4187              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4188 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4189 @end example
4191 You are strongly encouraged to declare the @var{variable} passed to
4192 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
4193 @code{AC_ARG_VAR}, for more details.
4195 @anchor{AC_CHECK_PROG}
4196 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4197   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4198   @ovar{reject})
4199 @acindex{CHECK_PROG}
4200 @caindex prog_@var{variable}
4201 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4202 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4203 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4204 absolute file name) even if it is the first found in the search path; in
4205 that case, set @var{variable} using the absolute file name of the
4206 @var{prog-to-check-for} found that is not @var{reject}.  If
4207 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4208 @var{variable}.  The result of this test can be overridden by setting the
4209 @var{variable} variable or the cache variable
4210 @code{ac_cv_prog_@var{variable}}.
4211 @end defmac
4213 @anchor{AC_CHECK_PROGS}
4214 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4215   @ovar{value-if-not-found}, @dvar{path, $PATH})
4216 @acindex{CHECK_PROGS}
4217 @caindex prog_@var{variable}
4218 Check for each program in the blank-separated list
4219 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4220 @var{variable} to the name of that program.  Otherwise, continue
4221 checking the next program in the list.  If none of the programs in the
4222 list are found, set @var{variable} to @var{value-if-not-found}; if
4223 @var{value-if-not-found} is not specified, the value of @var{variable}
4224 is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4225 this test can be overridden by setting the @var{variable} variable or the
4226 cache variable @code{ac_cv_prog_@var{variable}}.
4227 @end defmac
4229 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4230   @ovar{value-if-not-found}, @dvar{path, $PATH})
4231 @acindex{CHECK_TARGET_TOOL}
4232 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4233 with a prefix of the target type as determined by
4234 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4235 If the tool cannot be found with a prefix, and if the build and target
4236 types are equal, then it is also searched for without a prefix.
4238 As noted in @ref{Specifying Target Triplets}, the
4239 target is rarely specified, because most of the time it is the same
4240 as the host: it is the type of system for which any compiler tool in
4241 the package produces code.  What this macro looks for is,
4242 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4243 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4244 uses to produce objects, archives or executables}.
4245 @end defmac
4247 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4248   @ovar{value-if-not-found}, @dvar{path, $PATH})
4249 @acindex{CHECK_TOOL}
4250 @c @caindex prog_@var{VARIABLE}
4251 @c @caindex prog_ac_ct_@var{VARIABLE}
4252 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4253 with a prefix of the host type as specified by @option{--host}, followed by a
4254 dash.  For example, if the user runs
4255 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4256 @example
4257 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4258 @end example
4259 @noindent
4260 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4261 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4262 @var{path}, or to @samp{:} if neither program exists.
4264 When cross-compiling, this macro will issue a warning if no program
4265 prefixed with the host type could be found.
4266 For more information, see @ref{Specifying Target Triplets}.
4267 @end defmac
4269 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4270   @ovar{value-if-not-found}, @dvar{path, $PATH})
4271 @acindex{CHECK_TARGET_TOOLS}
4272 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4273 @var{progs-to-check-for} are checked with a prefix of the target type as
4274 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4275 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4276 prefix, and if the build and target types are equal, then the first one
4277 without a prefix is used.  If a tool is found, set @var{variable} to
4278 the name of that program.  If none of the tools in the list are found,
4279 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4280 is not specified, the value of @var{variable} is not changed.  Calls
4281 @code{AC_SUBST} for @var{variable}.
4282 @end defmac
4284 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4285   @ovar{value-if-not-found}, @dvar{path, $PATH})
4286 @acindex{CHECK_TOOLS}
4287 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4288 @var{progs-to-check-for} are checked with a prefix of the host type as
4289 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4290 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4291 prefix, then the first one without a prefix is used.  If a tool is found,
4292 set @var{variable} to the name of that program.  If none of the tools in
4293 the list are found, set @var{variable} to @var{value-if-not-found}; if
4294 @var{value-if-not-found} is not specified, the value of @var{variable}
4295 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4297 When cross-compiling, this macro will issue a warning if no program
4298 prefixed with the host type could be found.
4299 For more information, see @ref{Specifying Target Triplets}.
4300 @end defmac
4302 @anchor{AC_PATH_PROG}
4303 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4304   @ovar{value-if-not-found}, @dvar{path, $PATH})
4305 @acindex{PATH_PROG}
4306 @caindex path_@var{variable}
4307 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4308 name of @var{prog-to-check-for} if found.  The result of this test
4309 can be overridden by setting the @var{variable} variable.  A positive
4310 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4311 variable.
4312 @end defmac
4314 @anchor{AC_PATH_PROGS}
4315 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4316   @ovar{value-if-not-found}, @dvar{path, $PATH})
4317 @acindex{PATH_PROGS}
4318 @caindex path_@var{variable}
4319 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4320 are found, set @var{variable} to the absolute name of the program
4321 found.  The result of this test can be overridden by setting the
4322 @var{variable} variable.  A positive result of this test is cached in
4323 the @code{ac_cv_path_@var{variable}} variable.
4324 @end defmac
4326 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4327   @var{progs-to-check-for}, @var{feature-test}, @
4328   @ovar{action-if-not-found}, @dvar{path, $PATH})
4329 @acindex{PATH_PROGS_FEATURE_CHECK}
4330 @caindex path_@var{variable}
4331 @vrindex ac_path_@var{variable}
4332 @vrindex ac_path_@var{variable}_found
4333 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4334 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4335 its value.  Otherwise, check for each program in the blank-separated
4336 list @var{progs-to-check-for} existing in @var{path}.  For each program
4337 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4338 set to the absolute name of the candidate program.  If no invocation of
4339 @var{feature-test} sets the shell variable
4340 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4341 executed.  @var{feature-test} will be run even when
4342 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4343 choose a better candidate found later in @var{path}; to accept the
4344 current setting and bypass all futher checks, @var{feature-test} can
4345 execute @code{ac_path_@var{variable}_found=:}.
4347 Note that this macro has some subtle differences from
4348 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4349 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4350 particular, @var{variable} is not set to the final value of
4351 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4352 run.  Also, on failure, any action can be performed, whereas
4353 @code{AC_CHECK_PROGS} only performs
4354 @code{@var{variable}=@var{value-if-not-found}}.
4356 Here is an example, similar to what Autoconf uses in its own configure
4357 script.  It will search for an implementation of @command{m4} that
4358 supports the @code{indir} builtin, even if it goes by the name
4359 @command{gm4} or is not the first implementation on @env{PATH}.
4361 @example
4362 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4363   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4364     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4365       test "x$m4out" = x0 \
4366       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4367     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4368 AC_SUBST([M4], [$ac_cv_path_M4])
4369 @end example
4370 @end defmac
4372 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4373   @ovar{value-if-not-found}, @dvar{path, $PATH})
4374 @acindex{PATH_TARGET_TOOL}
4375 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4376 name of the program if it is found.
4377 @end defmac
4379 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4380   @ovar{value-if-not-found}, @dvar{path, $PATH})
4381 @acindex{PATH_TOOL}
4382 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4383 name of the program if it is found.
4385 When cross-compiling, this macro will issue a warning if no program
4386 prefixed with the host type could be found.
4387 For more information, see @ref{Specifying Target Triplets}.
4388 @end defmac
4391 @node Files
4392 @section Files
4393 @cindex File, checking
4395 You might also need to check for the existence of files.  Before using
4396 these macros, ask yourself whether a runtime test might not be a better
4397 solution.  Be aware that, like most Autoconf macros, they test a feature
4398 of the host machine, and therefore, they die when cross-compiling.
4400 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4401   @ovar{action-if-not-found})
4402 @acindex{CHECK_FILE}
4403 @caindex file_@var{file}
4404 Check whether file @var{file} exists on the native system.  If it is
4405 found, execute @var{action-if-found}, otherwise do
4406 @var{action-if-not-found}, if given.  The result of this test is cached
4407 in the @code{ac_cv_file_@var{file}} variable, with characters not
4408 suitable for a variable name mapped to underscores.
4409 @end defmac
4411 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4412   @ovar{action-if-not-found})
4413 @acindex{CHECK_FILES}
4414 @caindex file_@var{file}
4415 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4416 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4417 for each file found.  The results of each test are cached in the
4418 @code{ac_cv_file_@var{file}} variable, with characters not suitable for
4419 a variable name mapped to underscores.
4420 @end defmac
4423 @node Libraries
4424 @section Library Files
4425 @cindex Library, checking
4427 The following macros check for the presence of certain C, C++, or Fortran
4428 library archive files.
4430 @anchor{AC_CHECK_LIB}
4431 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4432   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4433 @acindex{CHECK_LIB}
4434 @caindex lib_@var{library}_@var{function}
4435 Test whether the library @var{library} is available by trying to link
4436 a test program that calls function @var{function} with the library.
4437 @var{function} should be a function provided by the library.
4438 Use the base
4439 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4440 the @var{library} argument.
4442 @var{action-if-found} is a list of shell commands to run if the link
4443 with the library succeeds; @var{action-if-not-found} is a list of shell
4444 commands to run if the link fails.  If @var{action-if-found} is not
4445 specified, the default action prepends @option{-l@var{library}} to
4446 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4447 capitals).  This macro is intended to support building @code{LIBS} in
4448 a right-to-left (least-dependent to most-dependent) fashion such that
4449 library dependencies are satisfied as a natural side effect of
4450 consecutive tests.  Linkers are sensitive to library ordering
4451 so the order in which @code{LIBS} is generated is important to reliable
4452 detection of libraries.
4454 If linking with @var{library} results in unresolved symbols that would
4455 be resolved by linking with additional libraries, give those libraries
4456 as the @var{other-libraries} argument, separated by spaces:
4457 e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4458 that @var{library} is present, because linking the test program can
4459 fail with unresolved symbols.  The @var{other-libraries} argument
4460 should be limited to cases where it is desirable to test for one library
4461 in the presence of another that is not already in @code{LIBS}.
4463 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4464 in some common cases.  Many standard functions like @code{gethostbyname}
4465 appear in the standard C library on some hosts, and in special libraries
4466 like @code{nsl} on other hosts.  On some hosts the special libraries
4467 contain variant implementations that you may not want to use.  These
4468 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4469 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4471 The result of this test is cached in the
4472 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4473 @end defmac
4475 @anchor{AC_SEARCH_LIBS}
4476 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4477   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4478 @acindex{SEARCH_LIBS}
4479 @caindex search_@var{function}
4480 Search for a library defining @var{function} if it's not already
4481 available.  This equates to calling
4482 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4483 no libraries, then for each library listed in @var{search-libs}.
4485 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4486 to contain @var{function}, and run @var{action-if-found}.  If the
4487 function is not found, run @var{action-if-not-found}.
4489 If linking with @var{library} results in unresolved symbols that would
4490 be resolved by linking with additional libraries, give those libraries
4491 as the @var{other-libraries} argument, separated by spaces:
4492 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4493 that @var{function} is present, because linking the test program
4494 always fails with unresolved symbols.
4496 The result of this test is cached in the
4497 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4498 @var{function} is already available, as @samp{no} if no library
4499 containing @var{function} was found, otherwise as the
4500 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4501 @end defmac
4505 @node Library Functions
4506 @section Library Functions
4508 The following macros check for particular C library functions.
4509 If there is no macro specifically defined to check for a function you need,
4510 and you don't need to check for any special properties of
4511 it, then you can use one of the general function-check macros.
4513 @menu
4514 * Function Portability::        Pitfalls with usual functions
4515 * Particular Functions::        Special handling to find certain functions
4516 * Generic Functions::           How to find other functions
4517 @end menu
4519 @node Function Portability
4520 @subsection Portability of C Functions
4521 @cindex Portability of C functions
4522 @cindex C function portability
4524 Most usual functions can either be missing, or be buggy, or be limited
4525 on some architectures.  This section tries to make an inventory of these
4526 portability issues.  By definition, this list always requires
4527 additions.  A much more complete list is maintained by the Gnulib
4528 project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4529 Current Posix Functions, gnulib, GNU gnulib}, @ref{Legacy Function
4530 Substitutes, , Legacy Functions, gnulib, GNU gnulib}, and @ref{Glibc
4531 Function Substitutes, , Glibc Functions, gnulib, GNU gnulib}.  Please
4532 help us keep the gnulib list as complete as possible.
4534 @table @asis
4535 @item @code{exit}
4536 @c @fuindex exit
4537 @prindex @code{exit}
4538 On ancient hosts, @code{exit} returned @code{int}.
4539 This is because @code{exit} predates @code{void}, and there was a long
4540 tradition of it returning @code{int}.
4542 On current hosts, the problem more likely is that @code{exit} is not
4543 declared, due to C++ problems of some sort or another.  For this reason
4544 we suggest that test programs not invoke @code{exit}, but return from
4545 @code{main} instead.
4547 @item @code{free}
4548 @c @fuindex free
4549 @prindex @code{free}
4550 The C standard says a call @code{free (NULL)} does nothing, but
4551 some old systems don't support this (e.g., NextStep).
4553 @item @code{isinf}
4554 @itemx @code{isnan}
4555 @c @fuindex isinf
4556 @c @fuindex isnan
4557 @prindex @code{isinf}
4558 @prindex @code{isnan}
4559 The C99 standard says that @code{isinf} and @code{isnan} are
4560 macros.  On some systems just macros are available
4561 (e.g., HP-UX and Solaris 10), on
4562 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4563 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4564 these functions are declared in nonstandard headers like
4565 @code{<sunmath.h>} and defined in non-default libraries like
4566 @option{-lm} or @option{-lsunmath}.
4568 The C99 @code{isinf} and @code{isnan} macros work correctly with
4569 @code{long double} arguments, but pre-C99 systems that use functions
4570 typically assume @code{double} arguments.  On such a system,
4571 @code{isinf} incorrectly returns true for a finite @code{long double}
4572 argument that is outside the range of @code{double}.
4574 The best workaround for these issues is to use gnulib modules
4575 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4576 solution involves code like the following.
4578 @smallexample
4579 #include <math.h>
4581 #ifndef isnan
4582 # define isnan(x) \
4583     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4584      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4585      : isnan_f (x))
4586 static inline int isnan_f  (float       x) @{ return x != x; @}
4587 static inline int isnan_d  (double      x) @{ return x != x; @}
4588 static inline int isnan_ld (long double x) @{ return x != x; @}
4589 #endif
4591 #ifndef isinf
4592 # define isinf(x) \
4593     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4594      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4595      : isinf_f (x))
4596 static inline int isinf_f  (float       x)
4597 @{ return !isnan (x) && isnan (x - x); @}
4598 static inline int isinf_d  (double      x)
4599 @{ return !isnan (x) && isnan (x - x); @}
4600 static inline int isinf_ld (long double x)
4601 @{ return !isnan (x) && isnan (x - x); @}
4602 #endif
4603 @end smallexample
4605 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4606 compilers that lack the @code{inline} keyword.  Some optimizing
4607 compilers mishandle these definitions, but systems with that bug
4608 typically have many other floating point corner-case compliance problems
4609 anyway, so it's probably not worth worrying about.
4611 @item @code{malloc}
4612 @c @fuindex malloc
4613 @prindex @code{malloc}
4614 The C standard says a call @code{malloc (0)} is implementation
4615 dependent.  It can return either @code{NULL} or a new non-null pointer.
4616 The latter is more common (e.g., the GNU C Library) but is by
4617 no means universal.  @code{AC_FUNC_MALLOC}
4618 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4620 @item @code{putenv}
4621 @c @fuindex putenv
4622 @prindex @code{putenv}
4623 Posix prefers @code{setenv} to @code{putenv}; among other things,
4624 @code{putenv} is not required of all Posix implementations, but
4625 @code{setenv} is.
4627 Posix specifies that @code{putenv} puts the given string directly in
4628 @code{environ}, but some systems make a copy of it instead (e.g.,
4629 glibc 2.0, or BSD).  And when a copy is made, @code{unsetenv} might
4630 not free it, causing a memory leak (e.g., FreeBSD 4).
4632 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4633 environment, but this is not standard usage and it dumps core
4634 on some systems (e.g., AIX).
4636 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4637 environment, rather than inserting it with an empty value.
4639 @item @code{realloc}
4640 @c @fuindex realloc
4641 @prindex @code{realloc}
4642 The C standard says a call @code{realloc (NULL, size)} is equivalent
4643 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4644 NextStep).
4646 @item @code{signal} handler
4647 @c @fuindex signal
4648 @prindex @code{signal}
4649 @prindex @code{sigaction}
4650 Normally @code{signal} takes a handler function with a return type of
4651 @code{void}, but some old systems required @code{int} instead.  Any
4652 actual @code{int} value returned is not used; this is only a
4653 difference in the function prototype demanded.
4655 All systems we know of in current use return @code{void}.  The
4656 @code{int} was to support K&R C, where of course @code{void} is not
4657 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4658 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4659 all cases.
4661 In most cases, it is more robust to use @code{sigaction} when it is
4662 available, rather than @code{signal}.
4664 @item @code{snprintf}
4665 @c @fuindex snprintf
4666 @prindex @code{snprintf}
4667 @c @fuindex vsnprintf
4668 @prindex @code{vsnprintf}
4669 The C99 standard says that if the output array isn't big enough
4670 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4671 truncate the output and return the number of bytes that ought to have
4672 been produced.  Some older systems return the truncated length (e.g.,
4673 GNU C Library 2.0.x or IRIX 6.5), some a negative value
4674 (e.g., earlier GNU C Library versions), and some the buffer
4675 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4676 older systems ignore the length and overrun the buffer (e.g., 64-bit
4677 Solaris 7).
4679 @item @code{sprintf}
4680 @c @fuindex sprintf
4681 @prindex @code{sprintf}
4682 @c @fuindex vsprintf
4683 @prindex @code{vsprintf}
4684 The C standard says @code{sprintf} and @code{vsprintf} return the
4685 number of bytes written.  On some ancient systems (SunOS 4 for
4686 instance) they return the buffer pointer instead, but these no
4687 longer need to be worried about.
4689 @item @code{sscanf}
4690 @c @fuindex sscanf
4691 @prindex @code{sscanf}
4692 On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4693 that its
4694 input string be writable (though it doesn't actually change it).  This
4695 can be a problem when using @command{gcc} since it normally puts
4696 constant strings in read-only memory (@pxref{Incompatibilities,
4697 Incompatibilities of GCC, , gcc, Using and
4698 Porting the GNU Compiler Collection}).  Apparently in some cases even
4699 having format strings read-only can be a problem.
4701 @item @code{strerror_r}
4702 @c @fuindex strerror_r
4703 @prindex @code{strerror_r}
4704 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4705 systems (e.g., GNU C Library version 2.2.4) provide a
4706 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4707 can detect which is in use (@pxref{Particular Functions}).
4709 @item @code{strnlen}
4710 @c @fuindex strnlen
4711 @prindex @code{strnlen}
4712 AIX 4.3 provides a broken version which produces the
4713 following results:
4715 @example
4716 strnlen ("foobar", 0) = 0
4717 strnlen ("foobar", 1) = 3
4718 strnlen ("foobar", 2) = 2
4719 strnlen ("foobar", 3) = 1
4720 strnlen ("foobar", 4) = 0
4721 strnlen ("foobar", 5) = 6
4722 strnlen ("foobar", 6) = 6
4723 strnlen ("foobar", 7) = 6
4724 strnlen ("foobar", 8) = 6
4725 strnlen ("foobar", 9) = 6
4726 @end example
4728 @item @code{sysconf}
4729 @c @fuindex sysconf
4730 @prindex @code{sysconf}
4731 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4732 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4733 @code{#ifdef}.
4735 @item @code{unlink}
4736 @c @fuindex unlink
4737 @prindex @code{unlink}
4738 The Posix spec says that @code{unlink} causes the given file to be
4739 removed only after there are no more open file handles for it.  Some
4740 non-Posix hosts have trouble with this requirement, though,
4741 and some DOS variants even corrupt the file system.
4743 @item @code{unsetenv}
4744 @c @fuindex unsetenv
4745 @prindex @code{unsetenv}
4746 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4747 can be removed with a call @code{putenv ("FOO=")}, as described under
4748 @code{putenv} above.
4750 @item @code{va_copy}
4751 @c @fuindex va_copy
4752 @prindex @code{va_copy}
4753 The C99 standard provides @code{va_copy} for copying
4754 @code{va_list} variables.  It may be available in older environments
4755 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4756 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4757 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4758 portability.
4760 @item @code{va_list}
4761 @c @fuindex va_list
4762 @prindex @code{va_list}
4763 @code{va_list} is not necessarily just a pointer.  It can be a
4764 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4765 not portable.  Or it can be an array (e.g., @command{gcc} in some
4766 PowerPC configurations), which means as a function parameter it can be
4767 effectively call-by-reference and library routines might modify the
4768 value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
4769 2.1).
4771 @item Signed @code{>>}
4772 Normally the C @code{>>} right shift of a signed type replicates the
4773 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4774 taken since Standard C doesn't require that behavior.  On those
4775 few processors without a native arithmetic shift (for instance Cray
4776 vector systems) zero bits may be shifted in, the same as a shift of an
4777 unsigned type.
4779 @item Integer @code{/}
4780 C divides signed integers by truncating their quotient toward zero,
4781 yielding the same result as Fortran.  However, before C99 the standard
4782 allowed C implementations to take the floor or ceiling of the quotient
4783 in some cases.  Hardly any implementations took advantage of this
4784 freedom, though, and it's probably not worth worrying about this issue
4785 nowadays.
4786 @end table
4789 @node Particular Functions
4790 @subsection Particular Function Checks
4791 @cindex Function, checking
4793 These macros check for particular C functions---whether they exist, and
4794 in some cases how they respond when given certain arguments.
4796 @anchor{AC_FUNC_ALLOCA}
4797 @defmac AC_FUNC_ALLOCA
4798 @acindex{FUNC_ALLOCA}
4799 @cvindex C_ALLOCA
4800 @cvindex HAVE_ALLOCA_H
4801 @ovindex ALLOCA
4802 @c @fuindex alloca
4803 @prindex @code{alloca}
4804 @hdrindex{alloca.h}
4805 @c @caindex working_alloca_h
4806 Check how to get @code{alloca}.  Tries to get a builtin version by
4807 checking for @file{alloca.h} or the predefined C preprocessor macros
4808 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4809 it defines @code{HAVE_ALLOCA_H}.
4811 If those attempts fail, it looks for the function in the standard C
4812 library.  If any of those methods succeed, it defines
4813 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4814 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4815 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4816 garbage collect).  This variable is separate from @code{LIBOBJS} so
4817 multiple programs can share the value of @code{ALLOCA} without needing
4818 to create an actual library, in case only some of them use the code in
4819 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4820 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4822 This macro does not try to get @code{alloca} from the System V R3
4823 @file{libPW} or the System V R4 @file{libucb} because those libraries
4824 contain some incompatible functions that cause trouble.  Some versions
4825 do not even contain @code{alloca} or contain a buggy version.  If you
4826 still want to use their @code{alloca}, use @code{ar} to extract
4827 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4829 Source files that use @code{alloca} should start with a piece of code
4830 like the following, to declare it properly.
4832 @example
4833 @group
4834 #ifdef STDC_HEADERS
4835 # include <stdlib.h>
4836 # include <stddef.h>
4837 #else
4838 # ifdef HAVE_STDLIB_H
4839 #  include <stdlib.h>
4840 # endif
4841 #endif
4842 #ifdef HAVE_ALLOCA_H
4843 # include <alloca.h>
4844 #elif defined __GNUC__
4845 # define alloca __builtin_alloca
4846 #elif defined _AIX
4847 # define alloca __alloca
4848 #elif defined _MSC_VER
4849 # include <malloc.h>
4850 # define alloca _alloca
4851 #else
4852 # ifndef HAVE_ALLOCA
4853 #  ifdef  __cplusplus
4854 extern "C"
4855 #  endif
4856 void *alloca (size_t);
4857 # endif
4858 #endif
4859 @end group
4860 @end example
4861 @end defmac
4863 @defmac AC_FUNC_CHOWN
4864 @acindex{FUNC_CHOWN}
4865 @cvindex HAVE_CHOWN
4866 @c @fuindex chown
4867 @prindex @code{chown}
4868 @caindex func_chown_works
4869 If the @code{chown} function is available and works (in particular, it
4870 should accept @option{-1} for @code{uid} and @code{gid}), define
4871 @code{HAVE_CHOWN}.  The result of this macro is cached in the
4872 @code{ac_cv_func_chown_works} variable.
4873 @end defmac
4875 @anchor{AC_FUNC_CLOSEDIR_VOID}
4876 @defmac AC_FUNC_CLOSEDIR_VOID
4877 @acindex{FUNC_CLOSEDIR_VOID}
4878 @cvindex CLOSEDIR_VOID
4879 @c @fuindex closedir
4880 @prindex @code{closedir}
4881 @caindex func_closedir_void
4882 If the @code{closedir} function does not return a meaningful value,
4883 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4884 return value for an error indicator.
4886 Currently this test is implemented by running a test program.  When
4887 cross compiling the pessimistic assumption that @code{closedir} does not
4888 return a meaningful value is made.
4890 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
4891 variable.
4893 This macro is obsolescent, as @code{closedir} returns a meaningful value
4894 on current systems.  New programs need not use this macro.
4895 @end defmac
4897 @defmac AC_FUNC_ERROR_AT_LINE
4898 @acindex{FUNC_ERROR_AT_LINE}
4899 @c @fuindex error_at_line
4900 @prindex @code{error_at_line}
4901 @caindex lib_error_at_line
4902 If the @code{error_at_line} function is not found, require an
4903 @code{AC_LIBOBJ} replacement of @samp{error}.
4905 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
4906 variable.
4908 The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent.  New programs
4909 should use Gnulib's @code{error} module.  @xref{Gnulib}.
4910 @end defmac
4912 @defmac AC_FUNC_FNMATCH
4913 @acindex{FUNC_FNMATCH}
4914 @c @fuindex fnmatch
4915 @prindex @code{fnmatch}
4916 @caindex func_fnmatch_works
4917 If the @code{fnmatch} function conforms to Posix, define
4918 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4919 the bugs in Solaris 2.4.
4921 Unlike the other specific
4922 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4923 broken/missing @code{fnmatch}.  This is for historical reasons.
4924 See @code{AC_REPLACE_FNMATCH} below.
4926 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
4927 variable.
4929 This macro is obsolescent.  New programs should use Gnulib's
4930 @code{fnmatch-posix} module.  @xref{Gnulib}.
4931 @end defmac
4933 @defmac AC_FUNC_FNMATCH_GNU
4934 @acindex{FUNC_FNMATCH_GNU}
4935 @c @fuindex fnmatch
4936 @prindex @code{fnmatch}
4937 @caindex func_fnmatch_gnu
4938 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4939 whether @code{fnmatch} supports GNU extensions.  Detect common
4940 implementation bugs, for example, the bugs in the GNU C
4941 Library 2.1.
4943 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
4944 variable.
4946 This macro is obsolescent.  New programs should use Gnulib's
4947 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4948 @end defmac
4950 @anchor{AC_FUNC_FORK}
4951 @defmac AC_FUNC_FORK
4952 @acindex{FUNC_FORK}
4953 @cvindex HAVE_VFORK_H
4954 @cvindex HAVE_WORKING_FORK
4955 @cvindex HAVE_WORKING_VFORK
4956 @cvindex vfork
4957 @c @fuindex fork
4958 @prindex @code{fork}
4959 @c @fuindex vfork
4960 @prindex @code{vfork}
4961 @hdrindex{vfork.h}
4962 @c @caindex func_fork
4963 @c @caindex func_fork_works
4964 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4965 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4966 checks whether @code{fork} is just a stub by trying to run it.
4968 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4969 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4970 define @code{vfork} to be @code{fork} for backward compatibility with
4971 previous versions of @command{autoconf}.  This macro checks for several known
4972 errors in implementations of @code{vfork} and considers the system to not
4973 have a working @code{vfork} if it detects any of them.  It is not considered
4974 to be an implementation error if a child's invocation of @code{signal}
4975 modifies the parent's signal handler, since child processes rarely change
4976 their signal handlers.
4978 Since this macro defines @code{vfork} only for backward compatibility with
4979 previous versions of @command{autoconf} you're encouraged to define it
4980 yourself in new code:
4981 @example
4982 @group
4983 #ifndef HAVE_WORKING_VFORK
4984 # define vfork fork
4985 #endif
4986 @end group
4987 @end example
4988 @end defmac
4990 @defmac AC_FUNC_FSEEKO
4991 @acindex{FUNC_FSEEKO}
4992 @cvindex _LARGEFILE_SOURCE
4993 @cvindex HAVE_FSEEKO
4994 @c @fuindex fseeko
4995 @prindex @code{fseeko}
4996 @c @fuindex ftello
4997 @prindex @code{ftello}
4998 @c @caindex sys_largefile_source
4999 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
5000 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
5001 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
5002 may occur when compiling with @code{AC_SYS_LARGEFILE} on
5003 largefile-sensitive systems where @code{off_t} does not default to a
5004 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
5005 @end defmac
5007 @defmac AC_FUNC_GETGROUPS
5008 @acindex{FUNC_GETGROUPS}
5009 @cvindex HAVE_GETGROUPS
5010 @ovindex GETGROUPS_LIBS
5011 @c @fuindex getgroups
5012 @prindex @code{getgroups}
5013 @caindex func_getgroups_works
5014 If the @code{getgroups} function is available and works (unlike on
5015 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
5016 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
5017 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
5018 @end defmac
5020 @anchor{AC_FUNC_GETLOADAVG}
5021 @defmac AC_FUNC_GETLOADAVG
5022 @acindex{FUNC_GETLOADAVG}
5023 @cvindex SVR4
5024 @cvindex DGUX
5025 @cvindex UMAX
5026 @cvindex UMAX4_3
5027 @cvindex HAVE_NLIST_H
5028 @cvindex NLIST_NAME_UNION
5029 @cvindex GETLOADAVG_PRIVILEGED
5030 @cvindex NEED_SETGID
5031 @cvindex C_GETLOADAVG
5032 @ovindex LIBOBJS
5033 @ovindex NEED_SETGID
5034 @ovindex KMEM_GROUP
5035 @ovindex GETLOADAVG_LIBS
5036 @c @fuindex getloadavg
5037 @prindex @code{getloadavg}
5038 Check how to get the system load averages.  To perform its tests
5039 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5040 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5041 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5043 If the system has the @code{getloadavg} function, define
5044 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5045 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
5046 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
5047 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
5048 possibly define several other C preprocessor macros and output
5049 variables:
5051 @enumerate
5052 @item
5053 Define @code{C_GETLOADAVG}.
5055 @item
5056 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5057 those systems.
5059 @item
5060 @hdrindex{nlist.h}
5061 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5063 @item
5064 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5065 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
5066 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5068 @item
5069 Programs may need to be installed set-group-ID (or set-user-ID) for
5070 @code{getloadavg} to work.  In this case, define
5071 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5072 to @samp{true} (and otherwise to @samp{false}), and set
5073 @code{KMEM_GROUP} to the name of the group that should own the installed
5074 program.
5075 @end enumerate
5077 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5078 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5079 @end defmac
5081 @anchor{AC_FUNC_GETMNTENT}
5082 @defmac AC_FUNC_GETMNTENT
5083 @acindex{FUNC_GETMNTENT}
5084 @cvindex HAVE_GETMNTENT
5085 @c @fuindex getmntent
5086 @prindex @code{getmntent}
5087 @caindex search_getmntent
5088 Check for @code{getmntent} in the standard C library, and then in the
5089 @file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5090 IRIX 4, PTX, and UnixWare, respectively.  Then, if
5091 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5092 @code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5093 @code{ac_cv_func_getmntent} to @code{no}.
5095 The result of this macro can be overridden by setting the cache variable
5096 @code{ac_cv_search_getmntent}.
5097 @end defmac
5099 @defmac AC_FUNC_GETPGRP
5100 @acindex{FUNC_GETPGRP}
5101 @cvindex GETPGRP_VOID
5102 @c @fuindex getpgid
5103 @c @fuindex getpgrp
5104 @prindex @code{getpgid}
5105 @prindex @code{getpgrp}
5106 @caindex func_getpgrp_void
5107 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5108 @code{getpgrp}; this is the Posix behavior.  On older BSD
5109 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5110 behaves like Posix's @code{getpgid}.
5112 @example
5113 #ifdef GETPGRP_VOID
5114   pid = getpgrp ();
5115 #else
5116   pid = getpgrp (0);
5117 #endif
5118 @end example
5120 This macro does not check whether
5121 @code{getpgrp} exists at all; if you need to work in that situation,
5122 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5124 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5125 variable.
5127 This macro is obsolescent, as current systems have a @code{getpgrp}
5128 whose signature conforms to Posix.  New programs need not use this macro.
5129 @end defmac
5131 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5132 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5133 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5134 @c @fuindex lstat
5135 @prindex @code{lstat}
5136 @caindex func_lstat_dereferences_slashed_symlink
5137 If @file{link} is a symbolic link, then @code{lstat} should treat
5138 @file{link/} the same as @file{link/.}.  However, many older
5139 @code{lstat} implementations incorrectly ignore trailing slashes.
5141 It is safe to assume that if @code{lstat} incorrectly ignores
5142 trailing slashes, then other symbolic-link-aware functions like
5143 @code{unlink} also incorrectly ignore trailing slashes.
5145 If @code{lstat} behaves properly, define
5146 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5147 @code{AC_LIBOBJ} replacement of @code{lstat}.
5149 The result of this macro is cached in the
5150 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5152 The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5153 New programs should use Gnulib's @code{lstat} module.  @xref{Gnulib}.
5154 @end defmac
5156 @defmac AC_FUNC_MALLOC
5157 @acindex{FUNC_MALLOC}
5158 @cvindex HAVE_MALLOC
5159 @cvindex malloc
5160 @c @fuindex malloc
5161 @prindex @code{malloc}
5162 @caindex func_malloc_0_nonnull
5163 If the @code{malloc} function is compatible with the GNU C
5164 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5165 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5166 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5167 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5168 native @code{malloc} is not used in the main project.
5170 Typically, the replacement file @file{malloc.c} should look like (note
5171 the @samp{#undef malloc}):
5173 @verbatim
5174 #include <config.h>
5175 #undef malloc
5177 #include <sys/types.h>
5179 void *malloc ();
5181 /* Allocate an N-byte block of memory from the heap.
5182    If N is zero, allocate a 1-byte block.  */
5184 void *
5185 rpl_malloc (size_t n)
5187   if (n == 0)
5188     n = 1;
5189   return malloc (n);
5191 @end verbatim
5193 The result of this macro is cached in the
5194 @code{ac_cv_func_malloc_0_nonnull} variable.
5195 @end defmac
5197 @defmac AC_FUNC_MBRTOWC
5198 @acindex{FUNC_MBRTOWC}
5199 @cvindex HAVE_MBRTOWC
5200 @c @fuindex mbrtowc
5201 @prindex @code{mbrtowc}
5202 @caindex func_mbrtowc
5203 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5204 type @code{mbstate_t} are properly declared.
5206 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5207 variable.
5208 @end defmac
5210 @defmac AC_FUNC_MEMCMP
5211 @acindex{FUNC_MEMCMP}
5212 @ovindex LIBOBJS
5213 @c @fuindex memcmp
5214 @prindex @code{memcmp}
5215 @caindex func_memcmp_working
5216 If the @code{memcmp} function is not available, or does not work on
5217 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5218 bytes or more and with at least one buffer not starting on a 4-byte
5219 boundary (such as the one on NeXT x86 OpenStep), require an
5220 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5222 The result of this macro is cached in the
5223 @code{ac_cv_func_memcmp_working} variable.
5225 This macro is obsolescent, as current systems have a working
5226 @code{memcmp}.  New programs need not use this macro.
5227 @end defmac
5229 @defmac AC_FUNC_MKTIME
5230 @acindex{FUNC_MKTIME}
5231 @ovindex LIBOBJS
5232 @c @fuindex mktime
5233 @prindex @code{mktime}
5234 @caindex func_working_mktime
5235 If the @code{mktime} function is not available, or does not work
5236 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5237 For the purposes of this test, @code{mktime} should conform to the
5238 Posix standard and should be the inverse of
5239 @code{localtime}.
5241 The result of this macro is cached in the
5242 @code{ac_cv_func_working_mktime} variable.
5244 The @code{AC_FUNC_MKTIME} macro is obsolescent.  New programs should
5245 use Gnulib's @code{mktime} module.  @xref{Gnulib}.
5246 @end defmac
5248 @anchor{AC_FUNC_MMAP}
5249 @defmac AC_FUNC_MMAP
5250 @acindex{FUNC_MMAP}
5251 @cvindex HAVE_MMAP
5252 @c @fuindex mmap
5253 @prindex @code{mmap}
5254 @caindex func_mmap_fixed_mapped
5255 If the @code{mmap} function exists and works correctly, define
5256 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5257 memory.
5259 The result of this macro is cached in the
5260 @code{ac_cv_func_mmap_fixed_mapped} variable.
5261 @end defmac
5263 @defmac AC_FUNC_OBSTACK
5264 @acindex{FUNC_OBSTACK}
5265 @cvindex HAVE_OBSTACK
5266 @cindex obstack
5267 @caindex func_obstack
5268 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5269 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5271 The result of this macro is cached in the @code{ac_cv_func_obstack}
5272 variable.
5273 @end defmac
5275 @defmac AC_FUNC_REALLOC
5276 @acindex{FUNC_REALLOC}
5277 @cvindex HAVE_REALLOC
5278 @cvindex realloc
5279 @c @fuindex realloc
5280 @prindex @code{realloc}
5281 @caindex func_realloc_0_nonnull
5282 If the @code{realloc} function is compatible with the GNU C
5283 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5284 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5285 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5286 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5287 the native @code{realloc} is not used in the main project.  See
5288 @code{AC_FUNC_MALLOC} for details.
5290 The result of this macro is cached in the
5291 @code{ac_cv_func_realloc_0_nonnull} variable.
5292 @end defmac
5294 @defmac AC_FUNC_SELECT_ARGTYPES
5295 @acindex{FUNC_SELECT_ARGTYPES}
5296 @cvindex SELECT_TYPE_ARG1
5297 @cvindex SELECT_TYPE_ARG234
5298 @cvindex SELECT_TYPE_ARG5
5299 @c @fuindex select
5300 @prindex @code{select}
5301 @c @caindex func_select_args
5302 Determines the correct type to be passed for each of the
5303 @code{select} function's arguments, and defines those types
5304 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5305 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5306 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5307 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5309 This macro is obsolescent, as current systems have a @code{select} whose
5310 signature conforms to Posix.  New programs need not use this macro.
5311 @end defmac
5313 @defmac AC_FUNC_SETPGRP
5314 @acindex{FUNC_SETPGRP}
5315 @cvindex SETPGRP_VOID
5316 @c @fuindex setpgrp
5317 @prindex @code{setpgrp}
5318 @caindex func_setpgrp_void
5319 If @code{setpgrp} takes no argument (the Posix version), define
5320 @code{SETPGRP_VOID}.  Otherwise, it is the BSD version, which takes
5321 two process IDs as arguments.  This macro does not check whether
5322 @code{setpgrp} exists at all; if you need to work in that situation,
5323 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5325 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5326 variable.
5328 This macro is obsolescent, as current systems have a @code{setpgrp}
5329 whose signature conforms to Posix.  New programs need not use this macro.
5330 @end defmac
5332 @defmac AC_FUNC_STAT
5333 @defmacx AC_FUNC_LSTAT
5334 @acindex{FUNC_STAT}
5335 @acindex{FUNC_LSTAT}
5336 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5337 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5338 @c @fuindex stat
5339 @prindex @code{stat}
5340 @c @fuindex lstat
5341 @prindex @code{lstat}
5342 @caindex func_stat_empty_string_bug
5343 @caindex func_lstat_empty_string_bug
5344 Determine whether @code{stat} or @code{lstat} have the bug that it
5345 succeeds when given the zero-length file name as argument.  The @code{stat}
5346 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5347 this.
5349 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5350 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5351 replacement of it.
5353 The results of these macros are cached in the
5354 @code{ac_cv_func_stat_empty_string_bug} and the
5355 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5357 These macros are obsolescent, as no current systems have the bug.
5358 New programs need not use these macros.
5359 @end defmac
5361 @anchor{AC_FUNC_STRCOLL}
5362 @defmac AC_FUNC_STRCOLL
5363 @acindex{FUNC_STRCOLL}
5364 @cvindex HAVE_STRCOLL
5365 @c @fuindex strcoll
5366 @prindex @code{strcoll}
5367 @caindex func_strcoll_works
5368 If the @code{strcoll} function exists and works correctly, define
5369 @code{HAVE_STRCOLL}.  This does a bit more than
5370 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5371 definitions of @code{strcoll} that should not be used.
5373 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5374 variable.
5375 @end defmac
5377 @defmac AC_FUNC_STRERROR_R
5378 @acindex{FUNC_STRERROR_R}
5379 @cvindex HAVE_STRERROR_R
5380 @cvindex HAVE_DECL_STRERROR_R
5381 @cvindex STRERROR_R_CHAR_P
5382 @c @fuindex strerror_r
5383 @caindex func_strerror_r_char_p
5384 @prindex @code{strerror_r}
5385 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5386 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5387 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5388 returns an @code{int} error number.  The Thread-Safe Functions option of
5389 Posix requires @code{strerror_r} to return @code{int}, but
5390 many systems (including, for example, version 2.2.4 of the GNU C
5391 Library) return a @code{char *} value that is not necessarily equal to
5392 the buffer argument.
5394 The result of this macro is cached in the
5395 @code{ac_cv_func_strerror_r_char_p} variable.
5396 @end defmac
5398 @anchor{AC_FUNC_STRFTIME}
5399 @defmac AC_FUNC_STRFTIME
5400 @acindex{FUNC_STRFTIME}
5401 @cvindex HAVE_STRFTIME
5402 @c @fuindex strftime
5403 @prindex @code{strftime}
5404 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5405 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5407 This macro is obsolescent, as no current systems require the @file{intl}
5408 library for @code{strftime}.  New programs need not use this macro.
5409 @end defmac
5411 @defmac AC_FUNC_STRTOD
5412 @acindex{FUNC_STRTOD}
5413 @ovindex POW_LIB
5414 @c @fuindex strtod
5415 @prindex @code{strtod}
5416 @caindex func_strtod
5417 @caindex func_pow
5418 If the @code{strtod} function does not exist or doesn't work correctly,
5419 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5420 because @file{strtod.c} is likely to need @samp{pow}, set the output
5421 variable @code{POW_LIB} to the extra library needed.
5423 This macro caches its result in the @code{ac_cv_func_strtod} variable
5424 and depends upon the result in the @code{ac_cv_func_pow} variable.
5426 The @code{AC_FUNC_STRTOD} macro is obsolescent.  New programs should
5427 use Gnulib's @code{strtod} module.  @xref{Gnulib}.
5428 @end defmac
5430 @defmac AC_FUNC_STRTOLD
5431 @acindex{FUNC_STRTOLD}
5432 @cvindex HAVE_STRTOLD
5433 @prindex @code{strtold}
5434 @caindex func_strtold
5435 If the @code{strtold} function exists and conforms to C99, define
5436 @code{HAVE_STRTOLD}.
5438 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5439 @end defmac
5441 @defmac AC_FUNC_STRNLEN
5442 @acindex{FUNC_STRNLEN}
5443 @cvindex HAVE_STRNLEN
5444 @c @fuindex strnlen
5445 @prindex @code{strnlen}
5446 @caindex func_strnlen_working
5447 If the @code{strnlen} function is not available, or is buggy (like the one
5448 from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5450 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5451 variable.
5452 @end defmac
5454 @anchor{AC_FUNC_UTIME_NULL}
5455 @defmac AC_FUNC_UTIME_NULL
5456 @acindex{FUNC_UTIME_NULL}
5457 @cvindex HAVE_UTIME_NULL
5458 @c @fuindex utime
5459 @prindex @code{utime}
5460 @caindex func_utime_null
5461 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5462 the present, define @code{HAVE_UTIME_NULL}.
5464 This macro caches its result in the @code{ac_cv_func_utime_null}
5465 variable.
5467 This macro is obsolescent, as all current systems have a @code{utime}
5468 that behaves this way.  New programs need not use this macro.
5469 @end defmac
5471 @anchor{AC_FUNC_VPRINTF}
5472 @defmac AC_FUNC_VPRINTF
5473 @acindex{FUNC_VPRINTF}
5474 @cvindex HAVE_VPRINTF
5475 @cvindex HAVE_DOPRNT
5476 @c @fuindex vprintf
5477 @prindex @code{vprintf}
5478 @c @fuindex vsprintf
5479 @prindex @code{vsprintf}
5480 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5481 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5482 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5483 are also available.)
5485 This macro is obsolescent, as all current systems have @code{vprintf}.
5486 New programs need not use this macro.
5487 @end defmac
5489 @defmac AC_REPLACE_FNMATCH
5490 @acindex{REPLACE_FNMATCH}
5491 @c @fuindex fnmatch
5492 @prindex @code{fnmatch}
5493 @hdrindex{fnmatch.h}
5494 @caindex func_fnmatch_works
5495 If the @code{fnmatch} function does not conform to Posix (see
5496 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5498 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5499 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5500 copy of the source code of GNU @code{fnmatch}.  If necessary,
5501 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5502 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5503 included in place of the system @code{<fnmatch.h>}.
5505 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5506 variable.
5508 This macro is obsolescent, as it assumes the use of particular source
5509 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5510 which provides this macro along with the source files.  @xref{Gnulib}.
5511 @end defmac
5515 @node Generic Functions
5516 @subsection Generic Function Checks
5518 These macros are used to find functions not covered by the ``particular''
5519 test macros.  If the functions might be in libraries other than the
5520 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5521 If you need to check the behavior of a function as well as find out
5522 whether it is present, you have to write your own test for
5523 it (@pxref{Writing Tests}).
5525 @anchor{AC_CHECK_FUNC}
5526 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5527   @ovar{action-if-not-found})
5528 @acindex{CHECK_FUNC}
5529 @caindex func_@var{function}
5530 If C function @var{function} is available, run shell commands
5531 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5532 want to define a symbol if the function is available, consider using
5533 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5534 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5535 standardized than C++.  (@pxref{Language Choice}, for more information
5536 about selecting the language for checks.)
5538 This macro caches its result in the @code{ac_cv_func_@var{function}}
5539 variable.
5540 @end defmac
5542 @anchor{AC_CHECK_FUNCS}
5543 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5544   @ovar{action-if-not-found})
5545 @acindex{CHECK_FUNCS}
5546 @cvindex HAVE_@var{function}
5547 For each @var{function} enumerated in the blank-or-newline-separated argument
5548 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5549 If @var{action-if-found} is given, it is additional shell code to
5550 execute when one of the functions is found.  You can give it a value of
5551 @samp{break} to break out of the loop on the first match.  If
5552 @var{action-if-not-found} is given, it is executed when one of the
5553 functions is not found.
5555 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5556 @end defmac
5558 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5559 @acindex{CHECK_FUNCS_ONCE}
5560 @cvindex HAVE_@var{function}
5561 For each @var{function} enumerated in the blank-or-newline-separated argument
5562 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5563 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5564 checking code at most once, so that @command{configure} is smaller and
5565 faster; but the checks cannot be conditionalized and are always done once,
5566 early during the @command{configure} run.
5567 @end defmac
5569 @sp 1
5571 Autoconf follows a philosophy that was formed over the years by those
5572 who have struggled for portability: isolate the portability issues in
5573 specific files, and then program as if you were in a Posix
5574 environment.  Some functions may be missing or unfixable, and your
5575 package must be ready to replace them.
5577 Suitable replacements for many such problem functions are available from
5578 Gnulib (@pxref{Gnulib}).
5580 @defmac AC_LIBOBJ (@var{function})
5581 @acindex{LIBOBJ}
5582 @ovindex LIBOBJS
5583 Specify that @samp{@var{function}.c} must be included in the executables
5584 to replace a missing or broken implementation of @var{function}.
5586 @vrindex ac_objext
5587 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5588 variable @code{LIBOBJS} if it is not already in, and calls
5589 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5590 directly change @code{LIBOBJS}, since this is not traceable.
5591 @end defmac
5593 @defmac AC_LIBSOURCE (@var{file})
5594 @acindex{LIBSOURCE}
5595 Specify that @var{file} might be needed to compile the project.  If you
5596 need to know what files might be needed by a @file{configure.ac}, you
5597 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5599 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5600 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5601 that case, since shell variables cannot be traced statically, you must
5602 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5603 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5604 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5605 @code{"foo"} or @code{"bar"}, you should do:
5607 @example
5608 AC_LIBSOURCE([foo.c])
5609 AC_LIBSOURCE([bar.c])
5610 AC_LIBOBJ([$foo_or_bar])
5611 @end example
5613 @noindent
5614 There is usually a way to avoid this, however, and you are encouraged to
5615 simply call @code{AC_LIBOBJ} with literal arguments.
5617 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5618 slightly different semantics: the old macro took the function name,
5619 e.g., @code{foo}, as its argument rather than the file name.
5620 @end defmac
5622 @defmac AC_LIBSOURCES (@var{files})
5623 @acindex{LIBSOURCES}
5624 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5625 comma-separated M4 list.  Thus, the above example might be rewritten:
5627 @example
5628 AC_LIBSOURCES([foo.c, bar.c])
5629 AC_LIBOBJ([$foo_or_bar])
5630 @end example
5631 @end defmac
5633 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5634 @acindex{CONFIG_LIBOBJ_DIR}
5635 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5636 @var{directory}, a name relative to the top level of the
5637 source tree.  The replacement directory defaults to @file{.}, the top
5638 level directory, and the most typical value is @file{lib}, corresponding
5639 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5641 @command{configure} might need to know the replacement directory for the
5642 following reasons: (i) some checks use the replacement files, (ii) some
5643 macros bypass broken system headers by installing links to the
5644 replacement headers (iii) when used in conjunction with Automake,
5645 within each makefile, @var{directory} is used as a relative path
5646 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5647 @code{LTLIBOBJS}, etc.
5648 @end defmac
5650 @sp 1
5652 It is common to merely check for the existence of a function, and ask
5653 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5654 a convenient shorthand.
5656 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5657 @acindex{REPLACE_FUNCS}
5658 @cvindex HAVE_@var{function}
5659 @ovindex LIBOBJS
5660 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5661 @var{action-if-not-found}.  You can declare your replacement function by
5662 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5663 system has the function, it probably declares it in a header file you
5664 should be including, so you shouldn't redeclare it lest your declaration
5665 conflict.
5666 @end defmac
5668 @node Header Files
5669 @section Header Files
5670 @cindex Header, checking
5672 The following macros check for the presence of certain C header files.
5673 If there is no macro specifically defined to check for a header file you need,
5674 and you don't need to check for any special properties of
5675 it, then you can use one of the general header-file check macros.
5677 @menu
5678 * Header Portability::          Collected knowledge on common headers
5679 * Particular Headers::          Special handling to find certain headers
5680 * Generic Headers::             How to find other headers
5681 @end menu
5683 @node Header Portability
5684 @subsection Portability of Headers
5685 @cindex Portability of headers
5686 @cindex Header portability
5688 This section documents some collected knowledge about common headers,
5689 and the problems they cause.  By definition, this list always requires
5690 additions.  A much more complete list is maintained by the Gnulib
5691 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5692 Posix Headers, gnulib, GNU gnulib} and @ref{Glibc Header File
5693 Substitutes, , Glibc Headers, gnulib, GNU gnulib}.  Please help us keep
5694 the gnulib list as complete as possible.
5696 @table @asis
5698 @item @file{limits.h}
5699 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5700 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5701 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5702 define them.
5704 @item @file{inttypes.h} vs.@: @file{stdint.h}
5705 @hdrindex{inttypes.h}
5706 @hdrindex{stdint.h}
5707 The C99 standard says that @file{inttypes.h} includes
5708 @file{stdint.h}, so there's no need to include @file{stdint.h}
5709 separately in a standard environment.  Some implementations have
5710 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5711 know of any implementation that has @file{stdint.h} but not
5712 @file{inttypes.h}.
5714 @item @file{linux/irda.h}
5715 @hdrindex{linux/irda.h}
5716 It requires @file{linux/types.h} and @file{sys/socket.h}.
5718 @item @file{linux/random.h}
5719 @hdrindex{linux/random.h}
5720 It requires @file{linux/types.h}.
5722 @item @file{net/if.h}
5723 @hdrindex{net/if.h}
5724 On Darwin, this file requires that @file{sys/socket.h} be included
5725 beforehand.  One should run:
5727 @example
5728 AC_CHECK_HEADERS([sys/socket.h])
5729 AC_CHECK_HEADERS([net/if.h], [], [],
5730 [#include <stdio.h>
5731 #ifdef STDC_HEADERS
5732 # include <stdlib.h>
5733 # include <stddef.h>
5734 #else
5735 # ifdef HAVE_STDLIB_H
5736 #  include <stdlib.h>
5737 # endif
5738 #endif
5739 #ifdef HAVE_SYS_SOCKET_H
5740 # include <sys/socket.h>
5741 #endif
5743 @end example
5745 @item @file{netinet/if_ether.h}
5746 @hdrindex{netinet/if_ether.h}
5747 On Darwin, this file requires that @file{stdio.h} and
5748 @file{sys/socket.h} be included beforehand.  One should run:
5750 @example
5751 AC_CHECK_HEADERS([sys/socket.h])
5752 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5753 [#include <stdio.h>
5754 #ifdef STDC_HEADERS
5755 # include <stdlib.h>
5756 # include <stddef.h>
5757 #else
5758 # ifdef HAVE_STDLIB_H
5759 #  include <stdlib.h>
5760 # endif
5761 #endif
5762 #ifdef HAVE_SYS_SOCKET_H
5763 # include <sys/socket.h>
5764 #endif
5766 @end example
5768 @item @file{stdint.h}
5769 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5771 @item @file{stdlib.h}
5772 @hdrindex{stdlib.h}
5773 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5775 @item @file{sys/mount.h}
5776 @hdrindex{sys/mount.h}
5777 On FreeBSD 4.8 on ia32 and using gcc version 2.95.4,
5778 @file{sys/params.h} is a prerequisite.
5780 @item @file{sys/ptem.h}
5781 @hdrindex{sys/ptem.h}
5782 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5784 @item @file{sys/socket.h}
5785 @hdrindex{sys/socket.h}
5786 On Darwin, @file{stdlib.h} is a prerequisite.
5788 @item @file{sys/ucred.h}
5789 @hdrindex{sys/ucred.h}
5790 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5792 @item @file{X11/extensions/scrnsaver.h}
5793 @hdrindex{X11/extensions/scrnsaver.h}
5794 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5795 so required that you might not even consider looking for it.
5797 @example
5798 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5799 [[#include <X11/Xlib.h>
5801 @end example
5802 @end table
5805 @node Particular Headers
5806 @subsection Particular Header Checks
5808 These macros check for particular system header files---whether they
5809 exist, and in some cases whether they declare certain symbols.
5811 @defmac AC_HEADER_ASSERT
5812 @acindex{HEADER_ASSERT}
5813 @cvindex NDEBUG
5814 @hdrindex{assert.h}
5815 Check whether to enable assertions in the style of @file{assert.h}.
5816 Assertions are enabled by default, but the user can override this by
5817 invoking @command{configure} with the @option{--disable-assert} option.
5818 @end defmac
5820 @anchor{AC_HEADER_DIRENT}
5821 @defmac AC_HEADER_DIRENT
5822 @acindex{HEADER_DIRENT}
5823 @cvindex HAVE_DIRENT_H
5824 @cvindex HAVE_NDIR_H
5825 @cvindex HAVE_SYS_DIR_H
5826 @cvindex HAVE_SYS_NDIR_H
5827 @hdrindex{dirent.h}
5828 @hdrindex{sys/ndir.h}
5829 @hdrindex{sys/dir.h}
5830 @hdrindex{ndir.h}
5831 Check for the following header files.  For the first one that is
5832 found and defines @samp{DIR}, define the listed C preprocessor macro:
5834 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5835 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5836 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5837 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5838 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5839 @end multitable
5841 The directory-library declarations in your source code should look
5842 something like the following:
5844 @example
5845 @group
5846 #include <sys/types.h>
5847 #ifdef HAVE_DIRENT_H
5848 # include <dirent.h>
5849 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5850 #else
5851 # define dirent direct
5852 # define NAMLEN(dirent) ((dirent)->d_namlen)
5853 # ifdef HAVE_SYS_NDIR_H
5854 #  include <sys/ndir.h>
5855 # endif
5856 # ifdef HAVE_SYS_DIR_H
5857 #  include <sys/dir.h>
5858 # endif
5859 # ifdef HAVE_NDIR_H
5860 #  include <ndir.h>
5861 # endif
5862 #endif
5863 @end group
5864 @end example
5866 Using the above declarations, the program would declare variables to be
5867 of type @code{struct dirent}, not @code{struct direct}, and would access
5868 the length of a directory entry name by passing a pointer to a
5869 @code{struct dirent} to the @code{NAMLEN} macro.
5871 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5873 This macro is obsolescent, as all current systems with directory
5874 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5876 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5877 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5878 @end defmac
5880 @anchor{AC_HEADER_MAJOR}
5881 @defmac AC_HEADER_MAJOR
5882 @acindex{HEADER_MAJOR}
5883 @cvindex MAJOR_IN_MKDEV
5884 @cvindex MAJOR_IN_SYSMACROS
5885 @hdrindex{sys/mkdev.h}
5886 @hdrindex{sys/sysmacros.h}
5887 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5888 @code{makedev}, but @file{sys/mkdev.h} does, define
5889 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5890 @code{MAJOR_IN_SYSMACROS}.
5891 @end defmac
5893 @defmac AC_HEADER_RESOLV
5894 @acindex{HEADER_RESOLV}
5895 @cvindex HAVE_RESOLV_H
5896 @hdrindex{resolv.h}
5897 Checks for header @file{resolv.h}, checking for prerequisites first.
5898 To properly use @file{resolv.h}, your code should contain something like
5899 the following:
5901 @verbatim
5902 #ifdef HAVE_SYS_TYPES_H
5903 #  include <sys/types.h>
5904 #endif
5905 #ifdef HAVE_NETINET_IN_H
5906 #  include <netinet/in.h>   /* inet_ functions / structs */
5907 #endif
5908 #ifdef HAVE_ARPA_NAMESER_H
5909 #  include <arpa/nameser.h> /* DNS HEADER struct */
5910 #endif
5911 #ifdef HAVE_NETDB_H
5912 #  include <netdb.h>
5913 #endif
5914 #include <resolv.h>
5915 @end verbatim
5916 @end defmac
5918 @anchor{AC_HEADER_STAT}
5919 @defmac AC_HEADER_STAT
5920 @acindex{HEADER_STAT}
5921 @cvindex STAT_MACROS_BROKEN
5922 @hdrindex{sys/stat.h}
5923 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5924 @file{sys/stat.h} do not work properly (returning false positives),
5925 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5926 Amdahl UTS and Motorola System V/88.
5928 This macro is obsolescent, as no current systems have the bug.
5929 New programs need not use this macro.
5930 @end defmac
5932 @defmac AC_HEADER_STDBOOL
5933 @acindex{HEADER_STDBOOL}
5934 @cvindex HAVE_STDBOOL_H
5935 @cvindex HAVE__BOOL
5936 @hdrindex{stdbool.h}
5937 @hdrindex{system.h}
5938 @caindex header_stdbool_h
5939 If @file{stdbool.h} exists and conforms to C99, define
5940 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5941 @code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5942 @file{system.h} could contain the following code:
5944 @verbatim
5945 #ifdef HAVE_STDBOOL_H
5946 # include <stdbool.h>
5947 #else
5948 # ifndef HAVE__BOOL
5949 #  ifdef __cplusplus
5950 typedef bool _Bool;
5951 #  else
5952 #   define _Bool signed char
5953 #  endif
5954 # endif
5955 # define bool _Bool
5956 # define false 0
5957 # define true 1
5958 # define __bool_true_false_are_defined 1
5959 #endif
5960 @end verbatim
5962 Alternatively you can use the @samp{stdbool} package of Gnulib
5963 (@pxref{Gnulib}); it packages the above code into a replacement header
5964 and contains a few other bells and whistles.
5966 This macro caches its result in the @code{ac_cv_header_stdbool_h}
5967 variable.
5968 @end defmac
5970 @anchor{AC_HEADER_STDC}
5971 @defmac AC_HEADER_STDC
5972 @acindex{HEADER_STDC}
5973 @cvindex STDC_HEADERS
5974 @hdrindex{stdlib.h}
5975 @hdrindex{stdarg.h}
5976 @hdrindex{string.h}
5977 @hdrindex{float.h}
5978 @hdrindex{ctype.h}
5979 @caindex header_stdc
5980 Define @code{STDC_HEADERS} if the system has C header files
5981 conforming to ANSI C89 (ISO C90).
5982 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
5983 @file{string.h}, and @file{float.h}; if the system has those, it
5984 probably has the rest of the C89 header files.  This macro also
5985 checks whether @file{string.h} declares @code{memchr} (and thus
5986 presumably the other @code{mem} functions), whether @file{stdlib.h}
5987 declare @code{free} (and thus presumably @code{malloc} and other related
5988 functions), and whether the @file{ctype.h} macros work on characters
5989 with the high bit set, as the C standard requires.
5991 If you use this macro, your code can refer to @code{STDC_HEADERS} to
5992 determine whether the system has conforming header files (and probably C
5993 library functions).
5995 This macro caches its result in the @code{ac_cv_header_stdc} variable.
5997 This macro is obsolescent, as current systems have conforming header
5998 files.  New programs need not use this macro.
6000 @hdrindex{string.h}
6001 @hdrindex{strings.h}
6002 Nowadays @file{string.h} is part of the C standard and declares functions like
6003 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
6004 BSD functions like @code{bcopy}; but
6005 historically, string functions were a major sticking point in this area.
6006 If you still want to worry about portability to ancient systems without
6007 standard headers, there is so much variation
6008 that it is probably easier to declare the functions you use than to
6009 figure out exactly what the system header files declare.  Some ancient systems
6010 contained a mix of functions from the C standard and from BSD;
6011 some were mostly standard but lacked @samp{memmove}; some defined the
6012 BSD functions as macros in @file{string.h} or
6013 @file{strings.h}; some had only the BSD functions but
6014 @file{string.h}; some declared the memory functions in @file{memory.h},
6015 some in @file{string.h}; etc.  It is probably sufficient to check for
6016 one string function and one memory function; if the library had the
6017 standard versions of those then it probably had most of the others.
6018 If you put the following in @file{configure.ac}:
6020 @example
6021 # This example is obsolescent.
6022 # Nowadays you can omit these macro calls.
6023 AC_HEADER_STDC
6024 AC_CHECK_FUNCS([strchr memcpy])
6025 @end example
6027 @noindent
6028 then, in your code, you can use declarations like this:
6030 @example
6031 @group
6032 /* This example is obsolescent.
6033    Nowadays you can just #include <string.h>.  */
6034 #ifdef STDC_HEADERS
6035 # include <string.h>
6036 #else
6037 # ifndef HAVE_STRCHR
6038 #  define strchr index
6039 #  define strrchr rindex
6040 # endif
6041 char *strchr (), *strrchr ();
6042 # ifndef HAVE_MEMCPY
6043 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
6044 #  define memmove(d, s, n) bcopy ((s), (d), (n))
6045 # endif
6046 #endif
6047 @end group
6048 @end example
6050 @noindent
6051 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
6052 or @code{strspn}, which have no BSD equivalent, then macros don't
6053 suffice to port to ancient hosts; you must provide an implementation of
6054 each function.  An easy
6055 way to incorporate your implementations only when needed (since the ones
6056 in system C libraries may be hand optimized) is to, taking @code{memchr}
6057 for example, put it in @file{memchr.c} and use
6058 @samp{AC_REPLACE_FUNCS([memchr])}.
6059 @end defmac
6061 @defmac AC_HEADER_SYS_WAIT
6062 @acindex{HEADER_SYS_WAIT}
6063 @cvindex HAVE_SYS_WAIT_H
6064 @hdrindex{sys/wait.h}
6065 @caindex header_sys_wait_h
6066 If @file{sys/wait.h} exists and is compatible with Posix, define
6067 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
6068 does not exist, or if it uses the old BSD @code{union wait} instead
6069 of @code{int} to store a status value.  If @file{sys/wait.h} is not
6070 Posix compatible, then instead of including it, define the
6071 Posix macros with their usual interpretations.  Here is an
6072 example:
6074 @example
6075 @group
6076 #include <sys/types.h>
6077 #ifdef HAVE_SYS_WAIT_H
6078 # include <sys/wait.h>
6079 #endif
6080 #ifndef WEXITSTATUS
6081 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6082 #endif
6083 #ifndef WIFEXITED
6084 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6085 #endif
6086 @end group
6087 @end example
6089 @noindent
6090 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6091 variable.
6093 This macro is obsolescent, as current systems are compatible with Posix.
6094 New programs need not use this macro.
6095 @end defmac
6097 @cvindex _POSIX_VERSION
6098 @hdrindex{unistd.h}
6099 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6100 Posix systems.  If there is no @file{unistd.h}, it is definitely
6101 not a Posix system.  However, some non-Posix systems do
6102 have @file{unistd.h}.
6104 The way to check whether the system supports Posix is:
6106 @example
6107 @group
6108 #ifdef HAVE_UNISTD_H
6109 # include <sys/types.h>
6110 # include <unistd.h>
6111 #endif
6113 #ifdef _POSIX_VERSION
6114 /* Code for Posix systems.  */
6115 #endif
6116 @end group
6117 @end example
6119 @anchor{AC_HEADER_TIME}
6120 @defmac AC_HEADER_TIME
6121 @acindex{HEADER_TIME}
6122 @cvindex TIME_WITH_SYS_TIME
6123 @hdrindex{time.h}
6124 @hdrindex{sys/time.h}
6125 @caindex header_time
6126 If a program may include both @file{time.h} and @file{sys/time.h},
6127 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
6128 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
6129 protected against multiple inclusion, so programs could not explicitly
6130 include both files.  This macro is useful in programs that use, for
6131 example, @code{struct timeval} as well as
6132 @code{struct tm}.  It is best used in conjunction with
6133 @code{HAVE_SYS_TIME_H}, which can be checked for using
6134 @code{AC_CHECK_HEADERS([sys/time.h])}.
6136 @example
6137 @group
6138 #ifdef TIME_WITH_SYS_TIME
6139 # include <sys/time.h>
6140 # include <time.h>
6141 #else
6142 # ifdef HAVE_SYS_TIME_H
6143 #  include <sys/time.h>
6144 # else
6145 #  include <time.h>
6146 # endif
6147 #endif
6148 @end group
6149 @end example
6151 @noindent
6152 This macro caches its result in the @code{ac_cv_header_time} variable.
6154 This macro is obsolescent, as current systems can include both files
6155 when they exist.  New programs need not use this macro.
6156 @end defmac
6159 @defmac AC_HEADER_TIOCGWINSZ
6160 @acindex{HEADER_TIOCGWINSZ}
6161 @cvindex GWINSZ_IN_SYS_IOCTL
6162 @hdrindex{sys/ioctl.h}
6163 @hdrindex{termios.h}
6164 @c FIXME: I need clarifications from Jim.
6165 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6166 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6167 found in @file{<termios.h>}.
6169 Use:
6171 @example
6172 @group
6173 #ifdef HAVE_TERMIOS_H
6174 # include <termios.h>
6175 #endif
6177 #ifdef GWINSZ_IN_SYS_IOCTL
6178 # include <sys/ioctl.h>
6179 #endif
6180 @end group
6181 @end example
6182 @end defmac
6184 @node Generic Headers
6185 @subsection Generic Header Checks
6187 These macros are used to find system header files not covered by the
6188 ``particular'' test macros.  If you need to check the contents of a header
6189 as well as find out whether it is present, you have to write your own
6190 test for it (@pxref{Writing Tests}).
6192 @anchor{AC_CHECK_HEADER}
6193 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6194   @ovar{action-if-not-found}, @ovar{includes})
6195 @acindex{CHECK_HEADER}
6196 @caindex header_@var{header-file}
6197 If the system header file @var{header-file} is compilable, execute shell
6198 commands @var{action-if-found}, otherwise execute
6199 @var{action-if-not-found}.  If you just want to define a symbol if the
6200 header file is available, consider using @code{AC_CHECK_HEADERS}
6201 instead.
6203 @var{includes} is decoded to determine the appropriate include
6204 directives.  If omitted or empty, @file{configure} will check for both header
6205 existence (with the preprocessor) and usability (with the compiler),
6206 using @code{AC_INCLUDES_DEFAULT} for the compile test.  If
6207 there is a discrepancy between the results, a warning is issued to the
6208 user, and the compiler results are favored (@pxref{Present But
6209 Cannot Be Compiled}).  In general, favoring the compiler results means
6210 that a header will be treated as not found even though the file exists,
6211 because you did not provide enough prerequisites.
6213 Providing a non-empty @var{includes} argument allows the code to provide
6214 any prerequisites prior to including the header under test; it is common
6215 to use the argument @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6216 Includes}).  With an explicit fourth argument, no preprocessor test is
6217 needed.  As a special case, an @var{includes} of exactly @samp{-}
6218 triggers the older preprocessor check, which merely determines existence
6219 of the file in the preprocessor search path; this should only be used as
6220 a last resort (it is safer to determine the actual prerequisites and
6221 perform a compiler check, or else use @code{AC_PREPROC_IFELSE} to make
6222 it obvious that only a preprocessor check is desired).
6224 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6225 variable, with characters not suitable for a variable name mapped to
6226 underscores.
6227 @end defmac
6229 @anchor{AC_CHECK_HEADERS}
6230 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6231   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6232   @ovar{includes})
6233 @acindex{CHECK_HEADERS}
6234 @cvindex HAVE_@var{header}
6235 @caindex header_@var{header-file}
6236 For each given system header file @var{header-file} in the
6237 blank-separated argument list that exists, define
6238 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6239 is given, it is additional shell code to execute when one of the header
6240 files is found.  You can give it a value of @samp{break} to break out of
6241 the loop on the first match.  If @var{action-if-not-found} is given, it
6242 is executed when one of the header files is not found.
6244 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6245 choose the set of preprocessor directives supplied before the header
6246 under test.
6248 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6249 variable, with characters not suitable for a variable name mapped to
6250 underscores.
6251 @end defmac
6253 Previous versions of Autoconf merely checked whether the header was
6254 accepted by the preprocessor.  This was changed because the old test was
6255 inappropriate for typical uses.  Headers are typically used to compile,
6256 not merely to preprocess, and the old behavior sometimes accepted
6257 headers that clashed at compile-time (@pxref{Present But Cannot Be
6258 Compiled}).  If you need to check whether a header is preprocessable,
6259 you can use @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}).
6261 Actually requiring a header to compile improves the robustness of the
6262 test, but it also requires
6263 that you make sure that headers that must be included before the
6264 @var{header-file} be part of the @var{includes}, (@pxref{Default
6265 Includes}).  If looking for @file{bar.h}, which requires that
6266 @file{foo.h} be included before if it exists, we suggest the following
6267 scheme:
6269 @verbatim
6270 AC_CHECK_HEADERS([foo.h])
6271 AC_CHECK_HEADERS([bar.h], [], [],
6272 [#ifdef HAVE_FOO_H
6273 # include <foo.h>
6274 #endif
6276 @end verbatim
6278 The following variant generates smaller, faster @command{configure}
6279 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
6281 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6282 @acindex{CHECK_HEADERS_ONCE}
6283 @cvindex HAVE_@var{header}
6284 For each given system header file @var{header-file} in the
6285 blank-separated argument list that exists, define
6286 @code{HAVE_@var{header-file}} (in all capitals).
6287 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
6288 checking code at most once, so that @command{configure} is smaller and
6289 faster; but the checks cannot be conditionalized and are always done once,
6290 early during the @command{configure} run.  Thus, this macro is only safe
6291 for checking headers that do not have prerequisites beyond what
6292 @code{AC_INCLUDES_DEFAULT} provides.
6293 @end defmac
6295 @node Declarations
6296 @section Declarations
6297 @cindex Declaration, checking
6299 The following macros check for the declaration of variables and
6300 functions.  If there is no macro specifically defined to check for a
6301 symbol you need, then you can use the general macros (@pxref{Generic
6302 Declarations}) or, for more complex tests, you may use
6303 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6305 @menu
6306 * Particular Declarations::     Macros to check for certain declarations
6307 * Generic Declarations::        How to find other declarations
6308 @end menu
6310 @node Particular Declarations
6311 @subsection Particular Declaration Checks
6313 There are no specific macros for declarations.
6315 @node Generic Declarations
6316 @subsection Generic Declaration Checks
6318 These macros are used to find declarations not covered by the ``particular''
6319 test macros.
6321 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6322   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6323 @acindex{CHECK_DECL}
6324 @caindex have_decl_@var{symbol}
6325 If @var{symbol} (a function, variable, or constant) is not declared in
6326 @var{includes} and a declaration is needed, run the shell commands
6327 @var{action-if-not-found}, otherwise @var{action-if-found}.
6328 @var{includes} is a series of include directives, defaulting to
6329 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6330 prior to the declaration under test.
6332 This macro actually tests whether @var{symbol} is defined as a macro or
6333 can be used as an r-value, not whether it is really declared, because it
6334 is much safer to avoid introducing extra declarations when they are not
6335 needed.  In order to facilitate use of C++ and overloaded function
6336 declarations, it is possible to specify function argument types in
6337 parentheses for types which can be zero-initialized:
6339 @example
6340 AC_CHECK_DECL([basename(char *)])
6341 @end example
6343 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6344 variable, with characters not suitable for a variable name mapped to
6345 underscores.
6346 @end defmac
6348 @anchor{AC_CHECK_DECLS}
6349 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6350   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6351 @acindex{CHECK_DECLS}
6352 @cvindex HAVE_DECL_@var{symbol}
6353 @caindex have_decl_@var{symbol}
6354 For each of the @var{symbols} (@emph{comma}-separated list with optional
6355 function argument types for C++ overloads), define
6356 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6357 @var{symbol} is declared, otherwise to @samp{0}.  If
6358 @var{action-if-not-found} is given, it is additional shell code to
6359 execute when one of the function declarations is needed, otherwise
6360 @var{action-if-found} is executed.
6362 @var{includes} is a series of include directives, defaulting to
6363 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6364 prior to the declarations under test.
6366 This macro uses an M4 list as first argument:
6367 @example
6368 AC_CHECK_DECLS([strdup])
6369 AC_CHECK_DECLS([strlen])
6370 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6371 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6372 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6373 @end example
6375 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6376 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6377 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6378 @emph{sure} that the check was performed, use
6379 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6381 @example
6382 #if !HAVE_DECL_SYMBOL
6383 extern char *symbol;
6384 #endif
6385 @end example
6387 @noindent
6388 If the test may have not been performed, however, because it is safer
6389 @emph{not} to declare a symbol than to use a declaration that conflicts
6390 with the system's one, you should use:
6392 @example
6393 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6394 void *malloc (size_t *s);
6395 #endif
6396 @end example
6398 @noindent
6399 You fall into the second category only in extreme situations: either
6400 your files may be used without being configured, or they are used during
6401 the configuration.  In most cases the traditional approach is enough.
6403 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6404 variables, with characters not suitable for a variable name mapped to
6405 underscores.
6406 @end defmac
6408 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6409 @acindex{CHECK_DECLS_ONCE}
6410 @cvindex HAVE_DECL_@var{symbol}
6411 For each of the @var{symbols} (@emph{comma}-separated list), define
6412 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6413 @var{symbol} is declared in the default include files, otherwise to
6414 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6415 generates the checking code at most once, so that @command{configure} is
6416 smaller and faster; but the checks cannot be conditionalized and are
6417 always done once, early during the @command{configure} run.
6418 @end defmac
6421 @node Structures
6422 @section Structures
6423 @cindex Structure, checking
6425 The following macros check for the presence of certain members in C
6426 structures.  If there is no macro specifically defined to check for a
6427 member you need, then you can use the general structure-member macros
6428 (@pxref{Generic Structures}) or, for more complex tests, you may use
6429 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6431 @menu
6432 * Particular Structures::       Macros to check for certain structure members
6433 * Generic Structures::          How to find other structure members
6434 @end menu
6436 @node Particular Structures
6437 @subsection Particular Structure Checks
6439 The following macros check for certain structures or structure members.
6441 @defmac AC_STRUCT_DIRENT_D_INO
6442 @acindex{STRUCT_DIRENT_D_INO}
6443 @cvindex HAVE_STRUCT_DIRENT_D_INO
6444 @c @caindex header_dirent_dirent_h
6445 @c @caindex member_struct_dirent_d_ino
6446 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6447 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6448 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6450 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6451 @code{d_ino}, not whether its contents are always reliable.
6452 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6453 though current systems hide this detail from the user and never return
6454 zero @code{d_ino} values.
6455 Many current systems report an incorrect @code{d_ino} for a directory
6456 entry that is a mount point.
6457 @end defmac
6459 @defmac AC_STRUCT_DIRENT_D_TYPE
6460 @acindex{STRUCT_DIRENT_D_TYPE}
6461 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6462 @c @caindex header_dirent_dirent_h
6463 @c @caindex member_struct_dirent_d_type
6464 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6465 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6466 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6467 @end defmac
6469 @anchor{AC_STRUCT_ST_BLOCKS}
6470 @defmac AC_STRUCT_ST_BLOCKS
6471 @acindex{STRUCT_ST_BLOCKS}
6472 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6473 @cvindex HAVE_ST_BLOCKS
6474 @ovindex LIBOBJS
6475 @caindex member_struct_stat_st_blocks
6476 If @code{struct stat} contains an @code{st_blocks} member, define
6477 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6478 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6479 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6480 future.
6482 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6483 variable.
6484 @end defmac
6486 @defmac AC_STRUCT_TM
6487 @acindex{STRUCT_TM}
6488 @cvindex TM_IN_SYS_TIME
6489 @hdrindex{time.h}
6490 @hdrindex{sys/time.h}
6491 If @file{time.h} does not define @code{struct tm}, define
6492 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6493 had better define @code{struct tm}.
6495 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6496 current systems.  New programs need not use this macro.
6497 @end defmac
6499 @anchor{AC_STRUCT_TIMEZONE}
6500 @defmac AC_STRUCT_TIMEZONE
6501 @acindex{STRUCT_TIMEZONE}
6502 @cvindex HAVE_DECL_TZNAME
6503 @cvindex HAVE_STRUCT_TM_TM_ZONE
6504 @cvindex HAVE_TM_ZONE
6505 @cvindex HAVE_TZNAME
6506 @c @caindex member_struct_tm_tm_zone
6507 @c @caindex struct_tm
6508 Figure out how to get the current timezone.  If @code{struct tm} has a
6509 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6510 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6511 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6512 define @code{HAVE_DECL_TZNAME}.
6513 @end defmac
6515 @node Generic Structures
6516 @subsection Generic Structure Checks
6518 These macros are used to find structure members not covered by the
6519 ``particular'' test macros.
6521 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6522   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6523   @dvar{includes, AC_INCLUDES_DEFAULT})
6524 @acindex{CHECK_MEMBER}
6525 @caindex member_@var{aggregate}_@var{member}
6526 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6527 If no @var{includes} are specified, the default includes are used
6528 (@pxref{Default Includes}).
6530 @example
6531 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6532                 [AC_MSG_ERROR([we need `passwd.pw_gecos'])],
6533                 [[#include <pwd.h>]])
6534 @end example
6536 You can use this macro for submembers:
6538 @example
6539 AC_CHECK_MEMBER(struct top.middle.bot)
6540 @end example
6542 This macro caches its result in the
6543 @code{av_cv_member_@var{aggregate}_@var{member}} variable, with
6544 characters not suitable for a variable name mapped to underscores.
6545 @end defmac
6547 @anchor{AC_CHECK_MEMBERS}
6548 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6549   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6550 @acindex{CHECK_MEMBERS}
6551 @cvindex HAVE_@var{aggregate}_@var{member}
6552 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6553 @var{members} using the previous macro.  When @var{member} belongs to
6554 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6555 capitals, with spaces and dots replaced by underscores).  If
6556 @var{action-if-found} is given, it is executed for each of the found
6557 members.  If @var{action-if-not-found} is given, it is executed for each
6558 of the members that could not be found.
6560 @var{includes} is a series of include directives, defaulting to
6561 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6562 prior to the members under test.
6564 This macro uses M4 lists:
6565 @example
6566 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6567 @end example
6568 @end defmac
6571 @node Types
6572 @section Types
6573 @cindex Types
6574 @cindex C types
6576 The following macros check for C types, either builtin or typedefs.  If
6577 there is no macro specifically defined to check for a type you need, and
6578 you don't need to check for any special properties of it, then you can
6579 use a general type-check macro.
6581 @menu
6582 * Particular Types::            Special handling to find certain types
6583 * Generic Types::               How to find other types
6584 @end menu
6586 @node Particular Types
6587 @subsection Particular Type Checks
6589 @hdrindex{sys/types.h}
6590 @hdrindex{stdlib.h}
6591 @hdrindex{stdint.h}
6592 @hdrindex{inttypes.h}
6593 These macros check for particular C types in @file{sys/types.h},
6594 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6595 exist.
6597 The Gnulib @code{stdint} module is an alternate way to define many of
6598 these symbols; it is useful if you prefer your code to assume a
6599 C99-or-better environment.  @xref{Gnulib}.
6601 @anchor{AC_TYPE_GETGROUPS}
6602 @defmac AC_TYPE_GETGROUPS
6603 @acindex{TYPE_GETGROUPS}
6604 @cvindex GETGROUPS_T
6605 @caindex type_getgroups
6606 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6607 is the base type of the array argument to @code{getgroups}.
6609 This macro caches the base type in the @code{ac_cv_type_getgroups}
6610 variable.
6611 @end defmac
6613 @defmac AC_TYPE_INT8_T
6614 @acindex{TYPE_INT8_T}
6615 @cvindex HAVE_INT8_T
6616 @cvindex int8_t
6617 @caindex c_int8_t
6618 If @file{stdint.h} or @file{inttypes.h} does not define the type
6619 @code{int8_t}, define @code{int8_t} to a signed
6620 integer type that is exactly 8 bits wide and that uses two's complement
6621 representation, if such a type exists.
6622 If you are worried about porting to hosts that lack such a type, you can
6623 use the results of this macro in C89-or-later code as follows:
6625 @example
6626 #if HAVE_STDINT_H
6627 # include <stdint.h>
6628 #endif
6629 #if defined INT8_MAX || defined int8_t
6630  @emph{code using int8_t}
6631 #else
6632  @emph{complicated alternative using >8-bit 'signed char'}
6633 #endif
6634 @end example
6636 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6637 @end defmac
6639 @defmac AC_TYPE_INT16_T
6640 @acindex{TYPE_INT16_T}
6641 @cvindex HAVE_INT16_T
6642 @cvindex int16_t
6643 @caindex c_int16_t
6644 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6645 @end defmac
6647 @defmac AC_TYPE_INT32_T
6648 @acindex{TYPE_INT32_T}
6649 @cvindex HAVE_INT32_T
6650 @cvindex int32_t
6651 @caindex c_int32_t
6652 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6653 @end defmac
6655 @defmac AC_TYPE_INT64_T
6656 @acindex{TYPE_INT64_T}
6657 @cvindex HAVE_INT64_T
6658 @cvindex int64_t
6659 @caindex c_int64_t
6660 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6661 @end defmac
6663 @defmac AC_TYPE_INTMAX_T
6664 @acindex{TYPE_INTMAX_T}
6665 @cvindex HAVE_INTMAX_T
6666 @cvindex intmax_t
6667 @c @caindex type_intmax_t
6668 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6669 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6670 widest signed integer type.
6671 @end defmac
6673 @defmac AC_TYPE_INTPTR_T
6674 @acindex{TYPE_INTPTR_T}
6675 @cvindex HAVE_INTPTR_T
6676 @cvindex intptr_t
6677 @c @caindex type_intptr_t
6678 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6679 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6680 signed integer type wide enough to hold a pointer, if such a type
6681 exists.
6682 @end defmac
6684 @defmac AC_TYPE_LONG_DOUBLE
6685 @acindex{TYPE_LONG_DOUBLE}
6686 @cvindex HAVE_LONG_DOUBLE
6687 @caindex type_long_double
6688 If the C compiler supports a working @code{long double} type, define
6689 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6690 same range and precision as @code{double}.
6692 This macro caches its result in the @code{ac_cv_type_long_double}
6693 variable.
6695 This macro is obsolescent, as current C compilers support @code{long
6696 double}.  New programs need not use this macro.
6697 @end defmac
6699 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6700 @acindex{TYPE_LONG_DOUBLE_WIDER}
6701 @cvindex HAVE_LONG_DOUBLE_WIDER
6702 @caindex type_long_double_wider
6703 If the C compiler supports a working @code{long double} type with more
6704 range or precision than the @code{double} type, define
6705 @code{HAVE_LONG_DOUBLE_WIDER}.
6707 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6708 variable.
6709 @end defmac
6711 @defmac AC_TYPE_LONG_LONG_INT
6712 @acindex{TYPE_LONG_LONG_INT}
6713 @cvindex HAVE_LONG_LONG_INT
6714 @caindex type_long_long_int
6715 If the C compiler supports a working @code{long long int} type, define
6716 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6717 @code{long long int} values in preprocessor @code{#if} expressions,
6718 because too many compilers mishandle such expressions.
6719 @xref{Preprocessor Arithmetic}.
6721 This macro caches its result in the @code{ac_cv_type_long_long_int}
6722 variable.
6723 @end defmac
6725 @defmac AC_TYPE_MBSTATE_T
6726 @acindex{TYPE_MBSTATE_T}
6727 @cvindex mbstate_t
6728 @hdrindex{wchar.h}
6729 @caindex type_mbstate_t
6730 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6731 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6732 @code{<wchar.h>} does not declare it.
6734 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6735 variable.
6736 @end defmac
6738 @anchor{AC_TYPE_MODE_T}
6739 @defmac AC_TYPE_MODE_T
6740 @acindex{TYPE_MODE_T}
6741 @cvindex mode_t
6742 @caindex type_mode_t
6743 Define @code{mode_t} to a suitable type, if standard headers do not
6744 define it.
6746 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6747 @end defmac
6749 @anchor{AC_TYPE_OFF_T}
6750 @defmac AC_TYPE_OFF_T
6751 @acindex{TYPE_OFF_T}
6752 @cvindex off_t
6753 @caindex type_off_t
6754 Define @code{off_t} to a suitable type, if standard headers do not
6755 define it.
6757 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6758 @end defmac
6760 @anchor{AC_TYPE_PID_T}
6761 @defmac AC_TYPE_PID_T
6762 @acindex{TYPE_PID_T}
6763 @cvindex pid_t
6764 @caindex type_pid_t
6765 Define @code{pid_t} to a suitable type, if standard headers do not
6766 define it.
6768 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6769 @end defmac
6771 @anchor{AC_TYPE_SIZE_T}
6772 @defmac AC_TYPE_SIZE_T
6773 @acindex{TYPE_SIZE_T}
6774 @cvindex size_t
6775 @caindex type_size_t
6776 Define @code{size_t} to a suitable type, if standard headers do not
6777 define it.
6779 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6780 @end defmac
6782 @defmac AC_TYPE_SSIZE_T
6783 @acindex{TYPE_SSIZE_T}
6784 @cvindex ssize_t
6785 @caindex type_ssize_t
6786 Define @code{ssize_t} to a suitable type, if standard headers do not
6787 define it.
6789 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6790 @end defmac
6792 @anchor{AC_TYPE_UID_T}
6793 @defmac AC_TYPE_UID_T
6794 @acindex{TYPE_UID_T}
6795 @cvindex uid_t
6796 @cvindex gid_t
6797 @caindex type_uid_t
6798 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6799 headers do not define them.
6801 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6802 @end defmac
6804 @defmac AC_TYPE_UINT8_T
6805 @acindex{TYPE_UINT8_T}
6806 @cvindex HAVE_UINT8_T
6807 @cvindex uint8_t
6808 @caindex c_uint8_t
6809 If @file{stdint.h} or @file{inttypes.h} does not define the type
6810 @code{uint8_t}, define @code{uint8_t} to an
6811 unsigned integer type that is exactly 8 bits wide, if such a type
6812 exists.
6813 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6814 @end defmac
6816 @defmac AC_TYPE_UINT16_T
6817 @acindex{TYPE_UINT16_T}
6818 @cvindex HAVE_UINT16_T
6819 @cvindex uint16_t
6820 @caindex c_uint16_t
6821 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6822 @end defmac
6824 @defmac AC_TYPE_UINT32_T
6825 @acindex{TYPE_UINT32_T}
6826 @cvindex HAVE_UINT32_T
6827 @cvindex uint32_t
6828 @caindex c_uint32_t
6829 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6830 @end defmac
6832 @defmac AC_TYPE_UINT64_T
6833 @acindex{TYPE_UINT64_T}
6834 @cvindex HAVE_UINT64_T
6835 @cvindex uint64_t
6836 @caindex c_uint64_t
6837 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6838 @end defmac
6840 @defmac AC_TYPE_UINTMAX_T
6841 @acindex{TYPE_UINTMAX_T}
6842 @cvindex HAVE_UINTMAX_T
6843 @cvindex uintmax_t
6844 @c @caindex type_uintmax_t
6845 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6846 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6847 widest unsigned integer type.
6848 @end defmac
6850 @defmac AC_TYPE_UINTPTR_T
6851 @acindex{TYPE_UINTPTR_T}
6852 @cvindex HAVE_UINTPTR_T
6853 @cvindex uintptr_t
6854 @c @caindex type_uintptr_t
6855 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6856 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6857 unsigned integer type wide enough to hold a pointer, if such a type
6858 exists.
6859 @end defmac
6861 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6862 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6863 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6864 @caindex type_unsigned_long_long_int
6865 If the C compiler supports a working @code{unsigned long long int} type,
6866 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6867 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6868 because too many compilers mishandle such expressions.
6869 @xref{Preprocessor Arithmetic}.
6871 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
6872 variable.
6873 @end defmac
6875 @node Generic Types
6876 @subsection Generic Type Checks
6878 These macros are used to check for types not covered by the ``particular''
6879 test macros.
6881 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6882   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6883 @acindex{CHECK_TYPE}
6884 @caindex type_@var{type}
6885 Check whether @var{type} is defined.  It may be a compiler builtin type
6886 or defined by the @var{includes}.  @var{includes} is a series of include
6887 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6888 Includes}), which are used prior to the type under test.
6890 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6891 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6892 same test is applied when compiling for C++, which means that in C++
6893 @var{type} should be a type-id and should not be an anonymous
6894 @samp{struct} or @samp{union}.
6896 This macro caches its result in the @code{ac_cv_type_@var{type}}
6897 variable, with @samp{*} mapped to @samp{p} and other characters not
6898 suitable for a variable name mapped to underscores.
6899 @end defmac
6902 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6903   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6904 @acindex{CHECK_TYPES}
6905 @cvindex HAVE_@var{type}
6906 For each @var{type} of the @var{types} that is defined, define
6907 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6908 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6909 specified, the default includes are used (@pxref{Default Includes}).  If
6910 @var{action-if-found} is given, it is additional shell code to execute
6911 when one of the types is found.  If @var{action-if-not-found} is given,
6912 it is executed when one of the types is not found.
6914 This macro uses M4 lists:
6915 @example
6916 AC_CHECK_TYPES([ptrdiff_t])
6917 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6918 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6919 @end example
6921 @end defmac
6923 Autoconf, up to 2.13, used to provide to another version of
6924 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6925 compatibility, a simple heuristic, quite safe but not totally, is
6926 implemented.  In case of doubt, read the documentation of the former
6927 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6930 @node Compilers and Preprocessors
6931 @section Compilers and Preprocessors
6932 @cindex Compilers
6933 @cindex Preprocessors
6935 @ovindex EXEEXT
6936 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6937 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6938 the output of the compiler, typically to the empty string if
6939 Posix and @samp{.exe} if a DOS variant.
6941 @ovindex OBJEXT
6942 They also define the output variable @code{OBJEXT} based on the
6943 output of the compiler, after @file{.c} files have been excluded, typically
6944 to @samp{o} if Posix, @samp{obj} if a DOS variant.
6946 If the compiler being used does not produce executables, the tests fail.  If
6947 the executables can't be run, and cross-compilation is not enabled, they
6948 fail too.  @xref{Manual Configuration}, for more on support for cross
6949 compiling.
6951 @menu
6952 * Specific Compiler Characteristics::  Some portability issues
6953 * Generic Compiler Characteristics::  Language independent tests and features
6954 * C Compiler::                  Checking its characteristics
6955 * C++ Compiler::                Likewise
6956 * Objective C Compiler::        Likewise
6957 * Objective C++ Compiler::      Likewise
6958 * Erlang Compiler and Interpreter::  Likewise
6959 * Fortran Compiler::            Likewise
6960 @end menu
6962 @node Specific Compiler Characteristics
6963 @subsection Specific Compiler Characteristics
6965 Some compilers exhibit different behaviors.
6967 @table @asis
6968 @item Static/Dynamic Expressions
6969 Autoconf relies on a trick to extract one bit of information from the C
6970 compiler: using negative array sizes.  For instance the following
6971 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6972 bytes wide:
6974 @example
6975 static int test_array[sizeof (int) == 4 ? 1 : -1];
6976 @end example
6978 @noindent
6979 To our knowledge, there is a single compiler that does not support this
6980 trick: the HP C compilers (the real ones, not only the
6981 ``bundled'') on HP-UX 11.00.
6982 They incorrectly reject the above program with the diagnostic
6983 ``Variable-length arrays cannot have static storage.''
6984 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
6985 not from the @code{? 1 : -1}, and
6986 Autoconf works around this problem by casting @code{sizeof (int)} to
6987 @code{long int} before comparing it.
6988 @end table
6990 @node Generic Compiler Characteristics
6991 @subsection Generic Compiler Characteristics
6993 @anchor{AC_CHECK_SIZEOF}
6994 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
6995   @dvar{includes, AC_INCLUDES_DEFAULT})
6996 @acindex{CHECK_SIZEOF}
6997 @cvindex SIZEOF_@var{type-or-expr}
6998 @caindex sizeof_@var{type-or-expr}
6999 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7000 the size in bytes of @var{type-or-expr}, which may be either a type or
7001 an expression returning a value that has a size.  If the expression
7002 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7003 @var{includes} is a series of include directives, defaulting to
7004 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7005 prior to the expression under test.
7007 This macro now works even when cross-compiling.  The @var{unused}
7008 argument was used when cross-compiling.
7010 For example, the call
7012 @example
7013 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7014 AC_CHECK_SIZEOF([int *])
7015 @end example
7017 @noindent
7018 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
7020 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7021 variable, with @samp{*} mapped to @samp{p} and other characters not
7022 suitable for a variable name mapped to underscores.
7023 @end defmac
7025 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7026 @acindex{CHECK_ALIGNOF}
7027 @cvindex ALIGNOF_@var{type}
7028 @caindex alignof_@var{type-or-expr}
7029 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7030 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
7031 a structure member declaration.  If @samp{type} is unknown, the result
7032 is 0.  If no @var{includes} are specified, the default includes are used
7033 (@pxref{Default Includes}).
7035 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7036 variable, with @samp{*} mapped to @samp{p} and other characters not
7037 suitable for a variable name mapped to underscores.
7038 @end defmac
7040 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7041   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7042 @acindex{COMPUTE_INT}
7043 Store into the shell variable @var{var} the value of the integer
7044 @var{expression}.  The
7045 value should fit in an initializer in a C variable of type @code{signed
7046 long}.  To support cross compilation (in which case, the macro only works on
7047 hosts that use twos-complement arithmetic), it should be possible to evaluate
7048 the expression at compile-time.  If no @var{includes} are specified, the
7049 default includes are used (@pxref{Default Includes}).
7051 Execute @var{action-if-fails} if the value cannot be determined correctly.
7052 @end defmac
7054 @defmac AC_LANG_WERROR
7055 @acindex{LANG_WERROR}
7056 Normally Autoconf ignores warnings generated by the compiler, linker, and
7057 preprocessor.  If this macro is used, warnings count as fatal
7058 errors for the current language.  This macro is useful when the
7059 results of configuration are used where warnings are unacceptable; for
7060 instance, if parts of a program are built with the GCC
7061 @option{-Werror}
7062 option.  If the whole program is built using @option{-Werror} it is
7063 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7064 etc.).
7065 @end defmac
7067 @defmac AC_OPENMP
7068 @acindex{OPENMP}
7069 @cvindex _OPENMP
7070 @ovindex OPENMP_CFLAGS
7071 @ovindex OPENMP_CXXFLAGS
7072 @ovindex OPENMP_FFLAGS
7073 @ovindex OPENMP_FCFLAGS
7074 @uref{http://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7075 and Fortran that simplify optimization of shared memory parallelism,
7076 which is a common problem on multicore CPUs.
7078 If the current language is C, the macro @code{AC_OPENMP} sets the
7079 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7080 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
7081 compiler already supports OpenMP, if it has no way to activate OpenMP
7082 support, or if the user rejects OpenMP support by invoking
7083 @samp{configure} with the @samp{--disable-openmp} option.
7085 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7086 preprocessing program source, and when linking programs.  Therefore you
7087 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7088 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
7089 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
7090 OpenMP support is revealed at compile time by the preprocessor macro
7091 @code{_OPENMP}.
7093 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7094 shared library to the program's dependencies, so its use is recommended
7095 only on programs that actually require OpenMP.
7097 If the current language is C++, @code{AC_OPENMP} sets the variable
7098 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7099 hold as for C.
7101 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7102 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7103 respectively.  Similar remarks as for C hold, except that
7104 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7105 signals OpenMP support.
7107 For portability, it is best to avoid spaces between @samp{#} and
7108 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7109 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7110 latter.
7111 @end defmac
7113 @node C Compiler
7114 @subsection C Compiler Characteristics
7116 The following macros provide ways to find and exercise a C Compiler.
7117 There are a few constructs that ought to be avoided, but do not deserve
7118 being checked for, since they can easily be worked around.
7120 @table @asis
7121 @item Don't use lines containing solitary backslashes
7122 They tickle a bug in the HP-UX C compiler (checked on
7123 HP-UX 10.20,
7124 11.00, and 11i).  When given the following source:
7126 @example
7127 #ifdef __STDC__
7129 * A comment with backslash-newlines in it.  %@{ %@} *\
7132 char str[] = "\\
7133 " A string with backslash-newlines in it %@{ %@} \\
7135 char apostrophe = '\\
7139 #endif
7140 @end example
7142 @noindent
7143 the compiler incorrectly fails with the diagnostics ``Non-terminating
7144 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7145 Removing the lines with solitary backslashes solves the problem.
7147 @item Don't compile several files at once if output matters to you
7148 Some compilers, such as HP's, report names of files being
7149 compiled when given more than one file operand.  For instance:
7151 @example
7152 $ @kbd{cc a.c b.c}
7153 a.c:
7154 b.c:
7155 @end example
7157 @noindent
7158 This can cause problems if you observe the output of the compiler to
7159 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7160 b.o} solves the issue.
7162 @item Don't rely on @code{#error} failing
7163 The IRIX C compiler does not fail when #error is preprocessed; it
7164 simply emits a diagnostic and continues, exiting successfully.  So,
7165 instead of an error directive like @code{#error "Unsupported word size"}
7166 it is more portable to use an invalid directive like @code{#Unsupported
7167 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7168 OK, since installers with inadequate compilers like IRIX can simply
7169 examine these compilers' diagnostic output.
7171 @item Don't rely on correct @code{#line} support
7172 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7173 diagnoses @code{#line} directives whose line
7174 numbers are greater than 32767.  Nothing in Posix
7175 makes this invalid.  That is why Autoconf stopped issuing
7176 @code{#line} directives.
7177 @end table
7179 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7180 @acindex{PROG_CC}
7181 @evindex CC
7182 @evindex CFLAGS
7183 @ovindex CC
7184 @ovindex CFLAGS
7185 @caindex prog_cc_c89
7186 Determine a C compiler to use.  If @code{CC} is not already set in the
7187 environment, check for @code{gcc} and @code{cc}, then for other C
7188 compilers.  Set output variable @code{CC} to the name of the compiler
7189 found.
7191 This macro may, however, be invoked with an optional first argument
7192 which, if specified, must be a blank-separated list of C compilers to
7193 search for.  This just gives the user an opportunity to specify an
7194 alternative search list for the C compiler.  For example, if you didn't
7195 like the default order, then you could invoke @code{AC_PROG_CC} like
7196 this:
7198 @example
7199 AC_PROG_CC([gcc cl cc])
7200 @end example
7202 If the C compiler does not handle function prototypes correctly by
7203 default, try to add an option to output variable @code{CC} to make it
7204 so.  This macro tries various options that select standard-conformance
7205 modes on various systems.
7207 After calling this macro you can check whether the C compiler has been
7208 set to accept ANSI C89 (ISO C90); if not, the shell
7209 variable
7210 @code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
7211 @code{AC_C_PROTOTYPES} below.
7213 If using the GNU C compiler, set shell variable @code{GCC} to
7214 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
7215 it to @option{-g -O2} for the GNU C compiler (@option{-O2} on systems
7216 where GCC does not accept @option{-g}), or @option{-g} for
7217 other compilers.  If your package does not like this default, then it is
7218 acceptable to insert the line @samp{: $@{CFLAGS=""@}} after @code{AC_INIT}
7219 and before @code{AC_PROG_CC} to select an empty default instead.
7221 Many Autoconf macros use a compiler, and thus call
7222 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7223 determined before the body of the outermost @code{AC_DEFUN} macro.
7224 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7225 performs certain checks (such as the proper value of @env{EXEEXT}) only
7226 on the first invocation.  Therefore, care must be used when invoking
7227 this macro from within another macro rather than at the top level
7228 (@pxref{Expanded Before Required}).
7229 @end defmac
7231 @anchor{AC_PROG_CC_C_O}
7232 @defmac AC_PROG_CC_C_O
7233 @acindex{PROG_CC_C_O}
7234 @cvindex NO_MINUS_C_MINUS_O
7235 @caindex prog_cc_@var{compiler}_c_o
7236 If the C compiler does not accept the @option{-c} and @option{-o} options
7237 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7238 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7239 the first @code{cc} in the path.  The test fails if one fails.  This
7240 macro was created for GNU Make to choose the default C compilation
7241 rule.
7243 For the compiler @var{compiler}, this macro caches its result in the
7244 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7245 @end defmac
7248 @defmac AC_PROG_CPP
7249 @acindex{PROG_CPP}
7250 @evindex CPP
7251 @ovindex CPP
7252 Set output variable @code{CPP} to a command that runs the
7253 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
7254 It is only portable to run @code{CPP} on files with a @file{.c}
7255 extension.
7257 Some preprocessors don't indicate missing include files by the error
7258 status.  For such preprocessors an internal variable is set that causes
7259 other macros to check the standard error from the preprocessor and
7260 consider the test failed if any warnings have been reported.
7261 For most preprocessors, though, warnings do not cause include-file
7262 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7263 @end defmac
7265 @defmac AC_PROG_CPP_WERROR
7266 @acindex{PROG_CPP_WERROR}
7267 @ovindex CPP
7268 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7269 preprocessor as errors even if the preprocessor exit status indicates
7270 success.  This is useful for avoiding headers that generate mandatory
7271 warnings, such as deprecation notices.
7272 @end defmac
7275 The following macros check for C compiler or machine architecture
7276 features.  To check for characteristics not listed here, use
7277 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7278 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7280 @defmac AC_PROG_CC_STDC
7281 @acindex{PROG_CC_STDC}
7282 @caindex prog_cc_stdc
7283 If the C compiler cannot compile ISO Standard C (currently
7284 C99), try to add an option to output variable @code{CC} to make it work.
7285 If the compiler does not support C99, fall back to supporting
7286 ANSI C89 (ISO C90).
7288 After calling this macro you can check whether the C compiler has been
7289 set to accept Standard C; if not, the shell variable
7290 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7291 @end defmac
7293 @defmac AC_PROG_CC_C89
7294 @acindex{PROG_CC_C89}
7295 @caindex prog_cc_c89
7296 If the C compiler is not in ANSI C89 (ISO C90) mode by
7297 default, try to add an option to output variable @code{CC} to make it
7298 so.  This macro tries various options that select ANSI C89 on
7299 some system or another, preferring extended functionality modes over
7300 strict conformance modes.  It considers the compiler to be in
7301 ANSI C89 mode if it handles function prototypes correctly.
7303 After calling this macro you can check whether the C compiler has been
7304 set to accept ANSI C89; if not, the shell variable
7305 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
7307 This macro is called automatically by @code{AC_PROG_CC}.
7308 @end defmac
7310 @defmac AC_PROG_CC_C99
7311 @acindex{PROG_CC_C99}
7312 @caindex prog_cc_c99
7313 If the C compiler is not in C99 mode by default, try to add an
7314 option to output variable @code{CC} to make it so.  This macro tries
7315 various options that select C99 on some system or another, preferring
7316 extended functionality modes over strict conformance modes.  It
7317 considers the compiler to be in C99 mode if it handles @code{_Bool},
7318 @code{//} comments, flexible array members, @code{inline}, signed and
7319 unsigned @code{long long int}, mixed code and declarations, named
7320 initialization of structs,
7321 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
7322 in @code{for} loops, and variable length arrays.
7324 After calling this macro you can check whether the C compiler has been
7325 set to accept C99; if not, the shell variable
7326 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
7327 @end defmac
7329 @defmac AC_C_BACKSLASH_A
7330 @acindex{C_BACKSLASH_A}
7331 @cvindex HAVE_C_BACKSLASH_A
7332 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7333 @samp{\a}.
7335 This macro is obsolescent, as current C compilers understand @samp{\a}.
7336 New programs need not use this macro.
7337 @end defmac
7339 @anchor{AC_C_BIGENDIAN}
7340 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7341   @ovar{action-if-unknown}, @ovar{action-if-universal})
7342 @acindex{C_BIGENDIAN}
7343 @cvindex WORDS_BIGENDIAN
7344 @cindex Endianness
7345 If words are stored with the most significant byte first (like Motorola
7346 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7347 the least significant byte first (like Intel and VAX CPUs), execute
7348 @var{action-if-false}.
7350 This macro runs a test-case if endianness cannot be determined from the
7351 system header files.  When cross-compiling, the test-case is not run but
7352 grep'ed for some magic values.  @var{action-if-unknown} is executed if
7353 the latter case fails to determine the byte sex of the host system.
7355 In some cases a single run of a compiler can generate code for multiple
7356 architectures.  This can happen, for example, when generating Mac OS X
7357 universal binary files, which work on both PowerPC and Intel
7358 architectures.  In this case, the different variants might be for
7359 different architectures whose endiannesses differ.  If
7360 @command{configure} detects this, it executes @var{action-if-universal}
7361 instead of @var{action-if-unknown}.
7363 The default for @var{action-if-true} is to define
7364 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7365 nothing.  The default for @var{action-if-unknown} is to
7366 abort configure and tell the installer how to bypass this test.
7367 And finally, the default for @var{action-if-universal} is to ensure that
7368 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7369 detected and the current code is big-endian; this default works only if
7370 @command{autoheader} is used (@pxref{autoheader Invocation}).
7372 If you use this macro without specifying @var{action-if-universal}, you
7373 should also use @code{AC_CONFIG_HEADERS}; otherwise
7374 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7375 binary files.
7376 @end defmac
7378 @anchor{AC_C_CONST}
7379 @defmac AC_C_CONST
7380 @acindex{C_CONST}
7381 @cvindex const
7382 @caindex c_const
7383 If the C compiler does not fully support the @code{const} keyword,
7384 define @code{const} to be empty.  Some C compilers that do
7385 not define @code{__STDC__} do support @code{const}; some compilers that
7386 define @code{__STDC__} do not completely support @code{const}.  Programs
7387 can simply use @code{const} as if every C compiler supported it; for
7388 those that don't, the makefile or configuration header file
7389 defines it as empty.
7391 Occasionally installers use a C++ compiler to compile C code, typically
7392 because they lack a C compiler.  This causes problems with @code{const},
7393 because C and C++ treat @code{const} differently.  For example:
7395 @example
7396 const int foo;
7397 @end example
7399 @noindent
7400 is valid in C but not in C++.  These differences unfortunately cannot be
7401 papered over by defining @code{const} to be empty.
7403 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7404 as this generally yields better results in practice.  However, using a
7405 C++ compiler to compile C code is not recommended or supported, and
7406 installers who run into trouble in this area should get a C compiler
7407 like GCC to compile their C code.
7409 This macro caches its result in the @code{ac_cv_c_const} variable.
7411 This macro is obsolescent, as current C compilers support @code{const}.
7412 New programs need not use this macro.
7413 @end defmac
7415 @defmac AC_C_RESTRICT
7416 @acindex{C_RESTRICT}
7417 @cvindex restrict
7418 @caindex c_restrict
7419 If the C compiler recognizes a variant spelling for the @code{restrict}
7420 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7421 then define @code{restrict} to that; this is more likely to do the right
7422 thing with compilers that support language variants where plain
7423 @code{restrict} is not a keyword.  Otherwise, if the C compiler
7424 recognizes the @code{restrict} keyword, don't do anything.
7425 Otherwise, define @code{restrict} to be empty.
7426 Thus, programs may simply use @code{restrict} as if every C compiler
7427 supported it; for those that do not, the makefile
7428 or configuration header defines it away.
7430 Although support in C++ for the @code{restrict} keyword is not
7431 required, several C++ compilers do accept the keyword.
7432 This macro works for them, too.
7434 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7435 if @code{restrict} is not supported, and a supported spelling otherwise.
7436 @end defmac
7438 @defmac AC_C_VOLATILE
7439 @acindex{C_VOLATILE}
7440 @cvindex volatile
7441 If the C compiler does not understand the keyword @code{volatile},
7442 define @code{volatile} to be empty.  Programs can simply use
7443 @code{volatile} as if every C compiler supported it; for those that do
7444 not, the makefile or configuration header defines it as
7445 empty.
7447 If the correctness of your program depends on the semantics of
7448 @code{volatile}, simply defining it to be empty does, in a sense, break
7449 your code.  However, given that the compiler does not support
7450 @code{volatile}, you are at its mercy anyway.  At least your
7451 program compiles, when it wouldn't before.
7452 @xref{Volatile Objects}, for more about @code{volatile}.
7454 In general, the @code{volatile} keyword is a standard C feature, so
7455 you might expect that @code{volatile} is available only when
7456 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7457 support volatile, but does not define @code{__STDC__}.
7459 This macro is obsolescent, as current C compilers support @code{volatile}.
7460 New programs need not use this macro.
7461 @end defmac
7463 @anchor{AC_C_INLINE}
7464 @defmac AC_C_INLINE
7465 @acindex{C_INLINE}
7466 @cvindex inline
7467 If the C compiler supports the keyword @code{inline}, do nothing.
7468 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7469 if it accepts one of those, otherwise define @code{inline} to be empty.
7470 @end defmac
7472 @anchor{AC_C_CHAR_UNSIGNED}
7473 @defmac AC_C_CHAR_UNSIGNED
7474 @acindex{C_CHAR_UNSIGNED}
7475 @cvindex __CHAR_UNSIGNED__
7476 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7477 unless the C compiler predefines it.
7479 These days, using this macro is not necessary.  The same information can
7480 be determined by this portable alternative, thus avoiding the use of
7481 preprocessor macros in the namespace reserved for the implementation.
7483 @example
7484 #include <limits.h>
7485 #if CHAR_MIN == 0
7486 # define CHAR_UNSIGNED 1
7487 #endif
7488 @end example
7489 @end defmac
7491 @defmac AC_C_STRINGIZE
7492 @acindex{C_STRINGIZE}
7493 @cvindex HAVE_STRINGIZE
7494 If the C preprocessor supports the stringizing operator, define
7495 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7496 found in macros such as this:
7498 @example
7499 #define x(y) #y
7500 @end example
7502 This macro is obsolescent, as current C compilers support the
7503 stringizing operator.  New programs need not use this macro.
7504 @end defmac
7506 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7507 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7508 @cvindex FLEXIBLE_ARRAY_MEMBER
7509 If the C compiler supports flexible array members, define
7510 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7511 That way, a declaration like this:
7513 @example
7514 struct s
7515   @{
7516     size_t n_vals;
7517     double val[FLEXIBLE_ARRAY_MEMBER];
7518   @};
7519 @end example
7521 @noindent
7522 will let applications use the ``struct hack'' even with compilers that
7523 do not support flexible array members.  To allocate and use such an
7524 object, you can use code like this:
7526 @example
7527 size_t i;
7528 size_t n = compute_value_count ();
7529 struct s *p =
7530    malloc (offsetof (struct s, val)
7531            + n * sizeof (double));
7532 p->n_vals = n;
7533 for (i = 0; i < n; i++)
7534   p->val[i] = compute_value (i);
7535 @end example
7536 @end defmac
7538 @defmac AC_C_VARARRAYS
7539 @acindex{C_VARARRAYS}
7540 @cvindex HAVE_C_VARARRAYS
7541 If the C compiler supports variable-length arrays, define
7542 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
7543 storage duration whose length is determined at run time, when the array
7544 is declared.
7545 @end defmac
7547 @defmac AC_C_TYPEOF
7548 @acindex{C_TYPEOF}
7549 @cvindex HAVE_TYPEOF
7550 @cvindex typeof
7551 If the C compiler supports GCC's @code{typeof} syntax either
7552 directly or
7553 through a different spelling of the keyword (e.g., @code{__typeof__}),
7554 define @code{HAVE_TYPEOF}.  If the support is available only through a
7555 different spelling, define @code{typeof} to that spelling.
7556 @end defmac
7558 @defmac AC_C_PROTOTYPES
7559 @acindex{C_PROTOTYPES}
7560 @cvindex PROTOTYPES
7561 @cvindex __PROTOTYPES
7562 @cvindex PARAMS
7563 If function prototypes are understood by the compiler (as determined by
7564 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7565 Defining @code{__PROTOTYPES} is for the benefit of
7566 header files that cannot use macros that infringe on user name space.
7568 This macro is obsolescent, as current C compilers support prototypes.
7569 New programs need not use this macro.
7570 @end defmac
7572 @anchor{AC_PROG_GCC_TRADITIONAL}
7573 @defmac AC_PROG_GCC_TRADITIONAL
7574 @acindex{PROG_GCC_TRADITIONAL}
7575 @ovindex CC
7576 Add @option{-traditional} to output variable @code{CC} if using the
7577 GNU C compiler and @code{ioctl} does not work properly without
7578 @option{-traditional}.  That usually happens when the fixed header files
7579 have not been installed on an old system.
7581 This macro is obsolescent, since current versions of the GNU C
7582 compiler fix the header files automatically when installed.
7583 @end defmac
7586 @node C++ Compiler
7587 @subsection C++ Compiler Characteristics
7590 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7591 @acindex{PROG_CXX}
7592 @evindex CXX
7593 @evindex CXXFLAGS
7594 @ovindex CXX
7595 @ovindex CXXFLAGS
7596 Determine a C++ compiler to use.  Check whether the environment variable
7597 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7598 variable @code{CXX} to its value.
7600 Otherwise, if the macro is invoked without an argument, then search for
7601 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7602 then other names).  If none of those checks succeed, then as a last
7603 resort set @code{CXX} to @code{g++}.
7605 This macro may, however, be invoked with an optional first argument
7606 which, if specified, must be a blank-separated list of C++ compilers to
7607 search for.  This just gives the user an opportunity to specify an
7608 alternative search list for the C++ compiler.  For example, if you
7609 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7610 like this:
7612 @example
7613 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7614 @end example
7616 If using the GNU C++ compiler, set shell variable @code{GXX} to
7617 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7618 it to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on
7619 systems where G++ does not accept @option{-g}), or @option{-g} for other
7620 compilers.  If your package does not like this default, then it is
7621 acceptable to insert the line @samp{: $@{CXXFLAGS=""@}} after @code{AC_INIT}
7622 and before @code{AC_PROG_CXX} to select an empty default instead.
7624 @end defmac
7626 @defmac AC_PROG_CXXCPP
7627 @acindex{PROG_CXXCPP}
7628 @evindex CXXCPP
7629 @ovindex CXXCPP
7630 Set output variable @code{CXXCPP} to a command that runs the C++
7631 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7632 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7633 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7635 Some preprocessors don't indicate missing include files by the error
7636 status.  For such preprocessors an internal variable is set that causes
7637 other macros to check the standard error from the preprocessor and
7638 consider the test failed if any warnings have been reported.  However,
7639 it is not known whether such broken preprocessors exist for C++.
7640 @end defmac
7642 @defmac AC_PROG_CXX_C_O
7643 @acindex{PROG_CXX_C_O}
7644 @cvindex CXX_NO_MINUS_C_MINUS_O
7645 Test whether the C++ compiler accepts the options @option{-c} and
7646 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7647 if it does not.
7648 @end defmac
7651 @node Objective C Compiler
7652 @subsection Objective C Compiler Characteristics
7655 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7656 @acindex{PROG_OBJC}
7657 @evindex OBJC
7658 @evindex OBJCFLAGS
7659 @ovindex OBJC
7660 @ovindex OBJCFLAGS
7661 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7662 set in the environment, check for Objective C compilers.  Set output
7663 variable @code{OBJC} to the name of the compiler found.
7665 This macro may, however, be invoked with an optional first argument
7666 which, if specified, must be a blank-separated list of Objective C compilers to
7667 search for.  This just gives the user an opportunity to specify an
7668 alternative search list for the Objective C compiler.  For example, if you
7669 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7670 like this:
7672 @example
7673 AC_PROG_OBJC([gcc objcc objc])
7674 @end example
7676 If using the GNU Objective C compiler, set shell variable
7677 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7678 already set, set it to @option{-g -O2} for the GNU Objective C
7679 compiler (@option{-O2} on systems where @command{gcc} does not accept
7680 @option{-g}), or @option{-g} for other compilers.
7681 @end defmac
7683 @defmac AC_PROG_OBJCPP
7684 @acindex{PROG_OBJCPP}
7685 @evindex OBJCPP
7686 @ovindex OBJCPP
7687 Set output variable @code{OBJCPP} to a command that runs the Objective C
7688 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7689 @end defmac
7692 @node Objective C++ Compiler
7693 @subsection Objective C++ Compiler Characteristics
7696 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7697 @acindex{PROG_OBJCXX}
7698 @evindex OBJCXX
7699 @evindex OBJCXXFLAGS
7700 @ovindex OBJCXX
7701 @ovindex OBJCXXFLAGS
7702 Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
7703 set in the environment, check for Objective C++ compilers.  Set output
7704 variable @code{OBJCXX} to the name of the compiler found.
7706 This macro may, however, be invoked with an optional first argument
7707 which, if specified, must be a blank-separated list of Objective C++ compilers
7708 to search for.  This just gives the user an opportunity to specify an
7709 alternative search list for the Objective C++ compiler.  For example, if you
7710 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7711 like this:
7713 @example
7714 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7715 @end example
7717 If using the GNU Objective C++ compiler, set shell variable
7718 @code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
7719 already set, set it to @option{-g -O2} for the GNU Objective C++
7720 compiler (@option{-O2} on systems where @command{gcc} does not accept
7721 @option{-g}), or @option{-g} for other compilers.
7722 @end defmac
7724 @defmac AC_PROG_OBJCXXCPP
7725 @acindex{PROG_OBJCXXCPP}
7726 @evindex OBJCXXCPP
7727 @ovindex OBJCXXCPP
7728 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7729 preprocessor.  If @samp{$OBJCXX -E} doesn't work, @file{/lib/cpp} is used.
7730 @end defmac
7733 @node Erlang Compiler and Interpreter
7734 @subsection Erlang Compiler and Interpreter Characteristics
7735 @cindex Erlang
7737 Autoconf defines the following macros for determining paths to the essential
7738 Erlang/OTP programs:
7740 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7741 @acindex{ERLANG_PATH_ERLC}
7742 @evindex ERLC
7743 @evindex ERLCFLAGS
7744 @ovindex ERLC
7745 @ovindex ERLCFLAGS
7746 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7747 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7748 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7749 is not set in the environment, set it to an empty value.
7751 The two optional arguments have the same meaning as the two last arguments of
7752 macro @code{AC_PROG_PATH} for looking for the @command{erlc} program.  For
7753 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7754 directory:
7756 @example
7757 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7758 @end example
7759 @end defmac
7761 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7762 @acindex{ERLANG_NEED_ERLC}
7763 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7764 error message and exits the @command{configure} script if the @command{erlc}
7765 program is not found.
7766 @end defmac
7768 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7769 @acindex{ERLANG_PATH_ERL}
7770 @evindex ERL
7771 @ovindex ERL
7772 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7773 set in the
7774 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7775 complete path of the interpreter command found.
7777 The two optional arguments have the same meaning as the two last arguments of
7778 macro @code{AC_PROG_PATH} for looking for the @command{erl} program.  For
7779 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7780 directory:
7782 @example
7783 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7784 @end example
7785 @end defmac
7787 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7788 @acindex{ERLANG_NEED_ERL}
7789 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7790 error message and exits the @command{configure} script if the @command{erl}
7791 program is not found.
7792 @end defmac
7795 @node Fortran Compiler
7796 @subsection Fortran Compiler Characteristics
7797 @cindex Fortran
7798 @cindex F77
7800 The Autoconf Fortran support is divided into two categories: legacy
7801 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7802 The former are intended for traditional Fortran 77 code, and have output
7803 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7804 are for newer programs that can (or must) compile under the newer
7805 Fortran standards, and have output variables like @code{FC},
7806 @code{FCFLAGS}, and @code{FCLIBS}.
7808 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7809 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7810 @code{FC} and @code{F77} macros behave almost identically, and so they
7811 are documented together in this section.
7814 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7815 @acindex{PROG_F77}
7816 @evindex F77
7817 @evindex FFLAGS
7818 @ovindex F77
7819 @ovindex FFLAGS
7820 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7821 set in the environment, then check for @code{g77} and @code{f77}, and
7822 then some other names.  Set the output variable @code{F77} to the name
7823 of the compiler found.
7825 This macro may, however, be invoked with an optional first argument
7826 which, if specified, must be a blank-separated list of Fortran 77
7827 compilers to search for.  This just gives the user an opportunity to
7828 specify an alternative search list for the Fortran 77 compiler.  For
7829 example, if you didn't like the default order, then you could invoke
7830 @code{AC_PROG_F77} like this:
7832 @example
7833 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7834 @end example
7836 If using @code{g77} (the GNU Fortran 77 compiler), then
7837 set the shell variable @code{G77} to @samp{yes}.
7838 If the output variable @code{FFLAGS} was not already set in the
7839 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7840 where @code{g77} does not accept @option{-g}).  Otherwise, set
7841 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7842 @end defmac
7844 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7845 @acindex{PROG_FC}
7846 @evindex FC
7847 @evindex FCFLAGS
7848 @ovindex FC
7849 @ovindex FCFLAGS
7850 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7851 the environment, then @code{dialect} is a hint to indicate what Fortran
7852 dialect to search for; the default is to search for the newest available
7853 dialect.  Set the output variable @code{FC} to the name of the compiler
7854 found.
7856 By default, newer dialects are preferred over older dialects, but if
7857 @code{dialect} is specified then older dialects are preferred starting
7858 with the specified dialect.  @code{dialect} can currently be one of
7859 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7860 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7861 and no attempt is made to guarantee that a particular language standard
7862 is actually supported.  Thus, it is preferable that you avoid the
7863 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7864 the latest Fortran standard.
7866 This macro may, alternatively, be invoked with an optional first argument
7867 which, if specified, must be a blank-separated list of Fortran
7868 compilers to search for, just as in @code{AC_PROG_F77}.
7870 If the output variable @code{FCFLAGS} was not already set in the
7871 environment, then set it to @option{-g -02} for GNU @code{g77} (or
7872 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7873 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7874 @end defmac
7876 @defmac AC_PROG_F77_C_O
7877 @defmacx AC_PROG_FC_C_O
7878 @acindex{PROG_F77_C_O}
7879 @acindex{PROG_FC_C_O}
7880 @cvindex F77_NO_MINUS_C_MINUS_O
7881 @cvindex FC_NO_MINUS_C_MINUS_O
7882 Test whether the Fortran compiler accepts the options @option{-c} and
7883 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7884 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7885 @end defmac
7887 The following macros check for Fortran compiler characteristics.
7888 To check for characteristics not listed here, use
7889 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7890 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7891 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7892 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7895 @defmac AC_F77_LIBRARY_LDFLAGS
7896 @defmacx AC_FC_LIBRARY_LDFLAGS
7897 @acindex{F77_LIBRARY_LDFLAGS}
7898 @ovindex FLIBS
7899 @acindex{FC_LIBRARY_LDFLAGS}
7900 @ovindex FCLIBS
7901 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7902 @dfn{Fortran intrinsic and runtime libraries} that are required to
7903 successfully link a Fortran program or shared library.  The output
7904 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7905 should be included after @code{LIBS} when linking).
7907 This macro is intended to be used in those situations when it is
7908 necessary to mix, e.g., C++ and Fortran source code in a single
7909 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7910 automake, GNU Automake}).
7912 For example, if object files from a C++ and Fortran compiler must be
7913 linked together, then the C++ compiler/linker must be used for linking
7914 (since special C++-ish things need to happen at link time like calling
7915 global constructors, instantiating templates, enabling exception
7916 support, etc.).
7918 However, the Fortran intrinsic and runtime libraries must be linked in
7919 as well, but the C++ compiler/linker doesn't know by default how to add
7920 these Fortran 77 libraries.  Hence, this macro was created to determine
7921 these Fortran libraries.
7923 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7924 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7925 link C/C++ with Fortran; see below.  Further, it is highly recommended
7926 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
7927 because the complex defines that the function wrapper macros create
7928 may not work with C/C++ compiler drivers.
7929 @end defmac
7931 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7932 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7933 @acindex{F77_DUMMY_MAIN}
7934 @cvindex F77_DUMMY_MAIN
7935 @acindex{FC_DUMMY_MAIN}
7936 @cvindex FC_DUMMY_MAIN
7937 With many compilers, the Fortran libraries detected by
7938 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7939 their own @code{main} entry function that initializes things like
7940 Fortran I/O, and which then calls a user-provided entry function named
7941 (say) @code{MAIN__} to run the user's program.  The
7942 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7943 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
7944 this interaction.
7946 When using Fortran for purely numerical functions (no I/O, etc.)@: often
7947 one prefers to provide one's own @code{main} and skip the Fortran
7948 library initializations.  In this case, however, one may still need to
7949 provide a dummy @code{MAIN__} routine in order to prevent linking errors
7950 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
7951 detects whether any such routine is @emph{required} for linking, and
7952 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
7953 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
7954 was found, and @code{none} when no such dummy main is needed.
7956 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
7957 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
7958 @emph{if} it is required.  @var{action-if-not-found} defaults to
7959 exiting with an error.
7961 In order to link with Fortran routines, the user's C/C++ program should
7962 then include the following code to define the dummy main if it is
7963 needed:
7965 @example
7966 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
7967 #ifdef F77_DUMMY_MAIN
7968 #  ifdef __cplusplus
7969      extern "C"
7970 #  endif
7971    int F77_DUMMY_MAIN () @{ return 1; @}
7972 #endif
7973 @end example
7975 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7977 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
7978 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
7979 explicitly unless one wants to change the default actions.
7980 @end defmac
7982 @defmac AC_F77_MAIN
7983 @defmacx AC_FC_MAIN
7984 @acindex{F77_MAIN}
7985 @cvindex F77_MAIN
7986 @acindex{FC_MAIN}
7987 @cvindex FC_MAIN
7988 As discussed above, many Fortran libraries allow you to provide an entry
7989 point called (say) @code{MAIN__} instead of the usual @code{main}, which
7990 is then called by a @code{main} function in the Fortran libraries that
7991 initializes things like Fortran I/O@.  The
7992 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
7993 @emph{possible} to utilize such an alternate main function, and defines
7994 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
7995 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
7996 simply defined to @code{main}.)
7998 Thus, when calling Fortran routines from C that perform things like I/O,
7999 one should use this macro and declare the "main" function like so:
8001 @example
8002 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8003 #ifdef __cplusplus
8004   extern "C"
8005 #endif
8006 int F77_MAIN (int argc, char *argv[]);
8007 @end example
8009 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8010 @end defmac
8012 @defmac AC_F77_WRAPPERS
8013 @defmacx AC_FC_WRAPPERS
8014 @acindex{F77_WRAPPERS}
8015 @cvindex F77_FUNC
8016 @cvindex F77_FUNC_
8017 @acindex{FC_WRAPPERS}
8018 @cvindex FC_FUNC
8019 @cvindex FC_FUNC_
8020 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8021 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8022 mangle the names of C/C++ identifiers, and identifiers with underscores,
8023 respectively, so that they match the name-mangling scheme used by the
8024 Fortran compiler.
8026 Fortran is case-insensitive, and in order to achieve this the Fortran
8027 compiler converts all identifiers into a canonical case and format.  To
8028 call a Fortran subroutine from C or to write a C function that is
8029 callable from Fortran, the C program must explicitly use identifiers in
8030 the format expected by the Fortran compiler.  In order to do this, one
8031 simply wraps all C identifiers in one of the macros provided by
8032 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
8033 you have the following Fortran 77 subroutine:
8035 @example
8036 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8037       subroutine foobar (x, y)
8038       double precision x, y
8039       y = 3.14159 * x
8040       return
8041       end
8042 @end example
8044 You would then declare its prototype in C or C++ as:
8046 @example
8047 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8048 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8049 #ifdef __cplusplus
8050 extern "C"  /* prevent C++ name mangling */
8051 #endif
8052 void FOOBAR_F77 (double *x, double *y);
8053 @end example
8055 Note that we pass both the lowercase and uppercase versions of the
8056 function name to @code{F77_FUNC} so that it can select the right one.
8057 Note also that all parameters to Fortran 77 routines are passed as
8058 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8059 Automake}).
8061 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8063 Although Autoconf tries to be intelligent about detecting the
8064 name-mangling scheme of the Fortran compiler, there may be Fortran
8065 compilers that it doesn't support yet.  In this case, the above code
8066 generates a compile-time error, but some other behavior
8067 (e.g., disabling Fortran-related features) can be induced by checking
8068 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8070 Now, to call that routine from a C program, we would do something like:
8072 @example
8073 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8075     double x = 2.7183, y;
8076     FOOBAR_F77 (&x, &y);
8078 @end example
8080 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8081 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8082 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
8083 because some Fortran compilers mangle names differently if they contain
8084 an underscore.
8085 @end defmac
8087 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8088 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8089 @acindex{F77_FUNC}
8090 @acindex{FC_FUNC}
8091 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8092 hold the mangled version @var{name} according to the rules of the
8093 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8094 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
8095 supplied, the shell variable is simply @var{name}.  The purpose of
8096 this macro is to give the caller a way to access the name-mangling
8097 information other than through the C preprocessor as above, for example,
8098 to call Fortran routines from some language other than C/C++.
8099 @end defmac
8101 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8102   @ovar{action-if-failure})
8103 @acindex{FC_SRCEXT}
8104 By default, the @code{FC} macros perform their tests using a @file{.f}
8105 extension for source-code files.  Some compilers, however, only enable
8106 newer language features for appropriately named files, e.g., Fortran 90
8107 features only for @file{.f90} files.  On the other hand, some other
8108 compilers expect all source files to end in @file{.f} and require
8109 special flags to support other file name extensions.  The
8110 @code{AC_FC_SRCEXT} macro deals with both of these issues.
8112 The @code{AC_FC_SRCEXT} tries to get the @code{FC} compiler to accept files
8113 ending with the extension .@var{ext} (i.e., @var{ext} does @emph{not}
8114 contain the dot).  If any special compiler flags are needed for this, it
8115 stores them in the output variable @code{FCFLAGS_}@var{ext}.  This
8116 extension and these flags are then used for all subsequent @code{FC} tests
8117 (until @code{AC_FC_SRCEXT} is called again).
8119 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8120 @file{.f90} extension in future tests, and it would set the
8121 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8122 to compile such files.
8124 The @code{FCFLAGS_}@var{ext} can @emph{not} be simply absorbed into
8125 @code{FCFLAGS}, for two reasons based on the limitations of some
8126 compilers.  First, only one @code{FCFLAGS_}@var{ext} can be used at a
8127 time, so files with different extensions must be compiled separately.
8128 Second, @code{FCFLAGS_}@var{ext} must appear @emph{immediately} before
8129 the source-code file name when compiling.  So, continuing the example
8130 above, you might compile a @file{foo.f90} file in your makefile with the
8131 command:
8133 @example
8134 foo.o: foo.f90
8135      $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8136 @end example
8138 If @code{AC_FC_SRCEXT} succeeds in compiling files with the @var{ext}
8139 extension, it calls @var{action-if-success} (defaults to nothing).  If
8140 it fails, and cannot find a way to make the @code{FC} compiler accept such
8141 files, it calls @var{action-if-failure} (defaults to exiting with an
8142 error message).
8144 @end defmac
8146 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @ovar{action-if-failure})
8147 @acindex{FC_FREEFORM}
8149 The @code{AC_FC_FREEFORM} tries to ensure that the Fortran compiler
8150 (@code{$FC}) allows free-format source code (as opposed to the older
8151 fixed-format style from Fortran 77).  If necessary, it may add some
8152 additional flags to @code{FCFLAGS}.
8154 This macro is most important if you are using the default @file{.f}
8155 extension, since many compilers interpret this extension as indicating
8156 fixed-format source unless an additional flag is supplied.  If you
8157 specify a different extension with @code{AC_FC_SRCEXT}, such as
8158 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8159 modifying @code{FCFLAGS}.  For extensions which the compiler does not
8160 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8161 the compiler assume Fortran 77 by default, however.
8163 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8164 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8165 calls @var{action-if-failure} (defaults to exiting with an error
8166 message).
8167 @end defmac
8169 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @ovar{action-if-failure})
8170 @acindex{FC_FIXEDFORM}
8172 The @code{AC_FC_FIXEDFORM} tries to ensure that the Fortran compiler
8173 (@code{$FC}) allows the old fixed-format source code (as opposed to
8174 free-format style).  If necessary, it may add some additional flags to
8175 @code{FCFLAGS}.
8177 This macro is needed for some compilers alias names like @command{xlf95}
8178 which assume free-form source code by default, and in case you want to
8179 use fixed-form source with an extension like @file{.f90} which many
8180 compilers interpret as free-form by default.  If you specify a different
8181 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8182 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8183 @code{FCFLAGS}.
8185 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8186 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8187 calls @var{action-if-failure} (defaults to exiting with an error
8188 message).
8189 @end defmac
8191 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8192   @ovar{action-if-failure})
8193 @acindex{FC_LINE_LENGTH}
8195 The @code{AC_FC_LINE_LENGTH} macro tries to ensure that the Fortran compiler
8196 (@code{$FC}) accepts long source code lines.  The @var{length} argument
8197 may be given as 80, 132, or unlimited, and defaults to 132.  Note that
8198 line lengths above 254 columns are not portable, and some compilers
8199 do not accept more than 132 columns at least for fixed format source.
8200 If necessary, it may add some additional flags to @code{FCFLAGS}.
8202 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8203 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8204 calls @var{action-if-failure} (defaults to exiting with an error
8205 message).
8206 @end defmac
8209 @node System Services
8210 @section System Services
8212 The following macros check for operating system services or capabilities.
8214 @anchor{AC_PATH_X}
8215 @defmac AC_PATH_X
8216 @acindex{PATH_X}
8217 @evindex XMKMF
8218 @cindex X Window System
8219 Try to locate the X Window System include files and libraries.  If the
8220 user gave the command line options @option{--x-includes=@var{dir}} and
8221 @option{--x-libraries=@var{dir}}, use those directories.
8223 If either or both were not given, get the missing values by running
8224 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8225 environment variable) on a trivial @file{Imakefile} and examining the
8226 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8227 disables this method.
8229 If this method fails to find the X Window System, @command{configure}
8230 looks for the files in several directories where they often reside.
8231 If either method is successful, set the shell variables
8232 @code{x_includes} and @code{x_libraries} to their locations, unless they
8233 are in directories the compiler searches by default.
8235 If both methods fail, or the user gave the command line option
8236 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8237 otherwise set it to the empty string.
8238 @end defmac
8240 @anchor{AC_PATH_XTRA}
8241 @defmac AC_PATH_XTRA
8242 @acindex{PATH_XTRA}
8243 @ovindex X_CFLAGS
8244 @ovindex X_LIBS
8245 @ovindex X_EXTRA_LIBS
8246 @ovindex X_PRE_LIBS
8247 @cvindex X_DISPLAY_MISSING
8248 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8249 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8250 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8251 available.
8253 This macro also checks for special libraries that some systems need in
8254 order to compile X programs.  It adds any that the system needs to
8255 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8256 libraries that need to be linked with before @option{-lX11}, and adds
8257 any found to the output variable @code{X_PRE_LIBS}.
8259 @c This is an incomplete kludge.  Make a real way to do it.
8260 @c If you need to check for other X functions or libraries yourself, then
8261 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8262 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8263 @end defmac
8265 @anchor{AC_SYS_INTERPRETER}
8266 @defmac AC_SYS_INTERPRETER
8267 @acindex{SYS_INTERPRETER}
8268 Check whether the system supports starting scripts with a line of the
8269 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8270 After running this macro, shell code in @file{configure.ac} can check
8271 the shell variable @code{interpval}; it is set to @samp{yes}
8272 if the system supports @samp{#!}, @samp{no} if not.
8273 @end defmac
8275 @defmac AC_SYS_LARGEFILE
8276 @acindex{SYS_LARGEFILE}
8277 @cvindex _FILE_OFFSET_BITS
8278 @cvindex _LARGE_FILES
8279 @ovindex CC
8280 @cindex Large file support
8281 @cindex LFS
8282 Arrange for 64-bit file offsets, known as
8283 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
8284 large-file support}.  On some hosts, one must use special compiler
8285 options to build programs that can access large files.  Append any such
8286 options to the output variable @code{CC}.  Define
8287 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8289 Large-file support can be disabled by configuring with the
8290 @option{--disable-largefile} option.
8292 If you use this macro, check that your program works even when
8293 @code{off_t} is wider than @code{long int}, since this is common when
8294 large-file support is enabled.  For example, it is not correct to print
8295 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8296 (long int) X)}.
8298 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8299 replace their C counterparts @code{fseek} and @code{ftell} that do not
8300 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8301 prototypes available when using them and large-file support is
8302 enabled.
8303 @end defmac
8305 @anchor{AC_SYS_LONG_FILE_NAMES}
8306 @defmac AC_SYS_LONG_FILE_NAMES
8307 @acindex{SYS_LONG_FILE_NAMES}
8308 @cvindex HAVE_LONG_FILE_NAMES
8309 If the system supports file names longer than 14 characters, define
8310 @code{HAVE_LONG_FILE_NAMES}.
8311 @end defmac
8313 @defmac AC_SYS_POSIX_TERMIOS
8314 @acindex{SYS_POSIX_TERMIOS}
8315 @cindex Posix termios headers
8316 @cindex termios Posix headers
8317 @caindex sys_posix_termios
8318 Check to see if the Posix termios headers and functions are available on the
8319 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8320 @samp{yes}.  If not, set the variable to @samp{no}.
8321 @end defmac
8323 @node Posix Variants
8324 @section Posix Variants
8326 The following macro makes it possible to use features of Posix that are
8327 extensions to C, as well as platform extensions not defined by Posix.
8329 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8330 @defmac AC_USE_SYSTEM_EXTENSIONS
8331 @acindex{USE_SYSTEM_EXTENSIONS}
8332 @cvindex _ALL_SOURCE
8333 @cvindex _GNU_SOURCE
8334 @cvindex _MINIX
8335 @cvindex _POSIX_1_SOURCE
8336 @cvindex _POSIX_PTHREAD_SEMANTICS
8337 @cvindex _POSIX_SOURCE
8338 @cvindex _TANDEM_SOURCE
8339 @cvindex __EXTENSIONS__
8340 This macro was introduced in Autoconf 2.60.  If possible, enable
8341 extensions to C or Posix on hosts that normally disable the extensions,
8342 typically due to standards-conformance namespace issues.  This should be
8343 called before any macros that run the C compiler.  The following
8344 preprocessor macros are defined where appropriate:
8346 @table @code
8347 @item _GNU_SOURCE
8348 Enable extensions on GNU/Linux.
8349 @item __EXTENSIONS__
8350 Enable general extensions on Solaris.
8351 @item _POSIX_PTHREAD_SEMANTICS
8352 Enable threading extensions on Solaris.
8353 @item _TANDEM_SOURCE
8354 Enable extensions for the HP NonStop platform.
8355 @item _ALL_SOURCE
8356 Enable extensions for AIX 3, and for Interix.
8357 @item _POSIX_SOURCE
8358 Enable Posix functions for Minix.
8359 @item _POSIX_1_SOURCE
8360 Enable additional Posix functions for Minix.
8361 @item _MINIX
8362 Identify Minix platform.  This particular preprocessor macro is
8363 obsolescent, and may be removed in a future release of Autoconf.
8364 @end table
8365 @end defmac
8368 @node Erlang Libraries
8369 @section Erlang Libraries
8370 @cindex Erlang, Library, checking
8372 The following macros check for an installation of Erlang/OTP, and for the
8373 presence of certain Erlang libraries.  All those macros require the
8374 configuration of an Erlang interpreter and an Erlang compiler
8375 (@pxref{Erlang Compiler and Interpreter}).
8377 @defmac AC_ERLANG_SUBST_ERTS_VER
8378 @acindex{ERLANG_SUBST_ERTS_VER}
8379 @ovindex ERLANG_ERTS_VER
8380 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8381 Erlang runtime system (as returned by Erlang's
8382 @code{erlang:system_info(version)} function).  The result of this test
8383 is cached if caching is enabled when running @command{configure}.  The
8384 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8385 for features of specific ERTS versions, but to be used for substituting
8386 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8387 files), as shown below.
8388 @end defmac
8390 @defmac AC_ERLANG_SUBST_ROOT_DIR
8391 @acindex{ERLANG_SUBST_ROOT_DIR}
8392 @ovindex ERLANG_ROOT_DIR
8393 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8394 directory in which Erlang/OTP is installed (as returned by Erlang's
8395 @code{code:root_dir/0} function).  The result of this test is cached if
8396 caching is enabled when running @command{configure}.
8397 @end defmac
8399 @defmac AC_ERLANG_SUBST_LIB_DIR
8400 @acindex{ERLANG_SUBST_LIB_DIR}
8401 @ovindex ERLANG_LIB_DIR
8402 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8403 directory of Erlang/OTP (as returned by Erlang's
8404 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8405 Erlang/OTP library.  The result of this test is cached if caching is enabled
8406 when running @command{configure}.
8407 @end defmac
8409 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8410   @ovar{action-if-not-found})
8411 @acindex{ERLANG_CHECK_LIB}
8412 @ovindex ERLANG_LIB_DIR_@var{library}
8413 @ovindex ERLANG_LIB_VER_@var{library}
8414 Test whether the Erlang/OTP library @var{library} is installed by
8415 calling Erlang's @code{code:lib_dir/1} function.  The result of this
8416 test is cached if caching is enabled when running @command{configure}.
8417 @var{action-if-found} is a list of shell commands to run if the library
8418 is installed; @var{action-if-not-found} is a list of shell commands to
8419 run if it is not.  Additionally, if the library is installed, the output
8420 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8421 library installation directory, and the output variable
8422 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8423 part of the subdirectory name, if it is in the standard form
8424 (@code{@var{library}-@var{version}}).  If the directory name does not
8425 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8426 empty string.  If the library is not installed,
8427 @samp{ERLANG_LIB_DIR_@var{library}} and
8428 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
8429 example, to check if library @code{stdlib} is installed:
8431 @example
8432 AC_ERLANG_CHECK_LIB([stdlib],
8433   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8434    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8435   [AC_MSG_ERROR([stdlib was not found!])])
8436 @end example
8438 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8439 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8440 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8441 testing for features of specific versions of libraries or of the Erlang
8442 runtime system.  Those variables are intended to be substituted in
8443 Erlang release resource files (@code{.rel} files).  For instance, to
8444 generate a @file{example.rel} file for an application depending on the
8445 @code{stdlib} library, @file{configure.ac} could contain:
8447 @example
8448 AC_ERLANG_SUBST_ERTS_VER
8449 AC_ERLANG_CHECK_LIB([stdlib],
8450   [],
8451   [AC_MSG_ERROR([stdlib was not found!])])
8452 AC_CONFIG_FILES([example.rel])
8453 @end example
8455 @noindent
8456 The @file{example.rel.in} file used to generate @file{example.rel}
8457 should contain:
8459 @example
8460 @{release,
8461     @{"@@PACKAGE@@", "@@VERSION@@"@},
8462     @{erts, "@@ERLANG_ERTS_VER@@"@},
8463     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8464      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8465 @end example
8466 @end defmac
8468 In addition to the above macros, which test installed Erlang libraries, the
8469 following macros determine the paths to the directories into which newly built
8470 Erlang libraries are to be installed:
8472 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8473 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8474 @ovindex ERLANG_INSTALL_LIB_DIR
8476 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8477 which every built Erlang library should be installed in a separate
8478 subdirectory.
8479 If this variable is not set in the environment when @command{configure} runs,
8480 its default value is @code{$@{libdir@}/erlang/lib}.
8481 @end defmac
8483 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8484 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8485 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8487 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8488 directory into which the built Erlang library @var{library} version
8489 @var{version} should be installed.  If this variable is not set in the
8490 environment when @command{configure} runs, its default value is
8491 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
8492 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
8493 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
8494 @end defmac
8500 @c ========================================================= Writing Tests
8502 @node Writing Tests
8503 @chapter Writing Tests
8505 If the existing feature tests don't do something you need, you have to
8506 write new ones.  These macros are the building blocks.  They provide
8507 ways for other macros to check whether various kinds of features are
8508 available and report the results.
8510 This chapter contains some suggestions and some of the reasons why the
8511 existing tests are written the way they are.  You can also learn a lot
8512 about how to write Autoconf tests by looking at the existing ones.  If
8513 something goes wrong in one or more of the Autoconf tests, this
8514 information can help you understand the assumptions behind them, which
8515 might help you figure out how to best solve the problem.
8517 These macros check the output of the compiler system of the current
8518 language (@pxref{Language Choice}).  They do not cache the results of
8519 their tests for future use (@pxref{Caching Results}), because they don't
8520 know enough about the information they are checking for to generate a
8521 cache variable name.  They also do not print any messages, for the same
8522 reason.  The checks for particular kinds of features call these macros
8523 and do cache their results and print messages about what they're
8524 checking for.
8526 When you write a feature test that could be applicable to more than one
8527 software package, the best thing to do is encapsulate it in a new macro.
8528 @xref{Writing Autoconf Macros}, for how to do that.
8530 @menu
8531 * Language Choice::             Selecting which language to use for testing
8532 * Writing Test Programs::       Forging source files for compilers
8533 * Running the Preprocessor::    Detecting preprocessor symbols
8534 * Running the Compiler::        Detecting language or header features
8535 * Running the Linker::          Detecting library features
8536 * Runtime::                     Testing for runtime features
8537 * Systemology::                 A zoology of operating systems
8538 * Multiple Cases::              Tests for several possible values
8539 @end menu
8541 @node Language Choice
8542 @section Language Choice
8543 @cindex Language
8545 Autoconf-generated @command{configure} scripts check for the C compiler and
8546 its features by default.  Packages that use other programming languages
8547 (maybe more than one, e.g., C and C++) need to test features of the
8548 compilers for the respective languages.  The following macros determine
8549 which programming language is used in the subsequent tests in
8550 @file{configure.ac}.
8552 @anchor{AC_LANG}
8553 @defmac AC_LANG (@var{language})
8554 @acindex{LANG}
8555 Do compilation tests using the compiler, preprocessor, and file
8556 extensions for the specified @var{language}.
8558 Supported languages are:
8560 @table @samp
8561 @item C
8562 Do compilation tests using @code{CC} and @code{CPP} and use extension
8563 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
8564 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
8566 @item C++
8567 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8568 extension @file{.C} for test programs.  Use compilation flags:
8569 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8570 @code{CXXFLAGS} with @code{CXX}.
8572 @item Fortran 77
8573 Do compilation tests using @code{F77} and use extension @file{.f} for
8574 test programs.  Use compilation flags: @code{FFLAGS}.
8576 @item Fortran
8577 Do compilation tests using @code{FC} and use extension @file{.f} (or
8578 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
8579 compilation flags: @code{FCFLAGS}.
8581 @item Erlang
8582 @ovindex ERLC
8583 @ovindex ERL
8584 @ovindex ERLCFLAGS
8585 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8586 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
8588 @item Objective C
8589 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8590 extension @file{.m} for test programs.  Use compilation flags:
8591 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8592 @code{OBJCFLAGS} with @code{OBJC}.
8594 @item Objective C++
8595 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
8596 extension @file{.mm} for test programs.  Use compilation flags:
8597 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
8598 @code{OBJCXXFLAGS} with @code{OBJCXX}.
8599 @end table
8600 @end defmac
8602 @anchor{AC_LANG_PUSH}
8603 @defmac AC_LANG_PUSH (@var{language})
8604 @acindex{LANG_PUSH}
8605 Remember the current language (as set by @code{AC_LANG}) on a stack, and
8606 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
8607 in macros that need to temporarily switch to a particular language.
8608 @end defmac
8610 @defmac AC_LANG_POP (@ovar{language})
8611 @acindex{LANG_POP}
8612 Select the language that is saved on the top of the stack, as set by
8613 @code{AC_LANG_PUSH}, and remove it from the stack.
8615 If given, @var{language} specifies the language we just @emph{quit}.  It
8616 is a good idea to specify it when it's known (which should be the
8617 case@dots{}), since Autoconf detects inconsistencies.
8619 @example
8620 AC_LANG_PUSH([Fortran 77])
8621 # Perform some tests on Fortran 77.
8622 # @dots{}
8623 AC_LANG_POP([Fortran 77])
8624 @end example
8625 @end defmac
8627 @defmac AC_LANG_ASSERT (@var{language})
8628 @acindex{LANG_ASSERT}
8629 Check statically that the current language is @var{language}.
8630 You should use this in your language specific macros
8631 to avoid that they be called with an inappropriate language.
8633 This macro runs only at @command{autoconf} time, and incurs no cost at
8634 @command{configure} time.  Sadly enough and because Autoconf is a two
8635 layer language @footnote{Because M4 is not aware of Sh code,
8636 especially conditionals, some optimizations that look nice statically
8637 may produce incorrect results at runtime.}, the macros
8638 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8639 therefore as much as possible you ought to avoid using them to wrap
8640 your code, rather, require from the user to run the macro with a
8641 correct current language, and check it with @code{AC_LANG_ASSERT}.
8642 And anyway, that may help the user understand she is running a Fortran
8643 macro while expecting a result about her Fortran 77 compiler@enddots{}
8644 @end defmac
8647 @defmac AC_REQUIRE_CPP
8648 @acindex{REQUIRE_CPP}
8649 Ensure that whichever preprocessor would currently be used for tests has
8650 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
8651 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
8652 depending on which language is current.
8653 @end defmac
8656 @node Writing Test Programs
8657 @section Writing Test Programs
8659 Autoconf tests follow a common scheme: feed some program with some
8660 input, and most of the time, feed a compiler with some source file.
8661 This section is dedicated to these source samples.
8663 @menu
8664 * Guidelines::                  General rules for writing test programs
8665 * Test Functions::              Avoiding pitfalls in test programs
8666 * Generating Sources::          Source program boilerplate
8667 @end menu
8669 @node Guidelines
8670 @subsection Guidelines for Test Programs
8672 The most important rule to follow when writing testing samples is:
8674 @center @emph{Look for realism.}
8676 This motto means that testing samples must be written with the same
8677 strictness as real programs are written.  In particular, you should
8678 avoid ``shortcuts'' and simplifications.
8680 Don't just play with the preprocessor if you want to prepare a
8681 compilation.  For instance, using @command{cpp} to check whether a header is
8682 functional might let your @command{configure} accept a header which
8683 causes some @emph{compiler} error.  Do not hesitate to check a header with
8684 other headers included before, especially required headers.
8686 Make sure the symbols you use are properly defined, i.e., refrain from
8687 simply declaring a function yourself instead of including the proper
8688 header.
8690 Test programs should not write to standard output.  They
8691 should exit with status 0 if the test succeeds, and with status 1
8692 otherwise, so that success
8693 can be distinguished easily from a core dump or other failure;
8694 segmentation violations and other failures produce a nonzero exit
8695 status.  Unless you arrange for @code{exit} to be declared, test
8696 programs should @code{return}, not @code{exit}, from @code{main},
8697 because on many systems @code{exit} is not declared by default.
8699 Test programs can use @code{#if} or @code{#ifdef} to check the values of
8700 preprocessor macros defined by tests that have already run.  For
8701 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
8702 @file{configure.ac} you can have a test program that includes
8703 @file{stdbool.h} conditionally:
8705 @example
8706 @group
8707 #ifdef HAVE_STDBOOL_H
8708 # include <stdbool.h>
8709 #endif
8710 @end group
8711 @end example
8713 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
8714 work with any standard C compiler.  Some developers prefer @code{#if}
8715 because it is easier to read, while others prefer @code{#ifdef} because
8716 it avoids diagnostics with picky compilers like GCC with the
8717 @option{-Wundef} option.
8719 If a test program needs to use or create a data file, give it a name
8720 that starts with @file{conftest}, such as @file{conftest.data}.  The
8721 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
8722 after running test programs and if the script is interrupted.
8724 @node Test Functions
8725 @subsection Test Functions
8727 These days it's safe to assume support for function prototypes
8728 (introduced in C89).
8730 Functions that test programs declare should also be conditionalized for
8731 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
8732 include any header files containing clashing prototypes.
8734 @example
8735 #ifdef __cplusplus
8736 extern "C"
8737 #endif
8738 void *valloc (size_t);
8739 @end example
8741 If a test program calls a function with invalid parameters (just to see
8742 whether it exists), organize the program to ensure that it never invokes
8743 that function.  You can do this by calling it in another function that is
8744 never invoked.  You can't do it by putting it after a call to
8745 @code{exit}, because GCC version 2 knows that @code{exit}
8746 never returns
8747 and optimizes out any code that follows it in the same block.
8749 If you include any header files, be sure to call the functions
8750 relevant to them with the correct number of arguments, even if they are
8751 just 0, to avoid compilation errors due to prototypes.  GCC
8752 version 2
8753 has internal prototypes for several functions that it automatically
8754 inlines; for example, @code{memcpy}.  To avoid errors when checking for
8755 them, either pass them the correct number of arguments or redeclare them
8756 with a different return type (such as @code{char}).
8759 @node Generating Sources
8760 @subsection Generating Sources
8762 Autoconf provides a set of macros that can be used to generate test
8763 source files.  They are written to be language generic, i.e., they
8764 actually depend on the current language (@pxref{Language Choice}) to
8765 ``format'' the output properly.
8768 @defmac AC_LANG_CONFTEST (@var{source})
8769 @acindex{LANG_CONFTEST}
8770 Save the @var{source} text in the current test source file:
8771 @file{conftest.@var{extension}} where the @var{extension} depends on the
8772 current language.  As of Autoconf 2.63b, the source file also contains
8773 the results of all of the @code{AC_DEFINE} performed so far.
8775 Note that the @var{source} is evaluated exactly once, like regular
8776 Autoconf macro arguments, and therefore (i) you may pass a macro
8777 invocation, (ii) if not, be sure to double quote if needed.
8779 This macro issues a warning during @command{autoconf} processing if
8780 @var{source} does not include an expansion of the macro
8781 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
8782 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
8784 This macro is seldom called directly, but is used under the hood by more
8785 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
8786 @end defmac
8788 @defmac AC_LANG_DEFINES_PROVIDED
8789 @acindex{LANG_DEFINES_PROVIDED}
8790 This macro is called as a witness that the file
8791 @file{conftest.@var{extension}} appropriate for the current language is
8792 complete, including all previously determined results from
8793 @code{AC_DEFINE}.  This macro is seldom called directly, but exists if
8794 you have a compelling reason to write a conftest file without using
8795 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
8796 @code{AC_LANG_CONFTEST}.
8797 @end defmac
8799 @defmac AC_LANG_SOURCE (@var{source})
8800 @acindex{LANG_SOURCE}
8801 Expands into the @var{source}, with the definition of
8802 all the @code{AC_DEFINE} performed so far.  This macro includes an
8803 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
8805 In many cases, you may find it more convenient to use the wrapper
8806 @code{AC_LANG_PROGRAM}.
8807 @end defmac
8809 For instance, executing (observe the double quotation!):
8811 @example
8812 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
8813 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
8814         [http://www.example.org/])
8815 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8816   [Greetings string.])
8817 AC_LANG([C])
8818 AC_LANG_CONFTEST(
8819    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
8820 gcc -E -dD conftest.c
8821 @end example
8823 @noindent
8824 on a system with @command{gcc} installed, results in:
8826 @example
8827 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
8828 @dots{}
8829 # 1 "conftest.c"
8831 #define PACKAGE_NAME "Hello"
8832 #define PACKAGE_TARNAME "hello"
8833 #define PACKAGE_VERSION "1.0"
8834 #define PACKAGE_STRING "Hello 1.0"
8835 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8836 #define PACKAGE_URL "http://www.example.org/"
8837 #define HELLO_WORLD "Hello, World\n"
8839 const char hw[] = "Hello, World\n";
8840 @end example
8842 When the test language is Fortran or Erlang, the @code{AC_DEFINE} definitions
8843 are not automatically translated into constants in the source code by this
8844 macro.
8846 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
8847 @acindex{LANG_PROGRAM}
8848 Expands into a source file which consists of the @var{prologue}, and
8849 then @var{body} as body of the main function (e.g., @code{main} in
8850 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
8851 available.
8852 @end defmac
8854 For instance:
8856 @example
8857 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
8858 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
8859         [http://www.example.org/])
8860 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8861   [Greetings string.])
8862 AC_LANG_CONFTEST(
8863 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8864                  [[fputs (hw, stdout);]])])
8865 gcc -E -dD conftest.c
8866 @end example
8868 @noindent
8869 on a system with @command{gcc} installed, results in:
8871 @example
8872 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
8873 @dots{}
8874 # 1 "conftest.c"
8876 #define PACKAGE_NAME "Hello"
8877 #define PACKAGE_TARNAME "hello"
8878 #define PACKAGE_VERSION "1.0"
8879 #define PACKAGE_STRING "Hello 1.0"
8880 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8881 #define PACKAGE_URL "http://www.example.org/"
8882 #define HELLO_WORLD "Hello, World\n"
8884 const char hw[] = "Hello, World\n";
8886 main ()
8888 fputs (hw, stdout);
8889   ;
8890   return 0;
8892 @end example
8894 In Erlang tests, the created source file is that of an Erlang module called
8895 @code{conftest} (@file{conftest.erl}).  This module defines and exports
8896 at least
8897 one @code{start/0} function, which is called to perform the test.  The
8898 @var{prologue} is optional code that is inserted between the module header and
8899 the @code{start/0} function definition.  @var{body} is the body of the
8900 @code{start/0} function without the final period (@pxref{Runtime}, about
8901 constraints on this function's behavior).
8903 For instance:
8905 @example
8906 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8907 AC_LANG(Erlang)
8908 AC_LANG_CONFTEST(
8909 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
8910                  [[io:format("~s~n", [?HELLO_WORLD])]])])
8911 cat conftest.erl
8912 @end example
8914 @noindent
8915 results in:
8917 @example
8918 -module(conftest).
8919 -export([start/0]).
8920 -define(HELLO_WORLD, "Hello, world!").
8921 start() ->
8922 io:format("~s~n", [?HELLO_WORLD])
8924 @end example
8926 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
8927 @acindex{LANG_CALL}
8928 Expands into a source file which consists of the @var{prologue}, and
8929 then a call to the @var{function} as body of the main function (e.g.,
8930 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
8931 of the latter are available.
8933 This function will probably be replaced in the future by a version
8934 which would enable specifying the arguments.  The use of this macro is
8935 not encouraged, as it violates strongly the typing system.
8937 This macro cannot be used for Erlang tests.
8938 @end defmac
8940 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
8941 @acindex{LANG_FUNC_LINK_TRY}
8942 Expands into a source file which uses the @var{function} in the body of
8943 the main function (e.g., @code{main} in C).  Since it uses
8944 @code{AC_LANG_PROGRAM}, the features of the latter are available.
8946 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
8947 It is considered to be severely broken, and in the future will be
8948 removed in favor of actual function calls (with properly typed
8949 arguments).
8951 This macro cannot be used for Erlang tests.
8952 @end defmac
8954 @node Running the Preprocessor
8955 @section Running the Preprocessor
8957 Sometimes one might need to run the preprocessor on some source file.
8958 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
8959 your project, not merely run the preprocessor on it; therefore you
8960 certainly want to run the compiler, not the preprocessor.  Resist the
8961 temptation of following the easiest path.
8963 Nevertheless, if you need to run the preprocessor, then use
8964 @code{AC_PREPROC_IFELSE}.
8966 The macros described in this section cannot be used for tests in Erlang or
8967 Fortran, since those languages require no preprocessor.
8969 @anchor{AC_PREPROC_IFELSE}
8970 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
8971   @ovar{action-if-false})
8972 @acindex{PREPROC_IFELSE}
8973 Run the preprocessor of the current language (@pxref{Language Choice})
8974 on the @var{input}, run the shell commands @var{action-if-true} on
8975 success, @var{action-if-false} otherwise.  The @var{input} can be made
8976 by @code{AC_LANG_PROGRAM} and friends.
8978 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
8979 @option{-g}, @option{-O}, etc.@: are not valid options to many C
8980 preprocessors.
8982 It is customary to report unexpected failures with
8983 @code{AC_MSG_FAILURE}.  If needed, @var{action-if-true} can further access
8984 the preprocessed output in the file @file{conftest.i}.
8985 @end defmac
8987 For instance:
8989 @example
8990 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8991 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8992   [Greetings string.])
8993 AC_PREPROC_IFELSE(
8994    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8995                     [[fputs (hw, stdout);]])],
8996    [AC_MSG_RESULT([OK])],
8997    [AC_MSG_FAILURE([unexpected preprocessor failure])])
8998 @end example
9000 @noindent
9001 results in:
9003 @example
9004 checking for gcc... gcc
9005 checking for C compiler default output file name... a.out
9006 checking whether the C compiler works... yes
9007 checking whether we are cross compiling... no
9008 checking for suffix of executables...
9009 checking for suffix of object files... o
9010 checking whether we are using the GNU C compiler... yes
9011 checking whether gcc accepts -g... yes
9012 checking for gcc option to accept ISO C89... none needed
9013 checking how to run the C preprocessor... gcc -E
9015 @end example
9017 @sp 1
9019 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9020 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9021 it impossible to use it to elaborate sources.  You are encouraged to
9022 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9023 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9024 to run the @emph{preprocessor} and not the compiler?
9026 @anchor{AC_EGREP_HEADER}
9027 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9028   @var{action-if-found}, @ovar{action-if-not-found})
9029 @acindex{EGREP_HEADER}
9030 If the output of running the preprocessor on the system header file
9031 @var{header-file} matches the extended regular expression
9032 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9033 execute @var{action-if-not-found}.
9034 @end defmac
9036 @anchor{AC_EGREP_CPP}
9037 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9038   @ovar{action-if-found}, @ovar{action-if-not-found})
9039 @acindex{EGREP_CPP}
9040 @var{program} is the text of a C or C++ program, on which shell
9041 variable, back quote, and backslash substitutions are performed.  If the
9042 output of running the preprocessor on @var{program} matches the
9043 extended regular expression @var{pattern}, execute shell commands
9044 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9045 @end defmac
9049 @node Running the Compiler
9050 @section Running the Compiler
9052 To check for a syntax feature of the current language's (@pxref{Language
9053 Choice}) compiler, such as whether it recognizes a certain keyword, or
9054 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9055 to compile a small program that uses that feature.
9057 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9058   @ovar{action-if-false})
9059 @acindex{COMPILE_IFELSE}
9060 Run the compiler and compilation flags of the current language
9061 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9062 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
9063 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9065 It is customary to report unexpected failures with
9066 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
9067 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9068 Linker}).  If needed, @var{action-if-true} can further access the
9069 just-compiled object file @file{conftest.$OBJEXT}.
9071 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9072 current language, which means that if the compiler has not yet been
9073 determined, the compiler determination will be made prior to the body of
9074 the outermust @code{AC_DEFUN} macro that triggered this macro to
9075 expand (@pxref{Expanded Before Required}).
9076 @end defmac
9078 @ovindex ERL
9079 For tests in Erlang, the @var{input} must be the source code of a module named
9080 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9081 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
9082 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9083 to ensure that the Erlang module has the right name.
9085 @node Running the Linker
9086 @section Running the Linker
9088 To check for a library, a function, or a global variable, Autoconf
9089 @command{configure} scripts try to compile and link a small program that
9090 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
9091 @code{ar} on the C library to try to figure out which functions are
9092 available.  Trying to link with the function is usually a more reliable
9093 approach because it avoids dealing with the variations in the options
9094 and output formats of @code{nm} and @code{ar} and in the location of the
9095 standard libraries.  It also allows configuring for cross-compilation or
9096 checking a function's runtime behavior if needed.  On the other hand,
9097 it can be slower than scanning the libraries once, but accuracy is more
9098 important than speed.
9100 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9101 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
9102 to check for libraries (@pxref{Libraries}), by adding the library being
9103 checked for to @code{LIBS} temporarily and trying to link a small
9104 program.
9106 @anchor{AC_LINK_IFELSE}
9107 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9108   @ovar{action-if-false})
9109 @acindex{LINK_IFELSE}
9110 Run the compiler (and compilation flags) and the linker of the current
9111 language (@pxref{Language Choice}) on the @var{input}, run the shell
9112 commands @var{action-if-true} on success, @var{action-if-false}
9113 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
9114 friends.  If needed, @var{action-if-true} can further access the
9115 just-linked program file @file{conftest$EXEEXT}.
9117 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9118 current compilation flags.
9120 It is customary to report unexpected failures with
9121 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
9122 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9123 @end defmac
9125 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9126 programs are interpreted and do not require linking.
9130 @node Runtime
9131 @section Checking Runtime Behavior
9133 Sometimes you need to find out how a system performs at runtime, such
9134 as whether a given function has a certain capability or bug.  If you
9135 can, make such checks when your program runs instead of when it is
9136 configured.  You can check for things like the machine's endianness when
9137 your program initializes itself.
9139 If you really need to test for a runtime behavior while configuring,
9140 you can write a test program to determine the result, and compile and
9141 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
9142 possible, because this prevents people from configuring your package for
9143 cross-compiling.
9145 @anchor{AC_RUN_IFELSE}
9146 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9147   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
9148 @acindex{RUN_IFELSE}
9149 If @var{program} compiles and links successfully and returns an exit
9150 status of 0 when executed, run shell commands @var{action-if-true}.
9151 Otherwise, run shell commands @var{action-if-false}.
9153 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9154 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9155 compilation flags of the current language (@pxref{Language Choice}).
9156 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9157 for further testing.
9159 If the compiler being used does not produce executables that run on the
9160 system where @command{configure} is being run, then the test program is
9161 not run.  If the optional shell commands @var{action-if-cross-compiling}
9162 are given, they are run instead.  Otherwise, @command{configure} prints
9163 an error message and exits.
9165 In the @var{action-if-false} section, the failing exit status is
9166 available in the shell variable @samp{$?}.  This exit status might be
9167 that of a failed compilation, or it might be that of a failed program
9168 execution.
9170 It is customary to report unexpected failures with
9171 @code{AC_MSG_FAILURE}.
9172 @end defmac
9174 Try to provide a pessimistic default value to use when cross-compiling
9175 makes runtime tests impossible.  You do this by passing the optional
9176 last argument to @code{AC_RUN_IFELSE}.  @command{autoconf} prints a
9177 warning message when creating @command{configure} each time it
9178 encounters a call to @code{AC_RUN_IFELSE} with no
9179 @var{action-if-cross-compiling} argument given.  You may ignore the
9180 warning, though users cannot configure your package for
9181 cross-compiling.  A few of the macros distributed with Autoconf produce
9182 this warning message.
9184 To configure for cross-compiling you can also choose a value for those
9185 parameters based on the canonical system name (@pxref{Manual
9186 Configuration}).  Alternatively, set up a test results cache file with
9187 the correct values for the host system (@pxref{Caching Results}).
9189 @ovindex cross_compiling
9190 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9191 in other macros, including a few of the ones that come with Autoconf,
9192 you can test whether the shell variable @code{cross_compiling} is set to
9193 @samp{yes}, and then use an alternate method to get the results instead
9194 of calling the macros.
9196 It is also permissible to temporarily assign to @code{cross_compiling}
9197 in order to force tests to behave as though they are in a
9198 cross-compilation environment, particularly since this provides a way to
9199 test your @var{action-if-cross-compiling} even when you are not using a
9200 cross-compiler.
9202 @example
9203 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9204 # to use the slow link-only method
9205 save_cross_compiling=$cross_compiling
9206 cross_compiling=yes
9207 AC_COMPUTE_INT([@dots{}])
9208 cross_compiling=$save_cross_compiling
9209 @end example
9211 A C or C++ runtime test should be portable.
9212 @xref{Portable C and C++}.
9214 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9215 function: the given status code is used to determine the success of the test
9216 (status is @code{0}) or its failure (status is different than @code{0}), as
9217 explained above.  It must be noted that data output through the standard output
9218 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9219 Therefore, if a test must output configuration information, it is recommended
9220 to create and to output data into the temporary file named @file{conftest.out},
9221 using the functions of module @code{file}.  The @code{conftest.out} file is
9222 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9223 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9224 macro is:
9226 @example
9227 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9228 AC_ERLANG_NEED_ERL
9229 AC_LANG(Erlang)
9230 AC_RUN_IFELSE(
9231   [AC_LANG_PROGRAM([], [dnl
9232     file:write_file("conftest.out", code:lib_dir()),
9233     halt(0)])],
9234   [echo "code:lib_dir() returned: `cat conftest.out`"],
9235   [AC_MSG_FAILURE([test Erlang program execution failed])])
9236 @end example
9239 @node Systemology
9240 @section Systemology
9241 @cindex Systemology
9243 This section aims at presenting some systems and pointers to
9244 documentation.  It may help you addressing particular problems reported
9245 by users.
9247 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
9248 derived from the @uref{http://@/www.bell-labs.com/@/history/@/unix/, Unix
9249 operating system}.
9251 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9252 contains a table correlating the features of various Posix-conforming
9253 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
9254 simplified diagram of how many Unix systems were derived from each
9255 other.
9257 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9258 provides some variants of traditional implementations of Unix utilities.
9260 @table @asis
9261 @item Darwin
9262 @cindex Darwin
9263 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
9264 case-preserving, but case insensitive.  This can cause nasty problems,
9265 since for instance the installation attempt for a package having an
9266 @file{INSTALL} file can result in @samp{make install} report that
9267 nothing was to be done!
9269 That's all dependent on whether the file system is a UFS (case
9270 sensitive) or HFS+ (case preserving).  By default Apple wants you to
9271 install the OS on HFS+.  Unfortunately, there are some pieces of
9272 software which really need to be built on UFS@.  We may want to rebuild
9273 Darwin to have both UFS and HFS+ available (and put the /local/build
9274 tree on the UFS).
9276 @item QNX 4.25
9277 @cindex QNX 4.25
9278 @c FIXME: Please, if you feel like writing something more precise,
9279 @c it'd be great.  In particular, I can't understand the difference with
9280 @c QNX Neutrino.
9281 QNX is a realtime operating system running on Intel architecture
9282 meant to be scalable from the small embedded systems to the hundred
9283 processor super-computer.  It claims to be Posix certified.  More
9284 information is available on the
9285 @uref{http://@/www.qnx.com/, QNX home page}.
9287 @item Tru64
9288 @cindex Tru64
9289 @uref{http://@/h30097.www3.hp.com/@/docs/,
9290 Documentation of several versions of Tru64} is available in different
9291 formats.
9293 @item Unix version 7
9294 @cindex Unix version 7
9295 @cindex V7
9296 Officially this was called the ``Seventh Edition'' of ``the UNIX
9297 time-sharing system'' but we use the more-common name ``Unix version 7''.
9298 Documentation is available in the
9299 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
9300 Previous versions of Unix are called ``Unix version 6'', etc., but
9301 they were not as widely used.
9302 @end table
9305 @node Multiple Cases
9306 @section Multiple Cases
9308 Some operations are accomplished in several possible ways, depending on
9309 the OS variant.  Checking for them essentially requires a ``case
9310 statement''.  Autoconf does not directly provide one; however, it is
9311 easy to simulate by using a shell variable to keep track of whether a
9312 way to perform the operation has been found yet.
9314 Here is an example that uses the shell variable @code{fstype} to keep
9315 track of whether the remaining cases need to be checked.  Note that
9316 since the value of @code{fstype} is under our control, we don't have to
9317 use the longer @samp{test "x$fstype" = xno}.
9319 @example
9320 @group
9321 AC_MSG_CHECKING([how to get file system type])
9322 fstype=no
9323 # The order of these tests is important.
9324 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9325 #include <sys/fstyp.h>]])],
9326                   [AC_DEFINE([FSTYPE_STATVFS], [1],
9327                      [Define if statvfs exists.])
9328                    fstype=SVR4])
9329 if test $fstype = no; then
9330   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9331 #include <sys/fstyp.h>]])],
9332                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9333                      [Define if USG statfs.])
9334                    fstype=SVR3])
9336 if test $fstype = no; then
9337   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9338 #include <sys/vmount.h>]])]),
9339                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9340                      [Define if AIX statfs.])
9341                    fstype=AIX])
9343 # (more cases omitted here)
9344 AC_MSG_RESULT([$fstype])
9345 @end group
9346 @end example
9348 @c ====================================================== Results of Tests.
9350 @node Results
9351 @chapter Results of Tests
9353 Once @command{configure} has determined whether a feature exists, what can
9354 it do to record that information?  There are four sorts of things it can
9355 do: define a C preprocessor symbol, set a variable in the output files,
9356 save the result in a cache file for future @command{configure} runs, and
9357 print a message letting the user know the result of the test.
9359 @menu
9360 * Defining Symbols::            Defining C preprocessor symbols
9361 * Setting Output Variables::    Replacing variables in output files
9362 * Special Chars in Variables::  Characters to beware of in variables
9363 * Caching Results::             Speeding up subsequent @command{configure} runs
9364 * Printing Messages::           Notifying @command{configure} users
9365 @end menu
9367 @node Defining Symbols
9368 @section Defining C Preprocessor Symbols
9370 A common action to take in response to a feature test is to define a C
9371 preprocessor symbol indicating the results of the test.  That is done by
9372 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9374 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9375 into the output variable @code{DEFS}, which contains an option
9376 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
9377 Autoconf version 1, there is no variable @code{DEFS} defined while
9378 @command{configure} is running.  To check whether Autoconf macros have
9379 already defined a certain C preprocessor symbol, test the value of the
9380 appropriate cache variable, as in this example:
9382 @example
9383 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9384                           [Define if vprintf exists.])])
9385 if test "x$ac_cv_func_vprintf" != xyes; then
9386   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9387                             [Define if _doprnt exists.])])
9389 @end example
9391 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9392 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9393 correct values into @code{#define} statements in a template file.
9394 @xref{Configuration Headers}, for more information about this kind of
9395 output.
9397 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9398 @defmacx AC_DEFINE (@var{variable})
9399 @cvindex @var{variable}
9400 @acindex{DEFINE}
9401 Define @var{variable} to @var{value} (verbatim), by defining a C
9402 preprocessor macro for @var{variable}.  @var{variable} should be a C
9403 identifier, optionally suffixed by a parenthesized argument list to
9404 define a C preprocessor macro with arguments.  The macro argument list,
9405 if present, should be a comma-separated list of C identifiers, possibly
9406 terminated by an ellipsis @samp{...} if C99 syntax is employed.
9407 @var{variable} should not contain comments, white space, trigraphs,
9408 backslash-newlines, universal character names, or non-ASCII
9409 characters.
9411 @var{value} may contain backslash-escaped newlines, which will be
9412 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9413 via @code{@@DEFS@@} (with no effect on the compilation, since the
9414 preprocessor sees only one line in the first place).  @var{value} should
9415 not contain raw newlines.  If you are not using
9416 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9417 characters, as @command{make} tends to eat them.  To use a shell
9418 variable, use @code{AC_DEFINE_UNQUOTED} instead.
9420 @var{description} is only useful if you are using
9421 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
9422 the generated @file{config.h.in} as the comment before the macro define.
9423 The following example defines the C preprocessor variable
9424 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
9426 @example
9427 AC_DEFINE([EQUATION], ["$a > $b"],
9428   [Equation string.])
9429 @end example
9431 If neither @var{value} nor @var{description} are given, then
9432 @var{value} defaults to 1 instead of to the empty string.  This is for
9433 backwards compatibility with older versions of Autoconf, but this usage
9434 is obsolescent and may be withdrawn in future versions of Autoconf.
9436 If the @var{variable} is a literal string, it is passed to
9437 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9439 If multiple @code{AC_DEFINE} statements are executed for the same
9440 @var{variable} name (not counting any parenthesized argument list),
9441 the last one wins.
9442 @end defmac
9444 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9445 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
9446 @acindex{DEFINE_UNQUOTED}
9447 @cvindex @var{variable}
9448 Like @code{AC_DEFINE}, but three shell expansions are
9449 performed---once---on @var{variable} and @var{value}: variable expansion
9450 (@samp{$}), command substitution (@samp{`}), and backslash escaping
9451 (@samp{\}), as if in an unquoted here-document.  Single and double quote
9452 characters in the value have no
9453 special meaning.  Use this macro instead of @code{AC_DEFINE} when
9454 @var{variable} or @var{value} is a shell variable.  Examples:
9456 @example
9457 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
9458   [Configuration machine file.])
9459 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
9460   [getgroups return type.])
9461 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
9462   [Translated header name.])
9463 @end example
9464 @end defmac
9466 Due to a syntactical bizarreness of the Bourne shell, do not use
9467 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
9468 calls from other macro calls or shell code; that can cause syntax errors
9469 in the resulting @command{configure} script.  Use either blanks or
9470 newlines.  That is, do this:
9472 @example
9473 AC_CHECK_HEADER([elf.h],
9474   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
9475 @end example
9477 @noindent
9478 or this:
9480 @example
9481 AC_CHECK_HEADER([elf.h],
9482   [AC_DEFINE([SVR4], [1], [System V Release 4])
9483    LIBS="-lelf $LIBS"])
9484 @end example
9486 @noindent
9487 instead of this:
9489 @example
9490 AC_CHECK_HEADER([elf.h],
9491   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
9492 @end example
9494 @node Setting Output Variables
9495 @section Setting Output Variables
9496 @cindex Output variables
9498 Another way to record the results of tests is to set @dfn{output
9499 variables}, which are shell variables whose values are substituted into
9500 files that @command{configure} outputs.  The two macros below create new
9501 output variables.  @xref{Preset Output Variables}, for a list of output
9502 variables that are always available.
9504 @defmac AC_SUBST (@var{variable}, @ovar{value})
9505 @acindex{SUBST}
9506 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
9507 substitute the variable @var{variable} into output files (typically one
9508 or more makefiles).  This means that @code{AC_OUTPUT}
9509 replaces instances of @samp{@@@var{variable}@@} in input files with the
9510 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
9511 is called.  The value can contain any non-@code{NUL} character, including
9512 newline.  If you are using Automake 1.11 or newer, for newlines in values
9513 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
9514 @command{automake} from adding a line @code{@var{variable} =
9515 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
9516 Automake, automake, Other things Automake recognizes}).
9518 Variable occurrences should not overlap: e.g., an input file should
9519 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
9520 are variable names.
9521 The substituted value is not rescanned for more output variables;
9522 occurrences of @samp{@@@var{variable}@@} in the value are inserted
9523 literally into the output file.  (The algorithm uses the special marker
9524 @code{|#_!!_#|} internally, so neither the substituted value nor the
9525 output file may contain @code{|#_!!_#|}.)
9527 If @var{value} is given, in addition assign it to @var{variable}.
9529 The string @var{variable} is passed to @code{m4_pattern_allow}
9530 (@pxref{Forbidden Patterns}).
9531 @end defmac
9533 @defmac AC_SUBST_FILE (@var{variable})
9534 @acindex{SUBST_FILE}
9535 Another way to create an output variable from a shell variable.  Make
9536 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
9537 named by shell variable @var{variable} into output files.  This means
9538 that @code{AC_OUTPUT} replaces instances of
9539 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
9540 with the contents of the file that the shell variable @var{variable}
9541 names when @code{AC_OUTPUT} is called.  Set the variable to
9542 @file{/dev/null} for cases that do not have a file to insert.
9543 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
9544 line by itself, optionally surrounded by spaces and tabs.  The
9545 substitution replaces the whole line, including the spaces, tabs, and
9546 the terminating newline.
9548 This macro is useful for inserting makefile fragments containing
9549 special dependencies or other @command{make} directives for particular host
9550 or target types into makefiles.  For example, @file{configure.ac}
9551 could contain:
9553 @example
9554 AC_SUBST_FILE([host_frag])
9555 host_frag=$srcdir/conf/sun4.mh
9556 @end example
9558 @noindent
9559 and then a @file{Makefile.in} could contain:
9561 @example
9562 @@host_frag@@
9563 @end example
9565 The string @var{variable} is passed to @code{m4_pattern_allow}
9566 (@pxref{Forbidden Patterns}).
9567 @end defmac
9569 @cindex Precious Variable
9570 @cindex Variable, Precious
9571 Running @command{configure} in varying environments can be extremely
9572 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
9573 ./configure}, then the cache, @file{config.h}, and many other output
9574 files depend upon @command{bizarre-cc} being the C compiler.  If
9575 for some reason the user runs @command{./configure} again, or if it is
9576 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
9577 and @pxref{config.status Invocation}), then the configuration can be
9578 inconsistent, composed of results depending upon two different
9579 compilers.
9581 Environment variables that affect this situation, such as @samp{CC}
9582 above, are called @dfn{precious variables}, and can be declared as such
9583 by @code{AC_ARG_VAR}.
9585 @defmac AC_ARG_VAR (@var{variable}, @var{description})
9586 @acindex{ARG_VAR}
9587 Declare @var{variable} is a precious variable, and include its
9588 @var{description} in the variable section of @samp{./configure --help}.
9590 Being precious means that
9591 @itemize @minus
9592 @item
9593 @var{variable} is substituted via @code{AC_SUBST}.
9595 @item
9596 The value of @var{variable} when @command{configure} was launched is
9597 saved in the cache, including if it was not specified on the command
9598 line but via the environment.  Indeed, while @command{configure} can
9599 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
9600 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
9601 which, unfortunately, is what most users do.
9603 We emphasize that it is the @emph{initial} value of @var{variable} which
9604 is saved, not that found during the execution of @command{configure}.
9605 Indeed, specifying @samp{./configure FOO=foo} and letting
9606 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
9607 different things.
9609 @item
9610 @var{variable} is checked for consistency between two
9611 @command{configure} runs.  For instance:
9613 @example
9614 $ @kbd{./configure --silent --config-cache}
9615 $ @kbd{CC=cc ./configure --silent --config-cache}
9616 configure: error: `CC' was not set in the previous run
9617 configure: error: changes in the environment can compromise \
9618 the build
9619 configure: error: run `make distclean' and/or \
9620 `rm config.cache' and start over
9621 @end example
9623 @noindent
9624 and similarly if the variable is unset, or if its content is changed.
9625 If the content has white space changes only, then the error is degraded
9626 to a warning only, but the old value is reused.
9628 @item
9629 @var{variable} is kept during automatic reconfiguration
9630 (@pxref{config.status Invocation}) as if it had been passed as a command
9631 line argument, including when no cache is used:
9633 @example
9634 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
9635 $ @kbd{./config.status --recheck}
9636 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
9637   CC=/usr/bin/cc  --no-create --no-recursion
9638 @end example
9639 @end itemize
9640 @end defmac
9642 @node Special Chars in Variables
9643 @section Special Characters in Output Variables
9644 @cindex Output variables, special characters in
9646 Many output variables are intended to be evaluated both by
9647 @command{make} and by the shell.  Some characters are expanded
9648 differently in these two contexts, so to avoid confusion these
9649 variables' values should not contain any of the following characters:
9651 @example
9652 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
9653 @end example
9655 Also, these variables' values should neither contain newlines, nor start
9656 with @samp{~}, nor contain white space or @samp{:} immediately followed
9657 by @samp{~}.  The values can contain nonempty sequences of white space
9658 characters like tabs and spaces, but each such sequence might
9659 arbitrarily be replaced by a single space during substitution.
9661 These restrictions apply both to the values that @command{configure}
9662 computes, and to the values set directly by the user.  For example, the
9663 following invocations of @command{configure} are problematic, since they
9664 attempt to use special characters within @code{CPPFLAGS} and white space
9665 within @code{$(srcdir)}:
9667 @example
9668 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
9670 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
9671 @end example
9673 @node Caching Results
9674 @section Caching Results
9675 @cindex Cache
9677 To avoid checking for the same features repeatedly in various
9678 @command{configure} scripts (or in repeated runs of one script),
9679 @command{configure} can optionally save the results of many checks in a
9680 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
9681 runs with caching enabled and finds a cache file, it reads the results
9682 of previous runs from the cache and avoids rerunning those checks.  As a
9683 result, @command{configure} can then run much faster than if it had to
9684 perform all of the checks every time.
9686 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
9687 @acindex{CACHE_VAL}
9688 Ensure that the results of the check identified by @var{cache-id} are
9689 available.  If the results of the check were in the cache file that was
9690 read, and @command{configure} was not given the @option{--quiet} or
9691 @option{--silent} option, print a message saying that the result was
9692 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
9693 the shell commands are run to determine the value, the value is
9694 saved in the cache file just before @command{configure} creates its output
9695 files.  @xref{Cache Variable Names}, for how to choose the name of the
9696 @var{cache-id} variable.
9698 The @var{commands-to-set-it} @emph{must have no side effects} except for
9699 setting the variable @var{cache-id}, see below.
9700 @end defmac
9702 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
9703   @var{commands-to-set-it})
9704 @acindex{CACHE_CHECK}
9705 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
9706 messages.  This macro provides a convenient shorthand for the most
9707 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
9708 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
9709 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
9711 The @var{commands-to-set-it} @emph{must have no side effects} except for
9712 setting the variable @var{cache-id}, see below.
9713 @end defmac
9715 It is common to find buggy macros using @code{AC_CACHE_VAL} or
9716 @code{AC_CACHE_CHECK}, because people are tempted to call
9717 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
9718 @emph{follows} the call to @code{AC_CACHE_VAL} should call
9719 @code{AC_DEFINE}, by examining the value of the cache variable.  For
9720 instance, the following macro is broken:
9722 @example
9723 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
9724 @group
9725 AC_DEFUN([AC_SHELL_TRUE],
9726 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9727                 [my_cv_shell_true_works=no
9728                  (true) 2>/dev/null && my_cv_shell_true_works=yes
9729                  if test "x$my_cv_shell_true_works" = xyes; then
9730                    AC_DEFINE([TRUE_WORKS], [1],
9731                              [Define if `true(1)' works properly.])
9732                  fi])
9734 @end group
9735 @end example
9737 @noindent
9738 This fails if the cache is enabled: the second time this macro is run,
9739 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
9742 @example
9743 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
9744 @group
9745 AC_DEFUN([AC_SHELL_TRUE],
9746 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9747                 [my_cv_shell_true_works=no
9748                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
9749  if test "x$my_cv_shell_true_works" = xyes; then
9750    AC_DEFINE([TRUE_WORKS], [1],
9751              [Define if `true(1)' works properly.])
9752  fi
9754 @end group
9755 @end example
9757 Also, @var{commands-to-set-it} should not print any messages, for
9758 example with @code{AC_MSG_CHECKING}; do that before calling
9759 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
9760 the results of the check are retrieved from the cache or determined by
9761 running the shell commands.
9763 @menu
9764 * Cache Variable Names::        Shell variables used in caches
9765 * Cache Files::                 Files @command{configure} uses for caching
9766 * Cache Checkpointing::         Loading and saving the cache file
9767 @end menu
9769 @node Cache Variable Names
9770 @subsection Cache Variable Names
9771 @cindex Cache variable
9773 The names of cache variables should have the following format:
9775 @example
9776 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
9777 @end example
9779 @noindent
9780 for example, @samp{ac_cv_header_stat_broken} or
9781 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
9783 @table @asis
9784 @item @var{package-prefix}
9785 An abbreviation for your package or organization; the same prefix you
9786 begin local Autoconf macros with, except lowercase by convention.
9787 For cache values used by the distributed Autoconf macros, this value is
9788 @samp{ac}.
9790 @item @code{_cv_}
9791 Indicates that this shell variable is a cache value.  This string
9792 @emph{must} be present in the variable name, including the leading
9793 underscore.
9795 @item @var{value-type}
9796 A convention for classifying cache values, to produce a rational naming
9797 system.  The values used in Autoconf are listed in @ref{Macro Names}.
9799 @item @var{specific-value}
9800 Which member of the class of cache values this test applies to.
9801 For example, which function (@samp{alloca}), program (@samp{gcc}), or
9802 output variable (@samp{INSTALL}).
9804 @item @var{additional-options}
9805 Any particular behavior of the specific member that this test applies to.
9806 For example, @samp{broken} or @samp{set}.  This part of the name may
9807 be omitted if it does not apply.
9808 @end table
9810 The values assigned to cache variables may not contain newlines.
9811 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
9812 names of files or functions; so this is not an important restriction.
9813 @ref{Cache Variable Index} for an index of cache variables with
9814 documented semantics.
9817 @node Cache Files
9818 @subsection Cache Files
9820 A cache file is a shell script that caches the results of configure
9821 tests run on one system so they can be shared between configure scripts
9822 and configure runs.  It is not useful on other systems.  If its contents
9823 are invalid for some reason, the user may delete or edit it, or override
9824 documented cache variables on the @command{configure} command line.
9826 By default, @command{configure} uses no cache file,
9827 to avoid problems caused by accidental
9828 use of stale cache files.
9830 To enable caching, @command{configure} accepts @option{--config-cache} (or
9831 @option{-C}) to cache results in the file @file{config.cache}.
9832 Alternatively, @option{--cache-file=@var{file}} specifies that
9833 @var{file} be the cache file.  The cache file is created if it does not
9834 exist already.  When @command{configure} calls @command{configure} scripts in
9835 subdirectories, it uses the @option{--cache-file} argument so that they
9836 share the same cache.  @xref{Subdirectories}, for information on
9837 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
9839 @file{config.status} only pays attention to the cache file if it is
9840 given the @option{--recheck} option, which makes it rerun
9841 @command{configure}.
9843 It is wrong to try to distribute cache files for particular system types.
9844 There is too much room for error in doing that, and too much
9845 administrative overhead in maintaining them.  For any features that
9846 can't be guessed automatically, use the standard method of the canonical
9847 system type and linking files (@pxref{Manual Configuration}).
9849 The site initialization script can specify a site-wide cache file to
9850 use, instead of the usual per-program cache.  In this case, the cache
9851 file gradually accumulates information whenever someone runs a new
9852 @command{configure} script.  (Running @command{configure} merges the new cache
9853 results with the existing cache file.)  This may cause problems,
9854 however, if the system configuration (e.g., the installed libraries or
9855 compilers) changes and the stale cache file is not deleted.
9857 If @command{configure} is interrupted at the right time when it updates
9858 a cache file outside of the build directory where the @command{configure}
9859 script is run, it may leave behind a temporary file named after the
9860 cache file with digits following it.  You may safely delete such a file.
9863 @node Cache Checkpointing
9864 @subsection Cache Checkpointing
9866 If your configure script, or a macro called from @file{configure.ac}, happens
9867 to abort the configure process, it may be useful to checkpoint the cache
9868 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
9869 reduces the amount of time it takes to rerun the configure script with
9870 (hopefully) the error that caused the previous abort corrected.
9872 @c FIXME: Do we really want to document this guy?
9873 @defmac AC_CACHE_LOAD
9874 @acindex{CACHE_LOAD}
9875 Loads values from existing cache file, or creates a new cache file if a
9876 cache file is not found.  Called automatically from @code{AC_INIT}.
9877 @end defmac
9879 @defmac AC_CACHE_SAVE
9880 @acindex{CACHE_SAVE}
9881 Flushes all cached values to the cache file.  Called automatically from
9882 @code{AC_OUTPUT}, but it can be quite useful to call
9883 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
9884 @end defmac
9886 For instance:
9888 @example
9889 @r{ @dots{} AC_INIT, etc. @dots{}}
9890 @group
9891 # Checks for programs.
9892 AC_PROG_CC
9893 AC_PROG_AWK
9894 @r{ @dots{} more program checks @dots{}}
9895 AC_CACHE_SAVE
9896 @end group
9898 @group
9899 # Checks for libraries.
9900 AC_CHECK_LIB([nsl], [gethostbyname])
9901 AC_CHECK_LIB([socket], [connect])
9902 @r{ @dots{} more lib checks @dots{}}
9903 AC_CACHE_SAVE
9904 @end group
9906 @group
9907 # Might abort@dots{}
9908 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
9909 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
9910 @end group
9911 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
9912 @end example
9914 @node Printing Messages
9915 @section Printing Messages
9916 @cindex Messages, from @command{configure}
9918 @command{configure} scripts need to give users running them several kinds
9919 of information.  The following macros print messages in ways appropriate
9920 for each kind.  The arguments to all of them get enclosed in shell
9921 double quotes, so the shell performs variable and back-quote
9922 substitution on them.
9924 These macros are all wrappers around the @command{echo} shell command.
9925 They direct output to the appropriate file descriptor (@pxref{File
9926 Descriptor Macros}).
9927 @command{configure} scripts should rarely need to run @command{echo} directly
9928 to print messages for the user.  Using these macros makes it easy to
9929 change how and when each kind of message is printed; such changes need
9930 only be made to the macro definitions and all the callers change
9931 automatically.
9933 To diagnose static issues, i.e., when @command{autoconf} is run, see
9934 @ref{Diagnostic Macros}.
9936 @defmac AC_MSG_CHECKING (@var{feature-description})
9937 @acindex{MSG_CHECKING}
9938 Notify the user that @command{configure} is checking for a particular
9939 feature.  This macro prints a message that starts with @samp{checking }
9940 and ends with @samp{...} and no newline.  It must be followed by a call
9941 to @code{AC_MSG_RESULT} to print the result of the check and the
9942 newline.  The @var{feature-description} should be something like
9943 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
9944 c89}.
9946 This macro prints nothing if @command{configure} is run with the
9947 @option{--quiet} or @option{--silent} option.
9948 @end defmac
9950 @anchor{AC_MSG_RESULT}
9951 @defmac AC_MSG_RESULT (@var{result-description})
9952 @acindex{MSG_RESULT}
9953 Notify the user of the results of a check.  @var{result-description} is
9954 almost always the value of the cache variable for the check, typically
9955 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
9956 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
9957 the completion of the message printed by the call to
9958 @code{AC_MSG_CHECKING}.
9960 This macro prints nothing if @command{configure} is run with the
9961 @option{--quiet} or @option{--silent} option.
9962 @end defmac
9964 @anchor{AC_MSG_NOTICE}
9965 @defmac AC_MSG_NOTICE (@var{message})
9966 @acindex{MSG_NOTICE}
9967 Deliver the @var{message} to the user.  It is useful mainly to print a
9968 general description of the overall purpose of a group of feature checks,
9969 e.g.,
9971 @example
9972 AC_MSG_NOTICE([checking if stack overflow is detectable])
9973 @end example
9975 This macro prints nothing if @command{configure} is run with the
9976 @option{--quiet} or @option{--silent} option.
9977 @end defmac
9979 @anchor{AC_MSG_ERROR}
9980 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
9981 @acindex{MSG_ERROR}
9982 Notify the user of an error that prevents @command{configure} from
9983 completing.  This macro prints an error message to the standard error
9984 output and exits @command{configure} with @var{exit-status} (@samp{$?}
9985 by default, except that @samp{0} is converted to @samp{1}).
9986 @var{error-description} should be something like @samp{invalid value
9987 $HOME for \$HOME}.
9989 The @var{error-description} should start with a lower-case letter, and
9990 ``cannot'' is preferred to ``can't''.
9991 @end defmac
9993 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
9994 @acindex{MSG_FAILURE}
9995 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
9996 prevents @command{configure} from completing @emph{and} that additional
9997 details are provided in @file{config.log}.  This is typically used when
9998 abnormal results are found during a compilation.
9999 @end defmac
10001 @anchor{AC_MSG_WARN}
10002 @defmac AC_MSG_WARN (@var{problem-description})
10003 @acindex{MSG_WARN}
10004 Notify the @command{configure} user of a possible problem.  This macro
10005 prints the message to the standard error output; @command{configure}
10006 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10007 provide a default (back-up) behavior for the situations they warn about.
10008 @var{problem-description} should be something like @samp{ln -s seems to
10009 make hard links}.
10010 @end defmac
10014 @c ====================================================== Programming in M4.
10016 @node Programming in M4
10017 @chapter Programming in M4
10018 @cindex M4
10020 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10021 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10022 provides macros dedicated to shell script generation.
10024 As of this version of Autoconf, these two layers still contain
10025 experimental macros, whose interface might change in the future.  As a
10026 matter of fact, @emph{anything that is not documented must not be used}.
10028 @menu
10029 * M4 Quotation::                Protecting macros from unwanted expansion
10030 * Using autom4te::              The Autoconf executables backbone
10031 * Programming in M4sugar::      Convenient pure M4 macros
10032 * Debugging via autom4te::      Figuring out what M4 was doing
10033 @end menu
10035 @node M4 Quotation
10036 @section M4 Quotation
10037 @cindex M4 quotation
10038 @cindex quotation
10040 The most common problem with existing macros is an improper quotation.
10041 This section, which users of Autoconf can skip, but which macro writers
10042 @emph{must} read, first justifies the quotation scheme that was chosen
10043 for Autoconf and then ends with a rule of thumb.  Understanding the
10044 former helps one to follow the latter.
10046 @menu
10047 * Active Characters::           Characters that change the behavior of M4
10048 * One Macro Call::              Quotation and one macro call
10049 * Quoting and Parameters::      M4 vs. shell parameters
10050 * Quotation and Nested Macros::  Macros calling macros
10051 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
10052 * Quadrigraphs::                Another way to escape special characters
10053 * Balancing Parentheses::       Dealing with unbalanced parentheses
10054 * Quotation Rule Of Thumb::     One parenthesis, one quote
10055 @end menu
10057 @node Active Characters
10058 @subsection Active Characters
10060 To fully understand where proper quotation is important, you first need
10061 to know what the special characters are in Autoconf: @samp{#} introduces
10062 a comment inside which no macro expansion is performed, @samp{,}
10063 separates arguments, @samp{[} and @samp{]} are the quotes
10064 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10065 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10066 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10067 @samp{$} inside a macro definition.
10069 In order to understand the delicate case of macro calls, we first have
10070 to present some obvious failures.  Below they are ``obvious-ified'',
10071 but when you find them in real life, they are usually in disguise.
10073 Comments, introduced by a hash and running up to the newline, are opaque
10074 tokens to the top level: active characters are turned off, and there is
10075 no macro expansion:
10077 @example
10078 # define([def], ine)
10079 @result{}# define([def], ine)
10080 @end example
10082 Each time there can be a macro expansion, there is a quotation
10083 expansion, i.e., one level of quotes is stripped:
10085 @example
10086 int tab[10];
10087 @result{}int tab10;
10088 [int tab[10];]
10089 @result{}int tab[10];
10090 @end example
10092 Without this in mind, the reader might try hopelessly to use her macro
10093 @code{array}:
10095 @example
10096 define([array], [int tab[10];])
10097 array
10098 @result{}int tab10;
10099 [array]
10100 @result{}array
10101 @end example
10103 @noindent
10104 How can you correctly output the intended results@footnote{Using
10105 @code{defn}.}?
10108 @node One Macro Call
10109 @subsection One Macro Call
10111 Let's proceed on the interaction between active characters and macros
10112 with this small macro, which just returns its first argument:
10114 @example
10115 define([car], [$1])
10116 @end example
10118 @noindent
10119 The two pairs of quotes above are not part of the arguments of
10120 @code{define}; rather, they are understood by the top level when it
10121 tries to find the arguments of @code{define}.  Therefore, assuming
10122 @code{car} is not already defined, it is equivalent to write:
10124 @example
10125 define(car, $1)
10126 @end example
10128 @noindent
10129 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10130 quotes, it is bad practice for Autoconf macros which must both be more
10131 robust and also advocate perfect style.
10133 At the top level, there are only two possibilities: either you
10134 quote or you don't:
10136 @example
10137 car(foo, bar, baz)
10138 @result{}foo
10139 [car(foo, bar, baz)]
10140 @result{}car(foo, bar, baz)
10141 @end example
10143 Let's pay attention to the special characters:
10145 @example
10146 car(#)
10147 @error{}EOF in argument list
10148 @end example
10150 The closing parenthesis is hidden in the comment; with a hypothetical
10151 quoting, the top level understood it this way:
10153 @example
10154 car([#)]
10155 @end example
10157 @noindent
10158 Proper quotation, of course, fixes the problem:
10160 @example
10161 car([#])
10162 @result{}#
10163 @end example
10165 Here are more examples:
10167 @example
10168 car(foo, bar)
10169 @result{}foo
10170 car([foo, bar])
10171 @result{}foo, bar
10172 car((foo, bar))
10173 @result{}(foo, bar)
10174 car([(foo], [bar)])
10175 @result{}(foo
10176 define([a], [b])
10177 @result{}
10178 car(a)
10179 @result{}b
10180 car([a])
10181 @result{}b
10182 car([[a]])
10183 @result{}a
10184 car([[[a]]])
10185 @result{}[a]
10186 @end example
10188 @node Quoting and Parameters
10189 @subsection Quoting and Parameters
10191 When M4 encounters @samp{$} within a macro definition, followed
10192 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10193 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10194 expansion.  This happens regardless of how many layers of quotes the
10195 parameter expansion is nested within, or even if it occurs in text that
10196 will be rescanned as a comment.
10198 @example
10199 define([none], [$1])
10200 @result{}
10201 define([one], [[$1]])
10202 @result{}
10203 define([two], [[[$1]]])
10204 @result{}
10205 define([comment], [# $1])
10206 @result{}
10207 define([active], [ACTIVE])
10208 @result{}
10209 none([active])
10210 @result{}ACTIVE
10211 one([active])
10212 @result{}active
10213 two([active])
10214 @result{}[active]
10215 comment([active])
10216 @result{}# active
10217 @end example
10219 On the other hand, since autoconf generates shell code, you often want
10220 to output shell variable expansion, rather than performing M4 parameter
10221 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10222 from the next character in the definition of your macro.  If the macro
10223 definition occurs in single-quoted text, then insert another level of
10224 quoting; if the usage is already inside a double-quoted string, then
10225 split it into concatenated strings.
10227 @example
10228 define([single], [a single-quoted $[]1 definition])
10229 @result{}
10230 define([double], [[a double-quoted $][1 definition]])
10231 @result{}
10232 single
10233 @result{}a single-quoted $1 definition
10234 double
10235 @result{}a double-quoted $1 definition
10236 @end example
10238 Posix states that M4 implementations are free to provide implementation
10239 extensions when @samp{$@{} is encountered in a macro definition.
10240 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10241 extensions that will be available in the future GNU M4 2.0,
10242 but guarantees that all other instances of @samp{$@{} will be output
10243 literally.  Therefore, this idiom can also be used to output shell code
10244 parameter references:
10246 @example
10247 define([first], [$@{1@}])first
10248 @result{}$@{1@}
10249 @end example
10251 Posix also states that @samp{$11} should expand to the first parameter
10252 concatenated with a literal @samp{1}, although some versions of
10253 GNU M4 expand the eleventh parameter instead.  For
10254 portability, you should only use single-digit M4 parameter expansion.
10256 With this in mind, we can explore the cases where macros invoke
10257 macros@enddots{}
10259 @node Quotation and Nested Macros
10260 @subsection Quotation and Nested Macros
10262 The examples below use the following macros:
10264 @example
10265 define([car], [$1])
10266 define([active], [ACT, IVE])
10267 define([array], [int tab[10]])
10268 @end example
10270 Each additional embedded macro call introduces other possible
10271 interesting quotations:
10273 @example
10274 car(active)
10275 @result{}ACT
10276 car([active])
10277 @result{}ACT, IVE
10278 car([[active]])
10279 @result{}active
10280 @end example
10282 In the first case, the top level looks for the arguments of @code{car},
10283 and finds @samp{active}.  Because M4 evaluates its arguments
10284 before applying the macro, @samp{active} is expanded, which results in:
10286 @example
10287 car(ACT, IVE)
10288 @result{}ACT
10289 @end example
10291 @noindent
10292 In the second case, the top level gives @samp{active} as first and only
10293 argument of @code{car}, which results in:
10295 @example
10296 active
10297 @result{}ACT, IVE
10298 @end example
10300 @noindent
10301 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10302 In the third case, @code{car} receives @samp{[active]}, which results in:
10304 @example
10305 [active]
10306 @result{}active
10307 @end example
10309 @noindent
10310 exactly as we already saw above.
10312 The example above, applied to a more realistic example, gives:
10314 @example
10315 car(int tab[10];)
10316 @result{}int tab10;
10317 car([int tab[10];])
10318 @result{}int tab10;
10319 car([[int tab[10];]])
10320 @result{}int tab[10];
10321 @end example
10323 @noindent
10324 Huh?  The first case is easily understood, but why is the second wrong,
10325 and the third right?  To understand that, you must know that after
10326 M4 expands a macro, the resulting text is immediately subjected
10327 to macro expansion and quote removal.  This means that the quote removal
10328 occurs twice---first before the argument is passed to the @code{car}
10329 macro, and second after the @code{car} macro expands to the first
10330 argument.
10332 As the author of the Autoconf macro @code{car}, you then consider it to
10333 be incorrect that your users have to double-quote the arguments of
10334 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
10335 quoted car:
10337 @example
10338 define([qar], [[$1]])
10339 @end example
10341 @noindent
10342 and check that @code{qar} is properly fixed:
10344 @example
10345 qar([int tab[10];])
10346 @result{}int tab[10];
10347 @end example
10349 @noindent
10350 Ahhh!  That's much better.
10352 But note what you've done: now that the result of @code{qar} is always
10353 a literal string, the only time a user can use nested macros is if she
10354 relies on an @emph{unquoted} macro call:
10356 @example
10357 qar(active)
10358 @result{}ACT
10359 qar([active])
10360 @result{}active
10361 @end example
10363 @noindent
10364 leaving no way for her to reproduce what she used to do with @code{car}:
10366 @example
10367 car([active])
10368 @result{}ACT, IVE
10369 @end example
10371 @noindent
10372 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10373 macros:
10375 @example
10376 define([my_includes], [#include <stdio.h>])
10377 car([my_includes])
10378 @result{}#include <stdio.h>
10379 qar(my_includes)
10380 @error{}EOF in argument list
10381 @end example
10383 This macro, @code{qar}, because it double quotes its arguments, forces
10384 its users to leave their macro calls unquoted, which is dangerous.
10385 Commas and other active symbols are interpreted by M4 before
10386 they are given to the macro, often not in the way the users expect.
10387 Also, because @code{qar} behaves differently from the other macros,
10388 it's an exception that should be avoided in Autoconf.
10390 @node Changequote is Evil
10391 @subsection @code{changequote} is Evil
10392 @cindex @code{changequote}
10394 The temptation is often high to bypass proper quotation, in particular
10395 when it's late at night.  Then, many experienced Autoconf hackers
10396 finally surrender to the dark side of the force and use the ultimate
10397 weapon: @code{changequote}.
10399 The M4 builtin @code{changequote} belongs to a set of primitives that
10400 allow one to adjust the syntax of the language to adjust it to one's
10401 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
10402 quotes, but in the context of shell programming (and actually of most
10403 programming languages), that's about the worst choice one can make:
10404 because of strings and back-quoted expressions in shell code (such as
10405 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
10406 programming languages (as in @samp{'0'}), there are many unbalanced
10407 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
10408 not impossible.  In order to make M4 useful in such a context, its
10409 designers have equipped it with @code{changequote}, which makes it
10410 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
10411 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
10412 because they are unlikely characters, but @emph{because they are
10413 characters unlikely to be unbalanced}.
10415 There are other magic primitives, such as @code{changecom} to specify
10416 what syntactic forms are comments (it is common to see
10417 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10418 @code{changeword} and @code{changesyntax} to change other syntactic
10419 details (such as the character to denote the @var{n}th argument, @samp{$} by
10420 default, the parentheses around arguments, etc.).
10422 These primitives are really meant to make M4 more useful for specific
10423 domains: they should be considered like command line options:
10424 @option{--quotes}, @option{--comments}, @option{--words}, and
10425 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
10426 it makes M4 libraries self contained (no need for additional options).
10428 There lies the problem@enddots{}
10430 @sp 1
10432 The problem is that it is then tempting to use them in the middle of an
10433 M4 script, as opposed to its initialization.  This, if not carefully
10434 thought out, can lead to disastrous effects: @emph{you are changing the
10435 language in the middle of the execution}.  Changing and restoring the
10436 syntax is often not enough: if you happened to invoke macros in between,
10437 these macros are lost, as the current syntax is probably not
10438 the one they were implemented with.
10440 @c FIXME: I've been looking for a short, real case example, but I
10441 @c lost them all :(
10444 @node Quadrigraphs
10445 @subsection Quadrigraphs
10446 @cindex quadrigraphs
10447 @cindex @samp{@@S|@@}
10448 @cindex @samp{@@&t@@}
10449 @c Info cannot handle `:' in index entries.
10450 @ifnotinfo
10451 @cindex @samp{@@<:@@}
10452 @cindex @samp{@@:>@@}
10453 @cindex @samp{@@%:@@}
10454 @cindex @samp{@@@{:@@}
10455 @cindex @samp{@@:@}@@}
10456 @end ifnotinfo
10458 When writing an Autoconf macro you may occasionally need to generate
10459 special characters that are difficult to express with the standard
10460 Autoconf quoting rules.  For example, you may need to output the regular
10461 expression @samp{[^[]}, which matches any character other than @samp{[}.
10462 This expression contains unbalanced brackets so it cannot be put easily
10463 into an M4 macro.
10465 Additionally, there are a few m4sugar macros (such as @code{m4_split}
10466 and @code{m4_expand}) which internally use special markers in addition
10467 to the regular quoting characters.  If the arguments to these macros
10468 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
10469 might behave incorrectly.
10471 You can work around these problems by using one of the following
10472 @dfn{quadrigraphs}:
10474 @table @samp
10475 @item @@<:@@
10476 @samp{[}
10477 @item @@:>@@
10478 @samp{]}
10479 @item @@S|@@
10480 @samp{$}
10481 @item @@%:@@
10482 @samp{#}
10483 @item @@@{:@@
10484 @samp{(}
10485 @item @@:@}@@
10486 @samp{)}
10487 @item @@&t@@
10488 Expands to nothing.
10489 @end table
10491 Quadrigraphs are replaced at a late stage of the translation process,
10492 after @command{m4} is run, so they do not get in the way of M4 quoting.
10493 For example, the string @samp{^@@<:@@}, independently of its quotation,
10494 appears as @samp{^[} in the output.
10496 The empty quadrigraph can be used:
10498 @itemize @minus
10499 @item to mark trailing spaces explicitly
10501 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
10503 @item to produce quadrigraphs and other strings reserved by m4sugar
10505 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
10506 contrived example:
10508 @example
10509 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
10510 m4_split([a )@}>=- b -=<@{( c])
10511 @result{}[a], [], [B], [], [c]
10512 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
10513 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
10514 @end example
10516 @item to escape @emph{occurrences} of forbidden patterns
10518 For instance you might want to mention @code{AC_FOO} in a comment, while
10519 still being sure that @command{autom4te} still catches unexpanded
10520 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
10521 @end itemize
10523 The name @samp{@@&t@@} was suggested by Paul Eggert:
10525 @quotation
10526 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
10527 own invention, but the @samp{t} came from the source code of the
10528 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
10529 and which used @samp{mt} to denote the empty string.  In C, it would
10530 have looked like something like:
10532 @example
10533 char const mt[] = "";
10534 @end example
10536 @noindent
10537 but of course the source code was written in Algol 68.
10539 I don't know where he got @samp{mt} from: it could have been his own
10540 invention, and I suppose it could have been a common pun around the
10541 Cambridge University computer lab at the time.
10542 @end quotation
10545 @node Balancing Parentheses
10546 @subsection Dealing with unbalanced parentheses
10547 @cindex balancing parentheses
10548 @cindex parentheses, balancing
10549 @cindex unbalanced parentheses, managing
10551 One of the pitfalls of portable shell programming is that @command{case}
10552 statements require unbalanced parentheses (@pxref{case, , Limitations of
10553 Shell Builtins}).  With syntax highlighting
10554 editors, the presence of unbalanced @samp{)} can interfere with editors
10555 that perform syntax highlighting of macro contents based on finding the
10556 matching @samp{(}.  Another concern is how much editing must be done
10557 when transferring code snippets between shell scripts and macro
10558 definitions.  But most importantly, the presence of unbalanced
10559 parentheses can introduce expansion bugs.
10561 For an example, here is an underquoted attempt to use the macro
10562 @code{my_case}, which happens to expand to a portable @command{case}
10563 statement:
10565 @example
10566 AC_DEFUN([my_case],
10567 [case $file_name in
10568   *.c) echo "C source code";;
10569 esac])
10570 AS_IF(:, my_case)
10571 @end example
10573 @noindent
10574 In the above example, the @code{AS_IF} call underquotes its arguments.
10575 As a result, the unbalanced @samp{)} generated by the premature
10576 expansion of @code{my_case} results in expanding @code{AS_IF} with a
10577 truncated parameter, and the expansion is syntactically invalid:
10579 @example
10580 if :; then
10581   case $file_name in
10582   *.c
10583 fi echo "C source code";;
10584 esac)
10585 @end example
10587 If nothing else, this should emphasize the importance of the quoting
10588 arguments to macro calls.  On the other hand, there are several
10589 variations for defining @code{my_case} to be more robust, even when used
10590 without proper quoting, each with some benefits and some drawbacks.
10592 @itemize @w{}
10593 @item Creative literal shell comment
10594 @example
10595 AC_DEFUN([my_case],
10596 [case $file_name in #(
10597   *.c) echo "C source code";;
10598 esac])
10599 @end example
10600 @noindent
10601 This version provides balanced parentheses to several editors, and can
10602 be copied and pasted into a terminal as is.  Unfortunately, it is still
10603 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
10604 that masks the normal properties of @samp{(}.
10606 @item Quadrigraph shell comment
10607 @example
10608 AC_DEFUN([my_case],
10609 [case $file_name in @@%:@@(
10610   *.c) echo "C source code";;
10611 esac])
10612 @end example
10613 @noindent
10614 This version provides balanced parentheses to even more editors, and can
10615 be used as a balanced Autoconf argument.  Unfortunately, it requires
10616 some editing before it can be copied and pasted into a terminal, and the
10617 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
10619 @item Quoting just the parenthesis
10620 @example
10621 AC_DEFUN([my_case],
10622 [case $file_name in
10623   *.c[)] echo "C source code";;
10624 esac])
10625 @end example
10626 @noindent
10627 This version quotes the @samp{)}, so that it can be used as a balanced
10628 Autoconf argument.  As written, this is not balanced to an editor, but
10629 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
10630 still requires some edits before it can be copied and pasted into a
10631 terminal.
10633 @item Double-quoting the entire statement
10634 @example
10635 AC_DEFUN([my_case],
10636 [[case $file_name in #(
10637   *.c) echo "C source code";;
10638 esac]])
10639 @end example
10640 @noindent
10641 Since the entire macro is double-quoted, there is no problem with using
10642 this as an Autoconf argument; and since the double-quoting is over the
10643 entire statement, this code can be easily copied and pasted into a
10644 terminal.  However, the double quoting prevents the expansion of any
10645 macros inside the case statement, which may cause its own set of
10646 problems.
10648 @item Using @code{AS_CASE}
10649 @example
10650 AC_DEFUN([my_case],
10651 [AS_CASE([$file_name],
10652   [*.c], [echo "C source code"])])
10653 @end example
10654 @noindent
10655 This version avoids the balancing issue altogether, by relying on
10656 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
10657 expansion of @code{AC_REQUIRE} to occur prior to the entire case
10658 statement, rather than within a branch of the case statement that might
10659 not be taken.  However, the abstraction comes with a penalty that it is
10660 no longer a quick copy, paste, and edit to get back to shell code.
10661 @end itemize
10664 @node Quotation Rule Of Thumb
10665 @subsection Quotation Rule Of Thumb
10667 To conclude, the quotation rule of thumb is:
10669 @center @emph{One pair of quotes per pair of parentheses.}
10671 Never over-quote, never under-quote, in particular in the definition of
10672 macros.  In the few places where the macros need to use brackets
10673 (usually in C program text or regular expressions), properly quote
10674 @emph{the arguments}!
10676 It is common to read Autoconf programs with snippets like:
10678 @example
10679 AC_TRY_LINK(
10680 changequote(<<, >>)dnl
10681 <<#include <time.h>
10682 #ifndef tzname /* For SGI.  */
10683 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10684 #endif>>,
10685 changequote([, ])dnl
10686 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
10687 @end example
10689 @noindent
10690 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
10691 double quoting, so you just need:
10693 @example
10694 AC_TRY_LINK(
10695 [#include <time.h>
10696 #ifndef tzname /* For SGI.  */
10697 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10698 #endif],
10699             [atoi (*tzname);],
10700             [ac_cv_var_tzname=yes],
10701             [ac_cv_var_tzname=no])
10702 @end example
10704 @noindent
10705 The M4-fluent reader might note that these two examples are rigorously
10706 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
10707 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
10708 quotes are not part of the arguments!
10710 Simplified, the example above is just doing this:
10712 @example
10713 changequote(<<, >>)dnl
10714 <<[]>>
10715 changequote([, ])dnl
10716 @end example
10718 @noindent
10719 instead of simply:
10721 @example
10722 [[]]
10723 @end example
10725 With macros that do not double quote their arguments (which is the
10726 rule), double-quote the (risky) literals:
10728 @example
10729 AC_LINK_IFELSE([AC_LANG_PROGRAM(
10730 [[#include <time.h>
10731 #ifndef tzname /* For SGI.  */
10732 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10733 #endif]],
10734                                 [atoi (*tzname);])],
10735                [ac_cv_var_tzname=yes],
10736                [ac_cv_var_tzname=no])
10737 @end example
10739 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
10740 should be using @code{AC_LINK_IFELSE} instead.
10742 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
10743 where quoting does not suffice.
10745 When you create a @command{configure} script using newly written macros,
10746 examine it carefully to check whether you need to add more quotes in
10747 your macros.  If one or more words have disappeared in the M4
10748 output, you need more quotes.  When in doubt, quote.
10750 However, it's also possible to put on too many layers of quotes.  If
10751 this happens, the resulting @command{configure} script may contain
10752 unexpanded macros.  The @command{autoconf} program checks for this problem
10753 by looking for the string @samp{AC_} in @file{configure}.  However, this
10754 heuristic does not work in general: for example, it does not catch
10755 overquoting in @code{AC_DEFINE} descriptions.
10758 @c ---------------------------------------- Using autom4te
10760 @node Using autom4te
10761 @section Using @command{autom4te}
10763 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
10764 to Autoconf per se, heavily rely on M4.  All these different uses
10765 revealed common needs factored into a layer over M4:
10766 @command{autom4te}@footnote{
10768 Yet another great name from Lars J. Aas.
10772 @command{autom4te} is a preprocessor that is like @command{m4}.
10773 It supports M4 extensions designed for use in tools like Autoconf.
10775 @menu
10776 * autom4te Invocation::         A GNU M4 wrapper
10777 * Customizing autom4te::        Customizing the Autoconf package
10778 @end menu
10780 @node autom4te Invocation
10781 @subsection Invoking @command{autom4te}
10783 The command line arguments are modeled after M4's:
10785 @example
10786 autom4te @var{options} @var{files}
10787 @end example
10789 @noindent
10790 @evindex M4
10791 where the @var{files} are directly passed to @command{m4}.  By default,
10792 GNU M4 is found during configuration, but the environment
10793 variable
10794 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
10795 to the regular expansion, it handles the replacement of the quadrigraphs
10796 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
10797 output.  It supports an extended syntax for the @var{files}:
10799 @table @file
10800 @item @var{file}.m4f
10801 This file is an M4 frozen file.  Note that @emph{all the previous files
10802 are ignored}.  See the option @option{--melt} for the rationale.
10804 @item @var{file}?
10805 If found in the library path, the @var{file} is included for expansion,
10806 otherwise it is ignored instead of triggering a failure.
10807 @end table
10809 @sp 1
10811 Of course, it supports the Autoconf common subset of options:
10813 @table @option
10814 @item --help
10815 @itemx -h
10816 Print a summary of the command line options and exit.
10818 @item --version
10819 @itemx -V
10820 Print the version number of Autoconf and exit.
10822 @item --verbose
10823 @itemx -v
10824 Report processing steps.
10826 @item --debug
10827 @itemx -d
10828 Don't remove the temporary files and be even more verbose.
10830 @item --include=@var{dir}
10831 @itemx -I @var{dir}
10832 Also look for input files in @var{dir}.  Multiple invocations
10833 accumulate.
10835 @item --output=@var{file}
10836 @itemx -o @var{file}
10837 Save output (script or trace) to @var{file}.  The file @option{-} stands
10838 for the standard output.
10839 @end table
10841 @sp 1
10843 As an extension of @command{m4}, it includes the following options:
10845 @table @option
10846 @item --warnings=@var{category}
10847 @itemx -W @var{category}
10848 @evindex WARNINGS
10849 @c FIXME: Point to the M4sugar macros, not Autoconf's.
10850 Report the warnings related to @var{category} (which can actually be a
10851 comma separated list).  @xref{Reporting Messages}, macro
10852 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
10853 values include:
10855 @table @samp
10856 @item all
10857 report all the warnings
10859 @item none
10860 report none
10862 @item error
10863 treats warnings as errors
10865 @item no-@var{category}
10866 disable warnings falling into @var{category}
10867 @end table
10869 Warnings about @samp{syntax} are enabled by default, and the environment
10870 variable @env{WARNINGS}, a comma separated list of categories, is
10871 honored.  @samp{autom4te -W @var{category}} actually
10872 behaves as if you had run:
10874 @example
10875 autom4te --warnings=syntax,$WARNINGS,@var{category}
10876 @end example
10878 @noindent
10879 For example, if you want to disable defaults and @env{WARNINGS}
10880 of @command{autom4te}, but enable the warnings about obsolete
10881 constructs, you would use @option{-W none,obsolete}.
10883 @cindex Back trace
10884 @cindex Macro invocation stack
10885 @command{autom4te} displays a back trace for errors, but not for
10886 warnings; if you want them, just pass @option{-W error}.
10888 @item --melt
10889 @itemx -M
10890 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
10891 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
10892 are executed only when the files are frozen, typically
10893 @code{m4_define}.  For instance, running:
10895 @example
10896 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
10897 @end example
10899 @noindent
10900 is roughly equivalent to running:
10902 @example
10903 m4 1.m4 2.m4 3.m4 4.m4 input.m4
10904 @end example
10906 @noindent
10907 while
10909 @example
10910 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
10911 @end example
10913 @noindent
10914 is equivalent to:
10916 @example
10917 m4 --reload-state=4.m4f input.m4
10918 @end example
10920 @item --freeze
10921 @itemx -F
10922 Produce a frozen state file.  @command{autom4te} freezing is stricter
10923 than M4's: it must produce no warnings, and no output other than empty
10924 lines (a line with white space is @emph{not} empty) and comments
10925 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
10926 this option takes no argument:
10928 @example
10929 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
10930 @end example
10932 @noindent
10933 corresponds to
10935 @example
10936 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
10937 @end example
10939 @item --mode=@var{octal-mode}
10940 @itemx -m @var{octal-mode}
10941 Set the mode of the non-traces output to @var{octal-mode}; by default
10942 @samp{0666}.
10943 @end table
10945 @sp 1
10947 @cindex @file{autom4te.cache}
10948 As another additional feature over @command{m4}, @command{autom4te}
10949 caches its results.  GNU M4 is able to produce a regular
10950 output and traces at the same time.  Traces are heavily used in the
10951 GNU Build System: @command{autoheader} uses them to build
10952 @file{config.h.in}, @command{autoreconf} to determine what
10953 GNU Build System components are used, @command{automake} to
10954 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
10955 traces are cached while performing regular expansion,
10956 and conversely.  This cache is (actually, the caches are) stored in
10957 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
10958 at any moment (especially if for some reason @command{autom4te}
10959 considers it trashed).
10961 @table @option
10962 @item --cache=@var{directory}
10963 @itemx -C @var{directory}
10964 Specify the name of the directory where the result should be cached.
10965 Passing an empty value disables caching.  Be sure to pass a relative
10966 file name, as for the time being, global caches are not supported.
10968 @item --no-cache
10969 Don't cache the results.
10971 @item --force
10972 @itemx -f
10973 If a cache is used, consider it obsolete (but update it anyway).
10974 @end table
10976 @sp 1
10978 Because traces are so important to the GNU Build System,
10979 @command{autom4te} provides high level tracing features as compared to
10980 M4, and helps exploiting the cache:
10982 @table @option
10983 @item --trace=@var{macro}[:@var{format}]
10984 @itemx -t @var{macro}[:@var{format}]
10985 Trace the invocations of @var{macro} according to the @var{format}.
10986 Multiple @option{--trace} arguments can be used to list several macros.
10987 Multiple @option{--trace} arguments for a single macro are not
10988 cumulative; instead, you should just make @var{format} as long as
10989 needed.
10991 The @var{format} is a regular string, with newlines if desired, and
10992 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
10993 use the following special escapes:
10995 @table @samp
10996 @item $$
10997 @c $$ restore font-lock
10998 The character @samp{$}.
11000 @item $f
11001 The file name from which @var{macro} is called.
11003 @item $l
11004 The line number from which @var{macro} is called.
11006 @item $d
11007 The depth of the @var{macro} call.  This is an M4 technical detail that
11008 you probably don't want to know about.
11010 @item $n
11011 The name of the @var{macro}.
11013 @item $@var{num}
11014 The @var{num}th argument of the call to @var{macro}.
11016 @item $@@
11017 @itemx $@var{sep}@@
11018 @itemx $@{@var{separator}@}@@
11019 All the arguments passed to @var{macro}, separated by the character
11020 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
11021 argument is quoted, i.e., enclosed in a pair of square brackets.
11023 @item $*
11024 @itemx $@var{sep}*
11025 @itemx $@{@var{separator}@}*
11026 As above, but the arguments are not quoted.
11028 @item $%
11029 @itemx $@var{sep}%
11030 @itemx $@{@var{separator}@}%
11031 As above, but the arguments are not quoted, all new line characters in
11032 the arguments are smashed, and the default separator is @samp{:}.
11034 The escape @samp{$%} produces single-line trace outputs (unless you put
11035 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11036 not.
11037 @end table
11039 @xref{autoconf Invocation}, for examples of trace uses.
11041 @item --preselect=@var{macro}
11042 @itemx -p @var{macro}
11043 Cache the traces of @var{macro}, but do not enable traces.  This is
11044 especially important to save CPU cycles in the future.  For instance,
11045 when invoked, @command{autoconf} preselects all the macros that
11046 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11047 trace, so that running @command{m4} is not needed to trace them: the
11048 cache suffices.  This results in a huge speed-up.
11049 @end table
11051 @sp 1
11053 @cindex Autom4te Library
11054 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11055 libraries}.  They consists in a powerful yet extremely simple feature:
11056 sets of combined command line arguments:
11058 @table @option
11059 @item --language=@var{language}
11060 @itemx -l @var{language}
11061 Use the @var{language} Autom4te library.  Current languages include:
11063 @table @code
11064 @item M4sugar
11065 create M4sugar output.
11067 @item M4sh
11068 create M4sh executable shell scripts.
11070 @item Autotest
11071 create Autotest executable test suites.
11073 @item Autoconf-without-aclocal-m4
11074 create Autoconf executable configure scripts without
11075 reading @file{aclocal.m4}.
11077 @item Autoconf
11078 create Autoconf executable configure scripts.  This language inherits
11079 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11080 additionally reads @file{aclocal.m4}.
11081 @end table
11083 @item --prepend-include=@var{dir}
11084 @itemx -B @var{dir}
11085 Prepend directory @var{dir} to the search path.  This is used to include
11086 the language-specific files before any third-party macros.
11088 @end table
11090 @cindex @file{autom4te.cfg}
11091 As an example, if Autoconf is installed in its default location,
11092 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11093 strictly equivalent to the command:
11095 @example
11096 autom4te --prepend-include /usr/local/share/autoconf \
11097   m4sugar/m4sugar.m4f --warnings syntax foo.m4
11098 @end example
11100 @noindent
11101 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11102 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11103 foo.m4}, i.e.:
11105 @example
11106 autom4te --prepend-include /usr/local/share/autoconf \
11107   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11108 @end example
11110 @noindent
11111 The definition of the languages is stored in @file{autom4te.cfg}.
11113 @node Customizing autom4te
11114 @subsection Customizing @command{autom4te}
11116 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11117 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11118 as found in the directory from which @command{autom4te} is run).  The
11119 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11120 then @file{./.autom4te.cfg}, and finally the command line arguments.
11122 In these text files, comments are introduced with @code{#}, and empty
11123 lines are ignored.  Customization is performed on a per-language basis,
11124 wrapped in between a @samp{begin-language: "@var{language}"},
11125 @samp{end-language: "@var{language}"} pair.
11127 Customizing a language stands for appending options (@pxref{autom4te
11128 Invocation}) to the current definition of the language.  Options, and
11129 more generally arguments, are introduced by @samp{args:
11130 @var{arguments}}.  You may use the traditional shell syntax to quote the
11131 @var{arguments}.
11133 As an example, to disable Autoconf caches (@file{autom4te.cache})
11134 globally, include the following lines in @file{~/.autom4te.cfg}:
11136 @verbatim
11137 ## ------------------ ##
11138 ## User Preferences.  ##
11139 ## ------------------ ##
11141 begin-language: "Autoconf-without-aclocal-m4"
11142 args: --no-cache
11143 end-language: "Autoconf-without-aclocal-m4"
11144 @end verbatim
11147 @node Programming in M4sugar
11148 @section Programming in M4sugar
11150 @cindex M4sugar
11151 M4 by itself provides only a small, but sufficient, set of all-purpose
11152 macros.  M4sugar introduces additional generic macros.  Its name was
11153 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11154 M4sugar''.
11156 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11157 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
11158 define your own macros into these namespaces.
11160 @menu
11161 * Redefined M4 Macros::         M4 builtins changed in M4sugar
11162 * Diagnostic Macros::           Diagnostic messages from M4sugar
11163 * Diversion support::           Diversions in M4sugar
11164 * Conditional constructs::      Conditions in M4
11165 * Looping constructs::          Iteration in M4
11166 * Evaluation Macros::           More quotation and evaluation control
11167 * Text processing Macros::      String manipulation in M4
11168 * Number processing Macros::    Arithmetic computation in M4
11169 * Set manipulation Macros::     Set manipulation in M4
11170 * Forbidden Patterns::          Catching unexpanded macros
11171 @end menu
11173 @node Redefined M4 Macros
11174 @subsection Redefined M4 Macros
11176 @msindex{builtin}
11177 @msindex{changecom}
11178 @msindex{changequote}
11179 @msindex{debugfile}
11180 @msindex{debugmode}
11181 @msindex{decr}
11182 @msindex{define}
11183 @msindex{divnum}
11184 @msindex{errprint}
11185 @msindex{esyscmd}
11186 @msindex{eval}
11187 @msindex{format}
11188 @msindex{ifdef}
11189 @msindex{incr}
11190 @msindex{index}
11191 @msindex{indir}
11192 @msindex{len}
11193 @msindex{pushdef}
11194 @msindex{shift}
11195 @msindex{substr}
11196 @msindex{syscmd}
11197 @msindex{sysval}
11198 @msindex{traceoff}
11199 @msindex{traceon}
11200 @msindex{translit}
11201 With a few exceptions, all the M4 native macros are moved in the
11202 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11203 @code{m4_define} etc.
11205 The list of macros unchanged from M4, except for their name, is:
11206 @itemize @minus
11207 @item m4_builtin
11208 @item m4_changecom
11209 @item m4_changequote
11210 @item m4_debugfile
11211 @item m4_debugmode
11212 @item m4_decr
11213 @item m4_define
11214 @item m4_divnum
11215 @item m4_errprint
11216 @item m4_esyscmd
11217 @item m4_eval
11218 @item m4_format
11219 @item m4_ifdef
11220 @item m4_incr
11221 @item m4_index
11222 @item m4_indir
11223 @item m4_len
11224 @item m4_pushdef
11225 @item m4_shift
11226 @item m4_substr
11227 @item m4_syscmd
11228 @item m4_sysval
11229 @item m4_traceoff
11230 @item m4_traceon
11231 @item m4_translit
11232 @end itemize
11234 Some M4 macros are redefined, and are slightly incompatible with their
11235 native equivalent.
11237 @defmac __file__
11238 @defmacx __line__
11239 @MSindex __file__
11240 @MSindex __line__
11241 All M4 macros starting with @samp{__} retain their original name: for
11242 example, no @code{m4__file__} is defined.
11243 @end defmac
11245 @defmac __oline__
11246 @MSindex __oline__
11247 This is not technically a macro, but a feature of Autom4te.  The
11248 sequence @code{__oline__} can be used similarly to the other m4sugar
11249 location macros, but rather than expanding to the location of the input
11250 file, it is translated to the line number where it appears in the output
11251 file after all other M4 expansions.
11252 @end defmac
11254 @defmac dnl
11255 @MSindex dnl
11256 This macro kept its original name: no @code{m4_dnl} is defined.
11257 @end defmac
11259 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11260 @msindex{bpatsubst}
11261 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
11262 is kept for future versions of M4sugar, once GNU M4 2.0 is
11263 released and supports extended regular expression syntax.
11264 @end defmac
11266 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11267 @msindex{bregexp}
11268 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
11269 is kept for future versions of M4sugar, once GNU M4 2.0 is
11270 released and supports extended regular expression syntax.
11271 @end defmac
11273 @defmac m4_copy (@var{source}, @var{dest})
11274 @defmacx m4_copy_force (@var{source}, @var{dest})
11275 @defmacx m4_rename (@var{source}, @var{dest})
11276 @defmacx m4_rename_force (@var{source}, @var{dest})
11277 @msindex{copy}
11278 @msindex{copy_force}
11279 @msindex{rename}
11280 @msindex{rename_force}
11281 These macros aren't directly builtins, but are closely related to
11282 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
11283 @code{m4_rename} ensure that @var{dest} is undefined, while
11284 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11285 definition.  All four macros then proceed to copy the entire pushdef
11286 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
11287 and @code{m4_copy_force} preserve the source (including in the special
11288 case where @var{source} is undefined), while @code{m4_rename} and
11289 @code{m4_rename_force} undefine the original macro name (making it an
11290 error to rename an undefined @var{source}).
11292 Note that attempting to invoke a renamed macro might not work, since the
11293 macro may have a dependence on helper macros accessed via composition of
11294 @samp{$0} but that were not also renamed; likewise, other macros may
11295 have a hard-coded dependence on @var{source} and could break if
11296 @var{source} has been deleted.  On the other hand, it is always safe to
11297 rename a macro to temporarily move it out of the way, then rename it
11298 back later to restore original semantics.
11299 @end defmac
11301 @defmac m4_defn (@var{macro}@dots{})
11302 @msindex{defn}
11303 This macro fails if @var{macro} is not defined, even when using older
11304 versions of M4 that did not warn.  See @code{m4_undefine}.
11305 Unfortunately, in order to support these older versions of M4, there are
11306 some situations involving unbalanced quotes where concatenating multiple
11307 macros together will work in newer M4 but not in m4sugar; use
11308 quadrigraphs to work around this.
11309 @end defmac
11311 @defmac m4_divert (@var{diversion})
11312 @msindex{divert}
11313 M4sugar relies heavily on diversions, so rather than behaving as a
11314 primitive, @code{m4_divert} behaves like:
11315 @example
11316 m4_divert_pop()m4_divert_push([@var{diversion}])
11317 @end example
11318 @noindent
11319 @xref{Diversion support}, for more details about the use of the
11320 diversion stack.  In particular, this implies that @var{diversion}
11321 should be a named diversion rather than a raw number.  But be aware that
11322 it is seldom necessary to explicitly change the diversion stack, and
11323 that when done incorrectly, it can lead to syntactically invalid
11324 scripts.
11325 @end defmac
11327 @defmac m4_dumpdef (@var{name}@dots{})
11328 @defmacx m4_dumpdefs (@var{name}@dots{})
11329 @msindex{dumpdef}
11330 @msindex{dumpdefs}
11331 @code{m4_dumpdef} is like the M4 builtin, except that this version
11332 requires at least one argument, output always goes to standard error
11333 rather than the current debug file, no sorting is done on multiple
11334 arguments, and an error is issued if any
11335 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
11336 calls @code{m4_dumpdef} for all of the
11337 @code{m4_pushdef} stack of definitions, starting with the current, and
11338 silently does nothing if @var{name} is undefined.
11340 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11341 builtin is output as the empty string.  This behavior is rectified by
11342 using M4 1.6 or newer.  However, this behavior difference means that
11343 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11344 and never in the final published form of a macro.
11345 @end defmac
11347 @defmac m4_esyscmd_s (@var{command})
11348 @msindex{esyscmd_s}
11349 Like @code{m4_esyscmd}, this macro expands to the result of running
11350 @var{command} in a shell.  The difference is that any trailing newlines
11351 are removed, so that the output behaves more like shell command
11352 substitution.
11353 @end defmac
11355 @defmac m4_exit (@var{exit-status})
11356 @msindex{exit}
11357 This macro corresponds to @code{m4exit}.
11358 @end defmac
11360 @defmac m4_if (@var{comment})
11361 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11362 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11363   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11364 @msindex{if}
11365 This macro corresponds to @code{ifelse}.  @var{string-1} and
11366 @var{string-2} are compared literally, so usually one of the two
11367 arguments is passed unquoted.  @xref{Conditional constructs}, for more
11368 conditional idioms.
11369 @end defmac
11371 @defmac m4_include (@var{file})
11372 @defmacx m4_sinclude (@var{file})
11373 @msindex{include}
11374 @msindex{sinclude}
11375 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11376 @end defmac
11378 @defmac m4_mkstemp (@var{template})
11379 @defmacx m4_maketemp (@var{template})
11380 @msindex{maketemp}
11381 @msindex{mkstemp}
11382 Posix requires @code{maketemp} to replace the trailing @samp{X}
11383 characters in @var{template} with the process id, without regards to the
11384 existence of a file by that name, but this a security hole.  When this
11385 was pointed out to the Posix folks, they agreed to invent a new macro
11386 @code{mkstemp} that always creates a uniquely named file, but not all
11387 versions of GNU M4 support the new macro.  In M4sugar,
11388 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11389 and both have the secure semantics regardless of which macro the
11390 underlying M4 provides.
11391 @end defmac
11393 @defmac m4_popdef (@var{macro}@dots{})
11394 @msindex{popdef}
11395 This macro fails if @var{macro} is not defined, even when using older
11396 versions of M4 that did not warn.  See @code{m4_undefine}.
11397 @end defmac
11399 @defmac m4_undefine (@var{macro}@dots{})
11400 @msindex{undefine}
11401 This macro fails if @var{macro} is not defined, even when using older
11402 versions of M4 that did not warn.  Use
11404 @example
11405 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11406 @end example
11408 @noindent
11409 if you are not sure whether @var{macro} is defined.
11410 @end defmac
11412 @defmac m4_undivert (@var{diversion}@dots{})
11413 @msindex{undivert}
11414 Unlike the M4 builtin, at least one @var{diversion} must be specified.
11415 Also, since the M4sugar diversion stack prefers named
11416 diversions, the use of @code{m4_undivert} to include files is risky.
11417 @xref{Diversion support}, for more details about the use of the
11418 diversion stack.  But be aware that it is seldom necessary to explicitly
11419 change the diversion stack, and that when done incorrectly, it can lead
11420 to syntactically invalid scripts.
11421 @end defmac
11423 @defmac m4_wrap (@var{text})
11424 @defmacx m4_wrap_lifo (@var{text})
11425 @msindex{wrap}
11426 @msindex{wrap_lifo}
11427 These macros correspond to @code{m4wrap}.  Posix requires arguments of
11428 multiple wrap calls to be reprocessed at EOF in the same order
11429 as the original calls (first-in, first-out).  GNU M4 versions
11430 through 1.4.10, however, reprocess them in reverse order (last-in,
11431 first-out).  Both orders are useful, therefore, you can rely on
11432 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11433 LIFO semantics, regardless of the underlying GNU M4 version.
11435 Unlike the GNU M4 builtin, these macros only recognize one
11436 argument, and avoid token pasting between consecutive invocations.  On
11437 the other hand, nested calls to @code{m4_wrap} from within wrapped text
11438 work just as in the builtin.
11439 @end defmac
11442 @node Diagnostic Macros
11443 @subsection Diagnostic messages from M4sugar
11444 @cindex Messages, from @command{M4sugar}
11446 When macros statically diagnose abnormal situations, benign or fatal,
11447 they should report them using these macros.  For issuing dynamic issues,
11448 i.e., when @command{configure} is run, see @ref{Printing Messages}.
11450 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
11451 @msindex{assert}
11452 Assert that the arithmetic @var{expression} evaluates to non-zero.
11453 Otherwise, issue a fatal error, and exit @command{autom4te} with
11454 @var{exit-status}.
11455 @end defmac
11457 @defmac m4_errprintn (@var{message})
11458 @msindex{errprintn}
11459 Similar to the builtin @code{m4_errprint}, except that a newline is
11460 guaranteed after @var{message}.
11461 @end defmac
11463 @anchor{m4_fatal}
11464 @defmac m4_fatal (@var{message})
11465 @msindex{fatal}
11466 Report a severe error @var{message} prefixed with the current location,
11467 and have @command{autom4te} die.
11468 @end defmac
11470 @defmac m4_location
11471 @msindex{location}
11472 Useful as a prefix in a message line.  Short for:
11473 @example
11474 __file__:__line__
11475 @end example
11476 @end defmac
11478 @anchor{m4_warn}
11479 @defmac m4_warn (@var{category}, @var{message})
11480 @msindex{warn}
11481 Report @var{message} as a warning (or as an error if requested by the
11482 user) if warnings of the @var{category} are turned on.  If the message
11483 is emitted, it is prefixed with the current location, and followed by a
11484 call trace of all macros defined via @code{AC_DEFUN} used to get to the
11485 current expansion.  You are encouraged to use standard categories, which
11486 currently include:
11488 @table @samp
11489 @item all
11490 messages that don't fall into one of the following categories.  Use of an
11491 empty @var{category} is equivalent.
11493 @item cross
11494 related to cross compilation issues.
11496 @item obsolete
11497 use of an obsolete construct.
11499 @item syntax
11500 dubious syntactic constructs, incorrectly ordered macro calls.
11501 @end table
11502 @end defmac
11505 @node Diversion support
11506 @subsection Diversion support
11508 M4sugar makes heavy use of diversions under the hood, because it is
11509 often the case that
11510 text that must appear early in the output is not discovered until late
11511 in the input.  Additionally, some of the topological sorting algorithms
11512 used in resolving macro dependencies use diversions.  However, most
11513 macros should not need to change diversions directly, but rather rely on
11514 higher-level M4sugar macros to manage diversions transparently.  If you
11515 change diversions improperly, you risk generating a syntactically
11516 invalid script, because an incorrect diversion will violate assumptions
11517 made by many macros about whether prerequisite text has been previously
11518 output.  In short, if you manually change the diversion, you should not
11519 expect any macros provided by the Autoconf package to work until you
11520 have restored the diversion stack back to its original state.
11522 In the rare case that it is necessary to write a macro that explicitly
11523 outputs text to a different diversion, it is important to be aware of an
11524 M4 limitation regarding diversions: text only goes to a diversion if it
11525 is not part of argument collection.  Therefore, any macro that changes
11526 the current diversion cannot be used as an unquoted argument to another
11527 macro, but must be expanded at the top level.  The macro
11528 @code{m4_expand} will diagnose any attempt to change diversions, since
11529 it is generally useful only as an argument to another macro.  The
11530 following example shows what happens when diversion manipulation is
11531 attempted within macro arguments:
11533 @example
11534 m4_do([normal text]
11535 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
11536 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
11537 @result{}normal text
11538 @result{}unwanted
11539 @end example
11541 @noindent
11542 Notice that the unquoted text @code{unwanted} is output, even though it
11543 was processed while the current diversion was @code{KILL}, because it
11544 was collected as part of the argument to @code{m4_do}.  However, the
11545 text @code{discarded} disappeared as desired, because the diversion
11546 changes were single-quoted, and were not expanded until the top-level
11547 rescan of the output of @code{m4_do}.
11549 To make diversion management easier, M4sugar uses the concept of named
11550 diversions.  Rather than using diversion numbers directly, it is nicer
11551 to associate a name with each diversion.  The diversion number associated
11552 with a particular diversion name is an implementation detail, and a
11553 syntax warning is issued if a diversion number is used instead of a
11554 name.  In general, you should not output text
11555 to a named diversion until after calling the appropriate initialization
11556 routine for your language (@code{m4_init}, @code{AS_INIT},
11557 @code{AT_INIT}, @dots{}), although there are some exceptions documented
11558 below.
11560 M4sugar defines two named diversions.
11561 @table @code
11562 @item KILL
11563 Text written to this diversion is discarded.  This is the default
11564 diversion once M4sugar is initialized.
11565 @item GROW
11566 This diversion is used behind the scenes by topological sorting macros,
11567 such as @code{AC_REQUIRE}.
11568 @end table
11570 M4sh adds several more named diversions.
11571 @table @code
11572 @item BINSH
11573 This diversion is reserved for the @samp{#!} interpreter line.
11574 @item HEADER-REVISION
11575 This diversion holds text from @code{AC_REVISION}.
11576 @item HEADER-COMMENT
11577 This diversion holds comments about the purpose of a file.
11578 @item HEADER-COPYRIGHT
11579 This diversion is managed by @code{AC_COPYRIGHT}.
11580 @item M4SH-SANITIZE
11581 This diversion contains M4sh sanitization code, used to ensure M4sh is
11582 executing in a reasonable shell environment.
11583 @item M4SH-INIT
11584 This diversion contains M4sh initialization code, initializing variables
11585 that are required by other M4sh macros.
11586 @item BODY
11587 This diversion contains the body of the shell code, and is the default
11588 diversion once M4sh is initialized.
11589 @end table
11591 Autotest inherits diversions from M4sh, and changes the default
11592 diversion from @code{BODY} back to @code{KILL}.  It also adds several
11593 more named diversions, with the following subset designed for developer
11594 use.
11595 @table @code
11596 @item PREPARE_TESTS
11597 This diversion contains initialization sequences which are executed
11598 after @file{atconfig} and @file{atlocal}, and after all command line
11599 arguments have been parsed, but prior to running any tests.  It can be
11600 used to set up state that is required across all tests.  This diversion
11601 will work even before @code{AT_INIT}.
11602 @end table
11604 Autoconf inherits diversions from M4sh, and adds the following named
11605 diversions which developers can utilize.
11606 @table @code
11607 @item DEFAULTS
11608 This diversion contains shell variable assignments to set defaults that
11609 must be in place before arguments are parsed.  This diversion is placed
11610 early enough in @file{configure} that it is unsafe to expand any
11611 autoconf macros into this diversion.
11612 @item HELP_ENABLE
11613 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
11614 diversion will be included as part of a quoted here-doc providing all of
11615 the @option{--help} output of @file{configure} related to options
11616 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
11617 @item INIT_PREPARE
11618 This diversion occurs after all command line options have been parsed,
11619 but prior to the main body of the @file{configure} script.  This
11620 diversion is the last chance to insert shell code such as variable
11621 assignments or shell function declarations that will used by the
11622 expansion of other macros.
11623 @end table
11625 For now, the remaining named diversions of Autoconf, Autoheader, and
11626 Autotest are not documented.  In other words,
11627 intentionally outputting text into an undocumented diversion is subject
11628 to breakage in a future release of Autoconf.
11630 @defmac m4_cleardivert (@var{diversion}@dots{})
11631 @msindex{cleardivert}
11632 Permanently discard any text that has been diverted into
11633 @var{diversion}.
11634 @end defmac
11636 @defmac m4_divert_once (@var{diversion}, @ovar{content})
11637 @msindex{divert_once}
11638 Similar to @code{m4_divert_text}, except that @var{content} is only
11639 output to @var{diversion} if this is the first time that
11640 @code{m4_divert_once} has been called with its particular arguments.
11641 @end defmac
11643 @defmac m4_divert_pop (@ovar{diversion})
11644 @msindex{divert_pop}
11645 If provided, check that the current diversion is indeed @var{diversion}.
11646 Then change to the diversion located earlier on the stack, giving an
11647 error if an attempt is made to pop beyond the initial m4sugar diversion
11648 of @code{KILL}.
11649 @end defmac
11651 @defmac m4_divert_push (@var{diversion})
11652 @msindex{divert_push}
11653 Remember the former diversion on the diversion stack, and output
11654 subsequent text into @var{diversion}.  M4sugar maintains a diversion
11655 stack, and issues an error if there is not a matching pop for every
11656 push.
11657 @end defmac
11659 @defmac m4_divert_text (@var{diversion}, @ovar{content})
11660 @msindex{divert_text}
11661 Output @var{content} and a newline into @var{diversion}, without
11662 affecting the current diversion.  Shorthand for:
11663 @example
11664 m4_divert_push([@var{diversion}])@var{content}
11665 m4_divert_pop([@var{diversion}])dnl
11666 @end example
11668 One use of @code{m4_divert_text} is to develop two related macros, where
11669 macro @samp{MY_A} does the work, but adjusts what work is performed
11670 based on whether the optional macro @samp{MY_B} has also been expanded.
11671 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
11672 require that @samp{MY_B} occurs first, if it occurs at all.  But this
11673 imposes an ordering restriction on the user; it would be nicer if macros
11674 @samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
11675 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
11676 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
11677 expanded.
11679 @example
11680 AC_DEFUN([MY_A],
11681 [# various actions
11682 if test -n "$b_was_used"; then
11683   # extra action
11684 fi])
11685 AC_DEFUN([MY_B],
11686 [AC_REQUIRE([MY_A])dnl
11687 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
11688 @end example
11690 @end defmac
11692 @defmac m4_init
11693 @msindex{init}
11694 Initialize the M4sugar environment, setting up the default named
11695 diversion to be @code{KILL}.
11696 @end defmac
11698 @node Conditional constructs
11699 @subsection Conditional constructs
11701 The following macros provide additional conditional constructs as
11702 convenience wrappers around @code{m4_if}.
11704 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
11705   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
11706 @msindex{bmatch}
11707 The string @var{string} is repeatedly compared against a series of
11708 @var{regex} arguments; if a match is found, the expansion is the
11709 corresponding @var{value}, otherwise, the macro moves on to the next
11710 @var{regex}.  If no @var{regex} match, then the result is the optional
11711 @var{default}, or nothing.
11712 @end defmac
11714 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
11715   @ovar{regex-2}, @ovar{subst-2}, @dots{})
11716 @msindex{bpatsubsts}
11717 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
11718 as if by:
11719 @example
11720 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
11721 @end example
11723 @noindent
11724 The result of the substitution is then passed through the next set of
11725 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
11726 deletion of any matched portions in the current string.  Note that this
11727 macro over-quotes @var{string}; this behavior is intentional, so that
11728 the result of each step of the recursion remains as a quoted string.
11729 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
11730 will line up with the extra quotations, and not the characters of the
11731 original string.  The overquoting is removed after the final
11732 substitution.
11733 @end defmac
11735 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
11736   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
11737 @msindex{case}
11738 Test @var{string} against multiple @var{value} possibilities, resulting
11739 in the first @var{if-value} for a match, or in the optional
11740 @var{default}.  This is shorthand for:
11741 @example
11742 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
11743       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
11744       [@var{default}])
11745 @end example
11746 @end defmac
11748 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
11749   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
11750 @msindex{cond}
11751 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
11752 except that each @var{test} is expanded only when it is encountered.
11753 This is useful for short-circuiting expensive tests; while @code{m4_if}
11754 requires all its strings to be expanded up front before doing
11755 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
11756 tests have failed.
11758 For an example, these two sequences give the same result, but in the
11759 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
11760 version only expands @code{m4_index} once, instead of five times, for
11761 faster computation if this is a common case for @samp{$1}.  Notice that
11762 every third argument is unquoted for @code{m4_if}, and quoted for
11763 @code{m4_cond}:
11765 @example
11766 m4_if(m4_index([$1], [\]), [-1], [$2],
11767       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
11768       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
11769       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
11770       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
11771       [$2])
11772 m4_cond([m4_index([$1], [\])], [-1], [$2],
11773         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
11774         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
11775         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
11776         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
11777         [$2])
11778 @end example
11779 @end defmac
11781 @defmac m4_default (@var{expr-1}, @var{expr-2})
11782 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
11783 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
11784 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
11785 @msindex{default}
11786 @msindex{default_quoted}
11787 @msindex{default_nblank}
11788 @msindex{default_nblank_quoted}
11789 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
11790 @code{m4_default} expands the result, while @code{m4_default_quoted}
11791 does not.  Useful for providing a fixed default if the expression that
11792 results in @var{expr-1} would otherwise be empty.  The difference
11793 between @code{m4_default} and @code{m4_default_nblank} is whether an
11794 argument consisting of just blanks (space, tab, newline) is
11795 significant.  When using the expanding versions, note that an argument
11796 may contain text but still expand to an empty string.
11798 @example
11799 m4_define([active], [ACTIVE])dnl
11800 m4_define([empty], [])dnl
11801 m4_define([demo1], [m4_default([$1], [$2])])dnl
11802 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
11803 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
11804 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
11805 demo1([active], [default])
11806 @result{}ACTIVE
11807 demo1([], [active])
11808 @result{}ACTIVE
11809 demo1([empty], [text])
11810 @result{}
11811 -demo1([ ], [active])-
11812 @result{}- -
11813 demo2([active], [default])
11814 @result{}active
11815 demo2([], [active])
11816 @result{}active
11817 demo2([empty], [text])
11818 @result{}empty
11819 -demo2([ ], [active])-
11820 @result{}- -
11821 demo3([active], [default])
11822 @result{}ACTIVE
11823 demo3([], [active])
11824 @result{}ACTIVE
11825 demo3([empty], [text])
11826 @result{}
11827 -demo3([ ], [active])-
11828 @result{}-ACTIVE-
11829 demo4([active], [default])
11830 @result{}active
11831 demo4([], [active])
11832 @result{}active
11833 demo4([empty], [text])
11834 @result{}empty
11835 -demo4([ ], [active])-
11836 @result{}-active-
11837 @end example
11838 @end defmac
11840 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
11841 @msindex{define_default}
11842 If @var{macro} does not already have a definition, then define it to
11843 @var{default-definition}.
11844 @end defmac
11846 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
11847 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
11848 @msindex{ifblank}
11849 @msindex{ifnblank}
11850 If @var{cond} is empty or consists only of blanks (space, tab, newline),
11851 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
11852 variants exist, in order to make it easier to select the correct logical
11853 sense when using only two parameters.  Note that this is more efficient
11854 than the equivalent behavior of:
11855 @example
11856 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
11857 @end example
11858 @end defmac
11860 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
11861 @msindex{ifndef}
11862 This is shorthand for:
11863 @example
11864 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
11865 @end example
11866 @end defmac
11868 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
11869 @msindex{ifset}
11870 If @var{macro} is undefined, or is defined as the empty string, expand
11871 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
11872 @example
11873 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
11874 @end example
11875 @noindent
11876 except that it is not an error if @var{macro} is undefined.
11877 @end defmac
11879 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
11880 @msindex{ifval}
11881 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
11882 @var{if-false}.  This is shorthand for:
11883 @example
11884 m4_if([@var{cond}], [], [@var{if-true}], [@var{if-false}])
11885 @end example
11886 @end defmac
11888 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
11889 @msindex{ifvaln}
11890 Similar to @code{m4_ifval}, except guarantee that a newline is present
11891 after any non-empty expansion.  Often followed by @code{dnl}.
11892 @end defmac
11894 @defmac m4_n (@var{text})
11895 @msindex{n}
11896 Expand to @var{text}, and add a newline if @var{text} is not empty.
11897 Often followed by @code{dnl}.
11898 @end defmac
11901 @node Looping constructs
11902 @subsection Looping constructs
11904 The following macros are useful in implementing recursive algorithms in
11905 M4, including loop operations.  An M4 list is formed by quoting a list
11906 of quoted elements; generally the lists are comma-separated, although
11907 @code{m4_foreach_w} is whitespace-separated.  For example, the list
11908 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
11909 It is common to see lists with unquoted elements when those elements are
11910 not likely to be macro names, as in @samp{[fputc_unlocked,
11911 fgetc_unlocked]}.
11913 Although not generally recommended, it is possible for quoted lists to
11914 have side effects; all side effects are expanded only once, and prior to
11915 visiting any list element.  On the other hand, the fact that unquoted
11916 macros are expanded exactly once means that macros without side effects
11917 can be used to generate lists.  For example,
11919 @example
11920 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
11921 @error{}hi
11922 @result{}123
11923 m4_define([list], [[1], [2], [3]])
11924 @result{}
11925 m4_foreach([i], [list], [i])
11926 @result{}123
11927 @end example
11929 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
11930 @msindex{argn}
11931 Extracts argument @var{n} (larger than 0) from the remaining arguments.
11932 If there are too few arguments, the empty string is used.  For any
11933 @var{n} besides 1, this is more efficient than the similar
11934 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
11935 @end defmac
11937 @defmac m4_car (@var{arg}@dots{})
11938 @msindex{car}
11939 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
11940 to recursively iterate
11941 through a list.  Generally, when using quoted lists of quoted elements,
11942 @code{m4_car} should be called without any extra quotes.
11943 @end defmac
11945 @defmac m4_cdr (@var{arg}@dots{})
11946 @msindex{cdr}
11947 Expands to a quoted list of all but the first @var{arg}, or the empty
11948 string if there was only one argument.  Generally, when using quoted
11949 lists of quoted elements, @code{m4_cdr} should be called without any
11950 extra quotes.
11952 For example, this is a simple implementation of @code{m4_map}; note how
11953 each iteration checks for the end of recursion, then merely applies the
11954 first argument to the first element of the list, then repeats with the
11955 rest of the list.  (The actual implementation in M4sugar is a bit more
11956 involved, to gain some speed and share code with @code{m4_map_sep}, and
11957 also to avoid expanding side effects in @samp{$2} twice).
11958 @example
11959 m4_define([m4_map], [m4_ifval([$2],
11960   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
11961 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
11962 @result{} 1 2 a
11963 @end example
11964 @end defmac
11966 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
11967   @var{expression})
11968 @msindex{for}
11969 Loop over the numeric values between @var{first} and @var{last}
11970 including bounds by increments of @var{step}.  For each iteration,
11971 expand @var{expression} with the numeric value assigned to @var{var}.
11972 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
11973 on the order of the limits.  If given, @var{step} has to match this
11974 order.  The number of iterations is determined independently from
11975 definition of @var{var}; iteration cannot be short-circuited or
11976 lengthened by modifying @var{var} from within @var{expression}.
11977 @end defmac
11979 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
11980 @msindex{foreach}
11981 Loop over the comma-separated M4 list @var{list}, assigning each value
11982 to @var{var}, and expand @var{expression}.  The following example
11983 outputs two lines:
11985 @example
11986 m4_foreach([myvar], [[foo], [bar, baz]],
11987            [echo myvar
11988 ])dnl
11989 @result{}echo foo
11990 @result{}echo bar, baz
11991 @end example
11993 Note that for some forms of @var{expression}, it may be faster to use
11994 @code{m4_map_args}.
11995 @end defmac
11997 @anchor{m4_foreach_w}
11998 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
11999 @msindex{foreach_w}
12000 Loop over the white-space-separated list @var{list}, assigning each value
12001 to @var{var}, and expand @var{expression}.  If @var{var} is only
12002 referenced once in @var{expression}, it is more efficient to use
12003 @code{m4_map_args_w}.
12005 The deprecated macro @code{AC_FOREACH} is an alias of
12006 @code{m4_foreach_w}.
12007 @end defmac
12009 @defmac m4_map (@var{macro}, @var{list})
12010 @defmacx m4_mapall (@var{macro}, @var{list})
12011 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12012 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12013 @msindex{map}
12014 @msindex{mapall}
12015 @msindex{map_sep}
12016 @msindex{mapall_sep}
12017 Loop over the comma separated quoted list of argument descriptions in
12018 @var{list}, and invoke @var{macro} with the arguments.  An argument
12019 description is in turn a comma-separated quoted list of quoted elements,
12020 suitable for @code{m4_apply}.  The macros @code{m4_map} and
12021 @code{m4_map_sep} ignore empty argument descriptions, while
12022 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12023 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12024 additionally expand @var{separator} between invocations of @var{macro}.
12026 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
12027 separating output with commas, this means that the map result can be
12028 used as a series of arguments, by using a single-quoted comma as
12029 @var{separator}, or as a single string, by using a double-quoted comma.
12031 @example
12032 m4_map([m4_count], [])
12033 @result{}
12034 m4_map([ m4_count], [[],
12035                      [[1]],
12036                      [[1], [2]]])
12037 @result{} 1 2
12038 m4_mapall([ m4_count], [[],
12039                         [[1]],
12040                         [[1], [2]]])
12041 @result{} 0 1 2
12042 m4_map_sep([m4_eval], [,], [[[1+2]],
12043                             [[10], [16]]])
12044 @result{}3,a
12045 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12046 @result{}a,b
12047 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12048 @result{}2
12049 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12050 @result{}a,b
12051 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12052 @result{}1
12053 @end example
12054 @end defmac
12056 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12057 @msindex{map_args}
12058 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12059 argument.  In the following example, three solutions are presented with
12060 the same expansion; the solution using @code{m4_map_args} is the most
12061 efficient.
12062 @example
12063 m4_define([active], [ACTIVE])dnl
12064 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12065 @result{} plain active
12066 m4_map([ m4_echo], [[[plain]], [[active]]])
12067 @result{} plain active
12068 m4_map_args([ m4_echo], [plain], [active])
12069 @result{} plain active
12070 @end example
12072 In cases where it is useful to operate on additional parameters besides
12073 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12074 to supply the argument currying necessary to generate the desired
12075 argument list.  In the following example, @code{list_add_n} is more
12076 efficient than @code{list_add_x}.  On the other hand, using
12077 @code{m4_map_args_sep} can be even more efficient.
12079 @example
12080 m4_define([list], [[1], [2], [3]])dnl
12081 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12082 dnl list_add_n(N, ARG...)
12083 dnl Output a list consisting of each ARG added to N
12084 m4_define([list_add_n],
12085 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12086 list_add_n([1], list)
12087 @result{}2,3,4
12088 list_add_n([2], list)
12089 @result{}3,4,5
12090 m4_define([list_add_x],
12091 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12092   [,add([$1],m4_defn([var]))]))])dnl
12093 list_add_x([1], list)
12094 @result{}2,3,4
12095 @end example
12096 @end defmac
12098 @defmac m4_map_args_pair (@var{macro}, @dvar{macro-end, macro}, @
12099   @var{arg}@dots{})
12100 @msindex{map_args_pair}
12101 For every pair of arguments @var{arg}, invoke @var{macro} with two
12102 arguments.  If there is an odd number of arguments, invoke
12103 @var{macro-end}, which defaults to @var{macro}, with the remaining
12104 argument.
12106 @example
12107 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12108 @result{}, 2, 1, 3
12109 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12110 @result{}, 2, 1, [3]
12111 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12112 @result{}, 2, 1, 4, 3
12113 @end example
12114 @end defmac
12116 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12117 @msindex{map_args_sep}
12118 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12119 argument, additionally expanding @var{sep} between arguments.  One
12120 common use of this macro is constructing a macro call, where the opening
12121 and closing parentheses are split between @var{pre} and @var{post}; in
12122 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12123 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
12124 macro provides the most efficient means for iterating over an arbitrary
12125 list of arguments, particularly when repeatedly constructing a macro
12126 call with more arguments than @var{arg}.
12127 @end defmac
12129 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12130 @msindex{map_args_w}
12131 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12132 the whitespace-separated @var{string}, additionally expanding @var{sep}
12133 between words.  This macro provides the most efficient means for
12134 iterating over a whitespace-separated string.  In particular,
12135 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12136 efficient than @code{m4_foreach_w([var], [@var{string}],
12137 [@var{action}(m4_defn([var]))])}.
12138 @end defmac
12140 @defmac m4_shiftn (@var{count}, @dots{})
12141 @defmacx m4_shift2 (@dots{})
12142 @defmacx m4_shift3 (@dots{})
12143 @msindex{shift2}
12144 @msindex{shift3}
12145 @msindex{shiftn}
12146 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12147 along with validation that enough arguments were passed in to match the
12148 shift count, and that the count is positive.  @code{m4_shift2} and
12149 @code{m4_shift3} are specializations
12150 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12151 for two and three shifts, respectively.
12152 @end defmac
12154 @defmac m4_stack_foreach (@var{macro}, @var{action})
12155 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12156 @msindex{stack_foreach}
12157 @msindex{stack_foreach_lifo}
12158 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12159 @var{action} with the single argument of a definition of @var{macro}.
12160 @code{m4_stack_foreach} starts with the oldest definition, while
12161 @code{m4_stack_foreach_lifo} starts with the current definition.
12162 @var{action} should not push or pop definitions of @var{macro}, nor is
12163 there any guarantee that the current definition of @var{macro} matches
12164 the argument that was passed to @var{action}.  The macro @code{m4_curry}
12165 can be used if @var{action} needs more than one argument, although in
12166 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12168 Due to technical limitations, there are a few low-level m4sugar
12169 functions, such as @code{m4_pushdef}, that cannot be used as the
12170 @var{macro} argument.
12172 @example
12173 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12174 m4_stack_foreach([a], [ m4_incr])
12175 @result{} 2 3
12176 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12177 @result{} cd bcd
12178 @end example
12179 @end defmac
12181 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12182 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12183   @ovar{sep})
12184 @msindex{stack_foreach_sep}
12185 @msindex{stack_foreach_sep_lifo}
12186 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12187 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12188 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
12189 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12190 the current definition first.  This macro provides the most efficient
12191 means for iterating over a pushdef stack.  In particular,
12192 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12193 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12194 @end defmac
12196 @node Evaluation Macros
12197 @subsection Evaluation Macros
12199 The following macros give some control over the order of the evaluation
12200 by adding or removing levels of quotes.
12202 @defmac m4_apply (@var{macro}, @var{list})
12203 @msindex{apply}
12204 Apply the elements of the quoted, comma-separated @var{list} as the
12205 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12206 without arguments.  Note the difference between @code{m4_indir}, which
12207 expects its first argument to be a macro name but can use names that are
12208 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12209 other text, but must end in a valid macro name.
12210 @example
12211 m4_apply([m4_count], [])
12212 @result{}0
12213 m4_apply([m4_count], [[]])
12214 @result{}1
12215 m4_apply([m4_count], [[1], [2]])
12216 @result{}2
12217 m4_apply([m4_join], [[|], [1], [2]])
12218 @result{}1|2
12219 @end example
12220 @end defmac
12222 @defmac m4_count (@var{arg}, @dots{})
12223 @msindex{count}
12224 This macro returns the decimal count of the number of arguments it was
12225 passed.
12226 @end defmac
12228 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12229 @msindex{curry}
12230 This macro performs argument currying.  The expansion of this macro is
12231 another macro name that expects exactly one argument; that argument is
12232 then appended to the @var{arg} list, and then @var{macro} is expanded
12233 with the resulting argument list.
12235 @example
12236 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12237 @result{}3, 2, 1
12238 @end example
12240 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12241 pass the definition of a builtin macro as the argument to the output of
12242 @code{m4_curry}; the empty string is used instead of the builtin token.
12243 This behavior is rectified by using M4 1.6 or newer.
12244 @end defmac
12246 @defmac m4_do (@var{arg}, @dots{})
12247 @msindex{do}
12248 This macro loops over its arguments and expands each @var{arg} in
12249 sequence.  Its main use is for readability; it allows the use of
12250 indentation and fewer @code{dnl} to result in the same expansion.  This
12251 macro guarantees that no expansion will be concatenated with subsequent
12252 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12253 @var{arg@dots{}}))}.
12255 @example
12256 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12257 m4_do([a],[b])c
12258 @result{}abc
12259 m4_unquote(m4_join([],[a],[b]))c
12260 @result{}3
12261 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12262 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12263 m4_do([a],[b])c
12264 @result{}ABC
12265 m4_unquote(m4_join([],[a],[b]))c
12266 @result{}3
12267 @end example
12268 @end defmac
12270 @defmac m4_dquote (@var{arg}, @dots{})
12271 @msindex{dquote}
12272 Return the arguments as a quoted list of quoted arguments.
12273 Conveniently, if there is just one @var{arg}, this effectively adds a
12274 level of quoting.
12275 @end defmac
12277 @defmac m4_dquote_elt (@var{arg}, @dots{})
12278 @msindex{dquote_elt}
12279 Return the arguments as a series of double-quoted arguments.  Whereas
12280 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12281 as many arguments as it was passed.
12282 @end defmac
12284 @defmac m4_echo (@var{arg}, @dots{})
12285 @msindex{echo}
12286 Return the arguments, with the same level of quoting.  Other than
12287 discarding whitespace after unquoted commas, this macro is a no-op.
12288 @end defmac
12290 @defmac m4_expand (@var{arg})
12291 @msindex{expand}
12292 Return the expansion of @var{arg} as a quoted string.  Whereas
12293 @code{m4_quote} is designed to collect expanded text into a single
12294 argument, @code{m4_expand} is designed to perform one level of expansion
12295 on quoted text.  One distinction is in the treatment of whitespace
12296 following a comma in the original @var{arg}.  Any time multiple
12297 arguments are collected into one with @code{m4_quote}, the M4 argument
12298 collection rules discard the whitespace.  However, with @code{m4_expand},
12299 whitespace is preserved, even after the expansion of macros contained in
12300 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
12301 would involve an unterminated comment, whereas expanding that same text
12302 as the argument to @code{m4_quote} runs into difficulty in finding the
12303 end of the argument.  Since manipulating diversions during argument
12304 collection is inherently unsafe, @code{m4_expand} issues an error if
12305 @var{arg} attempts to change the current diversion (@pxref{Diversion
12306 support}).
12308 @example
12309 m4_define([active], [ACT, IVE])dnl
12310 m4_define([active2], [[ACT, IVE]])dnl
12311 m4_quote(active, active)
12312 @result{}ACT,IVE,ACT,IVE
12313 m4_expand([active, active])
12314 @result{}ACT, IVE, ACT, IVE
12315 m4_quote(active2, active2)
12316 @result{}ACT, IVE,ACT, IVE
12317 m4_expand([active2, active2])
12318 @result{}ACT, IVE, ACT, IVE
12319 m4_expand([# m4_echo])
12320 @result{}# m4_echo
12321 m4_quote(# m4_echo)
12323 @result{}# m4_echo)
12324 @result{}
12325 @end example
12327 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12328 literal unbalanced quotes, but that quadrigraphs can be used when
12329 unbalanced output is necessary.  Likewise, unbalanced parentheses should
12330 be supplied with double quoting or a quadrigraph.
12332 @example
12333 m4_define([pattern], [[!@@<:@@]])dnl
12334 m4_define([bar], [BAR])dnl
12335 m4_expand([case $foo in
12336   m4_defn([pattern])@@:@}@@ bar ;;
12337   *[)] blah ;;
12338 esac])
12339 @result{}case $foo in
12340 @result{}  [![]) BAR ;;
12341 @result{}  *) blah ;;
12342 @result{}esac
12343 @end example
12344 @end defmac
12346 @defmac m4_ignore (@dots{})
12347 @msindex{ignore}
12348 This macro was introduced in Autoconf 2.62.  Expands to nothing,
12349 ignoring all of its arguments.  By itself, this isn't very useful.
12350 However, it can be used to conditionally ignore an arbitrary number of
12351 arguments, by deciding which macro name to apply to a list of arguments.
12352 @example
12353 dnl foo outputs a message only if [debug] is defined.
12354 m4_define([foo],
12355 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12356 @end example
12358 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12359 serve the same purpose, although it is less readable.
12360 @end defmac
12362 @defmac m4_make_list (@var{arg}, @dots{})
12363 @msindex{make_list}
12364 This macro exists to aid debugging of M4sugar algorithms.  Its net
12365 effect is similar to @code{m4_dquote}---it produces a quoted list of
12366 quoted arguments, for each @var{arg}.  The difference is that this
12367 version uses a comma-newline separator instead of just comma, to improve
12368 readability of the list; with the result that it is less efficient than
12369 @code{m4_dquote}.
12370 @example
12371 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12372 m4_dquote(zero, [one], [[two]])
12373 @result{}[0],[one],[[two]]
12374 m4_make_list(zero, [one], [[two]])
12375 @result{}[0],
12376 @result{}[one],
12377 @result{}[[two]]
12378 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12379 @result{} 0 1 two
12380 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12381 @result{} 0 1 two
12382 @end example
12383 @end defmac
12385 @c m4_noquote is too dangerous to document - it invokes macros that
12386 @c probably rely on @samp{[]} nested quoting for proper operation.  The
12387 @c user should generally prefer m4_unquote instead.
12389 @defmac m4_quote (@var{arg}, @dots{})
12390 @msindex{quote}
12391 Return the arguments as a single entity, i.e., wrap them into a pair of
12392 quotes.  This effectively collapses multiple arguments into one,
12393 although it loses whitespace after unquoted commas in the process.
12394 @end defmac
12396 @defmac m4_reverse (@var{arg}, @dots{})
12397 @msindex{reverse}
12398 Outputs each argument with the same level of quoting, but in reverse
12399 order, and with space following each comma for readability.
12401 @example
12402 m4_define([active], [ACT,IVE])
12403 @result{}
12404 m4_reverse(active, [active])
12405 @result{}active, IVE, ACT
12406 @end example
12407 @end defmac
12409 @defmac m4_unquote (@var{arg}, @dots{})
12410 @msindex{unquote}
12411 This macro was introduced in Autoconf 2.62.  Expand each argument,
12412 separated by commas.  For a single @var{arg}, this effectively removes a
12413 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12414 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
12415 this results in an unquoted list of expansions.  This is commonly used
12416 with @code{m4_split}, in order to convert a single quoted list into a
12417 series of quoted elements.
12418 @end defmac
12420 The following example aims at emphasizing the difference between several
12421 scenarios: not using these macros, using @code{m4_defn}, using
12422 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
12424 @example
12425 $ @kbd{cat example.m4}
12426 dnl Overquote, so that quotes are visible.
12427 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
12428 m4_define([a], [A])
12429 m4_define([mkargs], [1, 2[,] 3])
12430 m4_define([arg1], [[$1]])
12431 m4_divert([0])dnl
12432 show(a, b)
12433 show([a, b])
12434 show(m4_quote(a, b))
12435 show(m4_dquote(a, b))
12436 show(m4_expand([a, b]))
12438 arg1(mkargs)
12439 arg1([mkargs])
12440 arg1(m4_defn([mkargs]))
12441 arg1(m4_quote(mkargs))
12442 arg1(m4_dquote(mkargs))
12443 arg1(m4_expand([mkargs]))
12444 $ @kbd{autom4te -l m4sugar example.m4}
12445 $1 = A, $@@ = [A],[b]
12446 $1 = a, b, $@@ = [a, b]
12447 $1 = A,b, $@@ = [A,b]
12448 $1 = [A],[b], $@@ = [[A],[b]]
12449 $1 = A, b, $@@ = [A, b]
12452 mkargs
12453 1, 2[,] 3
12454 1,2, 3
12455 [1],[2, 3]
12456 1, 2, 3
12457 @end example
12460 @node Text processing Macros
12461 @subsection String manipulation in M4
12463 The following macros may be used to manipulate strings in M4.  Many of
12464 the macros in this section intentionally result in quoted strings as
12465 output, rather than subjecting the arguments to further expansions.  As
12466 a result, if you are manipulating text that contains active M4
12467 characters, the arguments are passed with single quoting rather than
12468 double.
12470 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
12471 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
12472   @ovar{if-uniq}, @ovar{if-duplicate})
12473 @msindex{append}
12474 @msindex{append_uniq}
12475 Redefine @var{macro-name} to its former contents with @var{separator}
12476 and @var{string} added at the end.  If @var{macro-name} was undefined
12477 before (but not if it was defined but empty), then no @var{separator} is
12478 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
12479 are expanded during this macro; instead, they are expanded when
12480 @var{macro-name} is invoked.
12482 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
12483 to grow strings without duplicating substrings.  Additionally,
12484 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
12485 @var{if-uniq} is expanded if @var{string} was appended, and
12486 @var{if-duplicate} is expanded if @var{string} was already present.
12487 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
12488 occurs within @var{string}, since that can lead to duplicates.
12490 Note that @code{m4_append} can scale linearly in the length of the final
12491 string, depending on the quality of the underlying M4 implementation,
12492 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
12493 If an algorithm can tolerate duplicates in the final string, use the
12494 former for speed.  If duplicates must be avoided, consider using
12495 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
12497 @example
12498 m4_define([active], [ACTIVE])dnl
12499 m4_append([sentence], [This is an])dnl
12500 m4_append([sentence], [ active ])dnl
12501 m4_append([sentence], [symbol.])dnl
12502 sentence
12503 @result{}This is an ACTIVE symbol.
12504 m4_undefine([active])dnl
12505 @result{}This is an active symbol.
12506 m4_append_uniq([list], [one], [, ], [new], [existing])
12507 @result{}new
12508 m4_append_uniq([list], [one], [, ], [new], [existing])
12509 @result{}existing
12510 m4_append_uniq([list], [two], [, ], [new], [existing])
12511 @result{}new
12512 m4_append_uniq([list], [three], [, ], [new], [existing])
12513 @result{}new
12514 m4_append_uniq([list], [two], [, ], [new], [existing])
12515 @result{}existing
12516 list
12517 @result{}one, two, three
12518 m4_dquote(list)
12519 @result{}[one],[two],[three]
12520 m4_append([list2], [one], [[, ]])dnl
12521 m4_append_uniq([list2], [two], [[, ]])dnl
12522 m4_append([list2], [three], [[, ]])dnl
12523 list2
12524 @result{}one, two, three
12525 m4_dquote(list2)
12526 @result{}[one, two, three]
12527 @end example
12528 @end defmac
12530 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
12531 @msindex{append_uniq_w}
12532 This macro was introduced in Autoconf 2.62.  It is similar to
12533 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
12534 separated list of words to append, and only appends unique words.
12535 @var{macro-name} is updated with a single space between new words.
12536 @example
12537 m4_append_uniq_w([numbers], [1 1 2])dnl
12538 m4_append_uniq_w([numbers], [ 2 3 ])dnl
12539 numbers
12540 @result{}1 2 3
12541 @end example
12542 @end defmac
12544 @defmac m4_chomp (@var{string})
12545 @defmacx m4_chomp_all (@var{string})
12546 @msindex{chomp}
12547 @msindex{chomp_all}
12548 Output @var{string} in quotes, but without a trailing newline.  The
12549 macro @code{m4_chomp} is slightly faster, and removes at most one
12550 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
12551 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
12552 and backslash does not influence the result.
12553 @end defmac
12555 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
12556   @var{suffix-1}, @ovar{suffix-2}, @dots{})
12557 @msindex{combine}
12558 This macro produces a quoted string containing the pairwise combination
12559 of every element of the quoted, comma-separated @var{prefix-list}, and
12560 every element from the @var{suffix} arguments.  Each pairwise
12561 combination is joined with @var{infix} in the middle, and successive
12562 pairs are joined by @var{separator}.  No expansion occurs on any of the
12563 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
12564 list is empty, but the lists can contain empty elements.
12565 @example
12566 m4_define([a], [oops])dnl
12567 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
12568 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
12569 m4_combine([, ], [[a], [b]], [-])
12570 @result{}
12571 m4_combine([, ], [[a], [b]], [-], [])
12572 @result{}a-, b-
12573 m4_combine([, ], [], [-], [1], [2])
12574 @result{}
12575 m4_combine([, ], [[]], [-], [1], [2])
12576 @result{}-1, -2
12577 @end example
12578 @end defmac
12580 @defmac m4_escape (@var{string})
12581 @msindex{escape}
12582 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
12583 within @var{string} into their respective quadrigraphs.  The result is
12584 still a quoted string.
12585 @end defmac
12587 @defmac m4_flatten (@var{string})
12588 @msindex{flatten}
12589 Flatten @var{string} into a single line.  Delete all backslash-newline
12590 pairs, and replace all remaining newlines with a space.  The result is
12591 still a quoted string.
12592 @end defmac
12594 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
12595 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
12596 @msindex{join}
12597 @msindex{joinall}
12598 Concatenate each @var{arg}, separated by @var{separator}.
12599 @code{joinall} uses every argument, while @code{join} omits empty
12600 arguments so that there are no back-to-back separators in the output.
12601 The result is a quoted string.
12602 @example
12603 m4_define([active], [ACTIVE])dnl
12604 m4_join([|], [one], [], [active], [two])
12605 @result{}one|active|two
12606 m4_joinall([|], [one], [], [active], [two])
12607 @result{}one||active|two
12608 @end example
12610 Note that if all you intend to do is join @var{args} with commas between
12611 them, to form a quoted list suitable for @code{m4_foreach}, it is more
12612 efficient to use @code{m4_dquote}.
12613 @end defmac
12615 @defmac m4_newline (@ovar{text})
12616 @msindex{newline}
12617 This macro was introduced in Autoconf 2.62, and expands to a newline,
12618 followed by any @var{text}.
12619 It is primarily useful for maintaining macro formatting, and ensuring
12620 that M4 does not discard leading whitespace during argument collection.
12621 @end defmac
12623 @defmac m4_normalize (@var{string})
12624 @msindex{normalize}
12625 Remove leading and trailing spaces and tabs, sequences of
12626 backslash-then-newline, and replace multiple spaces, tabs, and newlines
12627 with a single space.  This is a combination of @code{m4_flatten} and
12628 @code{m4_strip}.  To determine if @var{string} consists only of bytes
12629 that would be removed by @code{m4_normalize}, you can use
12630 @code{m4_ifblank}.
12631 @end defmac
12633 @defmac m4_re_escape (@var{string})
12634 @msindex{re_escape}
12635 Backslash-escape all characters in @var{string} that are active in
12636 regexps.
12637 @end defmac
12639 @c We cannot use @dvar because the macro expansion mistreats backslashes.
12640 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
12641 @msindex{split}
12642 Split @var{string} into an M4 list of elements quoted by @samp{[} and
12643 @samp{]}, while keeping white space at the beginning and at the end.
12644 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
12645 If @var{string} is empty, the result is an empty list.
12646 @end defmac
12648 @defmac m4_strip (@var{string})
12649 @msindex{strip}
12650 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
12651 reduced to a single space, then leading and trailing spaces are removed.
12652 The result is still a quoted string.  Note that this does not interfere
12653 with newlines; if you want newlines stripped as well, consider
12654 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
12655 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
12656 @end defmac
12658 @defmac m4_text_box (@var{message}, @dvar{frame, -})
12659 @msindex{text_box}
12660 Add a text box around @var{message}, using @var{frame} as the border
12661 character above and below the message.  The @var{frame} argument must be
12662 a single byte, and does not support quadrigraphs.
12663 The frame correctly accounts for
12664 the subsequent expansion of @var{message}.  For example:
12665 @example
12666 m4_define([macro], [abc])dnl
12667 m4_text_box([macro])
12668 @result{}## --- ##
12669 @result{}## abc ##
12670 @result{}## --- ##
12671 @end example
12673 The @var{message} must contain balanced quotes and parentheses, although
12674 quadrigraphs can be used to work around this.
12675 @end defmac
12677 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
12678   @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
12679 @msindex{text_wrap}
12680 Break @var{string} into a series of whitespace-separated words, then
12681 output those words separated by spaces, and wrapping lines any time the
12682 output would exceed @var{width} columns.  If given, @var{prefix1} begins
12683 the first line, and @var{prefix} begins all wrapped lines.  If
12684 @var{prefix1} is longer than @var{prefix}, then the first line consists
12685 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
12686 padding is inserted so that the first word of @var{string} begins at the
12687 same indentation as all wrapped lines.  Note that using literal tab
12688 characters in any of the arguments will interfere with the calculation
12689 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
12690 words of @var{string}, although quadrigraphs are recognized.
12692 For some examples:
12693 @example
12694 m4_text_wrap([Short string */], [   ], [/* ], [20])
12695 @result{}/* Short string */
12696 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
12697 @result{}/* Much longer
12698 @result{}   string */
12699 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
12700 @result{}  --short Short doc.
12701 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
12702 @result{}  --too-wide
12703 @result{}          Short doc.
12704 m4_text_wrap([Super long documentation.], [     ],
12705              [  --too-wide ], 30)
12706 @result{}  --too-wide
12707 @result{}     Super long
12708 @result{}     documentation.
12709 @end example
12710 @end defmac
12712 @defmac m4_tolower (@var{string})
12713 @defmacx m4_toupper (@var{string})
12714 @msindex{tolower}
12715 @msindex{toupper}
12716 Return @var{string} with letters converted to upper or lower case,
12717 respectively.
12718 @end defmac
12720 @node Number processing Macros
12721 @subsection Arithmetic computation in M4
12723 The following macros facilitate integer arithmetic operations.
12724 Where a parameter is documented as taking an arithmetic expression, you
12725 can use anything that can be parsed by @code{m4_eval}.
12727 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
12728 @msindex{cmp}
12729 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
12730 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
12731 equal, and @samp{1} if @var{expr-1} is larger.
12732 @end defmac
12734 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
12735 @msindex{list_cmp}
12736 Compare the two M4 lists consisting of comma-separated arithmetic
12737 expressions, left to right.  Expand to @samp{-1} for the first element
12738 pairing where the value from @var{list-1} is smaller, @samp{1} where the
12739 value from @var{list-2} is smaller, or @samp{0} if both lists have the
12740 same values.  If one list is shorter than the other, the remaining
12741 elements of the longer list are compared against zero.
12742 @example
12743 m4_list_cmp([1, 0],       [1])
12744 @result{}0
12745 m4_list_cmp([1, [1 * 0]], [1, 0])
12746 @result{}0
12747 m4_list_cmp([1, 2],       [1, 0])
12748 @result{}1
12749 m4_list_cmp([1, [1+1], 3],[1, 2])
12750 @result{}1
12751 m4_list_cmp([1, 2, -3],   [1, 2])
12752 @result{}-1
12753 m4_list_cmp([1, 0],       [1, 2])
12754 @result{}-1
12755 m4_list_cmp([1],          [1, 2])
12756 @result{}-1
12757 @end example
12758 @end defmac
12760 @defmac m4_max (@var{arg}, @dots{})
12761 @msindex{max}
12762 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
12763 of the maximum arithmetic expression among all the arguments.
12764 @end defmac
12766 @defmac m4_min (@var{arg}, @dots{})
12767 @msindex{min}
12768 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
12769 of the minimum arithmetic expression among all the arguments.
12770 @end defmac
12772 @defmac m4_sign (@var{expr})
12773 @msindex{sign}
12774 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
12775 @samp{1} if it is positive, and @samp{0} if it is zero.
12776 @end defmac
12778 @anchor{m4_version_compare}
12779 @defmac m4_version_compare (@var{version-1}, @var{version-2})
12780 @msindex{version_compare}
12781 This macro was introduced in Autoconf 2.53, but had a number of
12782 usability limitations that were not lifted until Autoconf 2.62.  Compare
12783 the version strings @var{version-1} and @var{version-2}, and expand to
12784 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
12785 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
12786 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
12787 element is a number along with optional case-insensitive letters
12788 designating beta releases.  The comparison stops at the leftmost element
12789 that contains a difference, although a 0 element compares equal to a
12790 missing element.
12792 It is permissible to include commit identifiers in @var{version}, such
12793 as an abbreviated SHA1 of the commit, provided there is still a
12794 monotonically increasing prefix to allow for accurate version-based
12795 comparisons.  For example, this paragraph was written when the
12796 development snapshot of autoconf claimed to be at version
12797 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
12798 abbreviated commit identification of @samp{dc51}.
12800 @example
12801 m4_version_compare([1.1], [2.0])
12802 @result{}-1
12803 m4_version_compare([2.0b], [2.0a])
12804 @result{}1
12805 m4_version_compare([1.1.1], [1.1.1a])
12806 @result{}-1
12807 m4_version_compare([1.2], [1.1.1a])
12808 @result{}1
12809 m4_version_compare([1.0], [1])
12810 @result{}0
12811 m4_version_compare([1.1pre], [1.1PRE])
12812 @result{}0
12813 m4_version_compare([1.1a], [1,10])
12814 @result{}-1
12815 m4_version_compare([2.61a], [2.61a-248-dc51])
12816 @result{}-1
12817 m4_version_compare([2.61b], [2.61a-248-dc51])
12818 @result{}1
12819 @end example
12820 @end defmac
12822 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
12823   @dvar{if-old, m4_fatal})
12824 @msindex{version_prereq}
12825 Compares @var{version} against the version of Autoconf currently
12826 running.  If the running version is at @var{version} or newer, expand
12827 @var{if-new-enough}, but if @var{version} is larger than the version
12828 currently executing, expand @var{if-old}, which defaults to printing an
12829 error message and exiting m4sugar with status 63.  When given only one
12830 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
12831 Remember that the autoconf philosophy favors feature checks over version
12832 checks.
12833 @end defmac
12835 @node Set manipulation Macros
12836 @subsection Set manipulation in M4
12837 @cindex Set manipulation
12838 @cindex Data structure, set
12839 @cindex Unordered set manipulation
12841 Sometimes, it is necessary to track a set of data, where the order does
12842 not matter and where there are no duplicates in the set.  The following
12843 macros facilitate set manipulations.  Each set is an opaque object,
12844 which can only be accessed via these basic operations.  The underlying
12845 implementation guarantees linear scaling for set creation, which is more
12846 efficient than using the quadratic @code{m4_append_uniq}.  Both set
12847 names and values can be arbitrary strings, except for unbalanced quotes.
12848 This implementation ties up memory for removed elements until the next
12849 operation that must traverse all the elements of a set; and although
12850 that may slow down some operations until the memory for removed elements
12851 is pruned, it still guarantees linear performance.
12853 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
12854 @msindex{set_add}
12855 Adds the string @var{value} as a member of set @var{set}.  Expand
12856 @var{if-uniq} if the element was added, or @var{if-dup} if it was
12857 previously in the set.  Operates in amortized constant time, so that set
12858 creation scales linearly.
12859 @end defmac
12861 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
12862 @msindex{set_add_all}
12863 Adds each @var{value} to the set @var{set}.  This is slightly more
12864 efficient than repeatedly invoking @code{m4_set_add}.
12865 @end defmac
12867 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
12868  @ovar{if-absent})
12869 @msindex{set_contains}
12870 Expands @var{if-present} if the string @var{value} is a member of
12871 @var{set}, otherwise @var{if-absent}.
12873 @example
12874 m4_set_contains([a], [1], [yes], [no])
12875 @result{}no
12876 m4_set_add([a], [1], [added], [dup])
12877 @result{}added
12878 m4_set_add([a], [1], [added], [dup])
12879 @result{}dup
12880 m4_set_contains([a], [1], [yes], [no])
12881 @result{}yes
12882 m4_set_remove([a], [1], [removed], [missing])
12883 @result{}removed
12884 m4_set_contains([a], [1], [yes], [no])
12885 @result{}no
12886 m4_set_remove([a], [1], [removed], [missing])
12887 @result{}missing
12888 @end example
12889 @end defmac
12891 @defmac m4_set_contents (@var{set}, @ovar{sep})
12892 @defmacx m4_set_dump (@var{set}, @ovar{sep})
12893 @msindex{set_contents}
12894 @msindex{set_dump}
12895 Expands to a single string consisting of all the members of the set
12896 @var{set}, each separated by @var{sep}, which is not expanded.
12897 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
12898 memory occupied by removed elements, while @code{m4_set_dump} is a
12899 faster one-shot action that also deletes the set.  No provision is made
12900 for disambiguating members that contain a non-empty @var{sep} as a
12901 substring; use @code{m4_set_empty} to distinguish between an empty set
12902 and the set containing only the empty string.  The order of the output
12903 is unspecified; in the current implementation, part of the speed of
12904 @code{m4_set_dump} results from using a different output order than
12905 @code{m4_set_contents}.  These macros scale linearly in the size of the
12906 set before memory pruning, and @code{m4_set_contents([@var{set}],
12907 [@var{sep}])} is faster than
12908 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
12910 @example
12911 m4_set_add_all([a], [1], [2], [3])
12912 @result{}
12913 m4_set_contents([a], [-])
12914 @result{}1-2-3
12915 m4_joinall([-]m4_set_listc([a]))
12916 @result{}1-2-3
12917 m4_set_dump([a], [-])
12918 @result{}3-2-1
12919 m4_set_contents([a])
12920 @result{}
12921 m4_set_add([a], [])
12922 @result{}
12923 m4_set_contents([a], [-])
12924 @result{}
12925 @end example
12926 @end defmac
12928 @defmac m4_set_delete (@var{set})
12929 @msindex{set_delete}
12930 Delete all elements and memory associated with @var{set}.  This is
12931 linear in the set size, and faster than removing one element at a time.
12932 @end defmac
12934 @defmac m4_set_difference (@var{seta}, @var{setb})
12935 @defmacx m4_set_intersection (@var{seta}, @var{setb})
12936 @defmacx m4_set_union (@var{seta}, @var{setb})
12937 @msindex{set_difference}
12938 @msindex{set_intersection}
12939 @msindex{set_union}
12940 Compute the relation between @var{seta} and @var{setb}, and output the
12941 result as a list of quoted arguments without duplicates and with a
12942 leading comma.  Set difference selects the elements in @var{seta} but
12943 not @var{setb}, intersection selects only elements in both sets, and
12944 union selects elements in either set.  These actions are linear in the
12945 sum of the set sizes.  The leading comma is necessary to distinguish
12946 between no elements and the empty string as the only element.
12948 @example
12949 m4_set_add_all([a], [1], [2], [3])
12950 @result{}
12951 m4_set_add_all([b], [3], [], [4])
12952 @result{}
12953 m4_set_difference([a], [b])
12954 @result{},1,2
12955 m4_set_difference([b], [a])
12956 @result{},,4
12957 m4_set_intersection([a], [b])
12958 @result{},3
12959 m4_set_union([a], [b])
12960 @result{},1,2,3,,4
12961 @end example
12962 @end defmac
12964 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
12965 @msindex{set_empty}
12966 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
12967 expand @var{if-elements}.  This macro operates in constant time.  Using
12968 this macro can help disambiguate output from @code{m4_set_contents} or
12969 @code{m4_set_list}.
12970 @end defmac
12972 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
12973 @msindex{set_foreach}
12974 For each element in the set @var{set}, expand @var{action} with the
12975 macro @var{variable} defined as the set element.  Behavior is
12976 unspecified if @var{action} recursively lists the contents of @var{set}
12977 (although listing other sets is acceptable), or if it modifies the set
12978 in any way other than removing the element currently contained in
12979 @var{variable}.  This macro is faster than the corresponding
12980 @code{m4_foreach([@var{variable}],
12981 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
12982 although @code{m4_set_map} might be faster still.
12984 @example
12985 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
12986 @result{}
12987 m4_set_contents([a])
12988 @result{}12345
12989 m4_set_foreach([a], [i],
12990   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
12991 @result{}24
12992 m4_set_contents([a])
12993 @result{}135
12994 @end example
12995 @end defmac
12997 @defmac m4_set_list (@var{set})
12998 @defmacx m4_set_listc (@var{set})
12999 @msindex{set_list}
13000 @msindex{set_listc}
13001 Produce a list of arguments, where each argument is a quoted element
13002 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
13003 by adding a leading comma if there are any set elements, whereas the
13004 variant @code{m4_set_list} cannot distinguish between an empty set and a
13005 set containing only the empty string.  These can be directly used in
13006 macros that take multiple arguments, such as @code{m4_join} or
13007 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13008 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
13009 memory occupied by removed elements is reclaimed during these macros.
13011 @example
13012 m4_set_add_all([a], [1], [2], [3])
13013 @result{}
13014 m4_set_list([a])
13015 @result{}1,2,3
13016 m4_set_list([b])
13017 @result{}
13018 m4_set_listc([b])
13019 @result{}
13020 m4_count(m4_set_list([b]))
13021 @result{}1
13022 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13023 @result{}0
13024 m4_set_add([b], [])
13025 @result{}
13026 m4_set_list([b])
13027 @result{}
13028 m4_set_listc([b])
13029 @result{},
13030 m4_count(m4_set_list([b]))
13031 @result{}1
13032 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13033 @result{}1
13034 @end example
13035 @end defmac
13037 @defmac m4_set_map (@var{set}, @var{action})
13038 @msindex{set_map}
13039 For each element in the set @var{set}, expand @var{action} with a single
13040 argument of the set element.  Behavior is unspecified if @var{action}
13041 recursively lists the contents of @var{set} (although listing other sets
13042 is acceptable), or if it modifies the set in any way other than removing
13043 the element passed as an argument.  This macro is faster than either
13044 corresponding counterpart of
13045 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13046 @code{m4_set_foreach([@var{set}], [var],
13047 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
13048 if more than one argument is needed for @var{action}, although it is
13049 more efficient to use @code{m4_set_map_sep} in that case.
13050 @end defmac
13052 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13053 @msindex{set_map_sep}
13054 For each element in the set @var{set}, expand
13055 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13056 between elements.  Behavior is unspecified if the expansion recursively
13057 lists the contents of @var{set} (although listing other sets
13058 is acceptable), or if it modifies the set in any way other than removing
13059 the element visited by the expansion.  This macro provides the most
13060 efficient means for non-destructively visiting the elements of a set; in
13061 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13062 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13063 @end defmac
13065 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13066  @ovar{if-absent})
13067 @msindex{set_remove}
13068 If @var{value} is an element in the set @var{set}, then remove it and
13069 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
13070 operates in constant time so that multiple removals will scale linearly
13071 rather than quadratically; but when used outside of
13072 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13073 until the set is later
13074 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
13075 other set operations are then less efficient between the time of element
13076 removal and subsequent memory compaction, but still maintain their
13077 guaranteed scaling performance.
13078 @end defmac
13080 @defmac m4_set_size (@var{set})
13081 @msindex{set_size}
13082 Expand to the size of the set @var{set}.  This implementation operates
13083 in constant time, and is thus more efficient than
13084 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13085 @end defmac
13088 @node Forbidden Patterns
13089 @subsection Forbidden Patterns
13090 @cindex Forbidden patterns
13091 @cindex Patterns, forbidden
13093 M4sugar provides a means to define suspicious patterns, patterns
13094 describing tokens which should not be found in the output.  For
13095 instance, if an Autoconf @file{configure} script includes tokens such as
13096 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13097 wrong (typically a macro was not evaluated because of overquotation).
13099 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13100 Additional layers, such as M4sh and Autoconf, add additional forbidden
13101 patterns to the list.
13103 @defmac m4_pattern_forbid (@var{pattern})
13104 @msindex{pattern_forbid}
13105 Declare that no token matching @var{pattern} must be found in the output.
13106 Comments are not checked; this can be a problem if, for instance, you
13107 have some macro left unexpanded after an @samp{#include}.  No consensus
13108 is currently found in the Autoconf community, as some people consider it
13109 should be valid to name macros in comments (which doesn't make sense to
13110 the authors of this documentation: input, such as macros, should be
13111 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13112 document the output).
13113 @end defmac
13115 Of course, you might encounter exceptions to these generic rules, for
13116 instance you might have to refer to @samp{$m4_flags}.
13118 @defmac m4_pattern_allow (@var{pattern})
13119 @msindex{pattern_allow}
13120 Any token matching @var{pattern} is allowed, including if it matches an
13121 @code{m4_pattern_forbid} pattern.
13122 @end defmac
13124 @node Debugging via autom4te
13125 @section Debugging via autom4te
13126 @cindex debugging tips
13127 @cindex autom4te debugging tips
13128 @cindex m4sugar debugging tips
13129 At times, it is desirable to see what was happening inside m4, to see
13130 why output was not matching expectations.  However, post-processing done
13131 by @command{autom4te} means that directly using the m4 builtin
13132 @code{m4_traceon} is likely to interfere with operation.  Also, frequent
13133 diversion changes and the concept of forbidden tokens make it difficult
13134 to use @code{m4_defn} to generate inline comments in the final output.
13136 There are a couple of tools to help with this.  One is the use of the
13137 @option{--trace} option provided by @command{autom4te} (as well as each
13138 of the programs that wrap @command{autom4te}, such as
13139 @command{autoconf}), in order to inspect when a macro is called and with
13140 which arguments.  For example, when this paragraph was written, the
13141 autoconf version could be found by:
13143 @example
13144 $ @kbd{autoconf --trace=AC_INIT}
13145 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13146 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13147 version is 2.63b.95-3963
13148 @end example
13150 Another trick is to print out the expansion of various m4 expressions to
13151 standard error or to an independent file, with no further m4 expansion,
13152 and without interfering with diversion changes or the post-processing
13153 done to standard output.  @code{m4_errprintn} shows a given expression
13154 on standard error.  For example, if you want to see the expansion of an
13155 autoconf primitive or of one of your autoconf macros, you can do it like
13156 this:
13158 @example
13159 $ @kbd{cat <<\EOF > configure.ac}
13160 AC_INIT
13161 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13162 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13163 AC_OUTPUT
13165 $ @kbd{autoconf}
13166 @error{}The definition of AC_DEFINE_UNQUOTED:
13167 @error{}_AC_DEFINE_Q([], $@@)
13168 @end example
13170 @node Programming in M4sh
13171 @chapter Programming in M4sh
13173 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13174 scripts.  This name was coined by Lars J. Aas, who notes that,
13175 according to the Webster's Revised Unabridged Dictionary (1913):
13177 @quotation
13178 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
13179 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
13181 @enumerate 1
13182 @item
13183 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13184 pressure@enddots{}
13186 @item
13187 A mixture of meal or bran and water fed to animals.
13189 @item
13190 A mess; trouble.  [Obs.] --Beau.@: & Fl.
13191 @end enumerate
13192 @end quotation
13194 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13195 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
13196 and environment variable namespace @samp{^as_}, and the here-document
13197 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
13198 define your own macros or output shell code that conflicts with these
13199 namespaces.
13201 @menu
13202 * Common Shell Constructs::     Portability layer for common shell constructs
13203 * Polymorphic Variables::       Support for indirect variable names
13204 * Initialization Macros::       Macros to establish a sane shell environment
13205 * File Descriptor Macros::      File descriptor macros for input and output
13206 @end menu
13208 @node Common Shell Constructs
13209 @section Common Shell Constructs
13211 M4sh provides portable alternatives for some common shell constructs
13212 that unfortunately are not portable in practice.
13214 @c Deprecated, to be replaced by a better API
13215 @ignore
13216 @defmac AS_BASENAME (@var{file-name})
13217 @asindex{BASENAME}
13218 Output the non-directory portion of @var{file-name}.  For example,
13219 if @code{$file} is @samp{/one/two/three}, the command
13220 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13221 @end defmac
13222 @end ignore
13224 @defmac AS_BOX (@var{text}, @dvar{char, -})
13225 @asindex{BOX}
13226 Expand into shell code that will output @var{text} surrounded by a box
13227 with @var{char} in the top and bottom border.  @var{text} should not
13228 contain a newline, but may contain shell expansions valid for unquoted
13229 here-documents.  @var{char} defaults to @samp{-}, but can be any
13230 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13231 @samp{&}, or @samp{`}.  This is useful for outputting a comment box into
13232 log files to separate distinct phases of script operation.
13233 @end defmac
13235 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13236   @dots{}, @ovar{default})
13237 @asindex{CASE}
13238 Expand into a shell @samp{case} statement, where @var{word} is matched
13239 against one or more patterns.  @var{if-matched} is run if the
13240 corresponding pattern matched @var{word}, else @var{default} is run.
13241 Avoids several portability issues (@pxref{case, , Limitations of Shell
13242 Builtins}).
13243 @end defmac
13245 @c Deprecated, to be replaced by a better API
13246 @defmac AS_DIRNAME (@var{file-name})
13247 @asindex{DIRNAME}
13248 Output the directory portion of @var{file-name}.  For example,
13249 if @code{$file} is @samp{/one/two/three}, the command
13250 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13252 This interface may be improved in the future to avoid forks and losing
13253 trailing newlines.
13254 @end defmac
13256 @defmac AS_ECHO (@var{word})
13257 @asindex{ECHO}
13258 Emits @var{word} to the standard output, followed by a newline.  @var{word}
13259 must be a single shell word (typically a quoted string).  The bytes of
13260 @var{word} are output as-is, even if it starts with "-" or contains "\".
13261 Redirections can be placed outside the macro invocation.  This is much
13262 more portable than using @command{echo} (@pxref{echo, , Limitations of
13263 Shell Builtins}).
13264 @end defmac
13266 @defmac AS_ECHO_N (@var{word})
13267 @asindex{ECHO_N}
13268 Emits @var{word} to the standard output, without a following newline.
13269 @var{word} must be a single shell word (typically a quoted string) and,
13270 for portability, should not include more than one newline.  The bytes of
13271 @var{word} are output as-is, even if it starts with "-" or contains "\".
13272 Redirections can be placed outside the macro invocation.
13273 @end defmac
13275 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13276 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13277 @asindex{ESCAPE}
13278 Expands to @var{string}, with any characters in @var{chars} escaped with
13279 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
13280 and only contain characters from the set @samp{`\"$}; however,
13281 characters may be safely listed more than once in @var{chars} for the
13282 sake of syntax highlighting editors.  The current implementation expands
13283 @var{string} after adding escapes; if @var{string} contains macro calls
13284 that in turn expand to text needing shell quoting, you can use
13285 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13287 The default for @var{chars} (@samp{\"$`}) is the set of characters
13288 needing escapes when @var{string} will be used literally within double
13289 quotes.  One common variant is the set of characters to protect when
13290 @var{string} will be used literally within back-ticks or an unquoted
13291 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
13292 be used to form a double-quoted string containing the same expansions
13293 that would have occurred if @var{string} were expanded in an unquoted
13294 here-document; however, when using this variant, care must be taken that
13295 @var{string} does not use double quotes within complex variable
13296 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13297 with improper escapes.
13299 This macro is often used with @code{AS_ECHO}.  For an example, observe
13300 the output generated by the shell code generated from this snippet:
13302 @example
13303 foo=bar
13304 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13305 @result{}"$foo" = "bar"
13306 m4_define([macro], [a, [\b]])
13307 AS_ECHO(["AS_ESCAPE([[macro]])"])
13308 @result{}macro
13309 AS_ECHO(["AS_ESCAPE([macro])"])
13310 @result{}a, b
13311 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13312 @result{}a, \b
13313 @end example
13315 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13316 @comment the case of @var{string} that does not contain '.
13317 To escape a string that will be placed within single quotes, use:
13319 @example
13320 m4_bpatsubst([[@var{string}]], ['], ['\\''])
13321 @end example
13322 @end defmac
13324 @defmac AS_EXIT (@dvar{status, $?})
13325 @asindex{EXIT}
13326 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13327 This macro
13328 works around shells that see the exit status of the command prior to
13329 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13330 of Shell Builtins}).
13331 @end defmac
13333 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13334 @asindex{IF}
13335 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
13336 run shell code @var{run-if-true1}, else examine further tests.  If no test
13337 exits with a zero status, run shell code @var{run-if-false}, with
13338 simplifications if either @var{run-if-true1} or @var{run-if-false}
13339 is empty.  For example,
13341 @example
13342 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13343       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13344       [echo foo not specified])
13345 @end example
13347 @noindent
13348 ensures any required macros of @code{HANDLE_FOO}
13349 are expanded before the first test.
13350 @end defmac
13352 @defmac AS_MKDIR_P (@var{file-name})
13353 @asindex{MKDIR_P}
13354 Make the directory @var{file-name}, including intervening directories
13355 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
13356 except that it is portable to older versions of @command{mkdir} that
13357 lack support for the @option{-p} option or for the @option{--}
13358 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
13359 @code{AS_MKDIR_P}
13360 succeeds if @var{file-name} is a symbolic link to an existing directory,
13361 even though Posix is unclear whether @samp{mkdir -p} should
13362 succeed in that case.  If creation of @var{file-name} fails, exit the
13363 script.
13365 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
13366 @end defmac
13368 @defmac AS_SET_STATUS (@var{status})
13369 @asindex{SET_STATUS}
13370 Emit shell code to set the value of @samp{$?} to @var{status}, as
13371 efficiently as possible.  However, this is not guaranteed to abort a
13372 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
13373 Builtins}).  This should also be used at the end of a complex shell
13374 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
13375 a DJGPP shell bug.
13376 @end defmac
13378 @defmac AS_TR_CPP (@var{expression})
13379 @asindex{TR_CPP}
13380 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
13381 For example:
13383 @example
13384 # This outputs "#define HAVE_CHAR_P 1".
13385 # Notice the m4 quoting around #, to prevent an m4 comment
13386 type="char *"
13387 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
13388 @end example
13389 @end defmac
13391 @defmac AS_TR_SH (@var{expression})
13392 @asindex{TR_SH}
13393 Transform @var{expression} into shell code that generates a valid shell
13394 variable name.  The result is literal when possible at m4 time, but must
13395 be used with @code{eval} if @var{expression} causes shell indirections.
13396 For example:
13398 @example
13399 # This outputs "Have it!".
13400 header="sys/some file.h"
13401 eval AS_TR_SH([HAVE_$header])=yes
13402 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
13403 @end example
13404 @end defmac
13406 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
13407 @asindex{SET_CATFILE}
13408 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
13409 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
13410 @var{file} is absolute, etc.).
13411 @end defmac
13413 @defmac AS_UNSET (@var{var})
13414 @asindex{UNSET}
13415 Unsets the shell variable @var{var}, working around bugs in older
13416 shells (@pxref{unset, , Limitations of Shell
13417 Builtins}).  @var{var} can be a literal or indirect variable name.
13418 @end defmac
13420 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
13421   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
13422 @asindex{VERSION_COMPARE}
13423 Compare two strings @var{version-1} and @var{version-2}, possibly
13424 containing shell variables, as version strings, and expand
13425 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
13426 depending upon the result.
13427 The algorithm to compare is similar to the one used by strverscmp in
13428 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
13429 The GNU C Library}).
13430 @end defmac
13432 @node Polymorphic Variables
13433 @section Support for indirect variable names
13434 @cindex variable name indirection
13435 @cindex polymorphic variable name
13436 @cindex indirection, variable name
13438 Often, it is convenient to write a macro that will emit shell code
13439 operating on a shell variable.  The simplest case is when the variable
13440 name is known.  But a more powerful idiom is writing shell code that can
13441 work through an indirection, where another variable or command
13442 substitution produces the name of the variable to actually manipulate.
13443 M4sh supports the notion of polymorphic shell variables, making it easy
13444 to write a macro that can deal with either literal or indirect variable
13445 names and output shell code appropriate for both use cases.  Behavior is
13446 undefined if expansion of an indirect variable does not result in a
13447 literal variable name.
13449 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
13450   @dvar{if-simple-ref, @var{if-not}})
13451 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
13452   @ovar{if-not}, @dvar{if-simple-ref, @var{if-not}})
13453 @asindex{LITERAL_IF}
13454 @asindex{LITERAL_WORD_IF}
13455 If the expansion of @var{expression} is definitely a shell literal,
13456 expand @var{if-literal}.  If the expansion of @var{expression} looks
13457 like it might contain shell indirections (such as @code{$var} or
13458 @code{`expr`}), then @var{if-not} is expanded.  Sometimes, it is
13459 possible to output optimized code if @var{expression} consists only of
13460 shell variable expansions (such as @code{$@{var@}}), in which case
13461 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
13462 should always be safe.  @code{AS_LITERAL_WORD_IF} only expands
13463 @var{if-literal} if @var{expression} looks like a single shell word,
13464 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
13465 in @var{expression}.
13467 In order to reduce the time spent recognizing whether an
13468 @var{expression} qualifies as a literal or a simple indirection, the
13469 implementation is somewhat conservative: @var{expression} must be a
13470 single shell word (possibly after stripping whitespace), consisting only
13471 of bytes that would have the same meaning whether unquoted or enclosed
13472 in double quotes (for example, @samp{a.b} results in @var{if-literal},
13473 even though it is not a valid shell variable name; while both @samp{'a'}
13474 and @samp{[$]} result in @var{if-not}, because they behave differently
13475 than @samp{"'a'"} and @samp{"[$]"}).  This macro can be used in contexts
13476 for recognizing portable file names (such as in the implementation of
13477 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
13478 valid variable names (such as in the implementation of @code{AS_TR_SH},
13479 which uses an additional @code{m4_translit} to convert @samp{.} to
13480 @samp{_}).
13482 This example shows how to read the contents of the shell variable
13483 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}.  It
13484 results in a script that will output the line @samp{hello} three times.
13486 @example
13487 AC_DEFUN([MY_ACTION],
13488 [AS_LITERAL_IF([$1],
13489   [echo "$$1"],
13490 @c $$
13491   [AS_VAR_COPY([var], [$1])
13492    echo "$var"],
13493   [eval 'echo "$'"$1"\"])])
13494 foo=bar bar=hello
13495 MY_ACTION([bar])
13496 MY_ACTION([`echo bar`])
13497 MY_ACTION([$foo])
13498 @end example
13499 @end defmac
13501 @defmac AS_VAR_APPEND (@var{var}, @var{text})
13502 @asindex{VAR_APPEND}
13503 Emit shell code to append the shell expansion of @var{text} to the end
13504 of the current contents of the polymorphic shell variable @var{var},
13505 taking advantage of shells that provide the @samp{+=} extension for more
13506 efficient scaling.
13508 For situations where the final contents of @var{var} are relatively
13509 short (less than 256 bytes), it is more efficient to use the simpler
13510 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
13511 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
13512 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}).  But in the case
13513 when the script will be repeatedly appending text into @code{var},
13514 issues of scaling start to become apparent.  A naive implementation
13515 requires execution time linear to the length of the current contents of
13516 @var{var} as well as the length of @var{text} for a single append, for
13517 an overall quadratic scaling with multiple appends.  This macro takes
13518 advantage of shells which provide the extension
13519 @code{@var{var}+=@var{text}}, which can provide amortized constant time
13520 for a single append, for an overall linear scaling with multiple
13521 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
13522 @var{text} be quoted properly to avoid field splitting and file name
13523 expansion.
13524 @end defmac
13526 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
13527 @asindex{VAR_ARITH}
13528 Emit shell code to compute the arithmetic expansion of @var{expression},
13529 assigning the result as the contents of the polymorphic shell variable
13530 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
13531 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
13532 syntax for a valid @var{expression} is rather limited: all operators
13533 must occur as separate shell arguments and with proper quoting, there is
13534 no portable equality operator, all variables containing numeric values
13535 must be expanded prior to the computation, all numeric values must be
13536 provided in decimal without leading zeroes, and the first shell argument
13537 should not be a negative number.  In the following example, this snippet
13538 will print @samp{(2+3)*4 == 20}.
13540 @example
13541 bar=3
13542 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
13543 echo "(2+$bar)*4 == $foo"
13544 @end example
13545 @end defmac
13547 @defmac AS_VAR_COPY (@var{dest}, @var{source})
13548 @asindex{VAR_COPY}
13549 Emit shell code to assign the contents of the polymorphic shell variable
13550 @var{source} to the polymorphic shell variable @var{dest}.  For example,
13551 executing this M4sh snippet will output @samp{bar hi}:
13553 @example
13554 foo=bar bar=hi
13555 AS_VAR_COPY([a], [foo])
13556 AS_VAR_COPY([b], [$foo])
13557 echo "$a $b"
13558 @end example
13560 When it is necessary to access the contents of an indirect variable
13561 inside a shell double-quoted context, the recommended idiom is to first
13562 copy the contents into a temporary literal shell variable.
13564 @smallexample
13565 for header in stdint_h inttypes_h ; do
13566   AS_VAR_COPY([var], [ac_cv_header_$header])
13567   echo "$header detected: $var"
13568 done
13569 @end smallexample
13570 @end defmac
13572 @comment AS_VAR_GET is intentionally undocumented; it can't handle
13573 @comment trailing newlines uniformly, and forks too much.
13575 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
13576   @ovar{if-not-equal})
13577 @asindex{VAR_IF}
13578 Output a shell conditional statement.  If the contents of the
13579 polymorphic shell variable @var{var} match the string @var{word},
13580 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  @var{word}
13581 must be a single shell word (typically a quoted string).  Avoids
13582 shell bugs if an interrupt signal arrives while a command substitution
13583 in @var{var} is being expanded.
13584 @end defmac
13586 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
13587 @defmacx AS_VAR_POPDEF (@var{m4-name})
13588 @asindex{VAR_PUSHDEF}
13589 @asindex{VAR_POPDEF}
13590 @cindex composing variable names
13591 @cindex variable names, composing
13592 A common M4sh idiom involves composing shell variable names from an m4
13593 argument (for example, writing a macro that uses a cache variable).
13594 @var{value} can be an arbitrary string, which will be transliterated
13595 into a valid shell name by @code{AS_TR_SH}.  In order to access the
13596 composed variable name based on @var{value}, it is easier to declare a
13597 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
13598 that macro as the argument to subsequent @code{AS_VAR} macros as a
13599 polymorphic variable name, and finally free the temporary macro with
13600 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
13601 to avoid excess newlines in the output.
13603 Here is an involved example, that shows the power of writing macros that
13604 can handle composed shell variable names:
13606 @example
13607 m4_define([MY_CHECK_HEADER],
13608 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
13609 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
13610 AS_VAR_POPDEF([my_Header])dnl
13612 MY_CHECK_HEADER([stdint.h])
13613 for header in inttypes.h stdlib.h ; do
13614   MY_CHECK_HEADER([$header])
13615 done
13616 @end example
13618 @noindent
13619 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
13620 variable names.  In the first invocation, the m4 argument is
13621 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
13622 As a result, the temporary macro @code{my_Header} expands to the literal
13623 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
13624 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
13625 temporary macro @code{my_Header} expands to the indirect shell name
13626 @samp{$as_my_Header}.  During the shell execution of the for loop, when
13627 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
13628 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
13629 platform where all three headers have been previously detected, the
13630 output of the script will include:
13632 @smallexample
13633 header stdint.h detected
13634 header inttypes.h detected
13635 header stdlib.h detected
13636 @end smallexample
13637 @end defmac
13639 @defmac AS_VAR_SET (@var{var}, @ovar{value})
13640 @asindex{VAR_SET}
13641 Emit shell code to assign the contents of the polymorphic shell variable
13642 @var{var} to the shell expansion of @var{value}.  @var{value} is not
13643 subject to field splitting or file name expansion, so if command
13644 substitution is used, it may be done with @samp{`""`} rather than using
13645 an intermediate variable (@pxref{Shell Substitutions}).  However,
13646 @var{value} does undergo rescanning for additional macro names; behavior
13647 is unspecified if late expansion results in any shell meta-characters.
13648 @end defmac
13650 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
13651 @asindex{VAR_SET_IF}
13652 Emit a shell conditional statement, which executes @var{if-set} if the
13653 polymorphic shell variable @code{var} is set to any value, and
13654 @var{if-undef} otherwise.
13655 @end defmac
13657 @defmac AS_VAR_TEST_SET (@var{var})
13658 @asindex{VAR_TEST_SET}
13659 Emit a shell statement that results in a successful exit status only if
13660 the polymorphic shell variable @code{var} is set.
13661 @end defmac
13663 @node Initialization Macros
13664 @section Initialization Macros
13666 @defmac AS_BOURNE_COMPATIBLE
13667 @asindex{BOURNE_COMPATIBLE}
13668 Set up the shell to be more compatible with the Bourne shell as
13669 standardized by Posix, if possible.  This may involve setting
13670 environment variables, or setting options, or similar
13671 implementation-specific actions.  This macro is deprecated, since
13672 @code{AS_INIT} already invokes it.
13673 @end defmac
13675 @defmac AS_INIT
13676 @asindex{INIT}
13677 @evindex LC_ALL
13678 @evindex SHELL
13679 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
13680 outputs the @code{#! /bin/sh} line, a notice about where the output was
13681 generated from, and code to sanitize the environment for the rest of the
13682 script.  Among other initializations, this sets @env{SHELL} to the shell
13683 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
13684 ensure the C locale.  Finally, it changes the current diversion to
13685 @code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
13686 and @code{AT_INIT}, so shell code in @file{configure},
13687 @file{config.status}, and @file{testsuite} all benefit from a sanitized
13688 shell environment.
13689 @end defmac
13691 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
13692 @asindex{INIT_GENERATED}
13693 Emit shell code to start the creation of a subsidiary shell script in
13694 @var{file}, including changing @var{file} to be executable.  This macro
13695 populates the child script with information learned from the parent
13696 (thus, the emitted code is equivalent in effect, but more efficient,
13697 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
13698 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
13699 beginning of the child, prior to the shell initialization code, and is
13700 subject to parameter expansion, command substitution, and backslash
13701 quote removal.  The
13702 parent script should check the exit status after this macro, in case
13703 @var{file} could not be properly created (for example, if the disk was
13704 full).  If successfully created, the parent script can then proceed to
13705 append additional M4sh constructs into the child script.
13707 Note that the child script starts life without a log file open, so if
13708 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
13709 must temporarily disable any attempts to use the log file until after
13710 emitting code to open a log within the child.  On the other hand, if the
13711 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
13712 @samp{1}, then the child script already has code that copies stdout to
13713 that descriptor.  Currently, the suggested
13714 idiom for writing a M4sh shell script from within another script is:
13716 @example
13717 AS_INIT_GENERATED([@var{file}], [[# My child script.
13718 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
13719 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
13720 cat >> "@var{file}" <<\__EOF__
13721 # Code to initialize AS_MESSAGE_LOG_FD
13722 m4_popdef([AS_MESSAGE_LOG_FD])dnl
13723 # Additional code
13724 __EOF__
13725 @end example
13727 This, however, may change in the future as the M4sh interface is
13728 stabilized further.
13730 Also, be aware that use of @env{LINENO} within the child script may
13731 report line numbers relative to their location in the parent script,
13732 even when using @code{AS_LINENO_PREPARE}, if the parent script was
13733 unable to locate a shell with working @env{LINENO} support.
13734 @end defmac
13736 @defmac AS_LINENO_PREPARE
13737 @asindex{LINENO_PREPARE}
13738 @evindex LINENO
13739 Find a shell that supports the special variable @env{LINENO}, which
13740 contains the number of the currently executing line.  This macro is
13741 automatically invoked by @code{AC_INIT} in configure scripts.
13742 @end defmac
13744 @defmac AS_ME_PREPARE
13745 @asindex{ME_PREPARE}
13746 Set up variable @env{as_me} to be the basename of the currently executing
13747 script.  This macro is automatically invoked by @code{AC_INIT} in
13748 configure scripts.
13749 @end defmac
13751 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
13752 @asindex{TMPDIR}
13753 @evindex TMPDIR
13754 @ovindex tmp
13755 Create, as safely as possible, a temporary sub-directory within
13756 @var{dir} with a name starting with @var{prefix}.  @var{prefix} should
13757 be 2-4 characters, to make it slightly easier to identify the owner of
13758 the directory.  If @var{dir} is omitted, then the value of @env{TMPDIR}
13759 will be used (defaulting to @samp{/tmp}).  On success, the name of the
13760 newly created directory is stored in the shell variable @code{tmp}.  On
13761 error, the script is aborted.
13763 Typically, this macro is coupled with some exit traps to delete the created
13764 directory and its contents on exit or interrupt.  However, there is a
13765 slight window between when the directory is created and when the name is
13766 actually known to the shell, so an interrupt at the right moment might
13767 leave the temporary directory behind.  Hence it is important to use a
13768 @var{prefix} that makes it easier to determine if a leftover temporary
13769 directory from an interrupted script is safe to delete.
13771 The use of the output variable @samp{$tmp} rather than something in the
13772 @samp{as_} namespace is historical; it has the unfortunate consequence
13773 that reusing this otherwise common name for any other purpose inside
13774 your script has the potential to break any cleanup traps designed to
13775 remove the temporary directory.
13776 @end defmac
13778 @defmac AS_SHELL_SANITIZE
13779 @asindex{SHELL_SANITIZE}
13780 Initialize the shell suitably for @command{configure} scripts.  This has
13781 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
13782 environment variables for predictable results from configuration tests.
13783 For example, it sets @env{LC_ALL} to change to the default C locale.
13784 @xref{Special Shell Variables}.  This macro is deprecated, since
13785 @code{AS_INIT} already invokes it.
13786 @end defmac
13789 @node File Descriptor Macros
13790 @section File Descriptor Macros
13791 @cindex input
13792 @cindex standard input
13793 @cindex file descriptors
13794 @cindex descriptors
13795 @cindex low-level output
13796 @cindex output, low-level
13798 The following macros define file descriptors used to output messages
13799 (or input values) from @file{configure} scripts.
13800 For example:
13802 @example
13803 echo "$wombats found" >&AS_MESSAGE_LOG_FD
13804 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
13805 read kangaroos <&AS_ORIGINAL_STDIN_FD`
13806 @end example
13808 @noindent
13809 However doing so is seldom needed, because Autoconf provides higher
13810 level macros as described below.
13812 @defmac AS_MESSAGE_FD
13813 @asindex{MESSAGE_FD}
13814 The file descriptor for @samp{checking for...}  messages and results.
13815 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
13816 clients.  However, @code{AC_INIT} shuffles things around to another file
13817 descriptor, in order to allow the @option{-q} option of
13818 @command{configure} to choose whether messages should go to the script's
13819 standard output or be discarded.
13821 If you want to display some messages, consider using one of the printing
13822 macros (@pxref{Printing Messages}) instead.  Copies of messages output
13823 via these macros are also recorded in @file{config.log}.
13824 @end defmac
13826 @anchor{AS_MESSAGE_LOG_FD}
13827 @defmac AS_MESSAGE_LOG_FD
13828 @asindex{MESSAGE_LOG_FD}
13829 This must either be empty, or expand to a file descriptor for log
13830 messages.  By default, @code{AS_INIT} sets this macro to the empty
13831 string for standalone M4sh clients, thus disabling logging.  However,
13832 @code{AC_INIT} shuffles things around so that both @command{configure}
13833 and @command{config.status} use @file{config.log} for log messages.
13834 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
13835 Compiler}), redirect all output to this descriptor.  You may want to do
13836 so if you develop such a low-level macro.
13837 @end defmac
13839 @defmac AS_ORIGINAL_STDIN_FD
13840 @asindex{ORIGINAL_STDIN_FD}
13841 This must expand to a file descriptor for the original standard input.
13842 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
13843 M4sh clients.  However, @code{AC_INIT} shuffles things around for
13844 safety.
13846 When @command{configure} runs, it may accidentally execute an
13847 interactive command that has the same name as the non-interactive meant
13848 to be used or checked.  If the standard input was the terminal, such
13849 interactive programs would cause @command{configure} to stop, pending
13850 some user input.  Therefore @command{configure} redirects its standard
13851 input from @file{/dev/null} during its initialization.  This is not
13852 normally a problem, since @command{configure} normally does not need
13853 user input.
13855 In the extreme case where your @file{configure} script really needs to
13856 obtain some values from the original standard input, you can read them
13857 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
13858 @end defmac
13861 @c =================================================== Writing Autoconf Macros.
13863 @node Writing Autoconf Macros
13864 @chapter Writing Autoconf Macros
13866 When you write a feature test that could be applicable to more than one
13867 software package, the best thing to do is encapsulate it in a new macro.
13868 Here are some instructions and guidelines for writing Autoconf macros.
13870 @menu
13871 * Macro Definitions::           Basic format of an Autoconf macro
13872 * Macro Names::                 What to call your new macros
13873 * Reporting Messages::          Notifying @command{autoconf} users
13874 * Dependencies Between Macros::  What to do when macros depend on other macros
13875 * Obsoleting Macros::           Warning about old ways of doing things
13876 * Coding Style::                Writing Autoconf macros @`a la Autoconf
13877 @end menu
13879 @node Macro Definitions
13880 @section Macro Definitions
13882 @defmac AC_DEFUN (@var{name}, @ovar{body})
13883 @acindex{DEFUN}
13884 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
13885 similar to the M4 builtin @code{m4_define} macro; this creates a macro
13886 named @var{name} and with @var{body} as its expansion.  In addition to
13887 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
13888 constrain the order in which macros are called, while avoiding redundant
13889 output (@pxref{Prerequisite Macros}).
13890 @end defmac
13892 An Autoconf macro definition looks like this:
13894 @example
13895 AC_DEFUN(@var{macro-name}, @var{macro-body})
13896 @end example
13898 You can refer to any arguments passed to the macro as @samp{$1},
13899 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
13900 GNU M4}, for more complete information on writing M4 macros.
13902 Most macros fall in one of two general categories.  The first category
13903 includes macros which take arguments, in order to generate output
13904 parameterized by those arguments.  Macros in this category are designed
13905 to be directly expanded, often multiple times, and should not be used as
13906 the argument to @code{AC_REQUIRE}.  The other category includes macros
13907 which are shorthand for a fixed block of text, and therefore do not take
13908 arguments.  For this category of macros, directly expanding the macro
13909 multiple times results in redundant output, so it is more common to use
13910 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
13911 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
13913 Be sure to properly quote both the @var{macro-body} @emph{and} the
13914 @var{macro-name} to avoid any problems if the macro happens to have
13915 been previously defined.
13917 Each macro should have a header comment that gives its prototype, and a
13918 brief description.  When arguments have default values, display them in
13919 the prototype.  For example:
13921 @example
13922 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
13923 # --------------------------------------
13924 m4_define([AC_MSG_ERROR],
13925   [@{ AS_MESSAGE([error: $1], [2])
13926      exit m4_default([$2], [1]); @}])
13927 @end example
13929 Comments about the macro should be left in the header comment.  Most
13930 other comments make their way into @file{configure}, so just keep
13931 using @samp{#} to introduce comments.
13933 @cindex @code{dnl}
13934 If you have some special comments about pure M4 code, comments
13935 that make no sense in @file{configure} and in the header comment, then
13936 use the builtin @code{dnl}: it causes M4 to discard the text
13937 through the next newline.
13939 Keep in mind that @code{dnl} is rarely needed to introduce comments;
13940 @code{dnl} is more useful to get rid of the newlines following macros
13941 that produce no output, such as @code{AC_REQUIRE}.
13943 Public third-party macros need to use @code{AC_DEFUN}, and not
13944 @code{m4_define}, in order to be found by @command{aclocal}
13945 (@pxref{Extending aclocal,,, automake, GNU Automake}).
13946 Additionally, if it is ever determined that a macro should be made
13947 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
13948 in order to have @command{autoupdate} assist the user in choosing a
13949 better alternative, but there is no corresponding way to make
13950 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
13952 There is another subtle, but important, difference between using
13953 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
13954 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
13955 block of text with a @code{m4_define} macro that will expand to the same
13956 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
13957 the same content does not necessarily give the same results, because it
13958 changes the location where any embedded but unsatisfied
13959 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
13960 example of this, see @ref{Expanded Before Required}.
13962 @node Macro Names
13963 @section Macro Names
13965 All of the public Autoconf macros have all-uppercase names in the
13966 namespace @samp{^AC_} to prevent them from accidentally conflicting with
13967 other text; Autoconf also reserves the namespace @samp{^_AC_} for
13968 internal macros.  All shell variables that they use for internal
13969 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
13970 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
13971 @command{configure}, files produced by Autoconf make heavy use of the
13972 file system namespace @samp{^conf}.
13974 Since Autoconf is built on top of M4sugar (@pxref{Programming in
13975 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
13976 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
13977 @file{configure.ac} is also designed to be scanned by Autoheader,
13978 Autoscan, Autoupdate, and Automake, you should be aware of the
13979 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
13980 the namespace of a package that does not own the macro or shell code you
13981 are writing.
13983 To ensure that your macros don't conflict with present or future
13984 Autoconf macros, you should prefix your own macro names and any shell
13985 variables they use with some other sequence.  Possibilities include your
13986 initials, or an abbreviation for the name of your organization or
13987 software package.  Historically, people have not always followed the
13988 rule of using a namespace appropriate for their package, and this has
13989 made it difficult for determining the origin of a macro (and where to
13990 report bugs about that macro), as well as difficult for the true
13991 namespace owner to add new macros without interference from pre-existing
13992 uses of third-party macros.  Perhaps the best example of this confusion
13993 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
13994 to Gettext.
13996 Most of the Autoconf macros' names follow a structured naming convention
13997 that indicates the kind of feature check by the name.  The macro names
13998 consist of several words, separated by underscores, going from most
13999 general to most specific.  The names of their cache variables use the
14000 same convention (@pxref{Cache Variable Names}, for more information on
14001 them).
14003 The first word of the name after the namespace initials (such as
14004 @samp{AC_}) usually tells the category
14005 of the feature being tested.  Here are the categories used in Autoconf for
14006 specific test macros, the kind of macro that you are more likely to
14007 write.  They are also used for cache variables, in all-lowercase.  Use
14008 them where applicable; where they're not, invent your own categories.
14010 @table @code
14011 @item C
14012 C language builtin features.
14013 @item DECL
14014 Declarations of C variables in header files.
14015 @item FUNC
14016 Functions in libraries.
14017 @item GROUP
14018 Posix group owners of files.
14019 @item HEADER
14020 Header files.
14021 @item LIB
14022 C libraries.
14023 @item PROG
14024 The base names of programs.
14025 @item MEMBER
14026 Members of aggregates.
14027 @item SYS
14028 Operating system features.
14029 @item TYPE
14030 C builtin or declared types.
14031 @item VAR
14032 C variables in libraries.
14033 @end table
14035 After the category comes the name of the particular feature being
14036 tested.  Any further words in the macro name indicate particular aspects
14037 of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
14038 C compiler supports ISO Standard C.
14040 An internal macro should have a name that starts with an underscore;
14041 Autoconf internals should therefore start with @samp{_AC_}.
14042 Additionally, a macro that is an internal subroutine of another macro
14043 should have a name that starts with an underscore and the name of that
14044 other macro, followed by one or more words saying what the internal
14045 macro does.  For example, @code{AC_PATH_X} has internal macros
14046 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14048 @node Reporting Messages
14049 @section Reporting Messages
14050 @cindex Messages, from @command{autoconf}
14052 When macros statically diagnose abnormal situations, benign or fatal, it
14053 is possible to make @command{autoconf} detect the problem, and refuse to
14054 create @file{configure} in the case of an error.  The macros in this
14055 section are considered obsolescent, and new code should use M4sugar
14056 macros for this purpose, see @ref{Diagnostic Macros}.
14058 On the other hand, it is possible to want to detect errors when
14059 @command{configure} is run, which are dependent on the environment of
14060 the user rather than the maintainer.  For dynamic diagnostics, see
14061 @ref{Printing Messages}.
14063 @defmac AC_DIAGNOSE (@var{category}, @var{message})
14064 @acindex{DIAGNOSE}
14065 Report @var{message} as a warning (or as an error if requested by the
14066 user) if warnings of the @var{category} are turned on.  This macro is
14067 obsolescent; you are encouraged to use:
14068 @example
14069 m4_warn([@var{category}], [@var{message}])
14070 @end example
14071 @noindent
14072 instead.  @xref{m4_warn}, for more details, including valid
14073 @var{category} names.
14074 @end defmac
14076 @defmac AC_WARNING (@var{message})
14077 @acindex{WARNING}
14078 Report @var{message} as a syntax warning.  This macro is obsolescent;
14079 you are encouraged to use:
14080 @example
14081 m4_warn([syntax], [@var{message}])
14082 @end example
14083 @noindent
14084 instead.  @xref{m4_warn}, for more details, as well as better
14085 finer-grained categories of warnings (not all problems have to do with
14086 syntax).
14087 @end defmac
14089 @defmac AC_FATAL (@var{message})
14090 @acindex{FATAL}
14091 Report a severe error @var{message}, and have @command{autoconf} die.
14092 This macro is obsolescent; you are encouraged to use:
14093 @example
14094 m4_fatal([@var{message}])
14095 @end example
14096 @noindent
14097 instead.  @xref{m4_fatal}, for more details.
14098 @end defmac
14100 When the user runs @samp{autoconf -W error}, warnings from
14101 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
14102 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
14104 @node Dependencies Between Macros
14105 @section Dependencies Between Macros
14106 @cindex Dependencies between macros
14108 Some Autoconf macros depend on other macros having been called first in
14109 order to work correctly.  Autoconf provides a way to ensure that certain
14110 macros are called if needed and a way to warn the user if macros are
14111 called in an order that might cause incorrect operation.
14113 @menu
14114 * Prerequisite Macros::         Ensuring required information
14115 * Suggested Ordering::          Warning about possible ordering problems
14116 * One-Shot Macros::             Ensuring a macro is called only once
14117 @end menu
14119 @node Prerequisite Macros
14120 @subsection Prerequisite Macros
14121 @cindex Prerequisite macros
14122 @cindex Macros, prerequisites
14124 A macro that you write might need to use values that have previously
14125 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
14126 examines the output of @code{flex} or @code{lex}, so it depends on
14127 @code{AC_PROG_LEX} having been called first to set the shell variable
14128 @code{LEX}.
14130 Rather than forcing the user of the macros to keep track of the
14131 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14132 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
14133 called if it is needed, and only called once.
14135 @defmac AC_REQUIRE (@var{macro-name})
14136 @acindex{REQUIRE}
14137 If the M4 macro @var{macro-name} has not already been called, call it
14138 (without any arguments).  Make sure to quote @var{macro-name} with
14139 square brackets.  @var{macro-name} must have been defined using
14140 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14141 that it has been called.
14143 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14144 must not be called from the top level.  Also, it does not make sense to
14145 require a macro that takes parameters.
14146 @end defmac
14148 @code{AC_REQUIRE} is often misunderstood.  It really implements
14149 dependencies between macros in the sense that if one macro depends upon
14150 another, the latter is expanded @emph{before} the body of the
14151 former.  To be more precise, the required macro is expanded before
14152 the outermost defined macro in the current expansion stack.
14153 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14154 @code{FOO}.  For instance, this definition of macros:
14156 @example
14157 @group
14158 AC_DEFUN([TRAVOLTA],
14159 [test "$body_temperature_in_celsius" -gt "38" &&
14160   dance_floor=occupied])
14161 AC_DEFUN([NEWTON_JOHN],
14162 [test "x$hair_style" = xcurly &&
14163   dance_floor=occupied])
14164 @end group
14166 @group
14167 AC_DEFUN([RESERVE_DANCE_FLOOR],
14168 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14169   AC_REQUIRE([TRAVOLTA])
14170   AC_REQUIRE([NEWTON_JOHN])
14171 fi])
14172 @end group
14173 @end example
14175 @noindent
14176 with this @file{configure.ac}
14178 @example
14179 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14180 RESERVE_DANCE_FLOOR
14181 if test "x$dance_floor" = xoccupied; then
14182   AC_MSG_ERROR([cannot pick up here, let's move])
14184 @end example
14186 @noindent
14187 does not leave you with a better chance to meet a kindred soul at
14188 other times than Saturday night since it expands into:
14190 @example
14191 @group
14192 test "$body_temperature_in_Celsius" -gt "38" &&
14193   dance_floor=occupied
14194 test "x$hair_style" = xcurly &&
14195   dance_floor=occupied
14197 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14201 @end group
14202 @end example
14204 This behavior was chosen on purpose: (i) it prevents messages in
14205 required macros from interrupting the messages in the requiring macros;
14206 (ii) it avoids bad surprises when shell conditionals are used, as in:
14208 @example
14209 @group
14210 if @dots{}; then
14211   AC_REQUIRE([SOME_CHECK])
14213 @dots{}
14214 SOME_CHECK
14215 @end group
14216 @end example
14218 However, this implementation can lead to another class of problems.
14219 Consider the case where an outer macro first expands, then indirectly
14220 requires, an inner macro:
14222 @example
14223 AC_DEFUN([TESTA], [[echo in A
14224 if test -n "$SEEN_A" ; then echo duplicate ; fi
14225 SEEN_A=:]])
14226 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14227 if test -z "$SEEN_A" ; then echo bug ; fi]])
14228 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14229 AC_DEFUN([OUTER], [[echo in OUTER]
14230 TESTA
14231 TESTC])
14232 OUTER
14233 @end example
14235 @noindent
14236 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14237 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14238 of @code{OUTER}, but because @code{TESTA} had already been directly
14239 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
14240 @code{TESTB} occurs prior to its prerequisites, leading to the following
14241 output:
14243 @example
14244 in B
14246 in OUTER
14247 in A
14248 in C
14249 @end example
14251 @noindent
14252 Newer Autoconf is smart enough to recognize this situation, and hoists
14253 @code{TESTA} even though it has already been expanded, but issues a
14254 syntax warning in the process.  This is because the hoisted expansion of
14255 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14256 redundant code, and causes its own set of problems if the hoisted macro
14257 is not idempotent:
14259 @example
14260 in A
14261 in B
14262 in OUTER
14263 in A
14264 duplicate
14265 in C
14266 @end example
14268 The bug is not in Autoconf, but in the macro definitions.  If you ever
14269 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14270 that the macro only needs to be expanded once.  But to enforce this,
14271 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14272 this only helps in Autoconf 2.64 or newer), or all
14273 uses of that macro should be through @code{AC_REQUIRE}; directly
14274 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14275 eliminate redundant expansion.  In the example, this rule of thumb was
14276 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14277 directly expands it.  One way of fixing the bug is to factor
14278 @code{TESTA} into two macros, the portion designed for direct and
14279 repeated use (here, named @code{TESTA}), and the portion designed for
14280 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14281 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
14282 calling convention according to their needs:
14284 @example
14285 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14286 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14287 if test -n "$SEEN_A" ; then echo duplicate ; fi
14288 SEEN_A=:]])
14289 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14290 if test -z "$SEEN_A" ; then echo bug ; fi]])
14291 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14292 AC_DEFUN([OUTER], [[echo in OUTER]
14293 TESTA
14294 TESTC])
14295 OUTER
14296 @end example
14298 @noindent
14299 the resulting output will then obey all dependency rules and avoid any
14300 syntax warnings, whether the script is built with old or new Autoconf
14301 versions:
14303 @example
14304 in A_PREREQ
14305 in B
14306 in OUTER
14307 in A
14308 in C
14309 @end example
14311 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
14312 enforce expansion of required macros outside of shell conditional
14313 constructs.  You are furthermore encouraged, although not required, to
14314 put all @code{AC_REQUIRE} calls
14315 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
14316 lines they leave.
14318 @node Suggested Ordering
14319 @subsection Suggested Ordering
14320 @cindex Macros, ordering
14321 @cindex Ordering macros
14323 Some macros should be run before another macro if both are called, but
14324 neither @emph{requires} that the other be called.  For example, a macro
14325 that changes the behavior of the C compiler should be called before any
14326 macros that run the C compiler.  Many of these dependencies are noted in
14327 the documentation.
14329 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14330 with this kind of dependency appear out of order in a
14331 @file{configure.ac} file.  The warning occurs when creating
14332 @command{configure} from @file{configure.ac}, not when running
14333 @command{configure}.
14335 For example, @code{AC_PROG_CPP} checks whether the C compiler
14336 can run the C preprocessor when given the @option{-E} option.  It should
14337 therefore be called after any macros that change which C compiler is
14338 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
14340 @example
14341 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14342 @end example
14344 @noindent
14345 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14346 when @code{AC_PROG_CC} is called.
14348 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14349 @acindex{BEFORE}
14350 Make M4 print a warning message to the standard error output if
14351 @var{called-macro-name} has already been called.  @var{this-macro-name}
14352 should be the name of the macro that is calling @code{AC_BEFORE}.  The
14353 macro @var{called-macro-name} must have been defined using
14354 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14355 that it has been called.
14356 @end defmac
14358 @node One-Shot Macros
14359 @subsection One-Shot Macros
14360 @cindex One-shot macros
14361 @cindex Macros, called once
14363 Some macros should be called only once, either because calling them
14364 multiple time is unsafe, or because it is bad style.  For instance
14365 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14366 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
14367 sense to run these expensive checks more than once.  Such one-shot
14368 macros can be defined using @code{AC_DEFUN_ONCE}.
14370 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14371 @acindex{DEFUN_ONCE}
14372 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14373 Definitions}), but add additional logic that guarantees that only the
14374 first use of the macro (whether by direct expansion or
14375 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14376 expansion will occur before the start of any enclosing macro defined by
14377 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
14378 Generally, it does not make sense for @var{macro-body} to use parameters
14379 such as @code{$1}.
14380 @end defmac
14382 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14383 emit a warning if it was directly expanded a second time, so for
14384 portability, it is better to use @code{AC_REQUIRE} than direct
14385 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14386 (@pxref{Prerequisite Macros}).
14388 @node Obsoleting Macros
14389 @section Obsoleting Macros
14390 @cindex Obsoleting macros
14391 @cindex Macros, obsoleting
14393 Configuration and portability technology has evolved over the years.
14394 Often better ways of solving a particular problem are developed, or
14395 ad-hoc approaches are systematized.  This process has occurred in many
14396 parts of Autoconf.  One result is that some of the macros are now
14397 considered @dfn{obsolete}; they still work, but are no longer considered
14398 the best thing to do, hence they should be replaced with more modern
14399 macros.  Ideally, @command{autoupdate} should replace the old macro calls
14400 with their modern implementation.
14402 Autoconf provides a simple means to obsolete a macro.
14404 @anchor{AU_DEFUN}
14405 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
14406 @auindex{DEFUN}
14407 Define @var{old-macro} as @var{implementation}.  The only difference
14408 with @code{AC_DEFUN} is that the user is warned that
14409 @var{old-macro} is now obsolete.
14411 If she then uses @command{autoupdate}, the call to @var{old-macro} is
14412 replaced by the modern @var{implementation}.  @var{message} should
14413 include information on what to do after running @command{autoupdate};
14414 @command{autoupdate} prints it as a warning, and includes it
14415 in the updated @file{configure.ac} file.
14417 The details of this macro are hairy: if @command{autoconf} encounters an
14418 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
14419 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
14420 macros are expanded here, while all other macros are disabled and
14421 appear literally in the updated @file{configure.ac}.
14422 @end defmac
14424 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
14425 @auindex{ALIAS}
14426 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
14427 with the same parameters.  This happens for example if the macro was renamed.
14428 @end defmac
14430 @node Coding Style
14431 @section Coding Style
14432 @cindex Coding style
14434 The Autoconf macros follow a strict coding style.  You are encouraged to
14435 follow this style, especially if you intend to distribute your macro,
14436 either by contributing it to Autoconf itself or the
14437 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
14438 Archive}, or by other means.
14440 The first requirement is to pay great attention to the quotation.  For
14441 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
14443 Do not try to invent new interfaces.  It is likely that there is a macro
14444 in Autoconf that resembles the macro you are defining: try to stick to
14445 this existing interface (order of arguments, default values, etc.).  We
14446 @emph{are} conscious that some of these interfaces are not perfect;
14447 nevertheless, when harmless, homogeneity should be preferred over
14448 creativity.
14450 Be careful about clashes both between M4 symbols and between shell
14451 variables.
14453 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
14454 you are unlikely to generate conflicts.  Nevertheless, when you need to
14455 set a special value, @emph{avoid using a regular macro name}; rather,
14456 use an ``impossible'' name.  For instance, up to version 2.13, the macro
14457 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
14458 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
14459 But since there is a macro named @code{AC_SUBST_FILE}, it was just
14460 impossible to @samp{AC_SUBST(FILE)}!  In this case,
14461 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
14462 have been used (yes, with the parentheses).
14463 @c or better yet, high-level macros such as @code{m4_expand_once}
14465 No Autoconf macro should ever enter the user-variable name space; i.e.,
14466 except for the variables that are the actual result of running the
14467 macro, all shell variables should start with @code{ac_}.  In
14468 addition, small macros or any macro that is likely to be embedded in
14469 other macros should be careful not to use obvious names.
14471 @cindex @code{dnl}
14472 Do not use @code{dnl} to introduce comments: most of the comments you
14473 are likely to write are either header comments which are not output
14474 anyway, or comments that should make their way into @file{configure}.
14475 There are exceptional cases where you do want to comment special M4
14476 constructs, in which case @code{dnl} is right, but keep in mind that it
14477 is unlikely.
14479 M4 ignores the leading blanks and newlines before each argument.
14480 Use this feature to
14481 indent in such a way that arguments are (more or less) aligned with the
14482 opening parenthesis of the macro being called.  For instance, instead of
14484 @example
14485 AC_CACHE_CHECK(for EMX OS/2 environment,
14486 ac_cv_emxos2,
14487 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
14488 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
14489 @end example
14491 @noindent
14492 write
14494 @example
14495 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14496 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14497                    [ac_cv_emxos2=yes],
14498                    [ac_cv_emxos2=no])])
14499 @end example
14501 @noindent
14502 or even
14504 @example
14505 AC_CACHE_CHECK([for EMX OS/2 environment],
14506                [ac_cv_emxos2],
14507                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
14508                                                    [return __EMX__;])],
14509                                   [ac_cv_emxos2=yes],
14510                                   [ac_cv_emxos2=no])])
14511 @end example
14513 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
14514 cross-compiling, provide a pessimistic value (typically @samp{no}).
14516 Feel free to use various tricks to prevent auxiliary tools, such as
14517 syntax-highlighting editors, from behaving improperly.  For instance,
14518 instead of:
14520 @example
14521 m4_bpatsubst([$1], [$"])
14522 @end example
14524 @noindent
14527 @example
14528 m4_bpatsubst([$1], [$""])
14529 @end example
14531 @noindent
14532 so that Emacsen do not open an endless ``string'' at the first quote.
14533 For the same reasons, avoid:
14535 @example
14536 test $[#] != 0
14537 @end example
14539 @noindent
14540 and use:
14542 @example
14543 test $[@@%:@@] != 0
14544 @end example
14546 @noindent
14547 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
14548 breaking the bracket-matching highlighting from Emacsen.  Note the
14549 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
14550 not escape when it is unnecessary.  Common examples of useless quotation
14551 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
14552 etc.  If you add portability issues to the picture, you'll prefer
14553 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
14554 better than hacking Autoconf @code{:-)}.
14556 When using @command{sed}, don't use @option{-e} except for indenting
14557 purposes.  With the @code{s} and @code{y} commands, the preferred
14558 separator is @samp{/} unless @samp{/} itself might appear in the pattern
14559 or replacement, in which case you should use @samp{|}, or optionally
14560 @samp{,} if you know the pattern and replacement cannot contain a file
14561 name.  If none of these characters will do, choose a printable character
14562 that cannot appear in the pattern or replacement.  Characters from the
14563 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
14564 replacement might contain a file name, since they have special meaning
14565 to the shell and are less likely to occur in file names.
14567 @xref{Macro Definitions}, for details on how to define a macro.  If a
14568 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
14569 of an @code{AC_REQUIRE} directive, and macros required by other macros
14570 inside arguments do not need to be expanded before this macro, then
14571 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
14572 Also take into account that public third-party macros need to use
14573 @code{AC_DEFUN} in order to be found by @command{aclocal}
14574 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14575 All the @code{AC_REQUIRE} statements should be at the beginning of the
14576 macro, and each statement should be followed by @code{dnl}.
14578 You should not rely on the number of arguments: instead of checking
14579 whether an argument is missing, test that it is not empty.  It provides
14580 both a simpler and a more predictable interface to the user, and saves
14581 room for further arguments.
14583 Unless the macro is short, try to leave the closing @samp{])} at the
14584 beginning of a line, followed by a comment that repeats the name of the
14585 macro being defined.  This introduces an additional newline in
14586 @command{configure}; normally, that is not a problem, but if you want to
14587 remove it you can use @samp{[]dnl} on the last line.  You can similarly
14588 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
14589 is recommended instead of @samp{dnl} to ensure that M4 does not
14590 interpret the @samp{dnl} as being attached to the preceding text or
14591 macro output.  For example, instead of:
14593 @example
14594 AC_DEFUN([AC_PATH_X],
14595 [AC_MSG_CHECKING([for X])
14596 AC_REQUIRE_CPP()
14597 @r{# @dots{}omitted@dots{}}
14598   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14599 fi])
14600 @end example
14602 @noindent
14603 you would write:
14605 @example
14606 AC_DEFUN([AC_PATH_X],
14607 [AC_REQUIRE_CPP()[]dnl
14608 AC_MSG_CHECKING([for X])
14609 @r{# @dots{}omitted@dots{}}
14610   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14611 fi[]dnl
14612 ])# AC_PATH_X
14613 @end example
14615 If the macro is long, try to split it into logical chunks.  Typically,
14616 macros that check for a bug in a function and prepare its
14617 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
14618 this setup.  Do not hesitate to introduce auxiliary macros to factor
14619 your code.
14621 In order to highlight the recommended coding style, here is a macro
14622 written the old way:
14624 @example
14625 dnl Check for EMX on OS/2.
14626 dnl _AC_EMXOS2
14627 AC_DEFUN(_AC_EMXOS2,
14628 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
14629 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
14630 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
14631 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
14632 @end example
14634 @noindent
14635 and the new way:
14637 @example
14638 # _AC_EMXOS2
14639 # ----------
14640 # Check for EMX on OS/2.
14641 m4_define([_AC_EMXOS2],
14642 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14643 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14644                    [ac_cv_emxos2=yes],
14645                    [ac_cv_emxos2=no])])
14646 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
14647 ])# _AC_EMXOS2
14648 @end example
14653 @c ============================================= Portable Shell Programming
14655 @node Portable Shell
14656 @chapter Portable Shell Programming
14657 @cindex Portable shell programming
14659 When writing your own checks, there are some shell-script programming
14660 techniques you should avoid in order to make your code portable.  The
14661 Bourne shell and upward-compatible shells like the Korn shell and Bash
14662 have evolved over the years, and many features added to the original
14663 System7 shell are now supported on all interesting porting targets.
14664 However, the following discussion between Russ Allbery and Robert Lipe
14665 is worth reading:
14667 @noindent
14668 Russ Allbery:
14670 @quotation
14671 The GNU assumption that @command{/bin/sh} is the one and only shell
14672 leads to a permanent deadlock.  Vendors don't want to break users'
14673 existing shell scripts, and there are some corner cases in the Bourne
14674 shell that are not completely compatible with a Posix shell.  Thus,
14675 vendors who have taken this route will @emph{never} (OK@dots{}``never say
14676 never'') replace the Bourne shell (as @command{/bin/sh}) with a
14677 Posix shell.
14678 @end quotation
14680 @noindent
14681 Robert Lipe:
14683 @quotation
14684 This is exactly the problem.  While most (at least most System V's) do
14685 have a Bourne shell that accepts shell functions most vendor
14686 @command{/bin/sh} programs are not the Posix shell.
14688 So while most modern systems do have a shell @emph{somewhere} that meets the
14689 Posix standard, the challenge is to find it.
14690 @end quotation
14692 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
14693 is to find such a shell.  But to prevent trouble, if you're not using
14694 M4sh you should not take advantage of features that were added after Unix
14695 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
14696 negated character classes, or even @command{unset}.  @code{#} comments,
14697 while not in Unix version 7, were retrofitted in the original Bourne
14698 shell and can be assumed to be part of the least common denominator.
14700 On the other hand, if you're using M4sh you can assume that the shell
14701 has the features that were added in SVR2 (circa 1984), including shell
14702 functions,
14703 @command{return}, @command{unset}, and I/O redirection for builtins.  For
14704 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
14705 However, some pitfalls have to be avoided for portable use of these
14706 constructs; these will be documented in the rest of this chapter.
14707 See in particular @ref{Shell Functions} and @ref{Limitations of
14708 Builtins, , Limitations of Shell Builtins}.
14710 Some ancient systems have quite
14711 small limits on the length of the @samp{#!} line; for instance, 32
14712 bytes (not including the newline) on SunOS 4.
14713 However, these ancient systems are no longer of practical concern.
14715 The set of external programs you should run in a @command{configure} script
14716 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
14717 Makefiles, standards, The GNU Coding Standards}, for the list.  This
14718 restriction allows users to start out with a fairly small set of
14719 programs and build the rest, avoiding too many interdependencies between
14720 packages.
14722 Some of these external utilities have a portable subset of features; see
14723 @ref{Limitations of Usual Tools}.
14725 There are other sources of documentation about shells.  The
14726 specification for the Posix
14727 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
14728 Command Language}, though more generous than the restrictive shell
14729 subset described above, is fairly portable nowadays.  Also please see
14730 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
14732 @menu
14733 * Shellology::                  A zoology of shells
14734 * Here-Documents::              Quirks and tricks
14735 * File Descriptors::            FDs and redirections
14736 * File System Conventions::     File names
14737 * Shell Pattern Matching::      Pattern matching
14738 * Shell Substitutions::         Variable and command expansions
14739 * Assignments::                 Varying side effects of assignments
14740 * Parentheses::                 Parentheses in shell scripts
14741 * Slashes::                     Slashes in shell scripts
14742 * Special Shell Variables::     Variables you should not change
14743 * Shell Functions::             What to look out for if you use them
14744 * Limitations of Builtins::     Portable use of not so portable /bin/sh
14745 * Limitations of Usual Tools::  Portable use of portable tools
14746 @end menu
14748 @node Shellology
14749 @section Shellology
14750 @cindex Shellology
14752 There are several families of shells, most prominently the Bourne family
14753 and the C shell family which are deeply incompatible.  If you want to
14754 write portable shell scripts, avoid members of the C shell family.  The
14755 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
14756 Shell difference FAQ} includes a small history of Posix shells, and a
14757 comparison between several of them.
14759 Below we describe some of the members of the Bourne shell family.
14761 @table @asis
14762 @item Ash
14763 @cindex Ash
14764 Ash is often used on GNU/Linux and BSD
14765 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
14766 bugs that are fixed in the 0.3.x series, but portable shell scripts
14767 should work around them, since version 0.2 is still shipped with many
14768 GNU/Linux distributions.
14770 To be compatible with Ash 0.2:
14772 @itemize @minus
14773 @item
14774 don't use @samp{$?} after expanding empty or unset variables,
14775 or at the start of an @command{eval}:
14777 @example
14778 foo=
14779 false
14780 $foo
14781 echo "Do not use it: $?"
14782 false
14783 eval 'echo "Do not use it: $?"'
14784 @end example
14786 @item
14787 don't use command substitution within variable expansion:
14789 @example
14790 cat $@{FOO=`bar`@}
14791 @end example
14793 @item
14794 beware that single builtin substitutions are not performed by a
14795 subshell, hence their effect applies to the current shell!  @xref{Shell
14796 Substitutions}, item ``Command Substitution''.
14797 @end itemize
14799 @item Bash
14800 @cindex Bash
14801 To detect whether you are running Bash, test whether
14802 @code{BASH_VERSION} is set.  To require
14803 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
14804 Mode, , Bash Posix Mode, bash, The GNU Bash Reference
14805 Manual}, for details.
14807 @item Bash 2.05 and later
14808 @cindex Bash 2.05 and later
14809 Versions 2.05 and later of Bash use a different format for the
14810 output of the @command{set} builtin, designed to make evaluating its
14811 output easier.  However, this output is not compatible with earlier
14812 versions of Bash (or with many other shells, probably).  So if
14813 you use Bash 2.05 or higher to execute @command{configure},
14814 you'll need to use Bash 2.05 for all other build tasks as well.
14816 @item Ksh
14817 @cindex Ksh
14818 @cindex Korn shell
14819 @prindex @samp{ksh}
14820 @prindex @samp{ksh88}
14821 @prindex @samp{ksh93}
14822 The Korn shell is compatible with the Bourne family and it mostly
14823 conforms to Posix.  It has two major variants commonly
14824 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
14825 release.  It is usually called @command{ksh}, but is called @command{sh}
14826 on some hosts if you set your path appropriately.
14828 Solaris systems have three variants:
14829 @prindex @command{/usr/bin/ksh} on Solaris
14830 @command{/usr/bin/ksh} is @samp{ksh88}; it is
14831 standard on Solaris 2.0 and later.
14832 @prindex @command{/usr/xpg4/bin/sh} on Solaris
14833 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
14834 @samp{ksh88}; it is standard on Solaris 9 and later.
14835 @prindex @command{/usr/dt/bin/dtksh} on Solaris
14836 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
14837 Variants that are not standard may be parts of optional
14838 packages.  There is no extra charge for these packages, but they are
14839 not part of a minimal OS install and therefore some installations may
14840 not have it.
14842 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
14843 is also available as @command{/usr/bin/posix/sh}.  If the environment
14844 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
14845 the standard shell conform to Posix.
14847 @item Pdksh
14848 @prindex @samp{pdksh}
14849 A public-domain clone of the Korn shell called @command{pdksh} is widely
14850 available: it has most of the @samp{ksh88} features along with a few of
14851 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
14852 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
14853 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
14854 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
14855 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
14856 at least one respect, see @ref{Shell Substitutions}.
14858 @item Zsh
14859 @cindex Zsh
14860 To detect whether you are running @command{zsh}, test whether
14861 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
14862 compatible with the Bourne shell: you must execute @samp{emulate sh},
14863 and for @command{zsh} versions before 3.1.6-dev-18 you must also
14864 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
14865 zsh, The Z Shell Manual}, for details.
14867 The default Mac OS X @command{sh} was originally Zsh; it was changed to
14868 Bash in Mac OS X 10.2.
14869 @end table
14871 @node Here-Documents
14872 @section Here-Documents
14873 @cindex Here-documents
14874 @cindex Shell here-documents
14876 Don't rely on @samp{\} being preserved just because it has no special
14877 meaning together with the next symbol.  In the native @command{sh}
14878 on OpenBSD 2.7 @samp{\"} expands to @samp{"} in here-documents with
14879 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
14880 use @samp{\\} to get @samp{\}.
14882 With OpenBSD 2.7's @command{sh}
14884 @example
14885 @group
14886 $ @kbd{cat <<EOF
14887 > \" \\
14888 > EOF}
14889 " \
14890 @end group
14891 @end example
14893 @noindent
14894 and with Bash:
14896 @example
14897 @group
14898 bash-2.04$ @kbd{cat <<EOF
14899 > \" \\
14900 > EOF}
14901 \" \
14902 @end group
14903 @end example
14905 Some shells mishandle large here-documents: for example,
14906 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
14907 derived from Korn shell version M-12/28/93d, mishandle braced variable
14908 expansion that crosses a 1024- or 4096-byte buffer boundary
14909 within a here-document.  Only the part of the variable name after the boundary
14910 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
14911 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
14912 boundary, the shell reports an error, as if you used @code{$@{@}}.
14913 Instead of @code{$@{variable-default@}}, the shell may expand
14914 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
14915 be worked around by omitting the braces: @code{$variable}.  The bug was
14916 fixed in
14917 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
14918 still shipping older versions with the bug.
14920 Empty here-documents are not portable either; with the following code,
14921 @command{zsh} up to at least version 4.3.10 creates a file with a single
14922 newline, whereas other shells create an empty file:
14924 @example
14925 cat >file <<EOF
14927 @end example
14929 Many shells (including the Bourne shell) implement here-documents
14930 inefficiently.  In particular, some shells can be extremely inefficient when
14931 a single statement contains many here-documents.  For instance if your
14932 @file{configure.ac} includes something like:
14934 @example
14935 @group
14936 if <cross_compiling>; then
14937   assume this and that
14938 else
14939   check this
14940   check that
14941   check something else
14942   @dots{}
14943   on and on forever
14944   @dots{}
14946 @end group
14947 @end example
14949 A shell parses the whole @code{if}/@code{fi} construct, creating
14950 temporary files for each here-document in it.  Some shells create links
14951 for such here-documents on every @code{fork}, so that the clean-up code
14952 they had installed correctly removes them.  It is creating the links
14953 that can take the shell forever.
14955 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
14956 @code{if}/@code{fi} constructs, would improve the performance
14957 significantly.  Anyway, this kind of construct is not exactly the
14958 typical use of Autoconf.  In fact, it's even not recommended, because M4
14959 macros can't look into shell conditionals, so we may fail to expand a
14960 macro when it was expanded before in a conditional path, and the
14961 condition turned out to be false at runtime, and we end up not
14962 executing the macro at all.
14964 Be careful with the use of @samp{<<-} to unindent here-documents.  The
14965 behavior is only portable for stripping leading @key{TAB}s, and things
14966 can silently break if an overzealous editor converts to using leading
14967 spaces (not all shells are nice enough to warn about unterminated
14968 here-documents).
14970 @example
14971 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
14974 done
14975 $ @kbd{printf 'cat <<-x\n 1\n  2\n x\n' | bash-3.2 && echo done}
14977   2
14979 done
14980 @end example
14982 @node File Descriptors
14983 @section File Descriptors
14984 @cindex Descriptors
14985 @cindex File descriptors
14986 @cindex Shell file descriptors
14988 Most shells, if not all (including Bash, Zsh, Ash), output traces on
14989 stderr, even for subshells.  This might result in undesirable content
14990 if you meant to capture the standard-error output of the inner command:
14992 @example
14993 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
14994 $ @kbd{cat stderr}
14995 + eval echo foo >&2
14996 + echo foo
14998 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
14999 $ @kbd{cat stderr}
15000 + eval 'echo foo >&2'
15001 ++ echo foo
15003 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15004 @i{# Traces on startup files deleted here.}
15005 $ @kbd{cat stderr}
15006 +zsh:1> eval echo foo >&2
15007 +zsh:1> echo foo
15009 @end example
15011 @noindent
15012 One workaround is to grep out uninteresting lines, hoping not to remove
15013 good ones.
15015 If you intend to redirect both standard error and standard output,
15016 redirect standard output first.  This works better with HP-UX,
15017 since its shell mishandles tracing if standard error is redirected
15018 first:
15020 @example
15021 $ @kbd{sh -x -c ': 2>err >out'}
15022 + :
15023 + 2> err $ @kbd{cat err}
15024 1> out
15025 @end example
15027 Don't try to redirect the standard error of a command substitution.  It
15028 must be done @emph{inside} the command substitution.  When running
15029 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15030 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15032 On the other hand, some shells, such as Solaris or FreeBSD
15033 @command{/bin/sh}, warn about missing programs before performing
15034 redirections.  Therefore, to silently check whether a program exists, it
15035 is necessary to perform redirections on a subshell or brace group:
15036 @example
15037 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15038 nosuch: not found
15039 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15040 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15041 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15042 @end example
15044 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15045 shell pipeline.
15047 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15048 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15050 Some shells, like @command{ash}, don't recognize bi-directional
15051 redirection (@samp{<>}).  And even on shells that recognize it, it is
15052 not portable to use on fifos: Posix does not require read-write support
15053 for named pipes, and Cygwin does not support it:
15055 @example
15056 $ @kbd{mkfifo fifo}
15057 $ @kbd{exec 5<>fifo}
15058 $ @kbd{echo hi >&5}
15059 bash: echo: write error: Communication error on send
15060 @end example
15062 @noindent
15063 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15064 regular files when using @samp{<>}:
15066 @example
15067 $ @kbd{echo a > file}
15068 $ @kbd{bash -c ': 1<>file'; cat file}
15070 $ @kbd{dash -c ': 1<>file'; cat file}
15071 $ rm a
15072 @end example
15074 When catering to old systems, don't redirect the same file descriptor
15075 several times, as you are doomed to failure under Ultrix.
15077 @example
15078 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
15079 UWS V4.4 (Rev. 11)
15080 $ @kbd{eval 'echo matter >fullness' >void}
15081 illegal io
15082 $ @kbd{eval '(echo matter >fullness)' >void}
15083 illegal io
15084 $ @kbd{(eval '(echo matter >fullness)') >void}
15085 Ambiguous output redirect.
15086 @end example
15088 @noindent
15089 In each case the expected result is of course @file{fullness} containing
15090 @samp{matter} and @file{void} being empty.  However, this bug is
15091 probably not of practical concern to modern platforms.
15093 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15094 in a loop after the first iteration, even if it is redirected:
15096 @example
15097 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15098 $ @kbd{ls}
15100 @end example
15102 @noindent
15103 As a workaround, @command{echo} or @command{eval} can be used.
15105 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15106 subsidiary program.  If any of these descriptors is closed, the
15107 operating system may open an unspecified file for the descriptor in the
15108 new process image.  Posix says this may be done only if the subsidiary
15109 program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15110 it even for ordinary programs.
15112 Don't rely on open file descriptors being open in child processes.  In
15113 @command{ksh}, file descriptors above 2 which are opened using
15114 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15115 that involved in the fork-and-exec which runs a program or script).
15116 Thus, using @command{sh}, we have:
15118 @example
15119 $ @kbd{cat ./descrips}
15120 #!/bin/sh -
15121 echo hello >&5
15122 $ @kbd{exec 5>t}
15123 $ @kbd{./descrips}
15124 $ @kbd{cat t}
15125 hello
15127 @end example
15129 @noindent
15130 But using ksh:
15132 @example
15133 $ @kbd{exec 5>t}
15134 $ @kbd{./descrips}
15135 hello
15136 $ @kbd{cat t}
15138 @end example
15140 @noindent
15141 Within the process which runs the @samp{descrips} script, file
15142 descriptor 5 is closed.
15144 Don't rely on duplicating a closed file descriptor to cause an
15145 error.  With Solaris @command{/bin/sh}, when the redirection fails, the
15146 output goes to the original file descriptor.
15148 @example
15149 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15150 bash: 3: Bad file descriptor
15152 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15155 @end example
15157 Fortunately, an attempt to close an already closed file descriptor will
15158 portably succeed.  Likewise, it is safe to use either style of
15159 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15160 even if it doesn't match the read/write mode that the file descriptor
15161 was opened with.
15163 DOS variants cannot rename or remove open files, such as in
15164 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15165 perfectly portable among Posix hosts.
15167 A few ancient systems reserved some file descriptors.  By convention,
15168 file descriptor 3 was opened to @file{/dev/tty} when you logged into
15169 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
15170 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
15171 1990), though we don't now remember what it was.  Both these systems are
15172 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15173 other file descriptors.
15175 On the other hand, you can't portably use multi-digit file descriptors.
15176 Solaris @command{ksh} doesn't understand any file descriptor larger than
15177 @samp{9}:
15179 @example
15180 $ @kbd{bash -c 'exec 10>&-'; echo $?}
15182 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
15184 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
15185 ksh[1]: exec: 10: not found
15187 @end example
15189 @node File System Conventions
15190 @section File System Conventions
15191 @cindex File system conventions
15193 Autoconf uses shell-script processing extensively, so the file names
15194 that it processes should not contain characters that are special to the
15195 shell.  Special characters include space, tab, newline, NUL, and
15196 the following:
15198 @example
15199 " # $ & ' ( ) * ; < = > ? [ \ ` |
15200 @end example
15202 Also, file names should not begin with @samp{~} or @samp{-}, and should
15203 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
15204 immediately after @samp{:}.  On Posix-like platforms, directory names
15205 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
15206 path separator.
15208 These restrictions apply not only to the files that you distribute, but
15209 also to the absolute file names of your source, build, and destination
15210 directories.
15212 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
15213 they should be avoided.
15215 Posix lets implementations treat leading @file{//} specially, but
15216 requires leading @file{///} and beyond to be equivalent to @file{/}.
15217 Most Unix variants treat @file{//} like @file{/}.  However, some treat
15218 @file{//} as a ``super-root'' that can provide access to files that are
15219 not otherwise reachable from @file{/}.  The super-root tradition began
15220 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
15221 has revived it.
15223 While @command{autoconf} and friends are usually run on some Posix
15224 variety, they can be used on other systems, most notably DOS
15225 variants.  This impacts several assumptions regarding file names.
15227 @noindent
15228 For example, the following code:
15230 @example
15231 case $foo_dir in
15232   /*) # Absolute
15233      ;;
15234   *)
15235      foo_dir=$dots$foo_dir ;;
15236 esac
15237 @end example
15239 @noindent
15240 fails to properly detect absolute file names on those systems, because
15241 they can use a drivespec, and usually use a backslash as directory
15242 separator.  If you want to be portable to DOS variants (at the
15243 price of rejecting valid but oddball Posix file names like @file{a:\b}),
15244 you can check for absolute file names like this:
15246 @cindex absolute file names, detect
15247 @example
15248 case $foo_dir in
15249   [\\/]* | ?:[\\/]* ) # Absolute
15250      ;;
15251   *)
15252      foo_dir=$dots$foo_dir ;;
15253 esac
15254 @end example
15256 @noindent
15257 Make sure you quote the brackets if appropriate and keep the backslash as
15258 first character (@pxref{case, , Limitations of Shell Builtins}).
15260 Also, because the colon is used as part of a drivespec, these systems don't
15261 use it as path separator.  When creating or accessing paths, you can use the
15262 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
15263 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
15264 starts up.
15266 File names need extra care as well.  While DOS variants
15267 that are Posixy enough to run @command{autoconf} (such as DJGPP)
15268 are usually able to handle long file names properly, there are still
15269 limitations that can seriously break packages.  Several of these issues
15270 can be easily detected by the
15271 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
15272 package.
15274 A short overview follows; problems are marked with SFN/LFN to
15275 indicate where they apply: SFN means the issues are only relevant to
15276 plain DOS, not to DOS under Microsoft Windows
15277 variants, while LFN identifies problems that exist even under
15278 Microsoft Windows variants.
15280 @table @asis
15281 @item No multiple dots (SFN)
15282 DOS cannot handle multiple dots in file names.  This is an especially
15283 important thing to remember when building a portable configure script,
15284 as @command{autoconf} uses a .in suffix for template files.
15286 This is perfectly OK on Posix variants:
15288 @example
15289 AC_CONFIG_HEADERS([config.h])
15290 AC_CONFIG_FILES([source.c foo.bar])
15291 AC_OUTPUT
15292 @end example
15294 @noindent
15295 but it causes problems on DOS, as it requires @samp{config.h.in},
15296 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
15297 to DOS-based environments, you should use this instead:
15299 @example
15300 AC_CONFIG_HEADERS([config.h:config.hin])
15301 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
15302 AC_OUTPUT
15303 @end example
15305 @item No leading dot (SFN)
15306 DOS cannot handle file names that start with a dot.  This is usually
15307 not important for @command{autoconf}.
15309 @item Case insensitivity (LFN)
15310 DOS is case insensitive, so you cannot, for example, have both a
15311 file called @samp{INSTALL} and a directory called @samp{install}.  This
15312 also affects @command{make}; if there's a file called @samp{INSTALL} in
15313 the directory, @samp{make install} does nothing (unless the
15314 @samp{install} target is marked as PHONY).
15316 @item The 8+3 limit (SFN)
15317 Because the DOS file system only stores the first 8 characters of
15318 the file name and the first 3 of the extension, those must be unique.
15319 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
15320 @file{foobar-prettybird.c} all resolve to the same file name
15321 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
15322 @file{foo.bartender}.
15324 The 8+3 limit is not usually a problem under Microsoft Windows, as it
15325 uses numeric
15326 tails in the short version of file names to make them unique.  However, a
15327 registry setting can turn this behavior off.  While this makes it
15328 possible to share file trees containing long file names between SFN
15329 and LFN environments, it also means the above problem applies there
15330 as well.
15332 @item Invalid characters (LFN)
15333 Some characters are invalid in DOS file names, and should therefore
15334 be avoided.  In a LFN environment, these are @samp{/}, @samp{\},
15335 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
15336 In a SFN environment, other characters are also invalid.  These
15337 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
15339 @item Invalid names (LFN)
15340 Some DOS file names are reserved, and cause problems if you
15341 try to use files with those names.  These names include @file{CON},
15342 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
15343 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
15344 File names are case insensitive, so even names like
15345 @file{aux/config.guess} are disallowed.
15347 @end table
15349 @node Shell Pattern Matching
15350 @section Shell Pattern Matching
15351 @cindex Shell pattern matching
15353 Nowadays portable patterns can use negated character classes like
15354 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
15355 some shells but not others; hence portable scripts should never use
15356 @samp{^} as the first character of a bracket pattern.
15358 Outside the C locale, patterns like @samp{[a-z]} are problematic since
15359 they may match characters that are not lower-case letters.
15361 @node Shell Substitutions
15362 @section Shell Substitutions
15363 @cindex Shell substitutions
15365 Contrary to a persistent urban legend, the Bourne shell does not
15366 systematically split variables and back-quoted expressions, in particular
15367 on the right-hand side of assignments and in the argument of @code{case}.
15368 For instance, the following code:
15370 @example
15371 case "$given_srcdir" in
15372 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
15373 *)  top_srcdir="$dots$given_srcdir" ;;
15374 esac
15375 @end example
15377 @noindent
15378 is more readable when written as:
15380 @example
15381 case $given_srcdir in
15382 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
15383 *)  top_srcdir=$dots$given_srcdir ;;
15384 esac
15385 @end example
15387 @noindent
15388 and in fact it is even @emph{more} portable: in the first case of the
15389 first attempt, the computation of @code{top_srcdir} is not portable,
15390 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
15391 for example Solaris 10 ksh:
15393 @example
15394 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
15395 ksh: : cannot execute
15396 ksh: bar | sed 's, ,,': cannot execute
15397 @end example
15399 @noindent
15400 Posix does not specify behavior for this sequence.  On the other hand,
15401 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by Posix,
15402 but in practice, not all shells understand it the same way: pdksh 5.2.14
15403 prints spurious quotes when in Posix mode:
15405 @example
15406 $ @kbd{echo "`echo \"hello\"`"}
15407 hello
15408 $ @kbd{set -o posix}
15409 $ @kbd{echo "`echo \"hello\"`"}
15410 "hello"
15411 @end example
15413 @noindent
15414 There is just no portable way to use double-quoted strings inside
15415 double-quoted back-quoted expressions (pfew!).
15417 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
15418 parameter expansions are elided during word splitting.  Meanwhile, zsh
15419 does not perform word splitting except when in Bourne compatibility
15420 mode.  In the example below, the correct behavior is to have five
15421 arguments to the function, and exactly two spaces on either side of the
15422 middle @samp{-}, since word splitting collapses multiple spaces in
15423 @samp{$f} but leaves empty arguments intact.
15425 @example
15426 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15427 3- - -
15428 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15429 5-  -  -
15430 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15431 3-   -   -
15432 $ @kbd{zsh -c 'emulate sh;}
15433 > @kbd{n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15434 5-  -  -
15435 @end example
15437 @noindent
15438 You can work around this by doing manual word splitting, such as using
15439 @samp{"$str" $list} rather than @samp{"$str"$list}.
15441 There are also portability pitfalls with particular expansions:
15443 @table @code
15444 @item $@@
15445 @cindex @code{"$@@"}
15446 One of the most famous shell-portability issues is related to
15447 @samp{"$@@"}.  When there are no positional arguments, Posix says
15448 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
15449 original Unix version 7 Bourne shell treated it as equivalent to
15450 @samp{""} instead, and this behavior survives in later implementations
15451 like Digital Unix 5.0.
15453 The traditional way to work around this portability problem is to use
15454 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
15455 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
15456 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
15458 @example
15459 zsh $ @kbd{emulate sh}
15460 zsh $ @kbd{for i in "$@@"; do echo $i; done}
15461 Hello World
15463 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
15464 Hello
15465 World
15467 @end example
15469 @noindent
15470 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
15471 @samp{"$@@"} because of the portability problems mentioned above.
15472 One workaround relies on Zsh's ``global aliases'' to convert
15473 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
15475 @example
15476 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
15477 @end example
15479 Zsh only recognizes this alias when a shell word matches it exactly;
15480 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
15481 case always yields at least one shell word, use plain @samp{"$@@"}.
15483 A more conservative workaround is to avoid @samp{"$@@"} if it is
15484 possible that there may be no positional arguments.  For example,
15485 instead of:
15487 @example
15488 cat conftest.c "$@@"
15489 @end example
15491 you can use this instead:
15493 @example
15494 case $# in
15495 0) cat conftest.c;;
15496 *) cat conftest.c "$@@";;
15497 esac
15498 @end example
15500 Autoconf macros often use the @command{set} command to update
15501 @samp{$@@}, so if you are writing shell code intended for
15502 @command{configure} you should not assume that the value of @samp{$@@}
15503 persists for any length of time.
15506 @item $@{10@}
15507 @cindex positional parameters
15508 The 10th, 11th, @dots{} positional parameters can be accessed only after
15509 a @code{shift}.  The 7th Edition shell reported an error if given
15510 @code{$@{10@}}, and
15511 Solaris 10 @command{/bin/sh} still acts that way:
15513 @example
15514 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
15515 $ @kbd{echo $@{10@}}
15516 bad substitution
15517 @end example
15519 @item $@{@var{var}:-@var{value}@}
15520 @c Info cannot handle `:' in index entries.
15521 @ifnotinfo
15522 @cindex @code{$@{@var{var}:-@var{value}@}}
15523 @end ifnotinfo
15524 @cindex @code{$@{@var{var}-@var{value}@}}
15525 Old BSD shells, including the Ultrix @code{sh}, don't accept the
15526 colon for any shell substitution, and complain and die.
15527 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
15528 However, all shells that support functions allow the use of colon in
15529 shell substitution, and since m4sh requires functions, you can portably
15530 use null variable substitution patterns in configure scripts.
15532 @item $@{@var{var}+@var{value}@}
15533 @cindex @code{$@{@var{var}+@var{value}@}}
15534 When using @samp{$@{@var{var}-@var{value}@}} or
15535 @samp{$@{@var{var}-@var{value}@}} for providing alternate substitutions,
15536 @var{value} must either be a single shell word, quoted, or in the
15537 context of an unquoted here-document.  Solaris
15538 @command{/bin/sh} complains otherwise.
15540 @example
15541 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
15542 /bin/sh: bad substitution
15543 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
15544 b c
15545 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
15546 b c
15547 $ @kbd{/bin/sh -c 'cat <<EOF
15548 $@{a-b c@}
15549 EOF}
15550 b c
15551 @end example
15553 According to Posix, if an expansion occurs inside double quotes, then
15554 the use of unquoted double quotes within @var{value} is unspecified, and
15555 any single quotes become literal characters; in that case, escaping must
15556 be done with backslash.  Likewise, the use of unquoted here-documents is
15557 a case where double quotes have unspecified results:
15559 @example
15560 $ @kbd{/bin/sh -c 'echo "$@{a-"b  c"@}"'}
15561 /bin/sh: bad substitution
15562 $ @kbd{ksh -c 'echo "$@{a-"b  c"@}"'}
15563 b c
15564 $ @kbd{bash -c 'echo "$@{a-"b  c"@}"'}
15565 b  c
15566 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b  c'\''@}'}
15567 b  c
15568 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b  c'\''@}"'}
15569 'b  c'
15570 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b  c\"@}"'}
15571 "b  c"
15572 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b  c@}"'}
15573 b  c
15574 $ @kbd{/bin/sh -c 'cat <<EOF
15575 $@{a-"b  c"@}
15576 EOF'}
15577 "b  c"
15578 $ @kbd{/bin/sh -c 'cat <<EOF
15579 $@{a-'b  c'@}
15580 EOF'}
15581 'b  c'
15582 $ @kbd{bash -c 'cat <<EOF
15583 $@{a-"b  c"@}
15584 EOF'}
15585 b  c
15586 $ @kbd{bash -c 'cat <<EOF
15587 $@{a-'b  c'@}
15588 EOF'}
15589 'b  c'
15590 @end example
15592 Perhaps the easiest way to work around quoting issues in a manner
15593 portable to all shells is to place the results in a temporary variable,
15594 then use @samp{$t} as the @var{value}, rather than trying to inline
15595 the expression needing quoting.
15597 @example
15598 $ @kbd{/bin/sh -c 't="a  b\"'\''@}\\"; echo "$@{a-$t@}"'}
15599 b  c"'@}\
15600 $ @kbd{ksh -c 't="a  b\"'\''@}\\"; echo "$@{a-$t@}"'}
15601 b  c"'@}\
15602 $ @kbd{bash -c 't="a  b\"'\''@}\\"; echo "$@{a-$t@}"'}
15603 b  c"'@}\
15604 @end example
15606 @item $@{@var{var}=@var{value}@}
15607 @cindex @code{$@{@var{var}=@var{value}@}}
15608 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
15609 to @var{var}, remember that even though the assignment to @var{var} does
15610 not undergo file name expansion, the result of the variable expansion
15611 does unless the expansion occurred within double quotes.  In particular,
15612 when using @command{:} followed by unquoted variable expansion for the
15613 side effect of setting a default value, if the final value of
15614 @samp{$var} contains any globbing characters (either from @var{value} or
15615 from prior contents), the shell has to spend time performing file name
15616 expansion and field splitting even though those results will not be
15617 used.  Therefore, it is a good idea to consider double quotes when performing
15618 default initialization; while remembering how this impacts any quoting
15619 characters appearing in @var{value}.
15621 @example
15622 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
15623 /usr/bin/*
15625 real    0m0.005s
15626 user    0m0.002s
15627 sys     0m0.003s
15628 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
15629 /usr/bin/*
15631 real    0m0.039s
15632 user    0m0.026s
15633 sys     0m0.009s
15634 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
15635 /usr/bin/*
15637 real    0m0.031s
15638 user    0m0.020s
15639 sys     0m0.010s
15641 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
15642 /usr/bin/*
15644 real    0m0.006s
15645 user    0m0.002s
15646 sys     0m0.003s
15647 @end example
15649 As with @samp{+} and @samp{-}, you must use quotes when using @samp{=}
15650 if the @var{value} contains more than one shell word; either single
15651 quotes for just the @var{value}, or double quotes around the entire
15652 expansion:
15654 @example
15655 $ @kbd{: $@{var1='Some words'@}}
15656 $ @kbd{: "$@{var2=like this@}"}
15657 $ @kbd{echo $var1 $var2}
15658 Some words like this
15659 @end example
15661 @noindent
15662 otherwise some shells, such as Solaris @command{/bin/sh} or on Digital
15663 Unix V 5.0, die because of a ``bad substitution''.  Meanwhile, Posix
15664 requires that with @samp{=}, quote removal happens prior to the
15665 assignment, and the expansion be the final contents of @var{var} without
15666 quoting (and thus subject to field splitting), in contrast to the
15667 behavior with @samp{-} passing the quoting through to the final
15668 expansion.  However, @command{bash} 4.1 does not obey this rule.
15670 @example
15671 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
15672 a  b
15673 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
15674 a b
15675 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
15676 a  b
15677 @end example
15679 Finally, Posix states that when mixing @samp{$@{a=b@}} with regular
15680 commands, it is unspecified whether the assignments affect the parent
15681 shell environment.  It is best to perform assignments independently from
15682 commands, to avoid the problems demonstrated in this example:
15684 @example
15685 $ @kbd{bash -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
15686 +b+b+
15688 $ @kbd{/bin/sh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
15689 ++b+
15691 $ @kbd{ksh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
15692 +b+b+
15694 @end example
15696 @item $@{@var{var}=@var{value}@}
15697 @cindex @code{$@{@var{var}=@var{literal}@}}
15698 Solaris @command{/bin/sh} has a frightening bug in its handling of
15699 literal assignments.  Imagine you need set a variable to a string containing
15700 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
15701 when the affected variable was already set.  This bug can be exercised
15702 by running:
15704 @example
15705 $ @kbd{unset foo}
15706 $ @kbd{foo=$@{foo='@}'@}}
15707 $ @kbd{echo $foo}
15709 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
15710 $ @kbd{echo $foo}
15712 $ @kbd{foo=$@{foo='@}'@}}
15713 $ @kbd{echo $foo}
15714 @}@}
15715  ^ ugh!
15716 @end example
15718 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
15719 though it is enclosed in single quotes.  The problem doesn't happen
15720 using double quotes, or when using a temporary variable holding the
15721 problematic string.
15723 @item $@{@var{var}=@var{expanded-value}@}
15724 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
15725 On Ultrix,
15726 running
15728 @example
15729 default="yu,yaa"
15730 : $@{var="$default"@}
15731 @end example
15733 @noindent
15734 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
15735 each char is set.  You don't observe the phenomenon using a simple
15736 @samp{echo $var} since apparently the shell resets the 8th bit when it
15737 expands $var.  Here are two means to make this shell confess its sins:
15739 @example
15740 $ @kbd{cat -v <<EOF
15741 $var
15742 EOF}
15743 @end example
15745 @noindent
15748 @example
15749 $ @kbd{set | grep '^var=' | cat -v}
15750 @end example
15752 One classic incarnation of this bug is:
15754 @example
15755 default="a b c"
15756 : $@{list="$default"@}
15757 for c in $list; do
15758   echo $c
15759 done
15760 @end example
15762 @noindent
15763 You'll get @samp{a b c} on a single line.  Why?  Because there are no
15764 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
15765 bit set, hence no IFS splitting is performed!!!
15767 One piece of good news is that Ultrix works fine with @samp{:
15768 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
15769 then that QNX 4.25 then sets @var{list} to the @emph{last} item of
15770 @var{default}!
15772 The portable way out consists in using a double assignment, to switch
15773 the 8th bit twice on Ultrix:
15775 @example
15776 list=$@{list="$default"@}
15777 @end example
15779 @noindent
15780 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
15781 use:
15783 @example
15784 test "$@{var+set@}" = set || var=@var{@{value@}}
15785 @end example
15787 @item $@{#@var{var}@}
15788 @itemx $@{@var{var}%@var{word}@}
15789 @itemx $@{@var{var}%%@var{word}@}
15790 @itemx $@{@var{var}#@var{word}@}
15791 @itemx $@{@var{var}##@var{word}@}
15792 @cindex @code{$@{#@var{var}@}}
15793 @cindex @code{$@{@var{var}%@var{word}@}}
15794 @cindex @code{$@{@var{var}%%@var{word}@}}
15795 @cindex @code{$@{@var{var}#@var{word}@}}
15796 @cindex @code{$@{@var{var}##@var{word}@}}
15797 Posix requires support for these usages, but they do not work with many
15798 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
15800 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
15801 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
15802 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
15803 yields the empty string.
15806 @item `@var{commands}`
15807 @cindex @code{`@var{commands}`}
15808 @cindex Command Substitution
15809 Posix requires shells to trim all trailing newlines from command
15810 output before substituting it, so assignments like
15811 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
15812 @samp{$file} ends in a newline.
15814 While in general it makes no sense, do not substitute a single builtin
15815 with side effects, because Ash 0.2, trying to optimize, does not fork a
15816 subshell to perform the command.
15818 For instance, if you wanted to check that @command{cd} is silent, do not
15819 use @samp{test -z "`cd /`"} because the following can happen:
15821 @example
15822 $ @kbd{pwd}
15823 /tmp
15824 $ @kbd{test -z "`cd /`" && pwd}
15826 @end example
15828 @noindent
15829 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
15831 The MSYS shell leaves a stray byte in the expansion of a double-quoted
15832 command substitution of a native program, if the end of the substitution
15833 is not aligned with the end of the double quote.  This may be worked
15834 around by inserting another pair of quotes:
15836 @example
15837 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
15838 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
15839 - broken differ: char 4, line 1
15840 @end example
15842 Upon interrupt or SIGTERM, some shells may abort a command substitution,
15843 replace it with a null string, and wrongly evaluate the enclosing
15844 command before entering the trap or ending the script.  This can lead to
15845 spurious errors:
15847 @example
15848 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
15849 $ @kbd{^C}
15850 sh: test: hi: unexpected operator/operand
15851 @end example
15853 @noindent
15854 You can avoid this by assigning the command substitution to a temporary
15855 variable:
15857 @example
15858 $ @kbd{sh -c 'res=`sleep 5; echo hi`
15859          if test "x$res" = xhi; then echo yes; fi'}
15860 $ @kbd{^C}
15861 @end example
15863 @item $(@var{commands})
15864 @cindex @code{$(@var{commands})}
15865 This construct is meant to replace @samp{`@var{commands}`},
15866 and it has most of the problems listed under @code{`@var{commands}`}.
15868 This construct can be
15869 nested while this is impossible to do portably with back quotes.
15870 Unfortunately it is not yet universally supported.  Most notably, even recent
15871 releases of Solaris don't support it:
15873 @example
15874 $ @kbd{showrev -c /bin/sh | grep version}
15875 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
15876 $ @kbd{echo $(echo blah)}
15877 syntax error: `(' unexpected
15878 @end example
15880 @noindent
15881 nor does IRIX 6.5's Bourne shell:
15882 @example
15883 $ @kbd{uname -a}
15884 IRIX firebird-image 6.5 07151432 IP22
15885 $ @kbd{echo $(echo blah)}
15886 $(echo blah)
15887 @end example
15889 If you do use @samp{$(@var{commands})}, make sure that the commands
15890 do not start with a parenthesis, as that would cause confusion with
15891 a different notation @samp{$((@var{expression}))} that in modern
15892 shells is an arithmetic expression not a command.  To avoid the
15893 confusion, insert a space between the two opening parentheses.
15895 Avoid @var{commands} that contain unbalanced parentheses in
15896 here-documents, comments, or case statement patterns, as many shells
15897 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
15898 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
15900 @example
15901 echo $(case x in x) echo hello;; esac)
15902 @end example
15905 @item $((@var{expression}))
15906 @cindex @code{$((@var{expression}))}
15907 Arithmetic expansion is not portable as some shells (most
15908 notably Solaris 10 @command{/bin/sh}) don't support it.
15910 Among shells that do support @samp{$(( ))}, not all of them obey the
15911 Posix rule that octal and hexadecimal constants must be recognized:
15913 @example
15914 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
15916 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
15918 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
15920 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
15921 pdksh:  010 + 0x10 : bad number `0x10'
15922 $ @kbd{pdksh -c 'echo $(( 010 ))'}
15924 @end example
15926 When it is available, using arithmetic expansion provides a noticeable
15927 speedup in script execution; but testing for support requires
15928 @command{eval} to avoid syntax errors.  The following construct is used
15929 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
15930 arguments are provided in decimal and without a leading zero, and all
15931 operators are properly quoted and appear as distinct arguments:
15933 @example
15934 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
15935   eval 'func_arith ()
15936   @{
15937     func_arith_result=$(( $* ))
15938   @}'
15939 else
15940   func_arith ()
15941   @{
15942     func_arith_result=`expr "$@@"`
15943   @}
15945 func_arith 1 + 1
15946 foo=$func_arith_result
15947 @end example
15950 @item ^
15951 @cindex @code{^} quoting
15952 Always quote @samp{^}, otherwise traditional shells such as
15953 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
15955 @end table
15958 @node Assignments
15959 @section Assignments
15960 @cindex Shell assignments
15962 When setting several variables in a row, be aware that the order of the
15963 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
15964 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
15965 You must use
15966 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
15968 Don't rely on the following to find @file{subdir/program}:
15970 @example
15971 PATH=subdir$PATH_SEPARATOR$PATH program
15972 @end example
15974 @noindent
15975 as this does not work with Zsh 3.0.6.  Use something like this
15976 instead:
15978 @example
15979 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
15980 @end example
15982 Don't rely on the exit status of an assignment: Ash 0.2 does not change
15983 the status and propagates that of the last statement:
15985 @example
15986 $ @kbd{false || foo=bar; echo $?}
15988 $ @kbd{false || foo=`:`; echo $?}
15990 @end example
15992 @noindent
15993 and to make things even worse, QNX 4.25 just sets the exit status
15994 to 0 in any case:
15996 @example
15997 $ @kbd{foo=`exit 1`; echo $?}
15999 @end example
16001 To assign default values, follow this algorithm:
16003 @enumerate
16004 @item
16005 If the default value is a literal and does not contain any closing
16006 brace, use:
16008 @example
16009 : "$@{var='my literal'@}"
16010 @end example
16012 @item
16013 If the default value contains no closing brace, has to be expanded, and
16014 the variable being initialized is not intended to be IFS-split
16015 (i.e., it's not a list), then use:
16017 @example
16018 : $@{var="$default"@}
16019 @end example
16021 @item
16022 If the default value contains no closing brace, has to be expanded, and
16023 the variable being initialized is intended to be IFS-split (i.e., it's a list),
16024 then use:
16026 @example
16027 var=$@{var="$default"@}
16028 @end example
16030 @item
16031 If the default value contains a closing brace, then use:
16033 @example
16034 test "$@{var+set@}" = set || var="has a '@}'"
16035 @end example
16036 @end enumerate
16038 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
16039 doubt, just use the last form.  @xref{Shell Substitutions}, items
16040 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
16041 for the rationale.
16043 @node Parentheses
16044 @section Parentheses in Shell Scripts
16045 @cindex Shell parentheses
16047 Beware of two opening parentheses in a row, as many shell
16048 implementations treat them specially, and Posix says that a portable
16049 script cannot use @samp{((} outside the @samp{$((} form used for shell
16050 arithmetic.  In traditional shells, @samp{((cat))} behaves like
16051 @samp{(cat)}; but many shells, including
16052 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
16053 expression equivalent to @samp{let "cat"}, and may or may not report an
16054 error when they detect that @samp{cat} is not a number.  As another
16055 example, @samp{pdksh} 5.2.14 does not treat the following code
16056 as a traditional shell would:
16058 @example
16059 if ((true) || false); then
16060   echo ok
16062 @end example
16064 @noindent
16065 To work around this problem, insert a space between the two opening
16066 parentheses.  There is a similar problem and workaround with
16067 @samp{$((}; see @ref{Shell Substitutions}.
16069 @node Slashes
16070 @section Slashes in Shell Scripts
16071 @cindex Shell slashes
16073 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
16074 arguments that contain two trailing slashes:
16076 @example
16077 $ @kbd{echo / // /// //// .// //.}
16078 / / // /// ./ //.
16079 $ @kbd{x=//}
16080 $ @kbd{eval "echo \$x"}
16082 $ @kbd{set -x}
16083 $ @kbd{echo abc | tr -t ab //}
16084 + echo abc
16085 + tr -t ab /
16087 @end example
16089 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
16090 variable is empty and the second double-quote is followed by a word that
16091 begins and ends with slash:
16093 @example
16094 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
16096 + echo //ouch/
16097 //ouch/
16098 @end example
16100 However, our understanding is that patches are available, so perhaps
16101 it's not worth worrying about working around these horrendous bugs.
16103 @node Special Shell Variables
16104 @section Special Shell Variables
16105 @cindex Shell variables
16106 @cindex Special shell variables
16108 Some shell variables should not be used, since they can have a deep
16109 influence on the behavior of the shell.  In order to recover a sane
16110 behavior from the shell, some variables should be unset; M4sh takes
16111 care of this and provides fallback values, whenever needed, to cater
16112 for a very old @file{/bin/sh} that does not support @command{unset}.
16113 (@pxref{Portable Shell, , Portable Shell Programming}).
16115 As a general rule, shell variable names containing a lower-case letter
16116 are safe; you can define and use these variables without worrying about
16117 their effect on the underlying system, and without worrying about
16118 whether the shell changes them unexpectedly.  (The exception is the
16119 shell variable @code{status}, as described below.)
16121 Here is a list of names that are known to cause trouble.  This list is
16122 not exhaustive, but you should be safe if you avoid the name
16123 @code{status} and names containing only upper-case letters and
16124 underscores.
16126 @c Alphabetical order, case insensitive, `A' before `a'.
16127 @table @code
16128 @item ?
16129 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
16130 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
16131 correctly in shell functions (@pxref{Shell Functions}) or in traps
16132 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
16133 @samp{$?} to zero after an empty command.
16135 @example
16136 $ @kbd{bash -c 'false; $empty; echo $?'}
16138 $ @kbd{zsh -c 'false; $empty; echo $?'}
16140 @end example
16142 @item _
16143 @evindex _
16144 Many shells reserve @samp{$_} for various purposes, e.g., the name of
16145 the last command executed.
16147 @item BIN_SH
16148 @evindex BIN_SH
16149 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
16150 the standard shell conform to Posix.
16152 @item CDPATH
16153 @evindex CDPATH
16154 When this variable is set it specifies a list of directories to search
16155 when invoking @code{cd} with a relative file name that did not start
16156 with @samp{./} or @samp{../}.  Posix
16157 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
16158 is used successfully, @code{cd} prints the resulting absolute
16159 file name.  Unfortunately this output can break idioms like
16160 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
16161 Also, many shells do not conform to this part of Posix; for
16162 example, @command{zsh} prints the result only if a directory name
16163 other than @file{.} was chosen from @env{CDPATH}.
16165 In practice the shells that have this problem also support
16166 @command{unset}, so you can work around the problem as follows:
16168 @example
16169 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
16170 @end example
16172 You can also avoid output by ensuring that your directory name is
16173 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
16175 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
16176 possible, so you need not worry about this problem in those scripts.
16178 @item CLICOLOR_FORCE
16179 @evindex CLICOLOR_FORCE
16180 When this variable is set, some implementations of tools like
16181 @command{ls} attempt to add color to their output via terminal escape
16182 sequences, even when the output is not directed to a terminal, and can
16183 thus cause spurious failures in scripts.  Configure scripts use M4sh,
16184 which automatically unsets this variable.
16186 @item DUALCASE
16187 @evindex DUALCASE
16188 In the MKS shell, case statements and file name generation are
16189 case-insensitive unless @env{DUALCASE} is nonzero.
16190 Autoconf-generated scripts export this variable when they start up.
16192 @item ENV
16193 @itemx MAIL
16194 @itemx MAILPATH
16195 @itemx PS1
16196 @itemx PS2
16197 @itemx PS4
16198 @evindex ENV
16199 @evindex MAIL
16200 @evindex MAILPATH
16201 @evindex PS1
16202 @evindex PS2
16203 @evindex PS4
16204 These variables should not matter for shell scripts, since they are
16205 supposed to affect only interactive shells.  However, at least one
16206 shell (the pre-3.0 UWIN Korn shell) gets confused about
16207 whether it is interactive, which means that (for example) a @env{PS1}
16208 with a side effect can unexpectedly modify @samp{$?}.  To work around
16209 this bug, M4sh scripts (including @file{configure} scripts) do something
16210 like this:
16212 @example
16213 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
16214 PS1='$ '
16215 PS2='> '
16216 PS4='+ '
16217 @end example
16219 @noindent
16220 (actually, there is some complication due to bugs in @command{unset};
16221 see @pxref{unset, , Limitations of Shell Builtins}).
16223 @item FPATH
16224 @evindex FPATH
16225 The Korn shell uses @env{FPATH} to find shell functions, so avoid
16226 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
16227 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
16228 to find whether a command exists, since they might report the wrong
16229 result if @env{FPATH} is also set.
16231 @item GREP_OPTIONS
16232 @evindex GREP_OPTIONS
16233 When this variable is set, some implementations of @command{grep} honor
16234 these options, even if the options include direction to enable colored
16235 output via terminal escape sequences, and the result can cause spurious
16236 failures when the output is not directed to a terminal.  Configure
16237 scripts use M4sh, which automatically unsets this variable.
16239 @item IFS
16240 @evindex IFS
16241 Long ago, shell scripts inherited @env{IFS} from the environment,
16242 but this caused many problems so modern shells ignore any environment
16243 settings for @env{IFS}.
16245 Don't set the first character of @env{IFS} to backslash.  Indeed,
16246 Bourne shells use the first character (backslash) when joining the
16247 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
16248 backslash escapes, so you can end up with backspace and other strange
16249 characters.
16251 The proper value for @env{IFS} (in regular code, not when performing
16252 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
16253 especially important, as it is used to join the arguments in @samp{$*};
16254 however, note that traditional shells, but also bash-2.04, fail to adhere
16255 to this and join with a space anyway.
16257 M4sh guarantees that @env{IFS} will have the default value at the
16258 beginning of a script, and many macros within autoconf rely on this
16259 setting.  It is okay to use blocks of shell code that temporarily change
16260 the value of @env{IFS} in order to split on another character, but
16261 remember to restore it before expanding further macros.
16263 Unsetting @code{IFS} instead of resetting it to the default sequence
16264 is not suggested, since code that tries to save and restore the
16265 variable's value will incorrectly reset it to an empty value, thus
16266 disabling field splitting:
16268 @example
16269 unset IFS
16270 # default separators used for field splitting
16272 save_IFS=$IFS
16273 IFS=:
16274 # ...
16275 IFS=$save_IFS
16276 # no field splitting performed
16277 @end example
16279 @item LANG
16280 @itemx LC_ALL
16281 @itemx LC_COLLATE
16282 @itemx LC_CTYPE
16283 @itemx LC_MESSAGES
16284 @itemx LC_MONETARY
16285 @itemx LC_NUMERIC
16286 @itemx LC_TIME
16287 @evindex LANG
16288 @evindex LC_ALL
16289 @evindex LC_COLLATE
16290 @evindex LC_CTYPE
16291 @evindex LC_MESSAGES
16292 @evindex LC_MONETARY
16293 @evindex LC_NUMERIC
16294 @evindex LC_TIME
16296 You should set all these variables to @samp{C} because so much
16297 configuration code assumes the C locale and Posix requires that locale
16298 environment variables be set to @samp{C} if the C locale is desired;
16299 @file{configure} scripts and M4sh do that for you.
16300 Export these variables after setting them.
16302 @c  However, some older, nonstandard
16303 @c  systems (notably SCO) break if locale environment variables
16304 @c  are set to @samp{C}, so when running on these systems
16305 @c  Autoconf-generated scripts unset the variables instead.
16307 @item LANGUAGE
16308 @evindex LANGUAGE
16310 @env{LANGUAGE} is not specified by Posix, but it is a GNU
16311 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
16312 should set it too.
16314 @item LC_ADDRESS
16315 @itemx LC_IDENTIFICATION
16316 @itemx LC_MEASUREMENT
16317 @itemx LC_NAME
16318 @itemx LC_PAPER
16319 @itemx LC_TELEPHONE
16320 @evindex LC_ADDRESS
16321 @evindex LC_IDENTIFICATION
16322 @evindex LC_MEASUREMENT
16323 @evindex LC_NAME
16324 @evindex LC_PAPER
16325 @evindex LC_TELEPHONE
16327 These locale environment variables are GNU extensions.  They
16328 are treated like their Posix brethren (@env{LC_COLLATE},
16329 etc.)@: as described above.
16331 @item LINENO
16332 @evindex LINENO
16333 Most modern shells provide the current line number in @code{LINENO}.
16334 Its value is the line number of the beginning of the current command.
16335 M4sh, and hence Autoconf, attempts to execute @command{configure} with
16336 a shell that supports @code{LINENO}.  If no such shell is available, it
16337 attempts to implement @code{LINENO} with a Sed prepass that replaces each
16338 instance of the string @code{$LINENO} (not followed by an alphanumeric
16339 character) with the line's number.  In M4sh scripts you should execute
16340 @code{AS_LINENO_PREPARE} so that these workarounds are included in
16341 your script; configure scripts do this automatically in @code{AC_INIT}.
16343 You should not rely on @code{LINENO} within @command{eval} or shell
16344 functions, as the behavior differs in practice.  The presence of a
16345 quoted newline within simple commands can alter which line number is
16346 used as the starting point for @code{$LINENO} substitutions within that
16347 command.  Also, the possibility of the Sed prepass means that you should
16348 not rely on @code{$LINENO} when quoted, when in here-documents, or when
16349 line continuations are used.  Subshells should be OK, though.  In the
16350 following example, lines 1, 9, and 14 are portable, but the other
16351 instances of @code{$LINENO} do not have deterministic values:
16353 @example
16354 @group
16355 $ @kbd{cat lineno}
16356 echo 1. $LINENO
16357 echo "2. $LINENO
16358 3. $LINENO"
16359 cat <<EOF
16360 5. $LINENO
16361 6. $LINENO
16362 7. \$LINENO
16364 ( echo 9. $LINENO )
16365 eval 'echo 10. $LINENO'
16366 eval 'echo 11. $LINENO
16367 echo 12. $LINENO'
16368 echo 13. '$LINENO'
16369 echo 14. $LINENO '
16370 15.' $LINENO
16371 f () @{ echo $1 $LINENO;
16372 echo $1 $LINENO @}
16373 f 18.
16374 echo 19. \
16375 $LINENO
16376 @end group
16377 @group
16378 $ @kbd{bash-3.2 ./lineno}
16379 1. 1
16380 2. 3
16381 3. 3
16382 5. 4
16383 6. 4
16384 7. $LINENO
16385 9. 9
16386 10. 10
16387 11. 12
16388 12. 13
16389 13. $LINENO
16390 14. 14
16391 15. 14
16392 18. 16
16393 18. 17
16394 19. 19
16395 @end group
16396 @group
16397 $ @kbd{zsh-4.3.4 ./lineno}
16398 1. 1
16399 2. 2
16400 3. 2
16401 5. 4
16402 6. 4
16403 7. $LINENO
16404 9. 9
16405 10. 1
16406 11. 1
16407 12. 2
16408 13. $LINENO
16409 14. 14
16410 15. 14
16411 18. 0
16412 18. 1
16413 19. 19
16414 @end group
16415 @group
16416 $ @kbd{pdksh-5.2.14 ./lineno}
16417 1. 1
16418 2. 2
16419 3. 2
16420 5. 4
16421 6. 4
16422 7. $LINENO
16423 9. 9
16424 10. 0
16425 11. 0
16426 12. 0
16427 13. $LINENO
16428 14. 14
16429 15. 14
16430 18. 16
16431 18. 17
16432 19. 19
16433 @end group
16434 @group
16435 $ @kbd{sed '=' <lineno |}
16436 > @kbd{  sed '}
16437 > @kbd{    N}
16438 > @kbd{    s,$,-,}
16439 > @kbd{    t loop}
16440 > @kbd{    :loop}
16441 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
16442 > @kbd{    t loop}
16443 > @kbd{    s,-$,,}
16444 > @kbd{    s,^[0-9]*\n,,}
16445 > @kbd{  ' |}
16446 > @kbd{  sh}
16447 1. 1
16448 2. 2
16449 3. 3
16450 5. 5
16451 6. 6
16452 7. \7
16453 9. 9
16454 10. 10
16455 11. 11
16456 12. 12
16457 13. 13
16458 14. 14
16459 15. 15
16460 18. 16
16461 18. 17
16462 19. 20
16463 @end group
16464 @end example
16466 In particular, note that @file{config.status} (and any other subsidiary
16467 script created by @code{AS_INIT_GENERATED}) might report line numbers
16468 relative to the parent script as a result of the potential Sed pass.
16470 @item NULLCMD
16471 @evindex NULLCMD
16472 When executing the command @samp{>foo}, @command{zsh} executes
16473 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
16474 compatibility mode and the @command{zsh} version is newer
16475 than 3.1.6-dev-18.  If you are using an older @command{zsh}
16476 and forget to set @env{NULLCMD},
16477 your script might be suspended waiting for data on its standard input.
16479 @item options
16480 @evindex options
16481 For @command{zsh} 4.3.10, @env{options} is treated as an associative
16482 array even after @code{emulate sh}, so it should not be used.
16484 @item PATH_SEPARATOR
16485 @evindex PATH_SEPARATOR
16486 On DJGPP systems, the @env{PATH_SEPARATOR} environment
16487 variable can be set to either @samp{:} or @samp{;} to control the path
16488 separator Bash uses to set up certain environment variables (such as
16489 @env{PATH}).  You can set this variable to @samp{;} if you want
16490 @command{configure} to use @samp{;} as a separator; this might be useful
16491 if you plan to use non-Posix shells to execute files.  @xref{File System
16492 Conventions}, for more information about @code{PATH_SEPARATOR}.
16494 @item POSIXLY_CORRECT
16495 @evindex POSIXLY_CORRECT
16496 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
16497 (even empty) causes programs to try harder to conform to Posix.
16498 Autoconf does not directly manipulate this variable, but @command{bash}
16499 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
16500 running in Posix mode.  Therefore, take care when exporting or unsetting
16501 this variable, so as not to change whether @command{bash} is in Posix
16502 mode.
16504 @example
16505 $ @kbd{bash --posix -c 'set -o | grep posix}
16506 > @kbd{unset POSIXLY_CORRECT}
16507 > @kbd{set -o | grep posix'}
16508 posix           on
16509 posix           off
16510 @end example
16512 @item PWD
16513 @evindex PWD
16514 Posix 1003.1-2001 requires that @command{cd} and
16515 @command{pwd} must update the @env{PWD} environment variable to point
16516 to the logical name of the current directory, but traditional shells
16517 do not support this.  This can cause confusion if one shell instance
16518 maintains @env{PWD} but a subsidiary and different shell does not know
16519 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
16520 points to the wrong directory.  Use @samp{`pwd`} rather than
16521 @samp{$PWD}.
16523 @item RANDOM
16524 @evindex RANDOM
16525 Many shells provide @code{RANDOM}, a variable that returns a different
16526 integer each time it is used.  Most of the time, its value does not
16527 change when it is not used, but on IRIX 6.5 the value changes all
16528 the time.  This can be observed by using @command{set}.  It is common
16529 practice to use @code{$RANDOM} as part of a file name, but code
16530 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
16532 @item status
16533 @evindex status
16534 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
16535 hence read-only.  Do not use it.
16536 @end table
16538 @node Shell Functions
16539 @section Shell Functions
16540 @cindex Shell Functions
16542 Nowadays, it is difficult to find a shell that does not support
16543 shell functions at all.  However, some differences should be expected.
16545 When declaring a shell function, you must include whitespace between the
16546 @samp{)} after the function name and the start of the compound
16547 expression, to avoid upsetting @command{ksh}.  While it is possible to
16548 use any compound command, most scripts use @samp{@{@dots{}@}}.
16550 @example
16551 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
16553 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
16554 ksh: syntax error at line 1: `@}' unexpected
16555 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
16557 @end example
16559 Inside a shell function, you should not rely on the error status of a
16560 subshell if the last command of that subshell was @code{exit} or
16561 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
16562 find a shell that does not exhibit the bug, zsh might be the only shell
16563 present on the user's machine.
16565 Likewise, the state of @samp{$?} is not reliable when entering a shell
16566 function.  This has the effect that using a function as the first
16567 command in a @command{trap} handler can cause problems.
16569 @example
16570 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
16573 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
16576 @end example
16578 DJGPP bash 2.04 has a bug in that @command{return} from a
16579 shell function which also used a command substitution causes a
16580 segmentation fault.  To work around the issue, you can use
16581 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
16582 in the execution flow of the function (@pxref{Common Shell Constructs}).
16584 Not all shells treat shell functions as simple commands impacted by
16585 @samp{set -e}, for example with Solaris 10 @command{bin/sh}:
16587 @example
16588 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops}
16589 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops}
16590 oops
16591 @end example
16593 Shell variables and functions may share the same namespace, for example
16594 with Solaris 10 @command{/bin/sh}:
16596 @example
16597 $ @kbd{f () @{ :; @}; f=; f}
16598 f: not found
16599 @end example
16601 @noindent
16602 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
16603 uses the prefix @samp{as_fn_} for its functions.
16605 Handling of positional parameters and shell options varies among shells.
16606 For example, Korn shells reset and restore trace output (@samp{set -x})
16607 and other options upon function entry and exit.  Inside a function,
16608 IRIX sh sets @samp{$0} to the function name.
16610 It is not portable to pass temporary environment variables to shell
16611 functions.  Solaris @command{/bin/sh} does not see the variable.
16612 Meanwhile, not all shells follow the Posix rule that the assignment must
16613 affect the current environment in the same manner as special built-ins.
16615 @example
16616 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
16617 @result{}
16618 @result{}
16619 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
16620 @result{}1
16621 @result{}
16622 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
16623 @result{}1
16624 @result{}1
16625 @end example
16627 Some ancient Bourne shell variants with function support did not reset
16628 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
16629 arguments of the script were lost after the first function invocation.
16630 It is probably not worth worrying about these shells any more.
16632 With AIX sh, a @command{trap} on 0 installed in a shell function
16633 triggers at function exit rather than at script exit.  @xref{trap, ,
16634 Limitations of Shell Builtins}.
16636 @node Limitations of Builtins
16637 @section Limitations of Shell Builtins
16638 @cindex Shell builtins
16639 @cindex Limitations of shell builtins
16641 No, no, we are serious: some shells do have limitations!  :)
16643 You should always keep in mind that any builtin or command may support
16644 options, and therefore differ in behavior with arguments
16645 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
16646 can give unexpected results when @code{word} starts with a dash.  It is
16647 often possible to avoid this problem using @samp{echo "x$word"}, taking
16648 the @samp{x} into account later in the pipe.  Many of these limitations
16649 can be worked around using M4sh (@pxref{Programming in M4sh}).
16651 @c This table includes things like `@command{test} (files)', so we can't
16652 @c use @table @command.
16653 @table @asis
16654 @item @command{.}
16655 @c --------------
16656 @prindex @command{.}
16657 Use @command{.} only with regular files (use @samp{test -f}).  Bash
16658 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
16659 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
16660 some shells, including bash 3.2, implicitly append the current directory
16661 to this @env{PATH} search, even though Posix forbids it.  So if you want
16662 to use @command{.} on a file @file{foo} in the current directory, you
16663 must use @samp{. ./foo}.
16665 Not all shells gracefully handle syntax errors within a sourced file.
16666 On one extreme, some non-interactive shells abort the entire script.  On
16667 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
16668 syntax error.
16670 @example
16671 $ @kbd{echo 'fi' > syntax}
16672 $ @kbd{bash -c '. ./syntax; echo $?'}
16673 ./syntax: line 1: syntax error near unexpected token `fi'
16674 ./syntax: line 1: `fi'
16676 $ @kbd{ash -c '. ./syntax; echo $?'}
16677 ./syntax: 1: Syntax error: "fi" unexpected
16678 $ @kbd{zsh -c '. ./syntax; echo $?'}
16679 ./syntax:1: parse error near `fi'
16681 @end example
16683 @item @command{!}
16684 @c --------------
16685 @prindex @command{!}
16686 The Unix version 7 shell did not support
16687 negating the exit status of commands with @command{!}, and this feature
16688 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
16689 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
16690 bugs when using @command{!}:
16692 @example
16693 $ @kbd{sh -c '! : | :'; echo $?}
16695 $ @kbd{ash -c '! : | :'; echo $?}
16697 $ @kbd{sh -c '! @{ :; @}'; echo $?}
16699 $ @kbd{ash -c '! @{ :; @}'; echo $?}
16700 @{: not found
16701 Syntax error: "@}" unexpected
16703 @end example
16705 Shell code like this:
16707 @example
16708 if ! cmp file1 file2 >/dev/null 2>&1; then
16709   echo files differ or trouble
16711 @end example
16713 is therefore not portable in practice.  Typically it is easy to rewrite
16714 such code, e.g.:
16716 @example
16717 cmp file1 file2 >/dev/null 2>&1 ||
16718   echo files differ or trouble
16719 @end example
16721 More generally, one can always rewrite @samp{! @var{command}} as:
16723 @example
16724 if @var{command}; then (exit 1); else :; fi
16725 @end example
16728 @item @command{@{...@}}
16729 @c --------------------
16730 @prindex @command{@{...@}}
16731 Bash 3.2 (and earlier versions) sometimes does not properly set
16732 @samp{$?} when failing to write redirected output of a compound command.
16733 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
16734 not occur with @samp{(@dots{})}.  For example:
16736 @example
16737 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
16738 bash: line 1: /bad: Permission denied
16740 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
16741 bash: line 1: /bad: Permission denied
16743 @end example
16745 To work around the bug, prepend @samp{:;}:
16747 @example
16748 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
16749 bash: line 1: /bad: Permission denied
16751 @end example
16753 Posix requires a syntax error if a brace list has no contents.  However,
16754 not all shells obey this rule; and on shells where empty lists are
16755 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
16756 ensure that a brace list is never empty.
16758 @example
16759 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
16760 bash: line 1: syntax error near unexpected token `@}'
16761 bash: line 1: `false; @{ @}; echo $?'
16763 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
16765 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
16767 @end example
16770 @item @command{break}
16771 @c ------------------
16772 @prindex @command{break}
16773 The use of @samp{break 2} etc.@: is safe.
16776 @anchor{case}
16777 @item @command{case}
16778 @c -----------------
16779 @prindex @command{case}
16780 You don't need to quote the argument; no splitting is performed.
16782 You don't need the final @samp{;;}, but you should use it.
16784 Posix requires support for @code{case} patterns with opening
16785 parentheses like this:
16787 @example
16788 case $file_name in
16789   (*.c) echo "C source code";;
16790 esac
16791 @end example
16793 @noindent
16794 but the @code{(} in this example is not portable to many Bourne
16795 shell implementations, which is a pity for those of us using tools that
16796 rely on balanced parentheses.  For instance, with Solaris
16797 @command{/bin/sh}:
16799 @example
16800 $ @kbd{case foo in (foo) echo foo;; esac}
16801 @error{}syntax error: `(' unexpected
16802 @end example
16804 @noindent
16805 The leading @samp{(} can be omitted safely.  Unfortunately, there are
16806 contexts where unbalanced parentheses cause other problems, such as when
16807 using a syntax-highlighting editor that searches for the balancing
16808 counterpart, or more importantly, when using a case statement as an
16809 underquoted argument to an Autoconf macro.  @xref{Balancing
16810 Parentheses}, for tradeoffs involved in various styles of dealing with
16811 unbalanced @samp{)}.
16813 Zsh handles pattern fragments derived from parameter expansions or
16814 command substitutions as though quoted:
16816 @example
16817 $ pat=\?; case aa in ?$pat) echo match;; esac
16818 $ pat=\?; case a? in ?$pat) echo match;; esac
16819 match
16820 @end example
16822 @noindent
16823 Because of a bug in its @code{fnmatch}, Bash fails to properly
16824 handle backslashes in character classes:
16826 @example
16827 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
16828 bash-2.02$
16829 @end example
16831 @noindent
16832 This is extremely unfortunate, since you are likely to use this code to
16833 handle Posix or MS-DOS absolute file names.  To work around this
16834 bug, always put the backslash first:
16836 @example
16837 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
16839 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
16841 @end example
16843 Many Bourne shells cannot handle closing brackets in character classes
16844 correctly.
16846 Some shells also have problems with backslash escaping in case you do not want
16847 to match the backslash: both a backslash and the escaped character match this
16848 pattern.  To work around this, specify the character class in a variable, so
16849 that quote removal does not apply afterwards, and the special characters don't
16850 have to be backslash-escaped:
16852 @example
16853 $ @kbd{case '\' in [\<]) echo OK;; esac}
16855 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
16857 @end example
16859 Even with this, Solaris @command{ksh} matches a backslash if the set
16860 contains any
16861 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
16863 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
16864 a closing parenthesis if not specified in a character class:
16866 @example
16867 $ @kbd{case foo in *\)*) echo fail ;; esac}
16868 fail
16869 $ @kbd{case foo in *')'*) echo fail ;; esac}
16870 fail
16871 @end example
16873 Some shells, such as Ash 0.3.8, are confused by an empty
16874 @code{case}/@code{esac}:
16876 @example
16877 ash-0.3.8 $ @kbd{case foo in esac;}
16878 @error{}Syntax error: ";" unexpected (expecting ")")
16879 @end example
16881 Posix requires @command{case} to give an exit status of 0 if no cases
16882 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
16883 rule.  Meanwhile, it is unclear whether a case that matches, but
16884 contains no statements, must also change the exit status to 0.  The M4sh
16885 macro @code{AS_CASE} works around these inconsistencies.
16887 @example
16888 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
16890 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
16892 @end example
16895 @item @command{cd}
16896 @c ---------------
16897 @prindex @command{cd}
16898 Posix 1003.1-2001 requires that @command{cd} must support
16899 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
16900 with @option{-L} being the default.  However, traditional shells do
16901 not support these options, and their @command{cd} command has the
16902 @option{-P} behavior.
16904 Portable scripts should assume neither option is supported, and should
16905 assume neither behavior is the default.  This can be a bit tricky,
16906 since the Posix default behavior means that, for example,
16907 @samp{ls ..} and @samp{cd ..} may refer to different directories if
16908 the current logical directory is a symbolic link.  It is safe to use
16909 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
16910 Also, Autoconf-generated scripts check for this problem when computing
16911 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
16912 so it is safe to @command{cd} to these variables.
16914 Posix states that behavior is undefined if @command{cd} is given an
16915 explicit empty argument.  Some shells do nothing, some change to the
16916 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
16917 the shell rather than returning an error.  Unfortunately, this means
16918 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
16919 than @samp{cd $var} (at least the latter is well-behaved in all shells
16920 at changing to @env{HOME}, although this is probably not what you wanted
16921 in a script).  You should check that a directory name was supplied
16922 before trying to change locations.
16924 @xref{Special Shell Variables}, for portability problems involving
16925 @command{cd} and the @env{CDPATH} environment variable.
16926 Also please see the discussion of the @command{pwd} command.
16929 @anchor{echo}
16930 @item @command{echo}
16931 @c -----------------
16932 @prindex @command{echo}
16933 The simple @command{echo} is probably the most surprising source of
16934 portability troubles.  It is not possible to use @samp{echo} portably
16935 unless both options and escape sequences are omitted.  Don't expect any
16936 option.
16938 Do not use backslashes in the arguments, as there is no consensus on
16939 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
16940 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
16941 The problem is truly @command{echo}: all the shells
16942 understand @samp{'\n'} as the string composed of a backslash and an
16943 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
16944 mess up the internal state of ksh88 on AIX 6.1 so that it will print
16945 the first character @samp{s} only, followed by a newline, and then
16946 entirely drop the output of the next echo in a command substitution.
16948 Because of these problems, do not pass a string containing arbitrary
16949 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
16950 only if you know that @var{foo}'s value cannot contain backslashes and
16951 cannot start with @samp{-}.
16953 If this may not be true, @command{printf} is in general safer and
16954 easier to use than @command{echo} and @command{echo -n}.  Thus, scripts
16955 where portability is not a major concern should use @command{printf
16956 '%s\n'} whenever @command{echo} could fail, and similarly use
16957 @command{printf %s} instead of @command{echo -n}. For portable shell
16958 scripts, instead, it is suggested to use a here-document like this:
16960 @example
16961 cat <<EOF
16962 $foo
16964 @end example
16966 Alternatively, M4sh provides @code{AS_ECHO} and @code{AS_ECHO_N} macros
16967 which choose between various portable implementations: @samp{echo}
16968 or @samp{print} where they work, @command{printf} if it is available,
16969 or else other creative tricks in order to work around the above problems.
16972 @item @command{eval}
16973 @c -----------------
16974 @prindex @command{eval}
16975 The @command{eval} command is useful in limited circumstances, e.g.,
16976 using commands like @samp{eval table_$key=\$value} and @samp{eval
16977 value=table_$key} to simulate a hash table when the key is known to be
16978 alphanumeric.
16980 You should also be wary of common bugs in @command{eval} implementations.
16981 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
16982 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
16983 4.2.5), the arguments of @samp{eval} are evaluated in a context where
16984 @samp{$?} is 0, so they exhibit behavior like this:
16986 @example
16987 $ @kbd{false; eval 'echo $?'}
16989 @end example
16991 The correct behavior here is to output a nonzero value,
16992 but portable scripts should not rely on this.
16994 You should not rely on @code{LINENO} within @command{eval}.
16995 @xref{Special Shell Variables}.
16997 Note that, even though these bugs are easily avoided,
16998 @command{eval} is tricky to use on arbitrary arguments.
16999 It is obviously unwise to use @samp{eval $cmd} if the string value of
17000 @samp{cmd} was derived from an untrustworthy source.  But even if the
17001 string value is valid, @samp{eval $cmd} might not work as intended,
17002 since it causes field splitting and file name expansion to occur twice,
17003 once for the @command{eval} and once for the command itself.  It is
17004 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
17005 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
17006 equivalent of @samp{cat test;.c} if there happens to be a file named
17007 @file{test;.c} in the current directory; and this in turn
17008 mistakenly attempts to invoke @command{cat} on the file @file{test} and
17009 then execute the command @command{.c}.  To avoid this problem, use
17010 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
17012 However, suppose that you want to output the text of the evaluated
17013 command just before executing it.  Assuming the previous example,
17014 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
17015 this output doesn't show the user that @samp{test;.c} is the actual name
17016 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
17017 works on this example, but it fails with @samp{cmd='cat foo >bar'},
17018 since it mistakenly replaces the contents of @file{bar} by the
17019 string @samp{cat foo}.  No simple, general, and portable solution to
17020 this problem is known.
17022 @item @command{exec}
17023 @c -----------------
17024 @prindex @command{exec}
17025 Posix describes several categories of shell built-ins.  Special
17026 built-ins (such as @command{exit}) must impact the environment of the
17027 current shell, and need not be available through @command{exec}.  All
17028 other built-ins are regular, and must not propagate variable assignments
17029 to the environment of the current shell.  However, the group of regular
17030 built-ins is further distinguished by commands that do not require a
17031 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
17032 are offered as a more efficient version of something that must still be
17033 found in a @env{PATH} search (such as @command{echo}).  Posix is not
17034 clear on whether @command{exec} must work with the list of 17 utilities
17035 that are invoked without a @env{PATH} search, and many platforms lack an
17036 executable for some of those built-ins:
17038 @example
17039 $ @kbd{sh -c 'exec cd /tmp'}
17040 sh: line 0: exec: cd: not found
17041 @end example
17043 All other built-ins that provide utilities specified by Posix must have
17044 a counterpart executable that exists on @env{PATH}, although Posix
17045 allows @command{exec} to use the built-in instead of the executable.
17046 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
17048 @example
17049 $ @kbd{bash -c 'pwd --version' | head -n1}
17050 bash: line 0: pwd: --: invalid option
17051 pwd: usage: pwd [-LP]
17052 $ @kbd{bash -c 'exec pwd --version' | head -n1}
17053 pwd (GNU coreutils) 6.10
17054 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
17055 pdksh: pwd: --: unknown option
17056 @end example
17058 When it is desired to avoid a regular shell built-in, the workaround is
17059 to use some other forwarding command, such as @command{env} or
17060 @command{nice}, that will ensure a path search:
17062 @example
17063 $ @kbd{pdksh -c 'exec true --version' | head -n1}
17064 $ @kbd{pdksh -c 'nice true --version' | head -n1}
17065 true (GNU coreutils) 6.10
17066 $ @kbd{pdksh -c 'env true --version' | head -n1}
17067 true (GNU coreutils) 6.10
17068 @end example
17070 @item @command{exit}
17071 @c -----------------
17072 @prindex @command{exit}
17073 The default value of @command{exit} is supposed to be @code{$?};
17074 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17075 perform @samp{exit 0}.
17077 @example
17078 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17079 fail
17080 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17081 fail
17082 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17083 bash-2.04$
17084 @end example
17086 Using @samp{exit $?} restores the expected behavior.
17088 Some shell scripts, such as those generated by @command{autoconf}, use a
17089 trap to clean up before exiting.  If the last shell command exited with
17090 nonzero status, the trap also exits with nonzero status so that the
17091 invoker can tell that an error occurred.
17093 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
17094 trap ignores the @code{exit} command's argument.  In these shells, a trap
17095 cannot determine whether it was invoked by plain @code{exit} or by
17096 @code{exit 1}.  Instead of calling @code{exit} directly, use the
17097 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
17100 @anchor{export}
17101 @item @command{export}
17102 @c -------------------
17103 @prindex @command{export}
17104 The builtin @command{export} dubs a shell variable @dfn{environment
17105 variable}.  Each update of exported variables corresponds to an update
17106 of the environment variables.  Conversely, each environment variable
17107 received by the shell when it is launched should be imported as a shell
17108 variable marked as exported.
17110 Alas, many shells, such as Solaris @command{/bin/sh},
17111 IRIX 6.3, IRIX 5.2,
17112 AIX 4.1.5, and Digital Unix 4.0, forget to
17113 @command{export} the environment variables they receive.  As a result,
17114 two variables coexist: the environment variable and the shell
17115 variable.  The following code demonstrates this failure:
17117 @example
17118 #!/bin/sh
17119 echo $FOO
17120 FOO=bar
17121 echo $FOO
17122 exec /bin/sh $0
17123 @end example
17125 @noindent
17126 when run with @samp{FOO=foo} in the environment, these shells print
17127 alternately @samp{foo} and @samp{bar}, although they should print only
17128 @samp{foo} and then a sequence of @samp{bar}s.
17130 Therefore you should @command{export} again each environment variable
17131 that you update; the export can occur before or after the assignment.
17133 Posix is not clear on whether the @command{export} of an undefined
17134 variable causes the variable to be defined with the value of an empty
17135 string, or merely marks any future definition of a variable by that name
17136 for export.  Various shells behave differently in this regard:
17138 @example
17139 $ @kbd{sh -c 'export foo; env | grep foo'}
17140 $ @kbd{ash -c 'export foo; env | grep foo'}
17141 foo=
17142 @end example
17144 @item @command{false}
17145 @c ------------------
17146 @prindex @command{false}
17147 Don't expect @command{false} to exit with status 1: in native
17148 Solaris @file{/bin/false} exits with status 255.
17151 @item @command{for}
17152 @c ----------------
17153 @prindex @command{for}
17154 To loop over positional arguments, use:
17156 @example
17157 for arg
17159   echo "$arg"
17160 done
17161 @end example
17163 @noindent
17164 You may @emph{not} leave the @code{do} on the same line as @code{for},
17165 since some shells improperly grok:
17167 @example
17168 for arg; do
17169   echo "$arg"
17170 done
17171 @end example
17173 If you want to explicitly refer to the positional arguments, given the
17174 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
17176 @example
17177 for arg in $@{1+"$@@"@}; do
17178   echo "$arg"
17179 done
17180 @end example
17182 @noindent
17183 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
17184 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
17185 item @samp{$@@}, for more.
17187 In Solaris @command{/bin/sh}, when the list of arguments of a
17188 @command{for} loop starts with @emph{unquoted} tokens looking like
17189 variable assignments, the loop is not executed on those tokens:
17191 @example
17192 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
17195 @end example
17197 @noindent
17198 Thankfully, quoting the assignment-like tokens, or starting the list
17199 with other tokens (including unquoted variable expansion that results in
17200 an assignment-like result), avoids the problem, so it is easy to work
17201 around:
17203 @example
17204 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
17206 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
17209 @end example
17211 @anchor{if}
17212 @item @command{if}
17213 @c ---------------
17214 @prindex @command{if}
17215 Using @samp{!} is not portable.  Instead of:
17217 @example
17218 if ! cmp -s file file.new; then
17219   mv file.new file
17221 @end example
17223 @noindent
17224 use:
17226 @example
17227 if cmp -s file file.new; then :; else
17228   mv file.new file
17230 @end example
17232 @noindent
17233 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
17234 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17235 of conditionals:
17237 @example
17238 AS_IF([cmp -s file file.new], [], [mv file.new file])
17239 @end example
17241 This is especially useful in other M4 macros, where the @dfn{then} and
17242 @dfn{else} branches might be macro arguments.
17244 Some very old shells did not reset the exit status from an @command{if}
17245 with no @command{else}:
17247 @example
17248 $ @kbd{if (exit 42); then true; fi; echo $?}
17250 @end example
17252 @noindent
17253 whereas a proper shell should have printed @samp{0}.  But this is no
17254 longer a portability problem; any shell that supports functions gets it
17255 correct.  However, it explains why some makefiles have lengthy
17256 constructs:
17258 @example
17259 if test -f "$file"; then
17260   install "$file" "$dest"
17261 else
17262   :
17264 @end example
17267 @item @command{printf}
17268 @c ------------------
17269 @prindex @command{printf}
17270 A format string starting with a @samp{-} can cause problems.
17271 Bash interprets it as an option and
17272 gives an error.  And @samp{--} to mark the end of options is not good
17273 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
17274 literally as the format string.  Putting the @samp{-} in a @samp{%c}
17275 or @samp{%s} is probably easiest:
17277 @example
17278 printf %s -foo
17279 @end example
17281 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
17283 @example
17284 $ @kbd{printf '\045'}
17285 bash: printf: `%': missing format character
17286 @end example
17288 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
17289 example, @file{/usr/bin/printf} is buggy, so when using
17290 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
17291 core.
17293 Since @command{printf} is not always a shell builtin, there is a
17294 potential speed penalty for using @code{printf '%s\n'} as a replacement
17295 for an @command{echo} that does not interpret @samp{\} or leading
17296 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
17297 -r --} for this role instead.
17299 For a discussion of portable alternatives to both @command{printf}
17300 and @command{echo}, @xref{echo, , Limitations of Shell Builtins}.
17303 @item @command{pwd}
17304 @c ----------------
17305 @prindex @command{pwd}
17306 With modern shells, plain @command{pwd} outputs a ``logical''
17307 directory name, some of whose components may be symbolic links.  These
17308 directory names are in contrast to ``physical'' directory names, whose
17309 components are all directories.
17311 Posix 1003.1-2001 requires that @command{pwd} must support
17312 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17313 with @option{-L} being the default.  However, traditional shells do
17314 not support these options, and their @command{pwd} command has the
17315 @option{-P} behavior.
17317 Portable scripts should assume neither option is supported, and should
17318 assume neither behavior is the default.  Also, on many hosts
17319 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
17320 does not require this behavior and portable scripts should not rely on
17323 Typically it's best to use plain @command{pwd}.  On modern hosts this
17324 outputs logical directory names, which have the following advantages:
17326 @itemize @bullet
17327 @item
17328 Logical names are what the user specified.
17329 @item
17330 Physical names may not be portable from one installation
17331 host to another due to network file system gymnastics.
17332 @item
17333 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
17334 some parent directory, but plain @command{pwd} cannot fail for this
17335 reason.
17336 @end itemize
17338 Also please see the discussion of the @command{cd} command.
17341 @item @command{read}
17342 @c -----------------
17343 @prindex @command{read}
17344 No options are portable, not even support @option{-r} (Solaris
17345 @command{/bin/sh} for example).
17348 @anchor{set}
17349 @item @command{set}
17350 @c ----------------
17351 @prindex @command{set}
17352 With the FreeBSD 6.0 shell, the @command{set} command (without
17353 any options) does not sort its output.
17355 The @command{set} builtin faces the usual problem with arguments
17356 starting with a
17357 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
17358 the end of the options (any argument after @option{--} is a parameter,
17359 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
17360 10 @command{/bin/sh}) simply stop option
17361 processing as soon as a non-option argument is found.  Therefore, use
17362 @samp{dummy} or simply @samp{x} to end the option processing, and use
17363 @command{shift} to pop it out:
17365 @example
17366 set x $my_list; shift
17367 @end example
17369 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
17370 longer requires support for this command, and in traditional shells
17371 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
17372 makes scripts harder to debug.
17374 Some nonstandard shells do not recognize more than one option
17375 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
17376 better to combine them:
17378 @example
17379 set -ex
17380 @end example
17382 @cindex @command{set -e}
17383 The option @option{-e} has historically been underspecified, with enough
17384 ambiguities to cause numerous differences across various shell
17385 implementations.  Perhaps the best reference is
17386 @uref{http://www.opengroup.org/@/austin/@/mailarchives/@/ag-review/@/msg03507.html,
17387 this link}, recommending a change to Posix 2008 to match @command{ksh88}
17388 behavior.  Note that mixing @code{set -e} and shell functions is asking
17389 for surprises:
17391 @example
17392 set -e
17393 doit()
17395   rm file
17396   echo one
17398 doit || echo two
17399 @end example
17401 @noindent
17402 According to the recommendation, @samp{one} should always be output
17403 regardless of whether the @command{rm} failed, because it occurs within
17404 the body of the shell function @samp{doit} invoked on the left side of
17405 @samp{||}, where the effects of @samp{set -e} are not enforced.
17406 Likewise, @samp{two} should never be printed, since the failure of
17407 @command{rm} does not abort the function, such that the status of
17408 @samp{doit} is 0.
17410 The BSD shell has had several problems with the @option{-e}
17411 option.  Older versions of the BSD
17412 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
17413 @samp{case} when @option{-e} was in effect, causing the shell to exit
17414 unexpectedly in some cases.  This was particularly a problem with
17415 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
17416 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
17417 wrapper works around the bug (@pxref{Failure in Make Rules}).
17419 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
17420 wrongly exit with @option{-e} if the last command within a compound
17421 statement fails and is guarded by an @samp{&&} only.  For example:
17423 @example
17424 #! /bin/sh
17425 set -e
17426 foo=''
17427 test -n "$foo" && exit 1
17428 echo one
17429 if :; then
17430   test -n "$foo" && exit 1
17431   echo two
17432   test -n "$foo" && exit 1
17434 echo three
17435 @end example
17437 @noindent
17438 does not print @samp{three}.  One workaround is to change the last
17439 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
17440 "$foo"; then exit 1; fi} instead.  Another possibility is to warn BSD
17441 users not to use @samp{sh -e}.
17443 When @samp{set -e} is in effect, a failed command substitution in
17444 Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
17446 @example
17447 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
17448 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
17451 @end example
17453 @noindent
17454 Moreover, a command substitution, successful or not, causes this shell to
17455 exit from a failing outer command even in presence of an @samp{&&} list:
17457 @example
17458 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
17460 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
17462 @end example
17464 Portable scripts should not use @samp{set -e} if @command{trap} is used
17465 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
17466 sometimes enters the trap handler with the exit status of the command
17467 prior to the one that triggered the errexit handler:
17469 @example
17470 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
17472 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
17474 @end example
17476 @noindent
17477 Thus, when writing a script in M4sh, rather than trying to rely on
17478 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
17479 statement where it is desirable to abort on failure.
17481 @cindex @command{set -b}
17482 @cindex @command{set -m}
17483 Job control is not provided by all shells, so the use of @samp{set -m}
17484 or @samp{set -b} must be done with care.  When using @command{zsh} in
17485 native mode, asynchronous notification (@samp{set -b}) is enabled by
17486 default, and using @samp{emulate sh} to switch to Posix mode does not
17487 clear this setting (although asynchronous notification has no impact
17488 unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
17489 earlier have a bug where job control can be manipulated in interactive
17490 shells, but not in subshells or scripts.  Furthermore, some shells, like
17491 @command{pdksh}, fail to treat subshells as interactive, even though the
17492 parent shell was.
17494 @example
17495 $ @kbd{echo $ZSH_VERSION}
17496 4.3.10
17497 $ @kbd{set -m; echo $?}
17499 $ @kbd{zsh -c 'set -m; echo $?'}
17500 set: can't change option: -m
17501 $ @kbd{(set -m); echo $?}
17502 set: can't change option: -m
17504 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
17507 @end example
17510 @item @command{shift}
17511 @c ------------------
17512 @prindex @command{shift}
17513 Not only is @command{shift}ing a bad idea when there is nothing left to
17514 shift, but in addition it is not portable: the shell of MIPS
17515 RISC/OS 4.52 refuses to do it.
17517 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
17518 it is also absent in many pre-Posix shells.
17521 @item @command{source}
17522 @c -------------------
17523 @prindex @command{source}
17524 This command is not portable, as Posix does not require it; use
17525 @command{.} instead.
17528 @item @command{test}
17529 @c -----------------
17530 @prindex @command{test}
17531 The @code{test} program is the way to perform many file and string
17532 tests.  It is often invoked by the alternate name @samp{[}, but using
17533 that name in Autoconf code is asking for trouble since it is an M4 quote
17534 character.
17536 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
17537 present in all implementations, and have been marked obsolete by Posix
17538 2008.  This is because there are inherent ambiguities in using them.
17539 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
17540 check whether two strings are both non-empty, but if @samp{$1} is the
17541 literal @samp{!}, then some implementations of @command{test} treat it
17542 as a negation of the unary operator @option{-a}.
17544 Thus, portable uses of @command{test} should never have more than four
17545 arguments, and scripts should use shell constructs like @samp{&&} and
17546 @samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
17547 statement, keep in mind that they have equal precedence, so it is often
17548 better to parenthesize even when this is redundant.  For example:
17550 @smallexample
17551 # Not portable:
17552 test "X$a" = "X$b" -a \
17553   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
17555 # Portable:
17556 test "X$a" = "X$b" &&
17557   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
17558 @end smallexample
17560 @command{test} does not process options like most other commands do; for
17561 example, it does not recognize the @option{--} argument as marking the
17562 end of options.
17564 It is safe to use @samp{!} as a @command{test} operator.  For example,
17565 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
17566 -d foo; @dots{}} is not.
17569 @item @command{test} (files)
17570 @c -------------------------
17571 To enable @command{configure} scripts to support cross-compilation, they
17572 shouldn't do anything that tests features of the build system instead of
17573 the host system.  But occasionally you may find it necessary to check
17574 whether some arbitrary file exists.  To do so, use @samp{test -f} or
17575 @samp{test -r}.  Do not use @samp{test -x}, because 4.3BSD does not
17576 have it.  Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
17577 lacks it.  To test for symbolic links on systems that have them, use
17578 @samp{test -h} rather than @samp{test -L}; either form conforms to
17579 Posix 1003.1-2001, but older shells like Solaris 8
17580 @code{/bin/sh} support only @option{-h}.
17582 @item @command{test} (strings)
17583 @c ---------------------------
17584 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
17585 not null, but this usage is not portable to traditional platforms like
17586 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
17587 @samp{-n}.
17589 Posix also says that @samp{test ! "@var{string}"},
17590 @samp{test -n "@var{string}"} and
17591 @samp{test -z "@var{string}"} work with any string, but many
17592 shells (such as Solaris, AIX 3.2, UNICOS 10.0.0.6,
17593 Digital Unix 4, etc.)@: get confused if
17594 @var{string} looks like an operator:
17596 @example
17597 $ @kbd{test -n =}
17598 test: argument expected
17599 $ @kbd{test ! -n}
17600 test: argument expected
17601 $ @kbd{test -z ")"; echo $?}
17603 @end example
17605 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
17606 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
17607 strings, but in practice this is not true for troublesome strings that
17608 look like operators or parentheses, or that begin with @samp{-}.
17610 It is best to protect such strings with a leading @samp{X}, e.g.,
17611 @samp{test "X@var{string}" != X} rather than @samp{test -n
17612 "@var{string}"} or @samp{test ! "@var{string}"}.
17614 It is common to find variations of the following idiom:
17616 @example
17617 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
17618   @var{action}
17619 @end example
17621 @noindent
17622 to take an action when a token matches a given pattern.  Such constructs
17623 should be avoided by using:
17625 @example
17626 case $ac_feature in
17627   *[!-a-zA-Z0-9_]*) @var{action};;
17628 esac
17629 @end example
17631 If the pattern is a complicated regular expression that cannot be
17632 expressed as a shell pattern, use something like this instead:
17634 @example
17635 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
17636   @var{action}
17637 @end example
17639 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
17640 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
17641 @samp{@var{foo}} contains backslashes.
17644 @anchor{trap}
17645 @item @command{trap}
17646 @c -----------------
17647 @prindex @command{trap}
17648 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
17649 trap 0, i.e., have the @command{trap} run when the script ends (either via an
17650 explicit @command{exit}, or the end of the script).  The trap for 0 should be
17651 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
17652 will invoke the trap at the end of this function.
17654 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
17655 specified signals to their default values, but many common shells (e.g.,
17656 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
17657 ``command'' named @command{-} when the specified conditions arise.
17658 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
17659 reset traps, as this is supported by a larger set of shells, but there
17660 are still shells like @command{dash} that mistakenly try to execute
17661 @command{1} instead of resetting the traps.  Therefore, there is no
17662 portable workaround, except for @samp{trap - 0}, for which
17663 @samp{trap '' 0} is a portable substitute.
17665 Although Posix is not absolutely clear on this point, it is widely
17666 admitted that when entering the trap @samp{$?} should be set to the exit
17667 status of the last command run before the trap.  The ambiguity can be
17668 summarized as: ``when the trap is launched by an @command{exit}, what is
17669 the @emph{last} command run: that before @command{exit}, or
17670 @command{exit} itself?''
17672 Bash considers @command{exit} to be the last command, while Zsh and
17673 Solaris @command{/bin/sh} consider that when the trap is run it is
17674 @emph{still} in the @command{exit}, hence it is the previous exit status
17675 that the trap receives:
17677 @example
17678 $ @kbd{cat trap.sh}
17679 trap 'echo $?' 0
17680 (exit 42); exit 0
17681 $ @kbd{zsh trap.sh}
17683 $ @kbd{bash trap.sh}
17685 @end example
17687 The portable solution is then simple: when you want to @samp{exit 42},
17688 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
17689 set the exit status to 42 for Zsh, and the second to trigger the trap
17690 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
17691 @code{AS_EXIT}.
17693 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
17694 reset to 0 by empty lines if the code is inside @command{trap}.
17696 @example
17697 $ @kbd{trap 'false}
17699 echo $?' 0
17700 $ @kbd{exit}
17702 @end example
17704 @noindent
17705 Fortunately, this bug only affects @command{trap}.
17707 Several shells fail to execute an exit trap that is defined inside a
17708 subshell, when the last command of that subshell is not a builtin.  A
17709 workaround is to use @samp{exit $?} as the shell builtin.
17711 @example
17712 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
17714 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
17715 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
17717 @end example
17719 @noindent
17720 Likewise, older implementations of @command{bash} failed to preserve
17721 @samp{$?} across an exit trap consisting of a single cleanup command.
17723 @example
17724 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
17726 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
17728 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
17730 @end example
17732 @item @command{true}
17733 @c -----------------
17734 @prindex @command{true}
17735 @c Info cannot handle `:' in index entries.
17736 @c @prindex @command{:}
17737 Don't worry: as far as we know @command{true} is portable.
17738 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
17739 portable shell community tends to prefer using @command{:}.  This has a
17740 funny side effect: when asked whether @command{false} is more portable
17741 than @command{true} Alexandre Oliva answered:
17743 @quotation
17744 In a sense, yes, because if it doesn't exist, the shell will produce an
17745 exit status of failure, which is correct for @command{false}, but not
17746 for @command{true}.
17747 @end quotation
17749 Remember that even though @samp{:} ignores its arguments, it still takes
17750 time to compute those arguments.  It is a good idea to use double quotes
17751 around any arguments to @samp{:} to avoid time spent in field splitting
17752 and file name expansion.
17755 @anchor{unset}
17756 @item @command{unset}
17757 @c ------------------
17758 @prindex @command{unset}
17759 In some nonconforming shells (e.g., Bash 2.05a), @code{unset FOO} fails
17760 when @code{FOO} is not set.  You can use
17762 @smallexample
17763 FOO=; unset FOO
17764 @end smallexample
17766 if you are not sure that @code{FOO} is set.
17768 A few ancient shells lack @command{unset} entirely.  For some variables
17769 such as @code{PS1}, you can use a neutralizing value instead:
17771 @smallexample
17772 PS1='$ '
17773 @end smallexample
17775 Usually, shells that do not support @command{unset} need less effort to
17776 make the environment sane, so for example is not a problem if you cannot
17777 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
17778 @code{unset MAIL} in some cases and dumps core.  So, you should do
17779 something like
17781 @smallexample
17782 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
17783 @end smallexample
17785 @noindent
17786 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
17787 @ref{export, , Limitations of Builtins}, for
17788 the case of environment variables.
17790 @item @command{wait}
17791 @c -----------------
17792 @prindex @command{wait}
17793 The exit status of @command{wait} is not always reliable.
17794 @end table
17796 @node Limitations of Usual Tools
17797 @section Limitations of Usual Tools
17798 @cindex Limitations of usual tools
17800 The small set of tools you can expect to find on any machine can still
17801 include some limitations you should be aware of.
17803 @comment Between this list and the list of builtins above, we should
17804 @comment mention all the tools in GNU Coding Standards ``Utilities in
17805 @comment Makefiles''.
17807 @c This table includes things like `@command{expr} (|)', so we can't
17808 @c use @table @command.
17809 @table @asis
17810 @anchor{awk}
17811 @item @command{awk}
17812 @c ----------------
17813 @prindex @command{awk}
17814 Don't leave white space before the opening parenthesis in a user function call.
17815 Posix does not allow this and GNU Awk rejects it:
17817 @example
17818 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
17819         BEGIN @{ die () @}'}
17820 gawk: cmd. line:2:         BEGIN @{ die () @}
17821 gawk: cmd. line:2:                      ^ parse error
17822 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
17823         BEGIN @{ die() @}'}
17824 Aaaaarg!
17825 @end example
17827 Posix says that if a program contains only @samp{BEGIN} actions, and
17828 contains no instances of @code{getline}, then the program merely
17829 executes the actions without reading input.  However, traditional Awk
17830 implementations (such as Solaris 10 @command{awk}) read and discard
17831 input in this case.  Portable scripts can redirect input from
17832 @file{/dev/null} to work around the problem.  For example:
17834 @example
17835 awk 'BEGIN @{print "hello world"@}' </dev/null
17836 @end example
17838 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
17839 @samp{$1}) retain their value from the last record read, if no
17840 intervening @samp{getline} occurred.  However, some implementations
17841 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
17842 @samp{awk}) reset these variables.  A workaround is to use an
17843 intermediate variable prior to the @samp{END} block.  For example:
17845 @example
17846 $ @kbd{cat end.awk}
17847 @{ tmp = $1 @}
17848 END @{ print "a", $1, $NF, "b", tmp @}
17849 $ @kbd{echo 1 | awk -f end.awk}
17850 a   b 1
17851 $ @kbd{echo 1 | gawk -f end.awk}
17852 a 1 1 b 1
17853 @end example
17855 If you want your program to be deterministic, don't depend on @code{for}
17856 on arrays:
17858 @example
17859 $ @kbd{cat for.awk}
17860 END @{
17861   arr["foo"] = 1
17862   arr["bar"] = 1
17863   for (i in arr)
17864     print i
17866 $ @kbd{gawk -f for.awk </dev/null}
17869 $ @kbd{nawk -f for.awk </dev/null}
17872 @end example
17874 Some Awk implementations, such as HP-UX 11.0's native one,
17875 mishandle anchors:
17877 @example
17878 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
17879 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
17881 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
17882 xfoo
17883 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
17885 @end example
17887 @noindent
17888 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
17889 or use a simple test to reject such implementations.
17891 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
17892 after @code{%u}:
17894 @example
17895 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
17896 0 0
17897 @end example
17899 AIX version 5.2 has an arbitrary limit of 399 on the
17900 length of regular expressions and literal strings in an Awk program.
17902 Traditional Awk implementations derived from Unix version 7, such as
17903 Solaris @command{/bin/awk}, have many limitations and do not
17904 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
17905 Programs}) finds you an Awk that doesn't have these problems, but if
17906 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
17907 address them.  For more detailed descriptions, see @ref{Language
17908 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
17910 Traditional Awk does not support multidimensional arrays or user-defined
17911 functions.
17913 Traditional Awk does not support the @option{-v} option.  You can use
17914 assignments after the program instead, e.g., @code{$AWK '@{print v
17915 $1@}' v=x}; however, don't forget that such assignments are not
17916 evaluated until they are encountered (e.g., after any @code{BEGIN}
17917 action).
17919 Traditional Awk does not support the keywords @code{delete} or @code{do}.
17921 Traditional Awk does not support the expressions
17922 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
17923 or @code{@var{a}^=@var{b}}.
17925 Traditional Awk does not support the predefined @code{CONVFMT} or
17926 @code{ENVIRON} variables.
17928 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
17929 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
17930 @code{sqrt}, and @code{substr}.
17932 Traditional Awk @code{getline} is not at all compatible with Posix;
17933 avoid it.
17935 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
17936 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
17938 In code portable to both traditional and modern Awk, @code{FS} must be a
17939 string containing just one ordinary character, and similarly for the
17940 field-separator argument to @code{split}.
17942 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
17943 implementations, like Tru64's, split the input even if you don't refer
17944 to any field in the script, to circumvent this problem, set @samp{FS}
17945 to an unusual character and use @code{split}.
17947 Traditional Awk has a limit of at most 99 bytes in a number formatted by
17948 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
17949 dumps core.
17951 The original version of Awk had a limit of at most 99 bytes per
17952 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
17953 per run of non-special characters in a @code{printf} format, but these
17954 bugs have been fixed on all practical hosts that we know of.
17956 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
17957 of at most 3070 bytes.
17959 @item @command{basename}
17960 @c ---------------------
17961 @prindex @command{basename}
17962 Not all hosts have a working @command{basename}.
17963 You can use @command{expr} instead.
17965 @c AS_BASENAME is to be replaced by a better API.
17966 @ignore
17967 Not all hosts have a working @command{basename}, and you should instead
17968 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
17969 @command{expr} if you need to strip a suffix.  For example:
17971 @example
17972 a=`basename "$aname"`       # This is not portable.
17973 a=`AS_BASENAME(["$aname"])` # This is more portable.
17975 # This is not portable.
17976 c=`basename "$cname" .c`
17978 # This is more portable.
17979 c=`AS_BASENAME(["$cname"])`
17980 case $c in
17981 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
17982 esac
17983 @end example
17984 @end ignore
17987 @item @command{cat}
17988 @c ----------------
17989 @prindex @command{cat}
17990 Don't rely on any option.
17993 @item @command{cc}
17994 @c ---------------
17995 @prindex @command{cc}
17996 The command @samp{cc -c foo.c} traditionally produces an object file
17997 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
17998 with @option{-o} to specify a different object file name, but
17999 Posix does not require this combination and a few compilers
18000 lack support for it.  @xref{C Compiler}, for how GNU Make
18001 tests for this feature with @code{AC_PROG_CC_C_O}.
18003 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
18004 (such as CDS on Reliant Unix) leave a @file{foo.o}.
18006 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
18007 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
18008 nothing.
18010 The default executable, produced by @samp{cc foo.c}, can be
18012 @itemize
18013 @item @file{a.out} --- usual Posix convention.
18014 @item @file{b.out} --- i960 compilers (including @command{gcc}).
18015 @item @file{a.exe} --- DJGPP port of @command{gcc}.
18016 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
18017 @item @file{foo.exe} --- various MS-DOS compilers.
18018 @end itemize
18020 The C compiler's traditional name is @command{cc}, but other names like
18021 @command{gcc} are common.  Posix 1003.1-2001 specifies the
18022 name @command{c99}, but older Posix editions specified
18023 @command{c89} and anyway these standard names are rarely used in
18024 practice.  Typically the C compiler is invoked from makefiles that use
18025 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
18026 compiler name.
18028 @item @command{chgrp}
18029 @itemx @command{chown}
18030 @c -------------------
18031 @prindex @command{chgrp}
18032 @prindex @command{chown}
18033 It is not portable to change a file's group to a group that the owner
18034 does not belong to.
18036 @item @command{chmod}
18037 @c ------------------
18038 @prindex @command{chmod}
18039 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
18040 instead, for two reasons.  First, plain @option{-w} does not necessarily
18041 make the file unwritable, since it does not affect mode bits that
18042 correspond to bits in the file mode creation mask.  Second,
18043 Posix says that the @option{-w} might be interpreted as an
18044 implementation-specific option, not as a mode; Posix suggests
18045 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
18046 @samp{--} does not work on some older hosts.
18049 @item @command{cmp}
18050 @c ----------------
18051 @prindex @command{cmp}
18052 @command{cmp} performs a raw data comparison of two files, while
18053 @command{diff} compares two text files.  Therefore, if you might compare
18054 DOS files, even if only checking whether two files are different, use
18055 @command{diff} to avoid spurious differences due to differences of
18056 newline encoding.
18059 @item @command{cp}
18060 @c ---------------
18061 @prindex @command{cp}
18062 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
18063 obsolescent and its behavior on special files is implementation-defined.
18064 Use @option{-R} instead.  On GNU hosts the two options
18065 are equivalent, but on Solaris hosts (for example) @code{cp -r}
18066 reads from pipes instead of replicating them.
18068 Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
18069 trailing slashes at the end of nonexistent destination directories.  To
18070 avoid this problem, omit the trailing slashes.  For example, use
18071 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
18072 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
18074 @c This is thanks to Ian.
18075 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
18076 its @command{mv} does.
18078 @cindex timestamp resolution
18079 Traditionally, file timestamps had 1-second resolution, and @samp{cp
18080 -p} copied the timestamps exactly.  However, many modern file systems
18081 have timestamps with 1-nanosecond resolution.  Unfortunately, @samp{cp
18082 -p} implementations truncate timestamps when copying files, so this
18083 can result in the destination file appearing to be older than the
18084 source.  The exact amount of truncation depends on the resolution of
18085 the system calls that @command{cp} uses; traditionally this was
18086 @code{utime}, which has 1-second resolution, but some newer
18087 @command{cp} implementations use @code{utimes}, which has
18088 1-microsecond resolution.  These newer implementations include GNU
18089 Core Utilities 5.0.91 or later, and Solaris 8 (sparc) patch 109933-02 or
18090 later.  Unfortunately as of January 2006 there is still no system
18091 call to set timestamps to the full nanosecond resolution.
18093 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
18094 ownerships.  But whether it actually does copy ownerships or not is a
18095 system dependent policy decision implemented by the kernel.  If the
18096 kernel allows it then it happens.  If the kernel does not allow it then
18097 it does not happen.  It is not something @command{cp} itself has control
18098 over.
18100 In Unix System V any user can chown files to any other user, and System
18101 V also has a non-sticky @file{/tmp}.  That probably derives from the
18102 heritage of System V in a business environment without hostile users.
18103 BSD changed this
18104 to be a more secure model where only root can @command{chown} files and
18105 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
18106 of BSD in a campus environment.
18108 GNU/Linux and Solaris by default follow BSD, but
18109 can be configured to allow a System V style @command{chown}.  On the
18110 other hand, HP-UX follows System V, but can
18111 be configured to use the modern security model and disallow
18112 @command{chown}.  Since it is an administrator-configurable parameter
18113 you can't use the name of the kernel as an indicator of the behavior.
18117 @item @command{date}
18118 @c -----------------
18119 @prindex @command{date}
18120 Some versions of @command{date} do not recognize special @samp{%} directives,
18121 and unfortunately, instead of complaining, they just pass them through,
18122 and exit with success:
18124 @example
18125 $ @kbd{uname -a}
18126 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
18127 $ @kbd{date "+%s"}
18129 @end example
18132 @item @command{diff}
18133 @c -----------------
18134 @prindex @command{diff}
18135 Option @option{-u} is nonportable.
18137 Some implementations, such as Tru64's, fail when comparing to
18138 @file{/dev/null}.  Use an empty file instead.
18141 @item @command{dirname}
18142 @c --------------------
18143 @prindex @command{dirname}
18144 Not all hosts have a working @command{dirname}, and you should instead
18145 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
18147 @example
18148 dir=`dirname "$file"`       # This is not portable.
18149 dir=`AS_DIRNAME(["$file"])` # This is more portable.
18150 @end example
18153 @item @command{egrep}
18154 @c ------------------
18155 @prindex @command{egrep}
18156 Posix 1003.1-2001 no longer requires @command{egrep},
18157 but many hosts do not yet support the Posix
18158 replacement @code{grep -E}.  Also, some traditional implementations do
18159 not work on long input lines.  To work around these problems, invoke
18160 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
18162 Portable extended regular expressions should use @samp{\} only to escape
18163 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
18164 is not portable, even though it typically matches @samp{@}}.
18166 The empty alternative is not portable.  Use @samp{?} instead.  For
18167 instance with Digital Unix v5.0:
18169 @example
18170 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
18171 |foo
18172 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
18173 bar|
18174 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
18176 |bar
18177 @end example
18179 @command{$EGREP} also suffers the limitations of @command{grep}
18180 (@pxref{grep, , Limitations of Usual Tools}).
18182 @item @command{expr}
18183 @c -----------------
18184 @prindex @command{expr}
18185 Not all implementations obey the Posix rule that @samp{--} separates
18186 options from arguments; likewise, not all implementations provide the
18187 extension to Posix that the first argument can be treated as part of a
18188 valid expression rather than an invalid option if it begins with
18189 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
18190 @samp{$var} might be a negative number, to keep @command{expr} from
18191 interpreting it as an option.
18193 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
18194 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
18195 misinterpreting @var{word}.
18197 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
18199 @item @command{expr} (@samp{|})
18200 @prindex @command{expr} (@samp{|})
18201 You can use @samp{|}.  Although Posix does require that @samp{expr
18202 ''} return the empty string, it does not specify the result when you
18203 @samp{|} together the empty string (or zero) with the empty string.  For
18204 example:
18206 @example
18207 expr '' \| ''
18208 @end example
18210 Posix 1003.2-1992 returns the empty string
18211 for this case, but traditional Unix returns @samp{0} (Solaris is
18212 one such example).  In Posix 1003.1-2001, the specification was
18213 changed to match traditional Unix's behavior (which is
18214 bizarre, but it's too late to fix this).  Please note that the same
18215 problem does arise when the empty string results from a computation,
18216 as in:
18218 @example
18219 expr bar : foo \| foo : bar
18220 @end example
18222 @noindent
18223 Avoid this portability problem by avoiding the empty string.
18226 @item @command{expr} (@samp{:})
18227 @c ----------------------------
18228 @prindex @command{expr}
18229 Portable @command{expr} regular expressions should use @samp{\} to
18230 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
18231 For example, alternation, @samp{\|}, is common but Posix does not
18232 require its support, so it should be avoided in portable scripts.
18233 Similarly, @samp{\+} and @samp{\?} should be avoided.
18235 Portable @command{expr} regular expressions should not begin with
18236 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
18237 not needed anyway.
18239 On the other hand, the behavior of the @samp{$} anchor is not portable
18240 on multi-line strings.  Posix is ambiguous whether the anchor applies to
18241 each line, as was done in older versions of GNU Coreutils, or
18242 whether it applies only to the end of the overall string, as in
18243 Coreutils 6.0 and most other implementations.
18245 @example
18246 $ @kbd{baz='foo}
18247 > @kbd{bar'}
18248 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
18250 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
18252 @end example
18254 The Posix standard is ambiguous as to whether
18255 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
18256 In practice, it outputs the empty string on most platforms, but portable
18257 scripts should not assume this.  For instance, the QNX 4.25 native
18258 @command{expr} returns @samp{0}.
18260 One might think that a way to get a uniform behavior would be to use
18261 the empty string as a default value:
18263 @example
18264 expr a : '\(b\)' \| ''
18265 @end example
18267 @noindent
18268 Unfortunately this behaves exactly as the original expression; see the
18269 @command{expr} (@samp{|}) entry for more information.
18271 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
18272 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
18273 @command{expr} to fail if the matched substring is longer than 120
18274 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
18275 @command{expr} fails.  Nowadays this is of practical importance only for
18276 the rare installer who mistakenly puts @file{/usr/ucb} before
18277 @file{/usr/bin} in @env{PATH}.
18279 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
18280 some cases.  For example, the command
18281 @example
18282 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
18283 @end example
18285 @noindent
18286 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
18287 This particular case can be worked around by substituting @samp{[^--]}
18288 for @samp{[^-]}.
18290 Don't leave, there is some more!
18292 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
18293 the empty string, has a funny behavior in its exit status: it's always 1
18294 when parentheses are used!
18296 @example
18297 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
18298 0: 1
18299 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
18300 1: 0
18302 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
18303 1: a
18304 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
18305 1: 0
18306 @end example
18308 @noindent
18309 In practice this can be a big problem if you are ready to catch failures
18310 of @command{expr} programs with some other method (such as using
18311 @command{sed}), since you may get twice the result.  For instance
18313 @example
18314 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
18315 @end example
18317 @noindent
18318 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25.  A
18319 simple workaround consists of testing @command{expr} and using a variable
18320 set to @command{expr} or to @command{false} according to the result.
18322 Tru64 @command{expr} incorrectly treats the result as a number, if it
18323 can be interpreted that way:
18325 @example
18326 $ @kbd{expr 00001 : '.*\(...\)'}
18328 @end example
18330 On HP-UX 11, @command{expr} only supports a single
18331 sub-expression.
18333 @example
18334 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
18335 expr: More than one '\(' was used.
18336 @end example
18339 @item @command{fgrep}
18340 @c ------------------
18341 @prindex @command{fgrep}
18342 Posix 1003.1-2001 no longer requires @command{fgrep},
18343 but many hosts do not yet support the Posix
18344 replacement @code{grep -F}.  Also, some traditional implementations do
18345 not work on long input lines.  To work around these problems, invoke
18346 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
18348 Tru64/OSF 5.1 @command{fgrep} does not match an empty pattern.
18351 @item @command{find}
18352 @c -----------------
18353 @prindex @command{find}
18354 The option @option{-maxdepth} seems to be GNU specific.
18355 Tru64 v5.1, NetBSD 1.5 and Solaris @command{find}
18356 commands do not understand it.
18358 The replacement of @samp{@{@}} is guaranteed only if the argument is
18359 exactly @emph{@{@}}, not if it's only a part of an argument.  For
18360 instance on DU, and HP-UX 10.20 and HP-UX 11:
18362 @example
18363 $ @kbd{touch foo}
18364 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
18365 @{@}-@{@}
18366 @end example
18368 @noindent
18369 while GNU @command{find} reports @samp{./foo-./foo}.
18372 @anchor{grep}
18373 @item @command{grep}
18374 @c -----------------
18375 @prindex @command{grep}
18376 Portable scripts can rely on the @command{grep} options @option{-c},
18377 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
18378 options.  For example, don't use @option{-w}, as Posix does not require
18379 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
18380 portable scripts should not combine @option{-c} with @option{-l},
18381 as Posix does not allow this.
18383 Some of the options required by Posix are not portable in practice.
18384 Don't use @samp{grep -q} to suppress output, because many @command{grep}
18385 implementations (e.g., Solaris) do not support @option{-q}.
18386 Don't use @samp{grep -s} to suppress output either, because Posix
18387 says @option{-s} does not suppress output, only some error messages;
18388 also, the @option{-s} option of traditional @command{grep} behaved
18389 like @option{-q} does in most modern implementations.  Instead,
18390 redirect the standard output and standard error (in case the file
18391 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
18392 status of @code{grep} to determine whether it found a match.
18394 The QNX4 implementation fails to count lines with @code{grep -c '$'},
18395 but works with @code{grep -c '^'}.  Other alternatives for counting
18396 lines are to use @code{sed -n '$='} or @code{wc -l}.
18398 Some traditional @command{grep} implementations do not work on long
18399 input lines.  On AIX the default @code{grep} silently truncates long
18400 lines on the input before matching.
18402 Also, many implementations do not support multiple regexps
18403 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
18404 or honor only the last pattern (e.g., IRIX 6.5 and NeXT).  To
18405 work around these problems, invoke @code{AC_PROG_GREP} and then use
18406 @code{$GREP}.
18408 Another possible workaround for the multiple @option{-e} problem is to
18409 separate the patterns by newlines, for example:
18411 @example
18412 grep 'foo
18413 bar' in.txt
18414 @end example
18416 @noindent
18417 except that this fails with traditional @command{grep}
18418 implementations and with OpenBSD 3.8 @command{grep}.
18420 Traditional @command{grep} implementations (e.g., Solaris) do not
18421 support the @option{-E} or @option{-F} options.  To work around these
18422 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
18423 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
18424 willing to require support for Posix @command{grep}, your script should
18425 not use both @option{-E} and @option{-F}, since Posix does not allow
18426 this combination.
18428 Portable @command{grep} regular expressions should use @samp{\} only to
18429 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
18430 alternation, @samp{\|}, is common but Posix does not require its
18431 support in basic regular expressions, so it should be avoided in
18432 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
18433 Similarly, the following escape sequences should also be avoided:
18434 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
18435 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
18437 Posix does not specify the behavior of @command{grep} on binary files.
18438 An example where this matters is using BSD @command{grep} to
18439 search text that includes embedded ANSI escape sequences for
18440 colored output to terminals (@samp{\033[m} is the sequence to restore
18441 normal output); the behavior depends on whether input is seekable:
18443 @example
18444 $ @kbd{printf 'esc\033[mape\n' > sample}
18445 $ @kbd{grep . sample}
18446 Binary file sample matches
18447 $ @kbd{cat sample | grep .}
18448 escape
18449 @end example
18452 @item @command{join}
18453 @c -----------------
18454 @prindex @command{join}
18455 Solaris 8 @command{join} has bugs when the second operand is standard
18456 input, and when standard input is a pipe.  For example, the following
18457 shell script causes Solaris 8 @command{join} to loop forever:
18459 @example
18460 cat >file <<'EOF'
18461 1 x
18462 2 y
18464 cat file | join file -
18465 @end example
18467 Use @samp{join - file} instead.
18470 @item @command{ln}
18471 @c ---------------
18472 @prindex @command{ln}
18473 @cindex Symbolic links
18474 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
18475 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
18477 For versions of the DJGPP before 2.04,
18478 @command{ln} emulates symbolic links
18479 to executables by generating a stub that in turn calls the real
18480 program.  This feature also works with nonexistent files like in the
18481 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
18482 which attempts to call @file{file.exe} if run.  But this feature only
18483 works for executables, so @samp{cp -p} is used instead for these
18484 systems.  DJGPP versions 2.04 and later have full support
18485 for symbolic links.
18488 @item @command{ls}
18489 @c ---------------
18490 @prindex @command{ls}
18491 @cindex Listing directories
18492 The portable options are @option{-acdilrtu}.  Current practice is for
18493 @option{-l} to output both owner and group, even though ancient versions
18494 of @command{ls} omitted the group.
18496 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
18497 to standard output if @file{foo} did not exist.  Hence a shell command
18498 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
18499 was equivalent to @samp{sources='*.c not found'} in the absence of
18500 @samp{.c} files.  This is no longer a practical problem, since current
18501 @command{ls} implementations send diagnostics to standard error.
18503 The behavior of @command{ls} on a directory that is being concurrently
18504 modified is not always predictable, because of a data race where cached
18505 information returned by @code{readdir} does not match the current
18506 directory state.  In fact, MacOS 10.5 has an intermittent bug where
18507 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
18508 once if other files were added or removed from the directory immediately
18509 prior to the @command{ls} call.  Since @command{ls} already sorts its
18510 output, the duplicate entries can be avoided by piping the results
18511 through @code{uniq}.
18513 @anchor{mkdir}
18514 @item @command{mkdir}
18515 @c ------------------
18516 @prindex @command{mkdir}
18517 @cindex Making directories
18518 No @command{mkdir} option is portable to older systems.  Instead of
18519 @samp{mkdir -p @var{file-name}}, you should use
18520 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
18521 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
18523 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
18524 go-w -p @var{dir}}, often leads to trouble.  FreeBSD
18525 @command{mkdir} incorrectly attempts to change the permissions of
18526 @var{dir} even if it already exists.  HP-UX 11.23 and
18527 IRIX 6.5 @command{mkdir} often assign the wrong permissions to
18528 any newly-created parents of @var{dir}.
18530 Posix does not clearly specify whether @samp{mkdir -p foo}
18531 should succeed when @file{foo} is a symbolic link to an already-existing
18532 directory.  The GNU Core Utilities 5.1.0 @command{mkdir}
18533 succeeds, but Solaris @command{mkdir} fails.
18535 Traditional @code{mkdir -p} implementations suffer from race conditions.
18536 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
18537 at the same time, both processes might detect that @file{a} is missing,
18538 one might create @file{a}, then the other might try to create @file{a}
18539 and fail with a @code{File exists} diagnostic.  The GNU Core
18540 Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
18541 NetBSD 2.0.2, and OpenBSD 2.4 are known to be
18542 race-free when two processes invoke @code{mkdir -p} simultaneously, but
18543 earlier versions are vulnerable.  Solaris @command{mkdir} is still
18544 vulnerable as of Solaris 10, and other traditional Unix systems are
18545 probably vulnerable too.  This possible race is harmful in parallel
18546 builds when several Make rules call @code{mkdir -p} to
18547 construct directories.  You may use
18548 @code{install-sh -d} as a safe replacement, provided this script is
18549 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
18550 OK, but copies from older versions are vulnerable.
18553 @item @command{mkfifo}
18554 @itemx @command{mknod}
18555 @c -------------------
18556 @prindex @command{mkfifo}
18557 @prindex @command{mknod}
18558 The GNU Coding Standards state that @command{mknod} is safe to use on
18559 platforms where it has been tested to exist; but it is generally portable
18560 only for creating named FIFOs, since device numbers are
18561 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
18562 testsuites.  Posix states that behavior is unspecified when opening a
18563 named FIFO for both reading and writing; on at least Cygwin, this
18564 results in failure on any attempt to read or write to that file
18565 descriptor.
18567 @item @command{mktemp}
18568 @c -------------------
18569 @prindex @command{mktemp}
18570 @cindex Creating temporary files
18571 Shell scripts can use temporary files safely with @command{mktemp}, but
18572 it does not exist on all systems.  A portable way to create a safe
18573 temporary file name is to create a temporary directory with mode 700 and
18574 use a file inside this directory.  Both methods prevent attackers from
18575 gaining control, though @command{mktemp} is far less likely to fail
18576 gratuitously under attack.
18578 Here is sample code to create a new temporary directory @samp{$dir} safely:
18580 @example
18581 # Create a temporary directory $dir in $TMPDIR (default /tmp).
18582 # Use mktemp if possible; otherwise fall back on mkdir,
18583 # with $RANDOM to make collisions less likely.
18584 : "$@{TMPDIR:=/tmp@}"
18586   dir=`
18587     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
18588   ` &&
18589   test -d "$dir"
18590 @} || @{
18591   dir=$TMPDIR/foo$$-$RANDOM
18592 @c $$ restore font-lock
18593   (umask 077 && mkdir "$dir")
18594 @} || exit $?
18595 @end example
18598 @item @command{mv}
18599 @c ---------------
18600 @prindex @command{mv}
18601 @cindex Moving open files
18602 The only portable options are @option{-f} and @option{-i}.
18604 Moving individual files between file systems is portable (it was in Unix
18605 version 6),
18606 but it is not always atomic: when doing @samp{mv new existing}, there's
18607 a critical section where neither the old nor the new version of
18608 @file{existing} actually exists.
18610 On some systems moving files from @file{/tmp} can sometimes cause
18611 undesirable (but perfectly valid) warnings, even if you created these
18612 files.  This is because @file{/tmp} belongs to a group that ordinary
18613 users are not members of, and files created in @file{/tmp} inherit
18614 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
18615 a diagnostic without failing:
18617 @smallexample
18618 $ @kbd{touch /tmp/foo}
18619 $ @kbd{mv /tmp/foo .}
18620 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
18621 $ @kbd{echo $?}
18623 $ @kbd{ls foo}
18625 @end smallexample
18627 @noindent
18628 This annoying behavior conforms to Posix, unfortunately.
18630 Moving directories across mount points is not portable, use @command{cp}
18631 and @command{rm}.
18633 DOS variants cannot rename or remove open files, and do not
18634 support commands like @samp{mv foo bar >foo}, even though this is
18635 perfectly portable among Posix hosts.
18638 @item @command{od}
18639 @c ---------------
18640 @prindex @command{od}
18642 In Mac OS X 10.3, @command{od} does not support the
18643 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
18644 @option{-t}, or the XSI option @option{-s}.  The only
18645 supported Posix option is @option{-v}, and the only supported
18646 XSI options are those in @option{-bcdox}.  The BSD
18647 @command{hexdump} program can be used instead.
18649 This problem no longer exists in Mac OS X 10.4.3.
18652 @item @command{rm}
18653 @c ---------------
18654 @prindex @command{rm}
18655 The @option{-f} and @option{-r} options are portable.
18657 It is not portable to invoke @command{rm} without operands.  For
18658 example, on many systems @samp{rm -f -r} (with no other arguments)
18659 silently succeeds without doing anything, but it fails with a diagnostic
18660 on NetBSD 2.0.2.
18662 A file might not be removed even if its parent directory is writable
18663 and searchable.  Many Posix hosts cannot remove a mount point, a named
18664 stream, a working directory, or a last link to a file that is being
18665 executed.
18667 DOS variants cannot rename or remove open files, and do not
18668 support commands like @samp{rm foo >foo}, even though this is
18669 perfectly portable among Posix hosts.
18671 @item @command{rmdir}
18672 @c ------------------
18673 @prindex @command{rmdir}
18674 Just as with @command{rm}, some platforms refuse to remove a working
18675 directory.
18677 @anchor{sed}
18678 @item @command{sed}
18679 @c ----------------
18680 @prindex @command{sed}
18681 Patterns should not include the separator (unless escaped), even as part
18682 of a character class.  In conformance with Posix, the Cray
18683 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
18684 Even when escaped, patterns should not include separators that are also
18685 used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
18686 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
18687 before evaluating the basic regular expression.
18689 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
18690 not require support for empty patterns, and Unicos 9 @command{sed} rejects
18691 them.
18693 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
18695 Sed scripts should not use branch labels longer than 7 characters and
18696 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
18697 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
18698 48 labels, which can not be circumvented by using more than one script
18699 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
18700 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
18701 about 6000 bytes for the internal representation of commands.
18703 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
18704 NetBSD 1.4.2's, incorrectly try to interpret the second
18705 @samp{;} as a command:
18707 @example
18708 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
18709 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
18710 @end example
18712 Input should not have unreasonably long lines, since some @command{sed}
18713 implementations have an input buffer limited to 4000 bytes.  Likewise,
18714 not all @command{sed} implementations can handle embedded @code{NUL} or
18715 a missing trailing newline.
18717 Remember that ranges within a bracket expression of a regular expression
18718 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
18719 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
18720 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
18721 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
18722 than to rely on @samp{[A-Z]}.
18724 Additionally, Posix states that regular expressions are only
18725 well-defined on characters.  Unfortunately, there exist platforms such
18726 as MacOS X 10.5 where not all 8-bit byte values are valid characters,
18727 even though that platform has a single-byte @samp{C} locale.  And Posix
18728 allows the existence of a multi-byte @samp{C} locale, although that does
18729 not yet appear to be a common implementation.  At any rate, it means
18730 that not all bytes will be matched by the regular expression @samp{.}:
18732 @example
18733 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
18735 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
18737 @end example
18739 Portable @command{sed} regular expressions should use @samp{\} only to escape
18740 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
18741 alternation, @samp{\|}, is common but Posix does not require its
18742 support, so it should be avoided in portable scripts.  Solaris
18743 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
18744 deletes only lines that contain the literal string @samp{a|b}.
18745 Similarly, @samp{\+} and @samp{\?} should be avoided.
18747 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
18749 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
18750 quite portable to current hosts, but was not supported by some ancient
18751 @command{sed} implementations like SVR3.
18753 Some @command{sed} implementations, e.g., Solaris, restrict the special
18754 role of the asterisk @samp{*} to one-character regular expressions and
18755 back-references, and the special role of interval expressions
18756 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
18757 to one-character regular expressions.  This may lead to unexpected behavior:
18759 @example
18760 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
18761 x2x4
18762 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
18764 @end example
18766 The @option{-e} option is mostly portable.
18767 However, its argument
18768 cannot start with @samp{a}, @samp{c}, or @samp{i},
18769 as this runs afoul of a Tru64 5.1 bug.
18770 Also, its argument cannot be empty, as this fails on AIX 5.3.
18771 Some people prefer to use @samp{-e}:
18773 @example
18774 sed -e '@var{command-1}' \
18775     -e '@var{command-2}'
18776 @end example
18778 @noindent
18779 as opposed to the equivalent:
18781 @example
18782 sed '
18783   @var{command-1}
18784   @var{command-2}
18786 @end example
18788 @noindent
18789 The following usage is sometimes equivalent:
18791 @example
18792 sed '@var{command-1};@var{command-2}'
18793 @end example
18795 but Posix says that this use of a semicolon has undefined effect if
18796 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
18797 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
18798 should use semicolon only with simple scripts that do not use these
18799 verbs.
18801 Posix up to the 2008 revision requires the argument of the @option{-e}
18802 option to be a syntactically complete script.  GNU @command{sed} allows
18803 to pass multiple script fragments, each as argument of a separate
18804 @option{-e} option, that are then combined, with newlines between the
18805 fragments, and a future Posix revision may allow this as well.  This
18806 approach is not portable with script fragments ending in backslash; for
18807 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
18808 don't allow splitting in this case:
18810 @example
18811 $ @kbd{echo a | sed -n -e 'i\}
18812 @kbd{0'}
18814 $ @kbd{echo a | sed -n -e 'i\' -e 0}
18815 Unrecognized command: 0
18816 @end example
18818 @noindent
18819 In practice, however, this technique of joining fragments
18820 through @option{-e} works for multiple @command{sed} functions within
18821 @samp{@{} and @samp{@}}, even if that is not specified by Posix:
18823 @example
18824 @c The quote around the closing brace silences interactive zsh.
18825 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
18827 @end example
18829 Commands inside @{ @} brackets are further restricted.  Posix 2008 says that
18830 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
18831 each command must be followed immediately by a newline, without any
18832 intervening blanks or semicolons.  The closing bracket must be alone on
18833 a line, other than white space preceding or following it.  However, a
18834 future version of Posix may standardize the use of addresses within brackets.
18836 Contrary to yet another urban legend, you may portably use @samp{&} in
18837 the replacement part of the @code{s} command to mean ``what was
18838 matched''.  All descendants of Unix version 7 @command{sed}
18839 (at least; we
18840 don't have first hand experience with older @command{sed} implementations) have
18841 supported it.
18843 Posix requires that you must not have any white space between
18844 @samp{!} and the following command.  It is OK to have blanks between
18845 the address and the @samp{!}.  For instance, on Solaris:
18847 @example
18848 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
18849 @error{}Unrecognized command: /bar/ ! p
18850 $ @kbd{echo "foo" | sed -n '/bar/! p'}
18851 @error{}Unrecognized command: /bar/! p
18852 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
18854 @end example
18856 Posix also says that you should not combine @samp{!} and @samp{;}.  If
18857 you use @samp{!}, it is best to put it on a command that is delimited by
18858 newlines rather than @samp{;}.
18860 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
18861 @samp{w} commands be followed by exactly one space before their argument.
18862 On the other hand, no white space is allowed between @samp{:} and the
18863 subsequent label name.
18865 If a sed script is specified on the command line and ends in an
18866 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
18867 should be followed by a newline.  Otherwise some @command{sed}
18868 implementations (e.g., OpenBSD 3.9) do not append a newline to the
18869 inserted text.
18871 Many @command{sed} implementations (e.g., MacOS X 10.4,
18872 OpenBSD 3.9, Solaris 10
18873 @command{/usr/ucb/sed}) strip leading white space from the text of
18874 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
18875 work around this incompatibility with Posix:
18877 @example
18878 $ @kbd{echo flushleft | sed 'a\}
18879 > @kbd{   indented}
18880 > @kbd{'}
18881 flushleft
18882 indented
18883 $ @kbd{echo foo | sed 'a\}
18884 > @kbd{\   indented}
18885 > @kbd{'}
18886 flushleft
18887    indented
18888 @end example
18890 Posix requires that with an empty regular expression, the last non-empty
18891 regular expression from either an address specification or substitution
18892 command is applied.  However, busybox 1.6.1 complains when using a
18893 substitution command with a replacement containing a back-reference to
18894 an empty regular expression; the workaround is repeating the regular
18895 expression.
18897 @example
18898 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
18899 sed: No previous regexp.
18900 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
18902 @end example
18905 @item @command{sed} (@samp{t})
18906 @c ---------------------------
18907 @prindex @command{sed} (@samp{t})
18908 Some old systems have @command{sed} that ``forget'' to reset their
18909 @samp{t} flag when starting a new cycle.  For instance on MIPS
18910 RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
18911 script (the line numbers are not actual part of the texts):
18913 @example
18914 s/keep me/kept/g  # a
18915 t end             # b
18916 s/.*/deleted/g    # c
18917 :end              # d
18918 @end example
18920 @noindent
18923 @example
18924 delete me         # 1
18925 delete me         # 2
18926 keep me           # 3
18927 delete me         # 4
18928 @end example
18930 @noindent
18931 you get
18933 @example
18934 deleted
18935 delete me
18936 kept
18937 deleted
18938 @end example
18940 @noindent
18941 instead of
18943 @example
18944 deleted
18945 deleted
18946 kept
18947 deleted
18948 @end example
18950 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
18951 flag, and the output is produced.  When processing
18952 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
18953 fails to match, but @command{sed} is not supposed to clear the @samp{t}
18954 flag when a substitution fails.  Command (b) sees that the flag is set,
18955 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
18956 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
18957 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
18958 Finally, since the flag is clear, line 4 is processed properly.
18960 There are two things one should remember about @samp{t} in @command{sed}.
18961 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
18962 succeeded, not only the immediately preceding substitution.  Therefore,
18963 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
18964 line, to reset the @samp{t} flag where needed.
18966 Secondly, you cannot rely on @command{sed} to clear the flag at each new
18967 cycle.
18969 One portable implementation of the script above is:
18971 @example
18972 t clear
18973 :clear
18974 s/keep me/kept/g
18975 t end
18976 s/.*/deleted/g
18977 :end
18978 @end example
18980 @item @command{sleep}
18981 @c ------------------
18982 @prindex @command{sleep}
18983 Using @command{sleep} is generally portable.  However, remember that
18984 adding a @command{sleep} to work around timestamp issues, with a minimum
18985 granularity of one second, doesn't scale well for parallel builds on
18986 modern machines with sub-second process completion.
18988 @item @command{sort}
18989 @c -----------------
18990 @prindex @command{sort}
18991 Remember that sort order is influenced by the current locale.  Inside
18992 @file{configure}, the C locale is in effect, but in Makefile snippets,
18993 you may need to specify @code{LC_ALL=C sort}.
18995 @item @command{tar}
18996 @c ----------------
18997 @prindex @command{tar}
18998 There are multiple file formats for @command{tar}; if you use Automake,
18999 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
19000 level of portability to use.
19002 @anchor{touch}
19003 @item @command{touch}
19004 @c ------------------
19005 @prindex @command{touch}
19006 @cindex timestamp resolution
19007 If you specify the desired timestamp (e.g., with the @option{-r}
19008 option), @command{touch} typically uses the @code{utime} or
19009 @code{utimes} system call, which can result in the same kind of
19010 timestamp truncation problems that @samp{cp -p} has.
19012 On ancient BSD systems, @command{touch} or any command that
19013 results in an empty file does not update the timestamps, so use a
19014 command like @command{echo} as a workaround.
19015 Also,
19016 GNU @command{touch} 3.16r (and presumably all before that)
19017 fails to work on SunOS 4.1.3 when the empty file is on an
19018 NFS-mounted 4.2 volume.
19019 However, these problems are no longer of practical concern.
19021 @item @command{tr}
19022 @c ---------------
19023 @prindex @command{tr}
19024 @cindex carriage return, deleting
19025 @cindex newline, deleting
19026 @cindex deleting carriage return
19027 Not all versions of @command{tr} handle all backslash character escapes.
19028 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
19029 Solaris contains more modern @command{tr} in other locations.
19030 Using octal escapes is more portable for carriage returns, since
19031 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
19032 literal carriage returns in scripts causes a number of other problems.
19033 But for other characters, like newline, using octal escapes ties the
19034 operation to ASCII, so it is better to use literal characters.
19036 @example
19037 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
19039 light
19040 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
19041 moonlight
19042 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
19043 moonlight
19044 $ @kbd{nl='}
19045 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
19046 moonlight
19047 @end example
19049 Not all versions of @command{tr} recognize direct ranges of characters: at
19050 least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
19051 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in Posix
19052 transliterate to themselves).
19054 @example
19055 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
19056 HAZy FAntAZy
19057 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
19058 HAZY FANTAZY
19059 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
19060 HAZY FANTAZY
19061 @end example
19063 When providing two arguments, be sure the second string is at least as
19064 long as the first.
19066 @example
19067 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
19069 $ @kbd{echo abc | coreutils/tr bc d}
19071 @end example
19073 Posix requires @command{tr} to operate on binary files.  But at least
19074 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
19075 @code{NUL} in the input prior to doing any translation.  When using
19076 @command{tr} to process a binary file that may contain @code{NUL} bytes,
19077 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
19078 @command{/usr/xpg6/bin/tr} if that is available.
19080 @example
19081 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
19082  61 62
19083 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
19084  61 62
19085 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
19086  61 00 62
19087 @end example
19089 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
19090 octal escape for @code{NUL}.
19092 @example
19093 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
19094  61 62 63
19095 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
19096  61 00 64
19097 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
19098  61 00 64
19099 @end example
19101 @end table
19104 @node Portable Make
19105 @chapter Portable Make Programming
19106 @prindex @command{make}
19107 @cindex Limitations of @command{make}
19109 Writing portable makefiles is an art.  Since a makefile's commands are
19110 executed by the shell, you must consider the shell portability issues
19111 already mentioned.  However, other issues are specific to @command{make}
19112 itself.
19114 @menu
19115 * $< in Ordinary Make Rules::   $< in ordinary rules
19116 * Failure in Make Rules::       Failing portably in rules
19117 * Special Chars in Names::      Special Characters in Macro Names
19118 * Backslash-Newline-Newline::   Empty last lines in macro definitions
19119 * Backslash-Newline Comments::  Spanning comments across line boundaries
19120 * Long Lines in Makefiles::     Line length limitations
19121 * Macros and Submakes::         @code{make macro=value} and submakes
19122 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
19123 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
19124 * Parallel Make::               Parallel @command{make} quirks
19125 * Comments in Make Rules::      Other problems with Make comments
19126 * Newlines in Make Rules::      Using literal newlines in rules
19127 * obj/ and Make::               Don't name a subdirectory @file{obj}
19128 * make -k Status::              Exit status of @samp{make -k}
19129 * VPATH and Make::              @code{VPATH} woes
19130 * Single Suffix Rules::         Single suffix rules and separated dependencies
19131 * Timestamps and Make::         Subsecond timestamp resolution
19132 @end menu
19134 @node $< in Ordinary Make Rules
19135 @section @code{$<} in Ordinary Make Rules
19137 Posix says that the @samp{$<} construct in makefiles can be
19138 used only in inference rules and in the @samp{.DEFAULT} rule; its
19139 meaning in ordinary rules is unspecified.  Solaris @command{make}
19140 for instance replaces it with the empty string.  OpenBSD (3.0 and
19141 later) @command{make} diagnoses these uses and errors out.
19143 @node Failure in Make Rules
19144 @section Failure in Make Rules
19146 Posix 2008 requires that @command{make} must invoke each command with
19147 the equivalent of a @samp{sh -e -c} subshell, which causes the
19148 subshell to exit immediately if a subsidiary simple-command fails,
19149 although not all @command{make} implementations have historically
19150 followed this rule.  For
19151 example, the command @samp{touch T; rm -f U} may attempt to
19152 remove @file{U} even if the @command{touch} fails, although this is not
19153 permitted with Posix make.  One way to work around failures in simple
19154 commands is to reword them so that they always succeed, e.g., @samp{touch
19155 T || :; rm -f U}.
19156 However, even this approach can run into common bugs in BSD
19157 implementations of the @option{-e} option of @command{sh} and
19158 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
19159 are worried
19160 about porting to buggy BSD shells it may be simpler to migrate
19161 complicated @command{make} actions into separate scripts.
19163 @node Special Chars in Names
19164 @section Special Characters in Make Macro Names
19166 Posix limits macro names to nonempty strings containing only
19167 ASCII letters and digits, @samp{.}, and @samp{_}.  Many
19168 @command{make} implementations allow a wider variety of characters, but
19169 portable makefiles should avoid them.  It is portable to start a name
19170 with a special character, e.g., @samp{$(.FOO)}.
19172 Some ancient @command{make} implementations don't support leading
19173 underscores in macro names.  An example is NEWS-OS 4.2R.
19175 @example
19176 $ @kbd{cat Makefile}
19177 _am_include = #
19178 _am_quote =
19179 all:; @@echo this is test
19180 $ @kbd{make}
19181 Make: Must be a separator on rules line 2.  Stop.
19182 $ @kbd{cat Makefile2}
19183 am_include = #
19184 am_quote =
19185 all:; @@echo this is test
19186 $ @kbd{make -f Makefile2}
19187 this is test
19188 @end example
19190 @noindent
19191 However, this problem is no longer of practical concern.
19193 @node Backslash-Newline-Newline
19194 @section Backslash-Newline-Newline in Make Macro Values
19196 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
19197 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
19198 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
19199 On some versions of HP-UX, @command{make} reads multiple newlines
19200 following a backslash, continuing to the next non-empty line.  For
19201 example,
19203 @example
19204 FOO = one \
19206 BAR = two
19208 test:
19209         : FOO is "$(FOO)"
19210         : BAR is "$(BAR)"
19211 @end example
19213 @noindent
19214 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
19215 sensibly let a backslash continue only to the immediately following
19216 line.
19218 @node Backslash-Newline Comments
19219 @section Backslash-Newline in Make Comments
19221 According to Posix, Make comments start with @code{#}
19222 and continue until an unescaped newline is reached.
19224 @example
19225 $ @kbd{cat Makefile}
19226 # A = foo \
19227       bar \
19228       baz
19230 all:
19231         @@echo ok
19232 $ @kbd{make}   # GNU make
19234 @end example
19236 @noindent
19237 However this is not always the case.  Some implementations
19238 discard everything from @code{#} through the end of the line, ignoring any
19239 trailing backslash.
19241 @example
19242 $ @kbd{pmake}  # BSD make
19243 "Makefile", line 3: Need an operator
19244 Fatal errors encountered -- cannot continue
19245 @end example
19247 @noindent
19248 Therefore, if you want to comment out a multi-line definition, prefix each
19249 line with @code{#}, not only the first.
19251 @example
19252 # A = foo \
19253 #     bar \
19254 #     baz
19255 @end example
19257 @node Long Lines in Makefiles
19258 @section Long Lines in Makefiles
19260 Tru64 5.1's @command{make} has been reported to crash when given a
19261 makefile with lines longer than around 20 kB.  Earlier versions are
19262 reported to exit with @code{Line too long} diagnostics.
19264 @node Macros and Submakes
19265 @section @code{make macro=value} and Submakes
19267 A command-line variable definition such as @code{foo=bar} overrides any
19268 definition of @code{foo} in a makefile.  Some @command{make}
19269 implementations (such as GNU @command{make}) propagate this
19270 override to subsidiary invocations of @command{make}.  Some other
19271 implementations do not pass the substitution along to submakes.
19273 @example
19274 $ @kbd{cat Makefile}
19275 foo = foo
19276 one:
19277         @@echo $(foo)
19278         $(MAKE) two
19279 two:
19280         @@echo $(foo)
19281 $ @kbd{make foo=bar}            # GNU make 3.79.1
19283 make two
19284 make[1]: Entering directory `/home/adl'
19286 make[1]: Leaving directory `/home/adl'
19287 $ @kbd{pmake foo=bar}           # BSD make
19289 pmake two
19291 @end example
19293 You have a few possibilities if you do want the @code{foo=bar} override
19294 to propagate to submakes.  One is to use the @option{-e}
19295 option, which causes all environment variables to have precedence over
19296 the makefile macro definitions, and declare foo as an environment
19297 variable:
19299 @example
19300 $ @kbd{env foo=bar make -e}
19301 @end example
19303 The @option{-e} option is propagated to submakes automatically,
19304 and since the environment is inherited between @command{make}
19305 invocations, the @code{foo} macro is overridden in
19306 submakes as expected.
19308 This syntax (@code{foo=bar make -e}) is portable only when used
19309 outside of a makefile, for instance from a script or from the
19310 command line.  When run inside a @command{make} rule, GNU
19311 @command{make} 3.80 and prior versions forget to propagate the
19312 @option{-e} option to submakes.
19314 Moreover, using @option{-e} could have unexpected side effects if your
19315 environment contains some other macros usually defined by the
19316 makefile.  (See also the note about @code{make -e} and @code{SHELL}
19317 below.)
19319 If you can foresee all macros that a user might want to override, then
19320 you can propagate them to submakes manually, from your makefile:
19322 @example
19323 foo = foo
19324 one:
19325         @@echo $(foo)
19326         $(MAKE) foo=$(foo) two
19327 two:
19328         @@echo $(foo)
19329 @end example
19331 Another way to propagate a variable to submakes in a portable way is to
19332 expand an extra variable in every invocation of @samp{$(MAKE)} within
19333 your makefile:
19335 @example
19336 foo = foo
19337 one:
19338         @@echo $(foo)
19339         $(MAKE) $(SUBMAKEFLAGS) two
19340 two:
19341         @@echo $(foo)
19342 @end example
19344 Users must be aware that this technique is in use to take advantage of
19345 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
19346 allows any macro to be overridden.  Makefiles generated by
19347 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
19348 on the command lines of submakes (@pxref{Subdirectories, , Automake,
19349 automake, GNU Automake}).
19351 @node The Make Macro MAKEFLAGS
19352 @section The Make Macro MAKEFLAGS
19353 @cindex @code{MAKEFLAGS} and @command{make}
19354 @cindex @command{make} and @code{MAKEFLAGS}
19356 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
19357 current and recursive invocations of make, but allows implementations
19358 several formats for the variable.  It is tricky to parse
19359 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
19360 or @option{-k} for continued execution are in effect.  For example, you
19361 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
19362 contains single-letter options, since in the Cygwin version of
19363 GNU @command{make} it is either @option{--unix} or
19364 @option{--win32} with the second word containing single-letter options.
19366 @example
19367 $ @kbd{cat Makefile}
19368 all:
19369         @@echo MAKEFLAGS = $(MAKEFLAGS)
19370 $ @kbd{make}
19371 MAKEFLAGS = --unix
19372 $ @kbd{make -k}
19373 MAKEFLAGS = --unix -k
19374 @end example
19376 @node The Make Macro SHELL
19377 @section The Make Macro @code{SHELL}
19378 @cindex @code{SHELL} and @command{make}
19379 @cindex @command{make} and @code{SHELL}
19381 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
19382 macro to spawn shell processes and execute Make rules.  This
19383 is a builtin macro supplied by @command{make}, but it can be modified
19384 by a makefile or by a command-line argument.
19386 Not all @command{make} implementations define this @code{SHELL} macro.
19387 Tru64
19388 @command{make} is an example; this implementation always uses
19389 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
19390 your makefiles.  If you use Autoconf, do
19392 @example
19393 SHELL = @@SHELL@@
19394 @end example
19396 @noindent
19397 If you use Automake, this is done for you.
19399 Do not force @code{SHELL = /bin/sh} because that is not correct
19400 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
19401 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
19402 Additionally, DJGPP lacks @code{/bin/sh}, and when its
19403 GNU @command{make} port sees such a setting it enters a
19404 special emulation mode where features like pipes and redirections are
19405 emulated on top of DOS's @command{command.com}.  Unfortunately this
19406 emulation is incomplete; for instance it does not handle command
19407 substitutions.  Using @code{@@SHELL@@} means that your makefile will
19408 benefit from the same improved shell, such as @command{bash} or
19409 @command{ksh}, that was discovered during @command{configure}, so that
19410 you aren't fighting two different sets of shell bugs between the two
19411 contexts.
19413 Posix-compliant @command{make} should never acquire the value of
19414 $(SHELL) from the environment, even when @code{make -e} is used
19415 (otherwise, think about what would happen to your rules if
19416 @code{SHELL=/bin/tcsh}).
19418 However not all @command{make} implementations have this exception.
19419 For instance it's not surprising that Tru64 @command{make} doesn't
19420 protect @code{SHELL}, since it doesn't use it.
19422 @example
19423 $ @kbd{cat Makefile}
19424 SHELL = /bin/sh
19425 FOO = foo
19426 all:
19427         @@echo $(SHELL)
19428         @@echo $(FOO)
19429 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
19430 /bin/tcsh
19432 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
19433 /bin/sh
19435 @end example
19437 Conversely, @command{make} is not supposed to export any changes to the
19438 macro @code{SHELL} to child processes.  Again, many implementations
19439 break this rule:
19441 @example
19442 $ @kbd{cat Makefile}
19443 all:
19444         @@echo $(SHELL)
19445         @@printenv SHELL
19446 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
19447 /bin/ksh
19448 /bin/ksh
19449 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
19450 /bin/ksh
19452 @end example
19454 @node Parallel Make
19455 @section Parallel Make
19456 @cindex Parallel @command{make}
19458 Support for parallel execution in @command{make} implementation varies.
19459 Generally, using GNU make is your best bet.  When NetBSD
19460 @command{make} is invoked with @option{-j@var{N}}, it will reuse the
19461 same shell for multiple commands within one recipe.  This can have
19462 unexpected consequences.@footnote{Note that GNU make has
19463 heuristics to avoid spawning a shell at all if the command is deemed
19464 safe to be executed directly.} For example, change of directories or
19465 variables persist between commands:
19467 @example
19468 all:
19469         @@var=value; cd /; pwd; echo $$var; echo $$$$
19470         @@pwd; echo $$var; echo $$$$
19471 @end example
19473 @noindent
19474 may output the following with @code{make -j1}:
19476 @example
19477 --- all ---
19479 value
19480 32235
19482 value
19483 32235
19484 @end example
19486 while without @option{-j1}, or with @option{-B}, the output looks less
19487 surprising:
19489 @example
19491 value
19492 32238
19493 /tmp
19495 32239
19496 @end example
19498 Another consequence of this is that, if one command in a recipe uses
19499 @code{exit 0} to indicate a successful exit, the shell will be gone
19500 and the remaining commands of this recipe will not be executed.
19502 The above example also shows additional status output NetBSD
19503 @command{make} produces in parallel mode for targets being updated.
19505 Furthermore, parallel NetBSD @command{make} will route standard error
19506 from commands that it spawns into its own standard output, and may
19507 remove leading whitespace from output lines.
19509 You can avoid these issues by using the @option{-B} option to enable
19510 compatibility semantics.  However, that will effectively also disable
19511 all parallelism as that will cause prerequisites to be updated in the
19512 order they are listed in a rule.
19514 @node Comments in Make Rules
19515 @section Comments in Make Rules
19516 @cindex Comments in @file{Makefile} rules
19517 @cindex @file{Makefile} rules and comments
19519 Never put comments in a rule.
19521 Some @command{make} treat anything starting with a tab as a command for
19522 the current rule, even if the tab is immediately followed by a @code{#}.
19523 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
19524 makefile runs @code{# foo} through the shell.
19526 @example
19527 all:
19528         # foo
19529 @end example
19531 As a workaround, you can use the @command{:} no-op command with a string
19532 argument that gets ignored:
19534 @example
19535 all:
19536         : "foo"
19537 @end example
19539 @node Newlines in Make Rules
19540 @section Newlines in Make Rules
19541 @cindex Newlines in @file{Makefile} rules
19542 @cindex @file{Makefile} rules and newlines
19544 In shell scripts, newlines can be used inside string literals.  But in
19545 the shell statements of @file{Makefile} rules, this is not possible:
19546 A newline not preceded by a backslash is a separator between shell
19547 statements.  Whereas a newline that is preceded by a backslash becomes
19548 part of the shell statement according to POSIX, but gets replaced,
19549 together with the backslash that precedes it, by a space in GNU
19550 @command{make} 3.80 and older.  So, how can a newline be used in a string
19551 literal?
19553 The trick is to set up a shell variable that contains a newline:
19555 @example
19556 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"
19557 @end example
19559 For example, in order to create a multiline @samp{sed} expression that
19560 inserts a blank line after every line of a file, this code can be used:
19562 @example
19563 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"; \
19564 sed -e "s/\$$/\\$$@{nl@}/" < input > output
19565 @end example
19567 @node obj/ and Make
19568 @section The @file{obj/} Subdirectory and Make
19569 @cindex @file{obj/}, subdirectory
19570 @cindex BSD @command{make} and @file{obj/}
19572 Never name one of your subdirectories @file{obj/} if you don't like
19573 surprises.
19575 If an @file{obj/} directory exists, BSD @command{make} enters it
19576 before reading the makefile.  Hence the makefile in the
19577 current directory is not read.
19579 @example
19580 $ @kbd{cat Makefile}
19581 all:
19582         echo Hello
19583 $ @kbd{cat obj/Makefile}
19584 all:
19585         echo World
19586 $ @kbd{make}      # GNU make
19587 echo Hello
19588 Hello
19589 $ @kbd{pmake}     # BSD make
19590 echo World
19591 World
19592 @end example
19594 @node make -k Status
19595 @section Exit Status of @code{make -k}
19596 @cindex @code{make -k}
19598 Do not rely on the exit status of @code{make -k}.  Some implementations
19599 reflect whether they encountered an error in their exit status; other
19600 implementations always succeed.
19602 @example
19603 $ @kbd{cat Makefile}
19604 all:
19605         false
19606 $ @kbd{make -k; echo exit status: $?}    # GNU make
19607 false
19608 make: *** [all] Error 1
19609 exit status: 2
19610 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
19611 false
19612 *** Error code 1 (continuing)
19613 exit status: 0
19614 @end example
19616 @node VPATH and Make
19617 @section @code{VPATH} and Make
19618 @cindex @code{VPATH}
19620 Posix does not specify the semantics of @code{VPATH}.  Typically,
19621 @command{make} supports @code{VPATH}, but its implementation is not
19622 consistent.
19624 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
19625 portable to recent-enough popular implementations of @command{make}, but
19626 to keep the resulting makefiles portable, a package's makefile
19627 prototypes must take the following issues into account.  These issues
19628 are complicated and are often poorly understood, and installers who use
19629 @code{VPATH} should expect to find many bugs in this area.  If you use
19630 @code{VPATH}, the simplest way to avoid these portability bugs is to
19631 stick with GNU @command{make}, since it is the most
19632 commonly-used @command{make} among Autoconf users.
19634 Here are some known issues with some @code{VPATH}
19635 implementations.
19637 @menu
19638 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
19639 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
19640 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
19641 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
19642 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
19643 * Make Target Lookup::          More details about @code{VPATH} lookup
19644 @end menu
19646 @node Variables listed in VPATH
19647 @subsection Variables listed in @code{VPATH}
19648 @cindex @code{VPATH} and variables
19649 @cindex variables and @code{VPATH}
19651 Do not set @code{VPATH} to the value of another variable, for example
19652 @samp{VPATH = $(srcdir)}, because some ancient versions of
19653 @command{make} do not do variable substitutions on the value of
19654 @code{VPATH}.  For example, use this
19656 @example
19657 srcdir = @@srcdir@@
19658 VPATH = @@srcdir@@
19659 @end example
19661 @noindent
19662 rather than @samp{VPATH = $(srcdir)}.  Note that with GNU
19663 Automake, there is no need to set this yourself.
19665 @node VPATH and Double-colon
19666 @subsection @code{VPATH} and Double-colon Rules
19667 @cindex @code{VPATH} and double-colon rules
19668 @cindex double-colon rules and @code{VPATH}
19670 With ancient versions of Sun @command{make},
19671 any assignment to @code{VPATH} causes @command{make} to execute only
19672 the first set of double-colon rules.
19673 However, this problem is no longer of practical concern.
19675 @node $< in Explicit Rules
19676 @subsection @code{$<} Not Supported in Explicit Rules
19677 @cindex explicit rules, @code{$<}, and @code{VPATH}
19678 @cindex @code{$<}, explicit rules, and @code{VPATH}
19679 @cindex @code{VPATH}, explicit rules, and @code{$<}
19681 Using @code{$<} in explicit rules is not portable.
19682 The prerequisite file must be named explicitly in the rule.  If you want
19683 to find the prerequisite via a @code{VPATH} search, you have to code the
19684 whole thing manually.  @xref{Build Directories}.
19686 @node Automatic Rule Rewriting
19687 @subsection Automatic Rule Rewriting
19688 @cindex @code{VPATH} and automatic rule rewriting
19689 @cindex automatic rule rewriting and @code{VPATH}
19691 Some @command{make} implementations, such as Solaris and Tru64,
19692 search for prerequisites in @code{VPATH} and
19693 then rewrite each occurrence as a plain word in the rule.
19694 For instance:
19696 @example
19697 # This isn't portable to GNU make.
19698 VPATH = ../pkg/src
19699 f.c: if.c
19700         cp if.c f.c
19701 @end example
19703 @noindent
19704 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
19705 found in @file{../pkg/src}.
19707 However, this rule leads to real problems in practice.  For example, if
19708 the source directory contains an ordinary file named @file{test} that is
19709 used in a dependency, Solaris @command{make} rewrites commands like
19710 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
19711 @dots{}}, which is typically undesirable.  To avoid this problem,
19712 portable makefiles should never mention a source file whose name is that
19713 of a shell keyword like @file{until} or a shell command like
19714 @command{cat} or @command{gcc} or @command{test}.
19716 Because of these problems GNU @command{make} and many other
19717 @command{make} implementations do not rewrite commands, so portable
19718 makefiles should
19719 search @code{VPATH} manually.  It is tempting to write this:
19721 @smallexample
19722 # This isn't portable to Solaris make.
19723 VPATH = ../pkg/src
19724 f.c: if.c
19725         cp `test -f if.c || echo $(VPATH)/`if.c f.c
19726 @end smallexample
19728 @noindent
19729 However, the ``prerequisite rewriting'' still applies here.  So if
19730 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
19731 execute
19733 @smallexample
19734 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
19735 @end smallexample
19737 @noindent
19738 which reduces to
19740 @example
19741 cp if.c f.c
19742 @end example
19744 @noindent
19745 and thus fails.  Oops.
19747 A simple workaround, and good practice anyway, is to use @samp{$?} and
19748 @samp{$@@} when possible:
19750 @smallexample
19751 VPATH = ../pkg/src
19752 f.c: if.c
19753         cp $? $@@
19754 @end smallexample
19756 @noindent
19757 but this does not generalize well to commands with multiple
19758 prerequisites.  A more general workaround is to rewrite the rule so that
19759 the prerequisite @file{if.c} never appears as a plain word.  For
19760 example, these three rules would be safe, assuming @file{if.c} is in
19761 @file{../pkg/src} and the other files are in the working directory:
19763 @smallexample
19764 VPATH = ../pkg/src
19765 f.c: if.c f1.c
19766         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
19767 g.c: if.c g1.c
19768         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
19769 h.c: if.c h1.c
19770         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
19771 @end smallexample
19773 Things get worse when your prerequisites are in a macro.
19775 @example
19776 VPATH = ../pkg/src
19777 HEADERS = f.h g.h h.h
19778 install-HEADERS: $(HEADERS)
19779         for i in $(HEADERS); do \
19780           $(INSTALL) -m 644 \
19781             `test -f $$i || echo $(VPATH)/`$$i \
19782             $(DESTDIR)$(includedir)/$$i; \
19783 @c $$ restore font-lock
19784         done
19785 @end example
19787 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
19788 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
19789 where @code{f.h} and @code{g.h} are plain words and are hence
19790 subject to @code{VPATH} adjustments.
19792 If the three files are in @file{../pkg/src}, the rule is run as:
19794 @example
19795 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
19796   install -m 644 \
19797      `test -f $i || echo ../pkg/src/`$i \
19798      /usr/local/include/$i; \
19799 done
19800 @end example
19802 where the two first @command{install} calls fail.  For instance,
19803 consider the @code{f.h} installation:
19805 @example
19806 install -m 644 \
19807   `test -f ../pkg/src/f.h || \
19808     echo ../pkg/src/ \
19809   `../pkg/src/f.h \
19810   /usr/local/include/../pkg/src/f.h;
19811 @end example
19813 @noindent
19814 It reduces to:
19816 @example
19817 install -m 644 \
19818   ../pkg/src/f.h \
19819   /usr/local/include/../pkg/src/f.h;
19820 @end example
19822 Note that the manual @code{VPATH} search did not cause any problems here;
19823 however this command installs @file{f.h} in an incorrect directory.
19825 Trying to quote @code{$(HEADERS)} in some way, as we did for
19826 @code{foo.c} a few makefiles ago, does not help:
19828 @example
19829 install-HEADERS: $(HEADERS)
19830         headers='$(HEADERS)'; \
19831         for i in $$headers; do \
19832           $(INSTALL) -m 644 \
19833             `test -f $$i || echo $(VPATH)/`$$i \
19834             $(DESTDIR)$(includedir)/$$i; \
19835         done
19836 @end example
19838 Now, @code{headers='$(HEADERS)'} macro-expands to:
19840 @example
19841 headers='f.h g.h h.h'
19842 @end example
19844 @noindent
19845 but @code{g.h} is still a plain word.  (As an aside, the idiom
19846 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
19847 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
19848 syntax error on @code{for i in;}.)
19850 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
19852 @example
19853 VPATH = ../pkg/src
19854 HEADERS = f.h g.h h.h
19855 install-HEADERS: $(HEADERS)
19856         headers='$(HEADERS)'; \
19857         for i in $$headers; do \
19858           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
19859           $(INSTALL) -m 644 \
19860             `test -f $$i || echo $(VPATH)/`$$i \
19861             $(DESTDIR)$(includedir)/$$i; \
19862 @c $$ restore font-lock
19863         done
19864 @end example
19866 Automake does something similar.  However the above hack works only if
19867 the files listed in @code{HEADERS} are in the current directory or a
19868 subdirectory; they should not be in an enclosing directory.  If we had
19869 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
19870 build with Tru64 @command{make}.  The reason is that not only does
19871 Tru64 @command{make} rewrite dependencies, but it also simplifies
19872 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
19873 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
19874 a leading @file{../pkg/src/} component.
19876 The following example makes the behavior of Tru64 @command{make}
19877 more apparent.
19879 @example
19880 $ @kbd{cat Makefile}
19881 VPATH = sub
19882 all: ../foo
19883         echo ../foo
19884 $ @kbd{ls}
19885 Makefile foo
19886 $ @kbd{make}
19887 echo foo
19889 @end example
19891 @noindent
19892 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
19893 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
19894 directory does not even exist, this just means that the simplification
19895 occurred before the file was checked for.)
19897 For the record here is how SunOS 4 @command{make} behaves on this
19898 example.
19900 @smallexample
19901 $ @kbd{make}
19902 make: Fatal error: Don't know how to make target `../foo'
19903 $ @kbd{mkdir sub}
19904 $ @kbd{make}
19905 echo sub/../foo
19906 sub/../foo
19907 @end smallexample
19910 @node Tru64 Directory Magic
19911 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
19912 @cindex @code{VPATH} and prerequisite directories
19913 @cindex prerequisite directories and @code{VPATH}
19915 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
19916 @command{make} creates it in the current directory.
19918 @example
19919 $ @kbd{mkdir -p foo/bar build}
19920 $ @kbd{cd build}
19921 $ @kbd{cat >Makefile <<END
19922 VPATH = ..
19923 all: foo/bar
19924 END}
19925 $ @kbd{make}
19926 mkdir foo
19927 mkdir foo/bar
19928 @end example
19930 This can yield unexpected results if a rule uses a manual @code{VPATH}
19931 search as presented before.
19933 @example
19934 VPATH = ..
19935 all : foo/bar
19936         command `test -d foo/bar || echo ../`foo/bar
19937 @end example
19939 The above @command{command} is run on the empty @file{foo/bar}
19940 directory that was created in the current directory.
19942 @node Make Target Lookup
19943 @subsection Make Target Lookup
19944 @cindex @code{VPATH}, resolving target pathnames
19946 GNU @command{make} uses a complex algorithm to decide when it
19947 should use files found via a @code{VPATH} search.  @xref{Search
19948 Algorithm, , How Directory Searches are Performed, make, The GNU Make
19949 Manual}.
19951 If a target needs to be rebuilt, GNU @command{make} discards the
19952 file name found during the @code{VPATH} search for this target, and
19953 builds the file locally using the file name given in the makefile.
19954 If a target does not need to be rebuilt, GNU @command{make} uses the
19955 file name found during the @code{VPATH} search.
19957 Other @command{make} implementations, like NetBSD @command{make}, are
19958 easier to describe: the file name found during the @code{VPATH} search
19959 is used whether the target needs to be rebuilt or not.  Therefore
19960 new files are created locally, but existing files are updated at their
19961 @code{VPATH} location.
19963 OpenBSD and FreeBSD @command{make}, however,
19964 never perform a
19965 @code{VPATH} search for a dependency that has an explicit rule.
19966 This is extremely annoying.
19968 When attempting a @code{VPATH} build for an autoconfiscated package
19969 (e.g., @code{mkdir build && cd build && ../configure}), this means
19971 @command{make} builds everything locally in the @file{build}
19972 directory, while BSD @command{make} builds new files locally and
19973 updates existing files in the source directory.
19975 @example
19976 $ @kbd{cat Makefile}
19977 VPATH = ..
19978 all: foo.x bar.x
19979 foo.x bar.x: newer.x
19980         @@echo Building $@@
19981 $ @kbd{touch ../bar.x}
19982 $ @kbd{touch ../newer.x}
19983 $ @kbd{make}        # GNU make
19984 Building foo.x
19985 Building bar.x
19986 $ @kbd{pmake}       # NetBSD make
19987 Building foo.x
19988 Building ../bar.x
19989 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
19990 Building foo.x
19991 Building bar.x
19992 $ @kbd{tmake}       # Tru64 make
19993 Building foo.x
19994 Building bar.x
19995 $ @kbd{touch ../bar.x}
19996 $ @kbd{make}        # GNU make
19997 Building foo.x
19998 $ @kbd{pmake}       # NetBSD make
19999 Building foo.x
20000 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20001 Building foo.x
20002 Building bar.x
20003 $ @kbd{tmake}       # Tru64 make
20004 Building foo.x
20005 Building bar.x
20006 @end example
20008 Note how NetBSD @command{make} updates @file{../bar.x} in its
20009 VPATH location, and how FreeBSD, OpenBSD, and Tru64
20010 @command{make} always
20011 update @file{bar.x}, even when @file{../bar.x} is up to date.
20013 Another point worth mentioning is that once GNU @command{make} has
20014 decided to ignore a @code{VPATH} file name (e.g., it ignored
20015 @file{../bar.x} in the above example) it continues to ignore it when
20016 the target occurs as a prerequisite of another rule.
20018 The following example shows that GNU @command{make} does not look up
20019 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
20020 because it ignored the @code{VPATH} result of @file{bar.x} while running
20021 the @code{bar.x: newer.x} rule.
20023 @example
20024 $ @kbd{cat Makefile}
20025 VPATH = ..
20026 all: bar.y
20027 bar.x: newer.x
20028         @@echo Building $@@
20029 .SUFFIXES: .x .y
20030 .x.y:
20031         cp $< $@@
20032 $ @kbd{touch ../bar.x}
20033 $ @kbd{touch ../newer.x}
20034 $ @kbd{make}        # GNU make
20035 Building bar.x
20036 cp bar.x bar.y
20037 cp: cannot stat `bar.x': No such file or directory
20038 make: *** [bar.y] Error 1
20039 $ @kbd{pmake}       # NetBSD make
20040 Building ../bar.x
20041 cp ../bar.x bar.y
20042 $ @kbd{rm bar.y}
20043 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20044 echo Building bar.x
20045 cp bar.x bar.y
20046 cp: cannot stat `bar.x': No such file or directory
20047 *** Error code 1
20048 $ @kbd{tmake}       # Tru64 make
20049 Building bar.x
20050 cp: bar.x: No such file or directory
20051 *** Exit 1
20052 @end example
20054 Note that if you drop away the command from the @code{bar.x: newer.x}
20055 rule, GNU @command{make} magically starts to work: it
20056 knows that @code{bar.x} hasn't been updated, therefore it doesn't
20057 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
20058 uses.  Tru64 also works, but FreeBSD and OpenBSD
20059 still don't.
20061 @example
20062 $ @kbd{cat Makefile}
20063 VPATH = ..
20064 all: bar.y
20065 bar.x: newer.x
20066 .SUFFIXES: .x .y
20067 .x.y:
20068         cp $< $@@
20069 $ @kbd{touch ../bar.x}
20070 $ @kbd{touch ../newer.x}
20071 $ @kbd{make}        # GNU make
20072 cp ../bar.x bar.y
20073 $ @kbd{rm bar.y}
20074 $ @kbd{pmake}       # NetBSD make
20075 cp ../bar.x bar.y
20076 $ @kbd{rm bar.y}
20077 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20078 cp bar.x bar.y
20079 cp: cannot stat `bar.x': No such file or directory
20080 *** Error code 1
20081 $ @kbd{tmake}       # Tru64 make
20082 cp ../bar.x bar.y
20083 @end example
20085 It seems the sole solution that would please every @command{make}
20086 implementation is to never rely on @code{VPATH} searches for targets.
20087 In other words, @code{VPATH} should be reserved to unbuilt sources.
20090 @node Single Suffix Rules
20091 @section Single Suffix Rules and Separated Dependencies
20092 @cindex Single Suffix Inference Rule
20093 @cindex Rule, Single Suffix Inference
20094 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
20095 (@samp{.from.to:}), but which @emph{destination} suffix is empty
20096 (@samp{.from:}).
20098 @cindex Separated Dependencies
20099 @dfn{Separated dependencies} simply refers to listing the prerequisite
20100 of a target, without defining a rule.  Usually one can list on the one
20101 hand side, the rules, and on the other hand side, the dependencies.
20103 Solaris @command{make} does not support separated dependencies for
20104 targets defined by single suffix rules:
20106 @example
20107 $ @kbd{cat Makefile}
20108 .SUFFIXES: .in
20109 foo: foo.in
20110 .in:
20111         cp $< $@@
20112 $ @kbd{touch foo.in}
20113 $ @kbd{make}
20114 $ @kbd{ls}
20115 Makefile  foo.in
20116 @end example
20118 @noindent
20119 while GNU Make does:
20121 @example
20122 $ @kbd{gmake}
20123 cp foo.in foo
20124 $ @kbd{ls}
20125 Makefile  foo       foo.in
20126 @end example
20128 Note it works without the @samp{foo: foo.in} dependency.
20130 @example
20131 $ @kbd{cat Makefile}
20132 .SUFFIXES: .in
20133 .in:
20134         cp $< $@@
20135 $ @kbd{make foo}
20136 cp foo.in foo
20137 @end example
20139 @noindent
20140 and it works with double suffix inference rules:
20142 @example
20143 $ @kbd{cat Makefile}
20144 foo.out: foo.in
20145 .SUFFIXES: .in .out
20146 .in.out:
20147         cp $< $@@
20148 $ @kbd{make}
20149 cp foo.in foo.out
20150 @end example
20152 As a result, in such a case, you have to write target rules.
20154 @node Timestamps and Make
20155 @section Timestamp Resolution and Make
20156 @cindex timestamp resolution
20157 Traditionally, file timestamps had 1-second resolution, and
20158 @command{make} used those timestamps to determine whether one file was
20159 newer than the other.  However, many modern file systems have
20160 timestamps with 1-nanosecond resolution.  Some @command{make}
20161 implementations look at the entire timestamp; others ignore the
20162 fractional part, which can lead to incorrect results.  Normally this
20163 is not a problem, but in some extreme cases you may need to use tricks
20164 like @samp{sleep 1} to work around timestamp truncation bugs.
20166 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
20167 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
20168 Tools}).  Hence you should be wary of rules like this:
20170 @example
20171 dest: src
20172         cp -p src dest
20173 @end example
20175 as @file{dest} often appears to be older than @file{src} after the
20176 timestamp is truncated, and this can cause @command{make} to do
20177 needless rework the next time it is invoked.  To work around this
20178 problem, you can use a timestamp file, e.g.:
20180 @example
20181 dest-stamp: src
20182         cp -p src dest
20183         date >dest-stamp
20184 @end example
20189 @c ======================================== Portable C and C++ Programming
20191 @node Portable C and C++
20192 @chapter Portable C and C++ Programming
20193 @cindex Portable C and C++ programming
20195 C and C++ programs often use low-level features of the underlying
20196 system, and therefore are often more difficult to make portable to other
20197 platforms.
20199 Several standards have been developed to help make your programs more
20200 portable.  If you write programs with these standards in mind, you can
20201 have greater confidence that your programs work on a wide variety
20202 of systems.
20203 @ifhtml
20204 @uref{http://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
20205 Standards Supported by GCC}
20206 @end ifhtml
20207 @ifnothtml
20208 @xref{Standards, , Language Standards Supported by
20209 GCC, gcc, Using the GNU Compiler Collection
20210 (GCC)},
20211 @end ifnothtml
20212 for a list of C-related standards.  Many programs also assume the
20213 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
20215 Some old code is written to be portable to K&R C, which predates any C
20216 standard.  K&R C compilers are no longer of practical interest, though,
20217 and the rest of section assumes at least C89, the first C standard.
20219 Program portability is a huge topic, and this section can only briefly
20220 introduce common pitfalls.  @xref{System Portability, , Portability
20221 between System Types, standards, The GNU Coding Standards}, for
20222 more information.
20224 @menu
20225 * Varieties of Unportability::  How to make your programs unportable
20226 * Integer Overflow::            When integers get too large
20227 * Preprocessor Arithmetic::     @code{#if} expression problems
20228 * Null Pointers::               Properties of null pointers
20229 * Buffer Overruns::             Subscript errors and the like
20230 * Volatile Objects::            @code{volatile} and signals
20231 * Floating Point Portability::  Portable floating-point arithmetic
20232 * Exiting Portably::            Exiting and the exit status
20233 @end menu
20235 @node Varieties of Unportability
20236 @section Varieties of Unportability
20237 @cindex portability
20239 Autoconf tests and ordinary programs often need to test what is allowed
20240 on a system, and therefore they may need to deliberately exceed the
20241 boundaries of what the standards allow, if only to see whether an
20242 optional feature is present.  When you write such a program, you should
20243 keep in mind the difference between constraints, unspecified behavior,
20244 and undefined behavior.
20246 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
20247 example constraint is that C programs must not declare a bit-field with
20248 negative width.  Tests can therefore reliably assume that programs with
20249 negative-width bit-fields are rejected by a compiler that conforms
20250 to the standard.
20252 @dfn{Unspecified behavior} is valid behavior, where the standard allows
20253 multiple possibilities.  For example, the order of evaluation of
20254 function arguments is unspecified.  Some unspecified behavior is
20255 @dfn{implementation-defined}, i.e., documented by the implementation,
20256 but since Autoconf tests cannot read the documentation they cannot
20257 distinguish between implementation-defined and other unspecified
20258 behavior.  It is common for Autoconf tests to probe implementations to
20259 determine otherwise-unspecified behavior.
20261 @dfn{Undefined behavior} is invalid behavior, where the standard allows
20262 the implementation to do anything it pleases.  For example,
20263 dereferencing a null pointer leads to undefined behavior.  If possible,
20264 test programs should avoid undefined behavior, since a program with
20265 undefined behavior might succeed on a test that should fail.
20267 The above rules apply to programs that are intended to conform to the
20268 standard.  However, strictly-conforming programs are quite rare, since
20269 the standards are so limiting.  A major goal of Autoconf is to support
20270 programs that use implementation features not described by the standard,
20271 and it is fairly common for test programs to violate the above rules, if
20272 the programs work well enough in practice.
20274 @node Integer Overflow
20275 @section Integer Overflow
20276 @cindex integer overflow
20277 @cindex overflow, signed integer
20278 @cindex signed integer overflow
20279 @cindex wraparound arithmetic
20281 In practice many portable C programs assume that signed integer overflow wraps
20282 around reliably using two's complement arithmetic.  Yet the C standard
20283 says that program behavior is undefined on overflow, and in a few cases
20284 C programs do not work on some modern implementations because their
20285 overflows do not wrap around as their authors expected.  Conversely, in
20286 signed integer remainder, the C standard requires overflow
20287 behavior that is commonly not implemented.
20289 @menu
20290 * Integer Overflow Basics::      Why integer overflow is a problem
20291 * Signed Overflow Examples::     Examples of code assuming wraparound
20292 * Optimization and Wraparound::  Optimizations that break uses of wraparound
20293 * Signed Overflow Advice::       Practical advice for signed overflow issues
20294 * Signed Integer Division::      @code{INT_MIN / -1} and @code{INT_MIN % -1}
20295 @end menu
20297 @node Integer Overflow Basics
20298 @subsection Basics of Integer Overflow
20299 @cindex integer overflow
20300 @cindex overflow, signed integer
20301 @cindex signed integer overflow
20302 @cindex wraparound arithmetic
20304 In languages like C, unsigned integer overflow reliably wraps around;
20305 e.g., @code{UINT_MAX + 1} yields zero.
20306 This is guaranteed by the C standard and is
20307 portable in practice, unless you specify aggressive,
20308 nonstandard optimization options
20309 suitable only for special applications.
20311 In contrast, the C standard says that signed integer overflow leads to
20312 undefined behavior where a program can do anything, including dumping
20313 core or overrunning a buffer.  The misbehavior can even precede the
20314 overflow.  Such an overflow can occur during addition, subtraction,
20315 multiplication, division, and left shift.
20317 Despite this requirement of the standard, many C programs and Autoconf
20318 tests assume that signed integer overflow silently wraps around modulo a
20319 power of two, using two's complement arithmetic, so long as you cast the
20320 resulting value to a signed integer type or store it into a signed
20321 integer variable.  If you use conservative optimization flags, such
20322 programs are generally portable to the vast majority of modern
20323 platforms, with a few exceptions discussed later.
20325 For historical reasons the C standard also allows implementations with
20326 ones' complement or signed magnitude arithmetic, but it is safe to
20327 assume two's complement nowadays.
20329 Also, overflow can occur when converting an out-of-range value to a
20330 signed integer type.  Here a standard implementation must define what
20331 happens, but this might include raising an exception.  In practice all
20332 known implementations support silent wraparound in this case, so you need
20333 not worry about other possibilities.
20335 @node Signed Overflow Examples
20336 @subsection Examples of Code Assuming Wraparound Overflow
20337 @cindex integer overflow
20338 @cindex overflow, signed integer
20339 @cindex signed integer overflow
20340 @cindex wraparound arithmetic
20342 There has long been a tension between what the C standard requires for
20343 signed integer overflow, and what C programs commonly assume.  The
20344 standard allows aggressive optimizations based on assumptions that
20345 overflow never occurs, but many practical C programs rely on overflow
20346 wrapping around.  These programs do not conform to the standard, but
20347 they commonly work in practice because compiler writers are
20348 understandably reluctant to implement optimizations that would break
20349 many programs, unless perhaps a user specifies aggressive optimization.
20351 The C Standard says that if a program has signed integer overflow its
20352 behavior is undefined, and the undefined behavior can even precede the
20353 overflow.  To take an extreme example:
20355 @c Inspired by Robert Dewar's example in
20356 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
20357 @example
20358 if (password == expected_password)
20359   allow_superuser_privileges ();
20360 else if (counter++ == INT_MAX)
20361   abort ();
20362 else
20363   printf ("%d password mismatches\n", counter);
20364 @end example
20366 @noindent
20367 If the @code{int} variable @code{counter} equals @code{INT_MAX},
20368 @code{counter++} must overflow and the behavior is undefined, so the C
20369 standard allows the compiler to optimize away the test against
20370 @code{INT_MAX} and the @code{abort} call.
20371 Worse, if an earlier bug in the program lets the compiler deduce that
20372 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
20373 the C standard allows the compiler to optimize away the password test
20374 and generate code that allows superuser privileges unconditionally.
20376 Despite this requirement by the standard, it has long been common for C
20377 code to assume wraparound arithmetic after signed overflow, and all
20378 known practical C implementations support some C idioms that assume
20379 wraparound signed arithmetic, even if the idioms do not conform
20380 strictly to the standard.  If your code looks like the following
20381 examples it will almost surely work with real-world compilers.
20383 Here is an example derived from the 7th Edition Unix implementation of
20384 @code{atoi} (1979-01-10):
20386 @example
20387 char *p;
20388 int f, n;
20389 @dots{}
20390 while (*p >= '0' && *p <= '9')
20391   n = n * 10 + *p++ - '0';
20392 return (f ? -n : n);
20393 @end example
20395 @noindent
20396 Even if the input string is in range, on most modern machines this has
20397 signed overflow when computing the most negative integer (the @code{-n}
20398 overflows) or a value near an extreme integer (the first @code{+}
20399 overflows).
20401 Here is another example, derived from the 7th Edition implementation of
20402 @code{rand} (1979-01-10).  Here the programmer expects both
20403 multiplication and addition to wrap on overflow:
20405 @example
20406 static long int randx = 1;
20407 @dots{}
20408 randx = randx * 1103515245 + 12345;
20409 return (randx >> 16) & 077777;
20410 @end example
20412 In the following example, derived from the GNU C Library 2.5
20413 implementation of @code{mktime} (2006-09-09), the code assumes
20414 wraparound arithmetic in @code{+} to detect signed overflow:
20416 @example
20417 time_t t, t1, t2;
20418 int sec_requested, sec_adjustment;
20419 @dots{}
20420 t1 = t + sec_requested;
20421 t2 = t1 + sec_adjustment;
20422 if (((t1 < t) != (sec_requested < 0))
20423     | ((t2 < t1) != (sec_adjustment < 0)))
20424   return -1;
20425 @end example
20427 If your code looks like these examples, it is probably safe even though
20428 it does not strictly conform to the C standard.  This might lead one to
20429 believe that one can generally assume wraparound on overflow, but that
20430 is not always true, as can be seen in the next section.
20432 @node Optimization and Wraparound
20433 @subsection Optimizations That Break Wraparound Arithmetic
20434 @cindex loop induction
20436 Compilers sometimes generate code that is incompatible with wraparound
20437 integer arithmetic.  A simple example is an algebraic simplification: a
20438 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
20439 because it assumes that @code{i * 2000} does not overflow.  The
20440 translation is not equivalent to the original when overflow occurs:
20441 e.g., in the typical case of 32-bit signed two's complement wraparound
20442 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
20443 the original expression returns @minus{}2147483 but the optimized
20444 version returns the mathematically correct value 2147484.
20446 More subtly, loop induction optimizations often exploit the undefined
20447 behavior of signed overflow.  Consider the following contrived function
20448 @code{sumc}:
20450 @example
20452 sumc (int lo, int hi)
20454   int sum = 0;
20455   int i;
20456   for (i = lo; i <= hi; i++)
20457     sum ^= i * 53;
20458   return sum;
20460 @end example
20462 @noindent
20463 To avoid multiplying by 53 each time through the loop, an optimizing
20464 compiler might internally transform @code{sumc} to the equivalent of the
20465 following:
20467 @example
20469 transformed_sumc (int lo, int hi)
20471   int sum = 0;
20472   int hic = hi * 53;
20473   int ic;
20474   for (ic = lo * 53; ic <= hic; ic += 53)
20475     sum ^= ic;
20476   return sum;
20478 @end example
20480 @noindent
20481 This transformation is allowed by the C standard, but it is invalid for
20482 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
20483 overflow in computing expressions like @code{hi * 53} can cause the
20484 expression @code{i <= hi} to yield a different value from the
20485 transformed expression @code{ic <= hic}.
20487 For this reason, compilers that use loop induction and similar
20488 techniques often do not support reliable wraparound arithmetic when a
20489 loop induction variable like @code{ic} is involved.  Since loop
20490 induction variables are generated by the compiler, and are not visible
20491 in the source code, it is not always trivial to say whether the problem
20492 affects your code.
20494 Hardly any code actually depends on wraparound arithmetic in cases like
20495 these, so in practice these loop induction optimizations are almost
20496 always useful.  However, edge cases in this area can cause problems.
20497 For example:
20499 @example
20500 int j;
20501 for (j = 1; 0 < j; j *= 2)
20502   test (j);
20503 @end example
20505 @noindent
20506 Here, the loop attempts to iterate through all powers of 2 that
20507 @code{int} can represent, but the C standard allows a compiler to
20508 optimize away the comparison and generate an infinite loop,
20509 under the argument that behavior is undefined on overflow.  As of this
20510 writing this optimization is not done by any production version of
20511 GCC with @option{-O2}, but it might be performed by other
20512 compilers, or by more aggressive GCC optimization options,
20513 and the GCC developers have not decided whether it will
20514 continue to work with GCC and @option{-O2}.
20516 @node Signed Overflow Advice
20517 @subsection Practical Advice for Signed Overflow Issues
20518 @cindex integer overflow
20519 @cindex overflow, signed integer
20520 @cindex signed integer overflow
20521 @cindex wraparound arithmetic
20523 Ideally the safest approach is to avoid signed integer overflow
20524 entirely.  For example, instead of multiplying two signed integers, you
20525 can convert them to unsigned integers, multiply the unsigned values,
20526 then test whether the result is in signed range.
20528 Rewriting code in this way will be inconvenient, though, particularly if
20529 the signed values might be negative.  Also, it may hurt
20530 performance.  Using unsigned arithmetic to check for overflow is
20531 particularly painful to do portably and efficiently when dealing with an
20532 integer type like @code{uid_t} whose width and signedness vary from
20533 platform to platform.
20535 Furthermore, many C applications pervasively assume wraparound behavior
20536 and typically it is not easy to find and remove all these assumptions.
20537 Hence it is often useful to maintain nonstandard code that assumes
20538 wraparound on overflow, instead of rewriting the code.  The rest of this
20539 section attempts to give practical advice for this situation.
20541 If your code wants to detect signed integer overflow in @code{sum = a +
20542 b}, it is generally safe to use an expression like @code{(sum < a) != (b
20543 < 0)}.
20545 If your code uses a signed loop index, make sure that the index cannot
20546 overflow, along with all signed expressions derived from the index.
20547 Here is a contrived example of problematic code with two instances of
20548 overflow.
20550 @example
20551 for (i = INT_MAX - 10; i <= INT_MAX; i++)
20552   if (i + 1 < 0)
20553     @{
20554       report_overflow ();
20555       break;
20556     @}
20557 @end example
20559 @noindent
20560 Because of the two overflows, a compiler might optimize away or
20561 transform the two comparisons in a way that is incompatible with the
20562 wraparound assumption.
20564 If your code uses an expression like @code{(i * 2000) / 1000} and you
20565 actually want the multiplication to wrap around on overflow, use
20566 unsigned arithmetic
20567 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
20569 If your code assumes wraparound behavior and you want to insulate it
20570 against any GCC optimizations that would fail to support that
20571 behavior, you should use GCC's @option{-fwrapv} option, which
20572 causes signed overflow to wrap around reliably (except for division and
20573 remainder, as discussed in the next section).
20575 If you need to port to platforms where signed integer overflow does not
20576 reliably wrap around (e.g., due to hardware overflow checking, or to
20577 highly aggressive optimizations), you should consider debugging with
20578 GCC's @option{-ftrapv} option, which causes signed overflow to
20579 raise an exception.
20581 @node Signed Integer Division
20582 @subsection Signed Integer Division and Integer Overflow
20583 @cindex division, integer
20585 Overflow in signed
20586 integer division is not always harmless: for example, on CPUs of the
20587 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
20588 which by default terminates the program.  Worse, taking the remainder
20589 of these two values typically yields the same signal on these CPUs,
20590 even though the C standard requires @code{INT_MIN % -1} to yield zero
20591 because the expression does not overflow.
20593 @node Preprocessor Arithmetic
20594 @section Preprocessor Arithmetic
20595 @cindex preprocessor arithmetic
20597 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
20598 be evaluated as if all signed values are of type @code{intmax_t} and all
20599 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
20600 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
20601 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
20602 @code{long long int}.  Also, some older preprocessors mishandle
20603 constants ending in @code{LL}.  To work around these problems, you can
20604 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
20605 @code{configure}-time rather than at @code{#if}-time.
20607 @node Null Pointers
20608 @section Properties of Null Pointers
20609 @cindex null pointers
20611 Most modern hosts reliably fail when you attempt to dereference a null
20612 pointer.
20614 On almost all modern hosts, null pointers use an all-bits-zero internal
20615 representation, so you can reliably use @code{memset} with 0 to set all
20616 the pointers in an array to null values.
20618 If @code{p} is a null pointer to an object type, the C expression
20619 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
20620 the standard says that it has undefined behavior.
20622 @node Buffer Overruns
20623 @section Buffer Overruns and Subscript Errors
20624 @cindex buffer overruns
20626 Buffer overruns and subscript errors are the most common dangerous
20627 errors in C programs.  They result in undefined behavior because storing
20628 outside an array typically modifies storage that is used by some other
20629 object, and most modern systems lack runtime checks to catch these
20630 errors.  Programs should not rely on buffer overruns being caught.
20632 There is one exception to the usual rule that a portable program cannot
20633 address outside an array.  In C, it is valid to compute the address just
20634 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
20635 so long as you do not dereference the resulting pointer.  But it is not
20636 valid to compute the address just before an object, e.g., @code{&a[-1]};
20637 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
20638 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
20639 reliable in general, and it is usually easy enough to avoid the
20640 potential portability problem, e.g., by allocating an extra unused array
20641 element at the start or end.
20643 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
20645 users might also consider using the @option{-fmudflap} option to catch
20646 overruns.
20648 Buffer overruns are usually caused by off-by-one errors, but there are
20649 more subtle ways to get them.
20651 Using @code{int} values to index into an array or compute array sizes
20652 causes problems on typical 64-bit hosts where an array index might
20653 be @math{2^{31}} or larger.  Index values of type @code{size_t} avoid this
20654 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
20655 are signed, and are wide enough in practice.
20657 If you add or multiply two numbers to calculate an array size, e.g.,
20658 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
20659 multiplication overflows.
20661 Many implementations of the @code{alloca} function silently misbehave
20662 and can generate buffer overflows if given sizes that are too large.
20663 The size limits are implementation dependent, but are at least 4000
20664 bytes on all platforms that we know about.
20666 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
20667 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
20668 portable code should not use them unless the inputs are known to be
20669 within certain limits.  The time-related functions can overflow their
20670 buffers if given timestamps out of range (e.g., a year less than -999
20671 or greater than 9999).  Time-related buffer overflows cannot happen with
20672 recent-enough versions of the GNU C library, but are possible
20673 with other
20674 implementations.  The @code{gets} function is the worst, since it almost
20675 invariably overflows its buffer when presented with an input line larger
20676 than the buffer.
20678 @node Volatile Objects
20679 @section Volatile Objects
20680 @cindex volatile objects
20682 The keyword @code{volatile} is often misunderstood in portable code.
20683 Its use inhibits some memory-access optimizations, but programmers often
20684 wish that it had a different meaning than it actually does.
20686 @code{volatile} was designed for code that accesses special objects like
20687 memory-mapped device registers whose contents spontaneously change.
20688 Such code is inherently low-level, and it is difficult to specify
20689 portably what @code{volatile} means in these cases.  The C standard
20690 says, ``What constitutes an access to an object that has
20691 volatile-qualified type is implementation-defined,'' so in theory each
20692 implementation is supposed to fill in the gap by documenting what
20693 @code{volatile} means for that implementation.  In practice, though,
20694 this documentation is usually absent or incomplete.
20696 One area of confusion is the distinction between objects defined with
20697 volatile types, and volatile lvalues.  From the C standard's point of
20698 view, an object defined with a volatile type has externally visible
20699 behavior.  You can think of such objects as having little oscilloscope
20700 probes attached to them, so that the user can observe some properties of
20701 accesses to them, just as the user can observe data written to output
20702 files.  However, the standard does not make it clear whether users can
20703 observe accesses by volatile lvalues to ordinary objects.  For example:
20705 @example
20706 /* Declare and access a volatile object.
20707    Accesses to X are "visible" to users.  */
20708 static int volatile x;
20709 x = 1;
20711 /* Access two ordinary objects via a volatile lvalue.
20712    It's not clear whether accesses to *P are "visible".  */
20713 int y;
20714 int *z = malloc (sizeof (int));
20715 int volatile *p;
20716 p = &y;
20717 *p = 1;
20718 p = z;
20719 *p = 1;
20720 @end example
20722 Programmers often wish that @code{volatile} meant ``Perform the memory
20723 access here and now, without merging several memory accesses, without
20724 changing the memory word size, and without reordering.''  But the C
20725 standard does not require this.  For objects defined with a volatile
20726 type, accesses must be done before the next sequence point; but
20727 otherwise merging, reordering, and word-size change is allowed.  Worse,
20728 it is not clear from the standard whether volatile lvalues provide more
20729 guarantees in general than nonvolatile lvalues, if the underlying
20730 objects are ordinary.
20732 Even when accessing objects defined with a volatile type,
20733 the C standard allows only
20734 extremely limited signal handlers: the behavior is undefined if a signal
20735 handler reads any nonlocal object, or writes to any nonlocal object
20736 whose type is not @code{sig_atomic_t volatile}, or calls any standard
20737 library function other than @code{abort}, @code{signal}, and (if C99)
20738 @code{_Exit}.  Hence C compilers need not worry about a signal handler
20739 disturbing ordinary computation, unless the computation accesses a
20740 @code{sig_atomic_t volatile} lvalue that is not a local variable.
20741 (There is an obscure exception for accesses via a pointer to a volatile
20742 character, since it may point into part of a @code{sig_atomic_t
20743 volatile} object.)  Posix
20744 adds to the list of library functions callable from a portable signal
20745 handler, but otherwise is like the C standard in this area.
20747 Some C implementations allow memory-access optimizations within each
20748 translation unit, such that actual behavior agrees with the behavior
20749 required by the standard only when calling a function in some other
20750 translation unit, and a signal handler acts like it was called from a
20751 different translation unit.  The C standard hints that in these
20752 implementations, objects referred to by signal handlers ``would require
20753 explicit specification of @code{volatile} storage, as well as other
20754 implementation-defined restrictions.''  But unfortunately even for this
20755 special case these other restrictions are often not documented well.
20756 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
20757 GNU Compiler Collection (GCC)}, for some
20758 restrictions imposed by GCC.  @xref{Defining Handlers, ,
20759 Defining Signal Handlers, libc, The GNU C Library}, for some
20760 restrictions imposed by the GNU C library.  Restrictions
20761 differ on other platforms.
20763 If possible, it is best to use a signal handler that fits within the
20764 limits imposed by the C and Posix standards.
20766 If this is not practical, you can try the following rules of thumb.  A
20767 signal handler should access only volatile lvalues, preferably lvalues
20768 that refer to objects defined with a volatile type, and should not
20769 assume that the accessed objects have an internally consistent state
20770 if they are larger than a machine word.  Furthermore, installers
20771 should employ compilers and compiler options that are commonly used
20772 for building operating system kernels, because kernels often need more
20773 from @code{volatile} than the C Standard requires, and installers who
20774 compile an application in a similar environment can sometimes benefit
20775 from the extra constraints imposed by kernels on compilers.
20776 Admittedly we are handwaving somewhat here, as there are few
20777 guarantees in this area; the rules of thumb may help to fix some bugs
20778 but there is a good chance that they will not fix them all.
20780 For @code{volatile}, C++ has the same problems that C does.
20781 Multithreaded applications have even more problems with @code{volatile},
20782 but they are beyond the scope of this section.
20784 The bottom line is that using @code{volatile} typically hurts
20785 performance but should not hurt correctness.  In some cases its use
20786 does help correctness, but these cases are often so poorly understood
20787 that all too often adding @code{volatile} to a data structure merely
20788 alleviates some symptoms of a bug while not fixing the bug in general.
20790 @node Floating Point Portability
20791 @section Floating Point Portability
20792 @cindex floating point
20794 Almost all modern systems use IEEE-754 floating point, and it is safe to
20795 assume IEEE-754 in most portable code these days.  For more information,
20796 please see David Goldberg's classic paper
20797 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
20798 Scientist Should Know About Floating-Point Arithmetic}.
20800 @node Exiting Portably
20801 @section Exiting Portably
20802 @cindex exiting portably
20804 A C or C++ program can exit with status @var{N} by returning
20805 @var{N} from the @code{main} function.  Portable programs are supposed
20806 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
20807 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
20808 fail by exiting with status 1, and test programs that assume Posix can
20809 fail by exiting with status values from 1 through 255.  Programs on
20810 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
20811 status when @code{main} returned nonzero, but ancient systems like these
20812 are no longer of practical concern.
20814 A program can also exit with status @var{N} by passing @var{N} to the
20815 @code{exit} function, and a program can fail by calling the @code{abort}
20816 function.  If a program is specialized to just some platforms, it can fail
20817 by calling functions specific to those platforms, e.g., @code{_exit}
20818 (Posix) and @code{_Exit} (C99).  However, like other functions, an exit
20819 function should be declared, typically by including a header.  For
20820 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
20821 either directly or via the default includes (@pxref{Default Includes}).
20823 A program can fail due to undefined behavior such as dereferencing a null
20824 pointer, but this is not recommended as undefined behavior allows an
20825 implementation to do whatever it pleases and this includes exiting
20826 successfully.
20829 @c ================================================== Manual Configuration
20831 @node Manual Configuration
20832 @chapter Manual Configuration
20834 A few kinds of features can't be guessed automatically by running test
20835 programs.  For example, the details of the object-file format, or
20836 special options that need to be passed to the compiler or linker.  You
20837 can check for such features using ad-hoc means, such as having
20838 @command{configure} check the output of the @code{uname} program, or
20839 looking for libraries that are unique to particular systems.  However,
20840 Autoconf provides a uniform method for handling unguessable features.
20842 @menu
20843 * Specifying Target Triplets::  Specifying target triplets
20844 * Canonicalizing::              Getting the canonical system type
20845 * Using System Type::           What to do with the system type
20846 @end menu
20848 @node Specifying Target Triplets
20849 @section Specifying target triplets
20850 @cindex System type
20851 @cindex Target triplet
20852 @c This node used to be named Specifying Names.  The @anchor allows old
20853 @c links to still work.
20854 @anchor{Specifying Names}
20856 Autoconf-generated
20857 @command{configure} scripts can make decisions based on a canonical name
20858 for the system type, or @dfn{target triplet}, which has the form:
20859 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
20860 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
20862 @command{configure} can usually guess the canonical name for the type of
20863 system it's running on.  To do so it runs a script called
20864 @command{config.guess}, which infers the name using the @code{uname}
20865 command or symbols predefined by the C preprocessor.
20867 Alternately, the user can specify the system type with command line
20868 arguments to @command{configure} (@pxref{System Type}.  Doing so is
20869 necessary when
20870 cross-compiling.  In the most complex case of cross-compiling, three
20871 system types are involved.  The options to specify them are:
20873 @table @option
20874 @item --build=@var{build-type}
20875 the type of system on which the package is being configured and
20876 compiled.  It defaults to the result of running @command{config.guess}.
20878 @item --host=@var{host-type}
20879 the type of system on which the package runs.  By default it is the
20880 same as the build machine.  Specifying it enables the cross-compilation
20881 mode.
20883 @item --target=@var{target-type}
20884 the type of system for which any compiler tools in the package
20885 produce code (rarely needed).  By default, it is the same as host.
20886 @end table
20888 If you mean to override the result of @command{config.guess}, use
20889 @option{--build}, not @option{--host}, since the latter enables
20890 cross-compilation.  For historical reasons,
20891 whenever you specify @option{--host},
20892 be sure to specify @option{--build} too; this will be fixed in the
20893 future.  So, to enter cross-compilation mode, use a command like this
20895 @example
20896 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
20897 @end example
20899 @noindent
20900 Note that if you do not specify @option{--host}, @command{configure}
20901 fails if it can't run the code generated by the specified compiler.  For
20902 example, configuring as follows fails:
20904 @example
20905 ./configure CC=m68k-coff-gcc
20906 @end example
20908 When cross-compiling, @command{configure} will warn about any tools
20909 (compilers, linkers, assemblers) whose name is not prefixed with the
20910 host type.  This is an aid to users performing cross-compilation.
20911 Continuing the example above, if a cross-compiler named @command{cc} is
20912 used with a native @command{pkg-config}, then libraries found by
20913 @command{pkg-config} will likely cause subtle build failures; but using
20914 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
20915 avoids any confusion.  Avoiding the warning is as simple as creating the
20916 correct symlinks naming the cross tools.
20918 @cindex @command{config.sub}
20919 @command{configure} recognizes short aliases for many system types; for
20920 example, @samp{decstation} can be used instead of
20921 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
20922 @command{config.sub} to canonicalize system type aliases.
20924 This section deliberately omits the description of the obsolete
20925 interface; see @ref{Hosts and Cross-Compilation}.
20928 @node Canonicalizing
20929 @section Getting the Canonical System Type
20930 @cindex System type
20931 @cindex Canonical system type
20933 The following macros make the system type available to @command{configure}
20934 scripts.
20936 @ovindex build_alias
20937 @ovindex host_alias
20938 @ovindex target_alias
20940 The variables @samp{build_alias}, @samp{host_alias}, and
20941 @samp{target_alias} are always exactly the arguments of @option{--build},
20942 @option{--host}, and @option{--target}; in particular, they are left empty
20943 if the user did not use them, even if the corresponding
20944 @code{AC_CANONICAL} macro was run.  Any configure script may use these
20945 variables anywhere.  These are the variables that should be used when in
20946 interaction with the user.
20948 If you need to recognize some special environments based on their system
20949 type, run the following macros to get canonical system names.  These
20950 variables are not set before the macro call.
20952 If you use these macros, you must distribute @command{config.guess} and
20953 @command{config.sub} along with your source code.  @xref{Output}, for
20954 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
20955 to control in which directory @command{configure} looks for those scripts.
20958 @defmac AC_CANONICAL_BUILD
20959 @acindex{CANONICAL_BUILD}
20960 @ovindex build
20961 @ovindex build_cpu
20962 @ovindex build_vendor
20963 @ovindex build_os
20964 Compute the canonical build-system type variable, @code{build}, and its
20965 three individual parts @code{build_cpu}, @code{build_vendor}, and
20966 @code{build_os}.
20968 If @option{--build} was specified, then @code{build} is the
20969 canonicalization of @code{build_alias} by @command{config.sub},
20970 otherwise it is determined by the shell script @command{config.guess}.
20971 @end defmac
20973 @defmac AC_CANONICAL_HOST
20974 @acindex{CANONICAL_HOST}
20975 @ovindex host
20976 @ovindex host_cpu
20977 @ovindex host_vendor
20978 @ovindex host_os
20979 Compute the canonical host-system type variable, @code{host}, and its
20980 three individual parts @code{host_cpu}, @code{host_vendor}, and
20981 @code{host_os}.
20983 If @option{--host} was specified, then @code{host} is the
20984 canonicalization of @code{host_alias} by @command{config.sub},
20985 otherwise it defaults to @code{build}.
20986 @end defmac
20988 @defmac AC_CANONICAL_TARGET
20989 @acindex{CANONICAL_TARGET}
20990 @ovindex target
20991 @ovindex target_cpu
20992 @ovindex target_vendor
20993 @ovindex target_os
20994 Compute the canonical target-system type variable, @code{target}, and its
20995 three individual parts @code{target_cpu}, @code{target_vendor}, and
20996 @code{target_os}.
20998 If @option{--target} was specified, then @code{target} is the
20999 canonicalization of @code{target_alias} by @command{config.sub},
21000 otherwise it defaults to @code{host}.
21001 @end defmac
21003 Note that there can be artifacts due to the backward compatibility
21004 code.  @xref{Hosts and Cross-Compilation}, for more.
21006 @node Using System Type
21007 @section Using the System Type
21009 In @file{configure.ac} the system type is generally used by one or more
21010 @code{case} statements to select system-specifics.  Shell wildcards can
21011 be used to match a group of system types.
21013 For example, an extra assembler code object file could be chosen, giving
21014 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
21015 following would be used in a makefile to add the object to a
21016 program or library.
21018 @example
21019 AS_CASE([$host],
21020   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
21021   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
21022   [CYCLE_OBJ=""]
21024 AC_SUBST([CYCLE_OBJ])
21025 @end example
21027 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
21028 to select variant source files, for example optimized code for some
21029 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
21030 so some runtime capability checks may be necessary too.
21032 @example
21033 case $host in
21034   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
21035   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
21036   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
21037 esac
21038 @end example
21040 The host system type can also be used to find cross-compilation tools
21041 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
21043 The above examples all show @samp{$host}, since this is where the code
21044 is going to run.  Only rarely is it necessary to test @samp{$build}
21045 (which is where the build is being done).
21047 Whenever you're tempted to use @samp{$host} it's worth considering
21048 whether some sort of probe would be better.  New system types come along
21049 periodically or previously missing features are added.  Well-written
21050 probes can adapt themselves to such things, but hard-coded lists of
21051 names can't.  Here are some guidelines,
21053 @itemize @bullet
21054 @item
21055 Availability of libraries and library functions should always be checked
21056 by probing.
21057 @item
21058 Variant behavior of system calls is best identified with runtime tests
21059 if possible, but bug workarounds or obscure difficulties might have to
21060 be driven from @samp{$host}.
21061 @item
21062 Assembler code is inevitably highly CPU-specific and is best selected
21063 according to @samp{$host_cpu}.
21064 @item
21065 Assembler variations like underscore prefix on globals or ELF versus
21066 COFF type directives are however best determined by probing, perhaps
21067 even examining the compiler output.
21068 @end itemize
21070 @samp{$target} is for use by a package creating a compiler or similar.
21071 For ordinary packages it's meaningless and should not be used.  It
21072 indicates what the created compiler should generate code for, if it can
21073 cross-compile.  @samp{$target} generally selects various hard-coded CPU
21074 and system conventions, since usually the compiler or tools under
21075 construction themselves determine how the target works.
21078 @c ===================================================== Site Configuration.
21080 @node Site Configuration
21081 @chapter Site Configuration
21083 @command{configure} scripts support several kinds of local configuration
21084 decisions.  There are ways for users to specify where external software
21085 packages are, include or exclude optional features, install programs
21086 under modified names, and set default values for @command{configure}
21087 options.
21089 @menu
21090 * Help Formatting::             Customizing @samp{configure --help}
21091 * External Software::           Working with other optional software
21092 * Package Options::             Selecting optional features
21093 * Pretty Help Strings::         Formatting help string
21094 * Option Checking::             Controlling checking of @command{configure} options
21095 * Site Details::                Configuring site details
21096 * Transforming Names::          Changing program names when installing
21097 * Site Defaults::               Giving @command{configure} local defaults
21098 @end menu
21100 @node Help Formatting
21101 @section Controlling Help Output
21103 Users consult @samp{configure --help} to learn of configuration
21104 decisions specific to your package.  By default, @command{configure}
21105 breaks this output into sections for each type of option; within each
21106 section, help strings appear in the order @file{configure.ac} defines
21107 them:
21109 @example
21110 Optional Features:
21111   @dots{}
21112   --enable-bar            include bar
21114 Optional Packages:
21115   @dots{}
21116   --with-foo              use foo
21117 @end example
21119 @defmac AC_PRESERVE_HELP_ORDER
21120 @acindex{PRESERVE_HELP_ORDER}
21122 Request an alternate @option{--help} format, in which options of all
21123 types appear together, in the order defined.  Call this macro before any
21124 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
21126 @example
21127 Optional Features and Packages:
21128   @dots{}
21129   --enable-bar            include bar
21130   --with-foo              use foo
21131 @end example
21133 @end defmac
21135 @node External Software
21136 @section Working With External Software
21137 @cindex External software
21139 Some packages require, or can optionally use, other software packages
21140 that are already installed.  The user can give @command{configure}
21141 command line options to specify which such external software to use.
21142 The options have one of these forms:
21144 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
21145 @c awful.
21146 @example
21147 --with-@var{package}@r{[}=@var{arg}@r{]}
21148 --without-@var{package}
21149 @end example
21151 For example, @option{--with-gnu-ld} means work with the GNU linker
21152 instead of some other linker.  @option{--with-x} means work with The X
21153 Window System.
21155 The user can give an argument by following the package name with
21156 @samp{=} and the argument.  Giving an argument of @samp{no} is for
21157 packages that are used by default; it says to @emph{not} use the
21158 package.  An argument that is neither @samp{yes} nor @samp{no} could
21159 include a name or number of a version of the other package, to specify
21160 more precisely which other package this program is supposed to work
21161 with.  If no argument is given, it defaults to @samp{yes}.
21162 @option{--without-@var{package}} is equivalent to
21163 @option{--with-@var{package}=no}.
21165 Normally @command{configure} scripts complain about
21166 @option{--with-@var{package}} options that they do not support.
21167 @xref{Option Checking}, for details, and for how to override the
21168 defaults.
21170 For each external software package that may be used, @file{configure.ac}
21171 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
21172 user asked to use it.  Whether each package is used or not by default,
21173 and which arguments are valid, is up to you.
21175 @anchor{AC_ARG_WITH}
21176 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
21177   @ovar{action-if-given}, @ovar{action-if-not-given})
21178 @acindex{ARG_WITH}
21179 If the user gave @command{configure} the option @option{--with-@var{package}}
21180 or @option{--without-@var{package}}, run shell commands
21181 @var{action-if-given}.  If neither option was given, run shell commands
21182 @var{action-if-not-given}.  The name @var{package} indicates another
21183 software package that this program should work with.  It should consist
21184 only of alphanumeric characters, dashes, plus signs, and dots.
21186 The option's argument is available to the shell commands
21187 @var{action-if-given} in the shell variable @code{withval}, which is
21188 actually just the value of the shell variable named
21189 @code{with_@var{package}}, with any non-alphanumeric characters in
21190 @var{package} changed into @samp{_}.  You may use that variable instead,
21191 if you wish.
21193 The argument @var{help-string} is a description of the option that
21194 looks like this:
21195 @example
21196   --with-readline         support fancy command line editing
21197 @end example
21199 @noindent
21200 @var{help-string} may be more than one line long, if more detail is
21201 needed.  Just make sure the columns line up in @samp{configure
21202 --help}.  Avoid tabs in the help string.  The easiest way to provide the
21203 proper leading whitespace is to format your @var{help-string} with the macro
21204 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
21206 The following example shows how to use the @code{AC_ARG_WITH} macro in
21207 a common situation.  You want to let the user decide whether to enable
21208 support for an external library (e.g., the readline library); if the user
21209 specified neither @option{--with-readline} nor @option{--without-readline},
21210 you want to enable support for readline only if the library is available
21211 on the system.
21213 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
21214 @example
21215 AC_ARG_WITH([readline],
21216   [AS_HELP_STRING([--with-readline],
21217     [support fancy command line editing @@<:@@default=check@@:>@@])],
21218   [],
21219   [with_readline=check])
21221 LIBREADLINE=
21222 AS_IF([test "x$with_readline" != xno],
21223   [AC_CHECK_LIB([readline], [main],
21224     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
21225      AC_DEFINE([HAVE_LIBREADLINE], [1],
21226                [Define if you have libreadline])
21227     ],
21228     [if test "x$with_readline" != xcheck; then
21229        AC_MSG_FAILURE(
21230          [--with-readline was given, but test for readline failed])
21231      fi
21232     ], -lncurses)])
21233 @end example
21235 The next example shows how to use @code{AC_ARG_WITH} to give the user the
21236 possibility to enable support for the readline library, in case it is still
21237 experimental and not well tested, and is therefore disabled by default.
21239 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
21240 @example
21241 AC_ARG_WITH([readline],
21242   [AS_HELP_STRING([--with-readline],
21243     [enable experimental support for readline])],
21244   [],
21245   [with_readline=no])
21247 LIBREADLINE=
21248 AS_IF([test "x$with_readline" != xno],
21249   [AC_CHECK_LIB([readline], [main],
21250     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
21251      AC_DEFINE([HAVE_LIBREADLINE], [1],
21252                [Define if you have libreadline])
21253     ],
21254     [AC_MSG_FAILURE(
21255        [--with-readline was given, but test for readline failed])],
21256     [-lncurses])])
21257 @end example
21259 The last example shows how to use @code{AC_ARG_WITH} to give the user the
21260 possibility to disable support for the readline library, given that it is
21261 an important feature and that it should be enabled by default.
21263 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
21264 @example
21265 AC_ARG_WITH([readline],
21266   [AS_HELP_STRING([--without-readline],
21267     [disable support for readline])],
21268   [],
21269   [with_readline=yes])
21271 LIBREADLINE=
21272 AS_IF([test "x$with_readline" != xno],
21273   [AC_CHECK_LIB([readline], [main],
21274     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
21275      AC_DEFINE([HAVE_LIBREADLINE], [1],
21276                [Define if you have libreadline])
21277     ],
21278     [AC_MSG_FAILURE(
21279        [readline test failed (--without-readline to disable)])],
21280     [-lncurses])])
21281 @end example
21283 These three examples can be easily adapted to the case where
21284 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
21285 @ref{Package Options}).
21286 @end defmac
21288 @node Package Options
21289 @section Choosing Package Options
21290 @cindex Package options
21291 @cindex Options, package
21293 If a software package has optional compile-time features, the user can
21294 give @command{configure} command line options to specify whether to
21295 compile them.  The options have one of these forms:
21297 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
21298 @c awful.
21299 @example
21300 --enable-@var{feature}@r{[}=@var{arg}@r{]}
21301 --disable-@var{feature}
21302 @end example
21304 These options allow users to choose which optional features to build and
21305 install.  @option{--enable-@var{feature}} options should never make a
21306 feature behave differently or cause one feature to replace another.
21307 They should only cause parts of the program to be built rather than left
21308 out.
21310 The user can give an argument by following the feature name with
21311 @samp{=} and the argument.  Giving an argument of @samp{no} requests
21312 that the feature @emph{not} be made available.  A feature with an
21313 argument looks like @option{--enable-debug=stabs}.  If no argument is
21314 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
21315 equivalent to @option{--enable-@var{feature}=no}.
21317 Normally @command{configure} scripts complain about
21318 @option{--enable-@var{package}} options that they do not support.
21319 @xref{Option Checking}, for details, and for how to override the
21320 defaults.
21322 For each optional feature, @file{configure.ac} should call
21323 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
21324 to include it.  Whether each feature is included or not by default, and
21325 which arguments are valid, is up to you.
21327 @anchor{AC_ARG_ENABLE}
21328 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
21329   @ovar{action-if-given}, @ovar{action-if-not-given})
21330 @acindex{ARG_ENABLE}
21331 If the user gave @command{configure} the option
21332 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
21333 shell commands @var{action-if-given}.  If neither option was given, run
21334 shell commands @var{action-if-not-given}.  The name @var{feature}
21335 indicates an optional user-level facility.  It should consist only of
21336 alphanumeric characters, dashes, plus signs, and dots.
21338 The option's argument is available to the shell commands
21339 @var{action-if-given} in the shell variable @code{enableval}, which is
21340 actually just the value of the shell variable named
21341 @code{enable_@var{feature}}, with any non-alphanumeric characters in
21342 @var{feature} changed into @samp{_}.  You may use that variable instead,
21343 if you wish.  The @var{help-string} argument is like that of
21344 @code{AC_ARG_WITH} (@pxref{External Software}).
21346 You should format your @var{help-string} with the macro
21347 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
21349 See the examples suggested with the definition of @code{AC_ARG_WITH}
21350 (@pxref{External Software}) to get an idea of possible applications of
21351 @code{AC_ARG_ENABLE}.
21352 @end defmac
21354 @node Pretty Help Strings
21355 @section Making Your Help Strings Look Pretty
21356 @cindex Help strings
21358 Properly formatting the @samp{help strings} which are used in
21359 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
21360 (@pxref{Package Options}) can be challenging.  Specifically, you want
21361 your own @samp{help strings} to line up in the appropriate columns of
21362 @samp{configure --help} just like the standard Autoconf @samp{help
21363 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
21365 @anchor{AS_HELP_STRING}
21366 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
21367   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
21368 @asindex{HELP_STRING}
21370 Expands into a help string that looks pretty when the user executes
21371 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
21372 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
21373 Options}).  The following example makes this clearer.
21375 @example
21376 AC_ARG_WITH([foo],
21377   [AS_HELP_STRING([--with-foo],
21378      [use foo (default is no)])],
21379   [use_foo=$withval],
21380   [use_foo=no])
21381 @end example
21383 Then the last few lines of @samp{configure --help} appear like
21384 this:
21386 @example
21387 --enable and --with options recognized:
21388   --with-foo              use foo (default is no)
21389 @end example
21391 Macro expansion is performed on the first argument.  However, the second
21392 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
21393 list of text to be reformatted, and is not subject to macro expansion.
21394 Since it is not expanded, it should not be double quoted.
21395 @xref{Autoconf Language}, for a more detailed explanation.
21397 The @code{AS_HELP_STRING} macro is particularly helpful when the
21398 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
21399 arguments, as shown in the following example.  Be aware that
21400 @var{left-hand-side} may not expand to unbalanced quotes,
21401 although quadrigraphs can be used.
21403 @example
21404 AC_DEFUN([MY_ARG_WITH],
21405   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
21406      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
21407                      [use $1 (default is $2)])],
21408      [use_[]$1=$withval],
21409      [use_[]$1=$2])])
21410 MY_ARG_WITH([a_b], [no])
21411 @end example
21412 @noindent
21413 Here, the last few lines of @samp{configure --help} will include:
21415 @example
21416 --enable and --with options recognized:
21417   --with-a-b              use a_b (default is no)
21418 @end example
21420 The parameters @var{indent-column} and @var{wrap-column} were introduced
21421 in Autoconf 2.62.  Generally, they should not be specified; they exist
21422 for fine-tuning of the wrapping.
21423 @example
21424 AS_HELP_STRING([--option], [description of option])
21425 @result{}  --option                description of option
21426 AS_HELP_STRING([--option], [description of option], [15], [30])
21427 @result{}  --option     description of
21428 @result{}               option
21429 @end example
21430 @end defmac
21433 @node Option Checking
21434 @section Controlling Checking of @command{configure} Options
21435 @cindex Options, Package
21437 The @command{configure} script checks its command-line options against a
21438 list of known options, like @option{--help} or @option{--config-cache}.
21439 An unknown option ordinarily indicates a mistake by the user and
21440 @command{configure} halts with an error.  However, by default unknown
21441 @option{--with-@var{package}} and @option{--enable-@var{feature}}
21442 options elicit only a warning, to support configuring entire source
21443 trees.
21445 Source trees often contain multiple packages with a top-level
21446 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
21447 (@pxref{Subdirectories}).  Because the packages generally support
21448 different @option{--with-@var{package}} and
21449 @option{--enable-@var{feature}} options, the GNU Coding
21450 Standards say they must accept unrecognized options without halting.
21451 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
21452 automatically disables the warnings.
21454 This default behavior may be modified in two ways.  First, the installer
21455 can invoke @code{configure --disable-option-checking} to disable
21456 these warnings, or invoke @code{configure --enable-option-checking=fatal}
21457 options to turn them into fatal errors, respectively.  Second, the
21458 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
21460 @defmac AC_DISABLE_OPTION_CHECKING
21461 @acindex{DISABLE_OPTION_CHECKING}
21463 By default, disable warnings related to any unrecognized
21464 @option{--with-@var{package}} or @option{--enable-@var{feature}}
21465 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
21467 The installer can override this behavior by passing
21468 @option{--enable-option-checking} (enable warnings) or
21469 @option{--enable-option-checking=fatal} (enable errors) to
21470 @command{configure}.
21471 @end defmac
21474 @node Site Details
21475 @section Configuring Site Details
21476 @cindex Site details
21478 Some software packages require complex site-specific information.  Some
21479 examples are host names to use for certain services, company names, and
21480 email addresses to contact.  Since some configuration scripts generated
21481 by Metaconfig ask for such information interactively, people sometimes
21482 wonder how to get that information in Autoconf-generated configuration
21483 scripts, which aren't interactive.
21485 Such site configuration information should be put in a file that is
21486 edited @emph{only by users}, not by programs.  The location of the file
21487 can either be based on the @code{prefix} variable, or be a standard
21488 location such as the user's home directory.  It could even be specified
21489 by an environment variable.  The programs should examine that file at
21490 runtime, rather than at compile time.  Runtime configuration is more
21491 convenient for users and makes the configuration process simpler than
21492 getting the information while configuring.  @xref{Directory Variables, ,
21493 Variables for Installation Directories, standards, The GNU Coding
21494 Standards}, for more information on where to put data files.
21496 @node Transforming Names
21497 @section Transforming Program Names When Installing
21498 @cindex Transforming program names
21499 @cindex Program names, transforming
21501 Autoconf supports changing the names of programs when installing them.
21502 In order to use these transformations, @file{configure.ac} must call the
21503 macro @code{AC_ARG_PROGRAM}.
21505 @defmac AC_ARG_PROGRAM
21506 @acindex{ARG_PROGRAM}
21507 @ovindex program_transform_name
21508 Place in output variable @code{program_transform_name} a sequence of
21509 @code{sed} commands for changing the names of installed programs.
21511 If any of the options described below are given to @command{configure},
21512 program names are transformed accordingly.  Otherwise, if
21513 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
21514 is given, the target type followed by a dash is used as a prefix.
21515 Otherwise, no program name transformation is done.
21516 @end defmac
21518 @menu
21519 * Transformation Options::      @command{configure} options to transform names
21520 * Transformation Examples::     Sample uses of transforming names
21521 * Transformation Rules::        Makefile uses of transforming names
21522 @end menu
21524 @node Transformation Options
21525 @subsection Transformation Options
21527 You can specify name transformations by giving @command{configure} these
21528 command line options:
21530 @table @option
21531 @item --program-prefix=@var{prefix}
21532 prepend @var{prefix} to the names;
21534 @item --program-suffix=@var{suffix}
21535 append @var{suffix} to the names;
21537 @item --program-transform-name=@var{expression}
21538 perform @code{sed} substitution @var{expression} on the names.
21539 @end table
21541 @node Transformation Examples
21542 @subsection Transformation Examples
21544 These transformations are useful with programs that can be part of a
21545 cross-compilation development environment.  For example, a
21546 cross-assembler running on a Sun 4 configured with
21547 @option{--target=i960-vxworks} is normally installed as
21548 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
21549 with a native Sun 4 assembler.
21551 You can force a program name to begin with @file{g}, if you don't want
21552 GNU programs installed on your system to shadow other programs with
21553 the same name.  For example, if you configure GNU @code{diff} with
21554 @option{--program-prefix=g}, then when you run @samp{make install} it is
21555 installed as @file{/usr/local/bin/gdiff}.
21557 As a more sophisticated example, you could use
21559 @example
21560 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
21561 @end example
21562 @noindent
21564 to prepend @samp{g} to most of the program names in a source tree,
21565 excepting those like @code{gdb} that already have one and those like
21566 @code{less} and @code{lesskey} that aren't GNU programs.  (That is
21567 assuming that you have a source tree containing those programs that is
21568 set up to use this feature.)
21570 One way to install multiple versions of some programs simultaneously is
21571 to append a version number to the name of one or both.  For example, if
21572 you want to keep Autoconf version 1 around for awhile, you can configure
21573 Autoconf version 2 using @option{--program-suffix=2} to install the
21574 programs as @file{/usr/local/bin/autoconf2},
21575 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
21576 that only the binaries are renamed, therefore you'd have problems with
21577 the library files which might overlap.
21579 @node Transformation Rules
21580 @subsection Transformation Rules
21582 Here is how to use the variable @code{program_transform_name} in a
21583 @file{Makefile.in}:
21585 @example
21586 PROGRAMS = cp ls rm
21587 transform = @@program_transform_name@@
21588 install:
21589         for p in $(PROGRAMS); do \
21590           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
21591                                               sed '$(transform)'`; \
21592         done
21594 uninstall:
21595         for p in $(PROGRAMS); do \
21596           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
21597 @c $$ restore font-lock
21598         done
21599 @end example
21601 It is guaranteed that @code{program_transform_name} is never empty, and
21602 that there are no useless separators.  Therefore you may safely embed
21603 @code{program_transform_name} within a sed program using @samp{;}:
21605 @example
21606 transform = @@program_transform_name@@
21607 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
21608 @end example
21610 Whether to do the transformations on documentation files (Texinfo or
21611 @code{man}) is a tricky question; there seems to be no perfect answer,
21612 due to the several reasons for name transforming.  Documentation is not
21613 usually particular to a specific architecture, and Texinfo files do not
21614 conflict with system documentation.  But they might conflict with
21615 earlier versions of the same files, and @code{man} pages sometimes do
21616 conflict with system documentation.  As a compromise, it is probably
21617 best to do name transformations on @code{man} pages but not on Texinfo
21618 manuals.
21620 @node Site Defaults
21621 @section Setting Site Defaults
21622 @cindex Site defaults
21623 @cindex config.site
21625 Autoconf-generated @command{configure} scripts allow your site to provide
21626 default values for some configuration values.  You do this by creating
21627 site- and system-wide initialization files.
21629 @evindex CONFIG_SITE
21630 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
21631 uses its value as the name of a shell script to read; it is recommended
21632 that this be an absolute file name.  Otherwise, it
21633 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
21634 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
21635 settings in machine-specific files override those in machine-independent
21636 ones in case of conflict.
21638 Site files can be arbitrary shell scripts, but only certain kinds of
21639 code are really appropriate to be in them.  Because @command{configure}
21640 reads any cache file after it has read any site files, a site file can
21641 define a default cache file to be shared between all Autoconf-generated
21642 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
21643 you set a default cache file in a site file, it is a good idea to also
21644 set the output variable @code{CC} in that site file, because the cache
21645 file is only valid for a particular compiler, but many systems have
21646 several available.
21648 You can examine or override the value set by a command line option to
21649 @command{configure} in a site file; options set shell variables that have
21650 the same names as the options, with any dashes turned into underscores.
21651 The exceptions are that @option{--without-} and @option{--disable-} options
21652 are like giving the corresponding @option{--with-} or @option{--enable-}
21653 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
21654 sets the variable @code{cache_file} to the value @samp{localcache};
21655 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
21656 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
21657 variable @code{prefix} to the value @samp{/usr}; etc.
21659 Site files are also good places to set default values for other output
21660 variables, such as @code{CFLAGS}, if you need to give them non-default
21661 values: anything you would normally do, repetitively, on the command
21662 line.  If you use non-default values for @var{prefix} or
21663 @var{exec_prefix} (wherever you locate the site file), you can set them
21664 in the site file if you specify it with the @code{CONFIG_SITE}
21665 environment variable.
21667 You can set some cache values in the site file itself.  Doing this is
21668 useful if you are cross-compiling, where it is impossible to check features
21669 that require running a test program.  You could ``prime the cache'' by
21670 setting those values correctly for that system in
21671 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
21672 variables you need to set, see the documentation of the respective
21673 Autoconf macro.  If the variables or their semantics are undocumented,
21674 you may need to look for shell variables with @samp{_cv_} in their names
21675 in the affected @command{configure} scripts, or in the Autoconf M4
21676 source code for those macros; but in that case, their name or semantics
21677 may change in a future Autoconf version.
21679 The cache file is careful to not override any variables set in the site
21680 files.  Similarly, you should not override command-line options in the
21681 site files.  Your code should check that variables such as @code{prefix}
21682 and @code{cache_file} have their default values (as set near the top of
21683 @command{configure}) before changing them.
21685 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
21686 command @samp{configure --prefix=/usr/share/local/gnu} would read this
21687 file (if @code{CONFIG_SITE} is not set to a different file).
21689 @example
21690 # /usr/share/local/gnu/share/config.site for configure
21692 # Change some defaults.
21693 test "$prefix" = NONE && prefix=/usr/share/local/gnu
21694 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
21695 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
21696 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
21698 # Give Autoconf 2.x generated configure scripts a shared default
21699 # cache file for feature test results, architecture-specific.
21700 if test "$cache_file" = /dev/null; then
21701   cache_file="$prefix/var/config.cache"
21702   # A cache file is only valid for one C compiler.
21703   CC=gcc
21705 @end example
21707 @cindex Filesystem Hierarchy Standard
21708 @cindex FHS
21710 Another use of @file{config.site} is for priming the directory variables
21711 in a manner consistent with the Filesystem Hierarchy Standard
21712 (FHS).  Once the following file is installed at
21713 @file{/usr/share/config.site}, a user can execute simply
21714 @code{./configure --prefix=/usr} to get all the directories chosen in
21715 the locations recommended by FHS.
21717 @example
21718 # /usr/share/config.site for FHS defaults when installing below /usr,
21719 # and the respective settings were not changed on the command line.
21720 if test "$prefix" = /usr; then
21721   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
21722   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
21723   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
21725 @end example
21727 @cindex @file{lib64}
21728 @cindex 64-bit libraries
21729 Likewise, on platforms where 64-bit libraries are built by default, then
21730 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
21731 it is appropriate to install @file{/usr/local/@/share/config.site}:
21733 @example
21734 # /usr/local/share/config.site for platforms that prefer
21735 # the directory /usr/local/lib64 over /usr/local/lib.
21736 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
21737 @end example
21740 @c ============================================== Running configure Scripts.
21742 @node Running configure Scripts
21743 @chapter Running @command{configure} Scripts
21744 @cindex @command{configure}
21746 Below are instructions on how to configure a package that uses a
21747 @command{configure} script, suitable for inclusion as an @file{INSTALL}
21748 file in the package.  A plain-text version of @file{INSTALL} which you
21749 may use comes with Autoconf.
21751 @menu
21752 * Basic Installation::          Instructions for typical cases
21753 * Compilers and Options::       Selecting compilers and optimization
21754 * Multiple Architectures::      Compiling for multiple architectures at once
21755 * Installation Names::          Installing in different directories
21756 * Optional Features::           Selecting optional features
21757 * Particular Systems::          Particular systems
21758 * System Type::                 Specifying the system type
21759 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
21760 * Defining Variables::          Specifying the compiler etc.
21761 * configure Invocation::        Changing how @command{configure} runs
21762 @end menu
21764 @set autoconf
21765 @include install.texi
21768 @c ============================================== config.status Invocation
21770 @node config.status Invocation
21771 @chapter config.status Invocation
21772 @cindex @command{config.status}
21774 The @command{configure} script creates a file named @file{config.status},
21775 which actually configures, @dfn{instantiates}, the template files.  It
21776 also records the configuration options that were specified when the
21777 package was last configured in case reconfiguring is needed.
21779 Synopsis:
21780 @example
21781 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
21782 @end example
21784 It configures each @var{tag}; if none are specified, all the templates
21785 are instantiated.  A @var{tag} refers to a file or other tag associated
21786 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
21787 macro (@pxref{Configuration Actions}).  The files must be specified
21788 without their dependencies, as in
21790 @example
21791 ./config.status foobar
21792 @end example
21794 @noindent
21797 @example
21798 ./config.status foobar:foo.in:bar.in
21799 @end example
21801 The supported options are:
21803 @table @option
21804 @item --help
21805 @itemx -h
21806 Print a summary of the command line options, the list of the template
21807 files, and exit.
21809 @item --version
21810 @itemx -V
21811 Print the version number of Autoconf and the configuration settings,
21812 and exit.
21814 @item --config
21815 Print the configuration settings in reusable way, quoted for the shell,
21816 and exit.  For example, for a debugging build that otherwise reuses the
21817 configuration from a different build directory @var{build-dir} of a
21818 package in @var{src-dir}, you could use the following:
21820 @example
21821 args=`@var{build-dir}/config.status --config`
21822 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
21823 @end example
21825 @noindent
21826 Note that it may be necessary to override a @option{--srcdir} setting
21827 that was saved in the configuration, if the arguments are used in a
21828 different build directory.
21830 @item --silent
21831 @itemx --quiet
21832 @itemx -q
21833 Do not print progress messages.
21835 @item --debug
21836 @itemx -d
21837 Don't remove the temporary files.
21839 @item --file=@var{file}[:@var{template}]
21840 Require that @var{file} be instantiated as if
21841 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
21842 @var{file} and @var{template} may be @samp{-} in which case the standard
21843 output and/or standard input, respectively, is used.  If a
21844 @var{template} file name is relative, it is first looked for in the build
21845 tree, and then in the source tree.  @xref{Configuration Actions}, for
21846 more details.
21848 This option and the following ones provide one way for separately
21849 distributed packages to share the values computed by @command{configure}.
21850 Doing so can be useful if some of the packages need a superset of the
21851 features that one of them, perhaps a common library, does.  These
21852 options allow a @file{config.status} file to create files other than the
21853 ones that its @file{configure.ac} specifies, so it can be used for a
21854 different package, or for extracting a subset of values.  For example,
21856 @example
21857 echo '@@CC@@' | ./config.status --file=-
21858 @end example
21860 @noindent
21861 provides the value of @code{@@CC@@} on standard output.
21863 @item --header=@var{file}[:@var{template}]
21864 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
21866 @item --recheck
21867 Ask @file{config.status} to update itself and exit (no instantiation).
21868 This option is useful if you change @command{configure}, so that the
21869 results of some tests might be different from the previous run.  The
21870 @option{--recheck} option reruns @command{configure} with the same arguments
21871 you used before, plus the @option{--no-create} option, which prevents
21872 @command{configure} from running @file{config.status} and creating
21873 @file{Makefile} and other files, and the @option{--no-recursion} option,
21874 which prevents @command{configure} from running other @command{configure}
21875 scripts in subdirectories.  (This is so other Make rules can
21876 run @file{config.status} when it changes; @pxref{Automatic Remaking},
21877 for an example).
21878 @end table
21880 @file{config.status} checks several optional environment variables that
21881 can alter its behavior:
21883 @anchor{CONFIG_SHELL}
21884 @defvar CONFIG_SHELL
21885 @evindex CONFIG_SHELL
21886 The shell with which to run @command{configure} for the @option{--recheck}
21887 option.  It must be Bourne-compatible.  The default is a shell that
21888 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
21889 Invoking @command{configure} by hand bypasses this setting, so you may
21890 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
21891 to insure that the same shell is used everywhere.  The absolute name of the
21892 shell should be passed.
21893 @end defvar
21895 @defvar CONFIG_STATUS
21896 @evindex CONFIG_STATUS
21897 The file name to use for the shell script that records the
21898 configuration.  The default is @file{./config.status}.  This variable is
21899 useful when one package uses parts of another and the @command{configure}
21900 scripts shouldn't be merged because they are maintained separately.
21901 @end defvar
21903 You can use @file{./config.status} in your makefiles.  For example, in
21904 the dependencies given above (@pxref{Automatic Remaking}),
21905 @file{config.status} is run twice when @file{configure.ac} has changed.
21906 If that bothers you, you can make each run only regenerate the files for
21907 that rule:
21908 @example
21909 @group
21910 config.h: stamp-h
21911 stamp-h: config.h.in config.status
21912         ./config.status config.h
21913         echo > stamp-h
21915 Makefile: Makefile.in config.status
21916         ./config.status Makefile
21917 @end group
21918 @end example
21920 The calling convention of @file{config.status} has changed; see
21921 @ref{Obsolete config.status Use}, for details.
21924 @c =================================================== Obsolete Constructs
21926 @node Obsolete Constructs
21927 @chapter Obsolete Constructs
21928 @cindex Obsolete constructs
21930 Autoconf changes, and throughout the years some constructs have been
21931 obsoleted.  Most of the changes involve the macros, but in some cases
21932 the tools themselves, or even some concepts, are now considered
21933 obsolete.
21935 You may completely skip this chapter if you are new to Autoconf.  Its
21936 intention is mainly to help maintainers updating their packages by
21937 understanding how to move to more modern constructs.
21939 @menu
21940 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
21941 * acconfig Header::             Additional entries in @file{config.h.in}
21942 * autoupdate Invocation::       Automatic update of @file{configure.ac}
21943 * Obsolete Macros::             Backward compatibility macros
21944 * Autoconf 1::                  Tips for upgrading your files
21945 * Autoconf 2.13::               Some fresher tips
21946 @end menu
21948 @node Obsolete config.status Use
21949 @section Obsolete @file{config.status} Invocation
21951 @file{config.status} now supports arguments to specify the files to
21952 instantiate; see @ref{config.status Invocation}, for more details.
21953 Before, environment variables had to be used.
21955 @defvar CONFIG_COMMANDS
21956 @evindex CONFIG_COMMANDS
21957 The tags of the commands to execute.  The default is the arguments given
21958 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
21959 @file{configure.ac}.
21960 @end defvar
21962 @defvar CONFIG_FILES
21963 @evindex CONFIG_FILES
21964 The files in which to perform @samp{@@@var{variable}@@} substitutions.
21965 The default is the arguments given to @code{AC_OUTPUT} and
21966 @code{AC_CONFIG_FILES} in @file{configure.ac}.
21967 @end defvar
21969 @defvar CONFIG_HEADERS
21970 @evindex CONFIG_HEADERS
21971 The files in which to substitute C @code{#define} statements.  The
21972 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
21973 macro was not called, @file{config.status} ignores this variable.
21974 @end defvar
21976 @defvar CONFIG_LINKS
21977 @evindex CONFIG_LINKS
21978 The symbolic links to establish.  The default is the arguments given to
21979 @code{AC_CONFIG_LINKS}; if that macro was not called,
21980 @file{config.status} ignores this variable.
21981 @end defvar
21983 In @ref{config.status Invocation}, using this old interface, the example
21984 would be:
21986 @example
21987 @group
21988 config.h: stamp-h
21989 stamp-h: config.h.in config.status
21990         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
21991           CONFIG_HEADERS=config.h ./config.status
21992         echo > stamp-h
21994 Makefile: Makefile.in config.status
21995         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
21996           CONFIG_FILES=Makefile ./config.status
21997 @end group
21998 @end example
22000 @noindent
22001 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
22002 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
22003 for @code{CONFIG_COMMANDS}, etc.)
22006 @node acconfig Header
22007 @section @file{acconfig.h}
22009 @cindex @file{acconfig.h}
22010 @cindex @file{config.h.top}
22011 @cindex @file{config.h.bot}
22013 In order to produce @file{config.h.in}, @command{autoheader} needs to
22014 build or to find templates for each symbol.  Modern releases of Autoconf
22015 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
22016 Macros}), but in older releases a file, @file{acconfig.h}, contained the
22017 list of needed templates.  @command{autoheader} copied comments and
22018 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
22019 the current directory, if present.  This file used to be mandatory if
22020 you @code{AC_DEFINE} any additional symbols.
22022 Modern releases of Autoconf also provide @code{AH_TOP} and
22023 @code{AH_BOTTOM} if you need to prepend/append some information to
22024 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
22025 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
22026 @command{autoheader} copies the lines before the line containing
22027 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
22028 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
22029 @command{autoheader} copies the lines after that line to the end of the
22030 file it generates.  Either or both of those strings may be omitted.  An
22031 even older alternate way to produce the same effect in ancient versions
22032 of Autoconf is to create the files @file{@var{file}.top} (typically
22033 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
22034 directory.  If they exist, @command{autoheader} copies them to the
22035 beginning and end, respectively, of its output.
22037 In former versions of Autoconf, the files used in preparing a software
22038 package for distribution were:
22039 @example
22040 @group
22041 configure.ac --.   .------> autoconf* -----> configure
22042                +---+
22043 [aclocal.m4] --+   `---.
22044 [acsite.m4] ---'       |
22045                        +--> [autoheader*] -> [config.h.in]
22046 [acconfig.h] ----.     |
22047                  +-----'
22048 [config.h.top] --+
22049 [config.h.bot] --'
22050 @end group
22051 @end example
22053 Using only the @code{AH_} macros, @file{configure.ac} should be
22054 self-contained, and should not depend upon @file{acconfig.h} etc.
22057 @node autoupdate Invocation
22058 @section Using @command{autoupdate} to Modernize @file{configure.ac}
22059 @cindex @command{autoupdate}
22061 The @command{autoupdate} program updates a @file{configure.ac} file that
22062 calls Autoconf macros by their old names to use the current macro names.
22063 In version 2 of Autoconf, most of the macros were renamed to use a more
22064 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
22065 description of the new scheme.  Although the old names still work
22066 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
22067 new names), you can make your @file{configure.ac} files more readable
22068 and make it easier to use the current Autoconf documentation if you
22069 update them to use the new macro names.
22071 @evindex SIMPLE_BACKUP_SUFFIX
22072 If given no arguments, @command{autoupdate} updates @file{configure.ac},
22073 backing up the original version with the suffix @file{~} (or the value
22074 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
22075 set).  If you give @command{autoupdate} an argument, it reads that file
22076 instead of @file{configure.ac} and writes the updated file to the
22077 standard output.
22079 @noindent
22080 @command{autoupdate} accepts the following options:
22082 @table @option
22083 @item --help
22084 @itemx -h
22085 Print a summary of the command line options and exit.
22087 @item --version
22088 @itemx -V
22089 Print the version number of Autoconf and exit.
22091 @item --verbose
22092 @itemx -v
22093 Report processing steps.
22095 @item --debug
22096 @itemx -d
22097 Don't remove the temporary files.
22099 @item --force
22100 @itemx -f
22101 Force the update even if the file has not changed.  Disregard the cache.
22103 @item --include=@var{dir}
22104 @itemx -I @var{dir}
22105 Also look for input files in @var{dir}.  Multiple invocations accumulate.
22106 Directories are browsed from last to first.
22108 @item --prepend-include=@var{dir}
22109 @itemx -B @var{dir}
22110 Prepend directory @var{dir} to the search path.  This is used to include
22111 the language-specific files before any third-party macros.
22112 @end table
22114 @node Obsolete Macros
22115 @section Obsolete Macros
22117 Several macros are obsoleted in Autoconf, for various reasons (typically
22118 they failed to quote properly, couldn't be extended for more recent
22119 issues, etc.).  They are still supported, but deprecated: their use
22120 should be avoided.
22122 During the jump from Autoconf version 1 to version 2, most of the
22123 macros were renamed to use a more uniform and descriptive naming scheme,
22124 but their signature did not change.  @xref{Macro Names}, for a
22125 description of the new naming scheme.  Below, if there is just the mapping
22126 from old names to new names for these macros, the reader is invited to
22127 refer to the definition of the new macro for the signature and the
22128 description.
22130 @defmac AC_AIX
22131 @acindex{AIX}
22132 @cvindex _ALL_SOURCE
22133 This macro is a platform-specific subset of
22134 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
22135 @end defmac
22137 @defmac AC_ALLOCA
22138 @acindex{ALLOCA}
22139 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
22140 @end defmac
22142 @defmac AC_ARG_ARRAY
22143 @acindex{ARG_ARRAY}
22144 Removed because of limited usefulness.
22145 @end defmac
22147 @defmac AC_C_CROSS
22148 @acindex{C_CROSS}
22149 This macro is obsolete; it does nothing.
22150 @end defmac
22152 @defmac AC_C_LONG_DOUBLE
22153 @acindex{C_LONG_DOUBLE}
22154 @cvindex HAVE_LONG_DOUBLE
22155 If the C compiler supports a working @code{long double} type with more
22156 range or precision than the @code{double} type, define
22157 @code{HAVE_LONG_DOUBLE}.
22159 You should use @code{AC_TYPE_LONG_DOUBLE} or
22160 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
22161 @end defmac
22163 @defmac AC_CANONICAL_SYSTEM
22164 @acindex{CANONICAL_SYSTEM}
22165 Determine the system type and set output variables to the names of the
22166 canonical system types.  @xref{Canonicalizing}, for details about the
22167 variables this macro sets.
22169 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
22170 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
22171 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
22172 other macros (@pxref{Canonicalizing}).
22173 @end defmac
22175 @defmac AC_CHAR_UNSIGNED
22176 @acindex{CHAR_UNSIGNED}
22177 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
22178 @end defmac
22180 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
22181 @acindex{CHECK_TYPE}
22182 Autoconf, up to 2.13, used to provide this version of
22183 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
22184 it is a member of the @code{CHECK} clan, it does
22185 more than just checking.  Secondly, missing types are defined
22186 using @code{#define}, not @code{typedef}, and this can lead to
22187 problems in the case of pointer types.
22189 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
22190 @ref{Generic Types}, for the description of the current macro.
22192 If the type @var{type} is not defined, define it to be the C (or C++)
22193 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
22195 This macro is equivalent to:
22197 @example
22198 AC_CHECK_TYPE([@var{type}], [],
22199   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
22200      [Define to `@var{default}'
22201       if <sys/types.h> does not define.])])
22202 @end example
22204 In order to keep backward compatibility, the two versions of
22205 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
22207 @enumerate
22208 @item
22209 If there are three or four arguments, the modern version is used.
22211 @item
22212 If the second argument appears to be a C or C++ type, then the
22213 obsolete version is used.  This happens if the argument is a C or C++
22214 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
22215 followed by one of @samp{[(* } and then by a string of zero or more
22216 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
22218 @item
22219 If the second argument is spelled with the alphabet of valid C and C++
22220 types, the user is warned and the modern version is used.
22222 @item
22223 Otherwise, the modern version is used.
22224 @end enumerate
22226 @noindent
22227 You are encouraged either to use a valid builtin type, or to use the
22228 equivalent modern code (see above), or better yet, to use
22229 @code{AC_CHECK_TYPES} together with
22231 @example
22232 #ifndef HAVE_LOFF_T
22233 typedef loff_t off_t;
22234 #endif
22235 @end example
22236 @end defmac
22237 @c end of AC_CHECK_TYPE
22239 @defmac AC_CHECKING (@var{feature-description})
22240 @acindex{CHECKING}
22241 Same as
22243 @example
22244 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
22245 @end example
22247 @noindent
22248 @xref{AC_MSG_NOTICE}.
22249 @end defmac
22251 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
22252   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
22253 @acindex{COMPILE_CHECK}
22254 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
22255 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
22256 addition that it prints @samp{checking for @var{echo-text}} to the
22257 standard output first, if @var{echo-text} is non-empty.  Use
22258 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
22259 messages (@pxref{Printing Messages}).
22260 @end defmac
22262 @defmac AC_CONST
22263 @acindex{CONST}
22264 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
22265 @end defmac
22267 @defmac AC_CROSS_CHECK
22268 @acindex{CROSS_CHECK}
22269 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
22270 @code{:-)}.
22271 @end defmac
22273 @defmac AC_CYGWIN
22274 @acindex{CYGWIN}
22275 @evindex CYGWIN
22276 Check for the Cygwin environment in which case the shell variable
22277 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
22278 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
22279 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
22281 @example
22282 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
22283 case $host_os in
22284   *cygwin* ) CYGWIN=yes;;
22285          * ) CYGWIN=no;;
22286 esac
22287 @end example
22289 Beware that the variable @env{CYGWIN} has a special meaning when
22290 running Cygwin, and should not be changed.  That's yet another reason
22291 not to use this macro.
22292 @end defmac
22294 @defmac AC_DECL_SYS_SIGLIST
22295 @acindex{DECL_SYS_SIGLIST}
22296 @cvindex SYS_SIGLIST_DECLARED
22297 Same as:
22299 @example
22300 AC_CHECK_DECLS([sys_siglist], [], [],
22301 [#include <signal.h>
22302 /* NetBSD declares sys_siglist in unistd.h.  */
22303 #ifdef HAVE_UNISTD_H
22304 # include <unistd.h>
22305 #endif
22307 @end example
22309 @noindent
22310 @xref{AC_CHECK_DECLS}.
22311 @end defmac
22313 @defmac AC_DECL_YYTEXT
22314 @acindex{DECL_YYTEXT}
22315 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
22316 @end defmac
22318 @defmac AC_DIR_HEADER
22319 @acindex{DIR_HEADER}
22320 @cvindex DIRENT
22321 @cvindex SYSNDIR
22322 @cvindex SYSDIR
22323 @cvindex NDIR
22324 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
22325 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
22326 (@pxref{AC_HEADER_DIRENT}),
22327 but defines a different set of C preprocessor macros to indicate which
22328 header file is found:
22330 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
22331 @item Header            @tab Old Symbol     @tab New Symbol
22332 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
22333 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
22334 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
22335 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
22336 @end multitable
22337 @end defmac
22339 @defmac AC_DYNIX_SEQ
22340 @acindex{DYNIX_SEQ}
22341 If on DYNIX/ptx, add @option{-lseq} to output variable
22342 @code{LIBS}.  This macro used to be defined as
22344 @example
22345 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
22346 @end example
22348 @noindent
22349 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
22350 @end defmac
22352 @defmac AC_EXEEXT
22353 @acindex{EXEEXT}
22354 @ovindex EXEEXT
22355 Defined the output variable @code{EXEEXT} based on the output of the
22356 compiler, which is now done automatically.  Typically set to empty
22357 string if Posix and @samp{.exe} if a DOS variant.
22358 @end defmac
22360 @defmac AC_EMXOS2
22361 @acindex{EMXOS2}
22362 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
22363 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
22364 check the nature of the host is using @code{AC_CANONICAL_HOST}
22365 (@pxref{Canonicalizing}).
22366 @end defmac
22368 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
22369   @ovar{action-if-not-given})
22370 @acindex{ENABLE}
22371 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
22372 support providing a help string (@pxref{AC_ARG_ENABLE}).
22373 @end defmac
22375 @defmac AC_ERROR
22376 @acindex{ERROR}
22377 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
22378 @end defmac
22380 @defmac AC_FIND_X
22381 @acindex{FIND_X}
22382 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
22383 @end defmac
22385 @defmac AC_FIND_XTRA
22386 @acindex{FIND_XTRA}
22387 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
22388 @end defmac
22390 @defmac AC_FOREACH
22391 @acindex{FOREACH}
22392 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
22393 @end defmac
22395 @defmac AC_FUNC_CHECK
22396 @acindex{FUNC_CHECK}
22397 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
22398 @end defmac
22400 @anchor{AC_FUNC_SETVBUF_REVERSED}
22401 @defmac AC_FUNC_SETVBUF_REVERSED
22402 @acindex{FUNC_SETVBUF_REVERSED}
22403 @cvindex SETVBUF_REVERSED
22404 @c @fuindex setvbuf
22405 @prindex @code{setvbuf}
22406 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
22407 the buffering type as its second argument and the buffer pointer as the
22408 third, instead of the other way around, and defined
22409 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
22410 were those based on SVR2, which became obsolete in 1987, and the macro
22411 is no longer needed.
22412 @end defmac
22414 @defmac AC_FUNC_WAIT3
22415 @acindex{FUNC_WAIT3}
22416 @cvindex HAVE_WAIT3
22417 @c @fuindex wait3
22418 @prindex @code{wait3}
22419 If @code{wait3} is found and fills in the contents of its third argument
22420 (a @samp{struct rusage *}), which HP-UX does not do, define
22421 @code{HAVE_WAIT3}.
22423 These days portable programs should use @code{waitpid}, not
22424 @code{wait3}, as @code{wait3} has been removed from Posix.
22425 @end defmac
22427 @defmac AC_GCC_TRADITIONAL
22428 @acindex{GCC_TRADITIONAL}
22429 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
22430 @end defmac
22432 @defmac AC_GETGROUPS_T
22433 @acindex{GETGROUPS_T}
22434 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
22435 @end defmac
22437 @defmac AC_GETLOADAVG
22438 @acindex{GETLOADAVG}
22439 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
22440 @end defmac
22442 @defmac AC_GNU_SOURCE
22443 @acindex{GNU_SOURCE}
22444 @cvindex _GNU_SOURCE
22445 This macro is a platform-specific subset of
22446 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
22447 @end defmac
22449 @defmac AC_HAVE_FUNCS
22450 @acindex{HAVE_FUNCS}
22451 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
22452 @end defmac
22454 @defmac AC_HAVE_HEADERS
22455 @acindex{HAVE_HEADERS}
22456 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
22457 @end defmac
22459 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
22460   @ovar{action-if-not-found}, @ovar{other-libraries})
22461 @acindex{HAVE_LIBRARY}
22462 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
22463 @var{function} argument of @code{main}.  In addition, @var{library} can
22464 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
22465 all of those cases, the compiler is passed @option{-lfoo}.  However,
22466 @var{library} cannot be a shell variable; it must be a literal name.
22467 @xref{AC_CHECK_LIB}.
22468 @end defmac
22470 @defmac AC_HAVE_POUNDBANG
22471 @acindex{HAVE_POUNDBANG}
22472 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
22473 @end defmac
22475 @defmac AC_HEADER_CHECK
22476 @acindex{HEADER_CHECK}
22477 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
22478 @end defmac
22480 @defmac AC_HEADER_EGREP
22481 @acindex{HEADER_EGREP}
22482 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
22483 @end defmac
22485 @defmac AC_HELP_STRING
22486 @acindex{HELP_STRING}
22487 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
22488 @end defmac
22490 @defmac AC_INIT (@var{unique-file-in-source-dir})
22491 @acindex{INIT}
22492 Formerly @code{AC_INIT} used to have a single argument, and was
22493 equivalent to:
22495 @example
22496 AC_INIT
22497 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
22498 @end example
22499 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
22500 @end defmac
22502 @defmac AC_INLINE
22503 @acindex{INLINE}
22504 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
22505 @end defmac
22507 @defmac AC_INT_16_BITS
22508 @acindex{INT_16_BITS}
22509 @cvindex INT_16_BITS
22510 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
22511 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
22512 @end defmac
22514 @defmac AC_IRIX_SUN
22515 @acindex{IRIX_SUN}
22516 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
22517 @code{LIBS}.  If you were using it to get @code{getmntent}, use
22518 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
22519 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
22520 getpwnam)}.  Up to Autoconf 2.13, it used to be
22522 @example
22523 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
22524 @end example
22526 @noindent
22527 now it is defined as
22529 @example
22530 AC_FUNC_GETMNTENT
22531 AC_CHECK_LIB([sun], [getpwnam])
22532 @end example
22534 @noindent
22535 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
22536 @end defmac
22538 @defmac AC_ISC_POSIX
22539 @acindex{ISC_POSIX}
22540 @ovindex LIBS
22541 This macro adds @option{-lcposix} to output variable @code{LIBS} if
22542 necessary for Posix facilities.  Sun dropped support for the obsolete
22543 INTERACTIVE Systems Corporation Unix on 2006-07-23.  New programs
22544 need not use this macro.  It is implemented as
22545 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
22546 @end defmac
22548 @defmac AC_LANG_C
22549 @acindex{LANG_C}
22550 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
22551 @end defmac
22553 @defmac AC_LANG_CPLUSPLUS
22554 @acindex{LANG_CPLUSPLUS}
22555 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
22556 @end defmac
22558 @defmac AC_LANG_FORTRAN77
22559 @acindex{LANG_FORTRAN77}
22560 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
22561 @end defmac
22563 @defmac AC_LANG_RESTORE
22564 @acindex{LANG_RESTORE}
22565 Select the @var{language} that is saved on the top of the stack, as set
22566 by @code{AC_LANG_SAVE}, remove it from the stack, and call
22567 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
22568 preferred way to change languages.
22569 @end defmac
22571 @defmac AC_LANG_SAVE
22572 @acindex{LANG_SAVE}
22573 Remember the current language (as set by @code{AC_LANG}) on a stack.
22574 The current language does not change.  @code{AC_LANG_PUSH} is preferred
22575 (@pxref{AC_LANG_PUSH}).
22576 @end defmac
22578 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
22579 @acindex{LINK_FILES}
22580 This is an obsolete version of @code{AC_CONFIG_LINKS}
22581 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
22583 @example
22584 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
22585               host.h            object.h)
22586 @end example
22588 @noindent
22591 @example
22592 AC_CONFIG_LINKS([host.h:config/$machine.h
22593                 object.h:config/$obj_format.h])
22594 @end example
22595 @end defmac
22597 @defmac AC_LN_S
22598 @acindex{LN_S}
22599 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
22600 @end defmac
22602 @defmac AC_LONG_64_BITS
22603 @acindex{LONG_64_BITS}
22604 @cvindex LONG_64_BITS
22605 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
22606 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
22607 (@pxref{AC_CHECK_SIZEOF}).
22608 @end defmac
22610 @defmac AC_LONG_DOUBLE
22611 @acindex{LONG_DOUBLE}
22612 If the C compiler supports a working @code{long double} type with more
22613 range or precision than the @code{double} type, define
22614 @code{HAVE_LONG_DOUBLE}.
22616 You should use @code{AC_TYPE_LONG_DOUBLE} or
22617 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
22618 @end defmac
22620 @defmac AC_LONG_FILE_NAMES
22621 @acindex{LONG_FILE_NAMES}
22622 Replaced by
22623 @example
22624 AC_SYS_LONG_FILE_NAMES
22625 @end example
22626 @noindent
22627 @xref{AC_SYS_LONG_FILE_NAMES}.
22628 @end defmac
22630 @defmac AC_MAJOR_HEADER
22631 @acindex{MAJOR_HEADER}
22632 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
22633 @end defmac
22635 @defmac AC_MEMORY_H
22636 @acindex{MEMORY_H}
22637 @cvindex NEED_MEMORY_H
22638 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
22639 defined in @file{memory.h}.  Today it is equivalent to
22640 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
22641 your code to depend upon
22642 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
22643 Symbols}.
22644 @end defmac
22646 @defmac AC_MINGW32
22647 @acindex{MINGW32}
22648 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
22649 environment and sets @code{MINGW32}.  Don't use this macro, the
22650 dignified means to check the nature of the host is using
22651 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
22652 @end defmac
22654 @defmac AC_MINIX
22655 @acindex{MINIX}
22656 @cvindex _MINIX
22657 @cvindex _POSIX_SOURCE
22658 @cvindex _POSIX_1_SOURCE
22659 This macro is a platform-specific subset of
22660 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
22661 @end defmac
22663 @defmac AC_MINUS_C_MINUS_O
22664 @acindex{MINUS_C_MINUS_O}
22665 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
22666 @end defmac
22668 @defmac AC_MMAP
22669 @acindex{MMAP}
22670 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
22671 @end defmac
22673 @defmac AC_MODE_T
22674 @acindex{MODE_T}
22675 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
22676 @end defmac
22678 @defmac AC_OBJEXT
22679 @acindex{OBJEXT}
22680 @ovindex OBJEXT
22681 Defined the output variable @code{OBJEXT} based on the output of the
22682 compiler, after .c files have been excluded.  Typically set to @samp{o}
22683 if Posix, @samp{obj} if a DOS variant.
22684 Now the compiler checking macros handle
22685 this automatically.
22686 @end defmac
22688 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
22689 @acindex{OBSOLETE}
22690 Make M4 print a message to the standard error output warning that
22691 @var{this-macro-name} is obsolete, and giving the file and line number
22692 where it was called.  @var{this-macro-name} should be the name of the
22693 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
22694 it is printed at the end of the warning message; for example, it can be
22695 a suggestion for what to use instead of @var{this-macro-name}.
22697 For instance
22699 @example
22700 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
22701 @end example
22703 @noindent
22704 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
22705 services to the user (@pxref{AU_DEFUN}).
22706 @end defmac
22708 @defmac AC_OFF_T
22709 @acindex{OFF_T}
22710 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
22711 @end defmac
22713 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
22714 @acindex{OUTPUT}
22715 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
22716 interface is equivalent to:
22718 @example
22719 @group
22720 AC_CONFIG_FILES(@var{file}@dots{})
22721 AC_CONFIG_COMMANDS([default],
22722                    @var{extra-cmds}, @var{init-cmds})
22723 AC_OUTPUT
22724 @end group
22725 @end example
22727 @noindent
22728 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
22729 @end defmac
22731 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
22732 @acindex{OUTPUT_COMMANDS}
22733 Specify additional shell commands to run at the end of
22734 @file{config.status}, and shell commands to initialize any variables
22735 from @command{configure}.  This macro may be called multiple times.  It is
22736 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
22738 Here is an unrealistic example:
22740 @example
22741 fubar=27
22742 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
22743                    [fubar=$fubar])
22744 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
22745                    [echo init bit])
22746 @end example
22748 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
22749 additional key, an important difference is that
22750 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
22751 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
22752 can safely be given macro calls as arguments:
22754 @example
22755 AC_CONFIG_COMMANDS(foo, [my_FOO()])
22756 @end example
22758 @noindent
22759 Conversely, where one level of quoting was enough for literal strings
22760 with @code{AC_OUTPUT_COMMANDS}, you need two with
22761 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
22763 @example
22764 @group
22765 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
22766 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
22767 @end group
22768 @end example
22769 @end defmac
22771 @defmac AC_PID_T
22772 @acindex{PID_T}
22773 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
22774 @end defmac
22776 @defmac AC_PREFIX
22777 @acindex{PREFIX}
22778 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
22779 @end defmac
22781 @defmac AC_PROGRAMS_CHECK
22782 @acindex{PROGRAMS_CHECK}
22783 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
22784 @end defmac
22786 @defmac AC_PROGRAMS_PATH
22787 @acindex{PROGRAMS_PATH}
22788 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
22789 @end defmac
22791 @defmac AC_PROGRAM_CHECK
22792 @acindex{PROGRAM_CHECK}
22793 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
22794 @end defmac
22796 @defmac AC_PROGRAM_EGREP
22797 @acindex{PROGRAM_EGREP}
22798 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
22799 @end defmac
22801 @defmac AC_PROGRAM_PATH
22802 @acindex{PROGRAM_PATH}
22803 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
22804 @end defmac
22806 @defmac AC_REMOTE_TAPE
22807 @acindex{REMOTE_TAPE}
22808 Removed because of limited usefulness.
22809 @end defmac
22811 @defmac AC_RESTARTABLE_SYSCALLS
22812 @acindex{RESTARTABLE_SYSCALLS}
22813 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
22814 these days portable programs should use @code{sigaction} with
22815 @code{SA_RESTART} if they want restartable system calls.  They should
22816 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
22817 system call is restartable is a dynamic issue, not a configuration-time
22818 issue.
22819 @end defmac
22821 @defmac AC_RETSIGTYPE
22822 @acindex{RETSIGTYPE}
22823 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
22824 is obsolete when assuming C89 or better.
22825 @end defmac
22827 @defmac AC_RSH
22828 @acindex{RSH}
22829 Removed because of limited usefulness.
22830 @end defmac
22832 @defmac AC_SCO_INTL
22833 @acindex{SCO_INTL}
22834 @ovindex LIBS
22835 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
22836 macro used to do this:
22838 @example
22839 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
22840 @end example
22842 @noindent
22843 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
22844 @end defmac
22846 @defmac AC_SETVBUF_REVERSED
22847 @acindex{SETVBUF_REVERSED}
22848 Replaced by
22849 @example
22850 AC_FUNC_SETVBUF_REVERSED
22851 @end example
22852 @noindent
22853 @xref{AC_FUNC_SETVBUF_REVERSED}.
22854 @end defmac
22856 @defmac AC_SET_MAKE
22857 @acindex{SET_MAKE}
22858 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
22859 @end defmac
22861 @defmac AC_SIZEOF_TYPE
22862 @acindex{SIZEOF_TYPE}
22863 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
22864 @end defmac
22866 @defmac AC_SIZE_T
22867 @acindex{SIZE_T}
22868 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
22869 @end defmac
22871 @defmac AC_STAT_MACROS_BROKEN
22872 @acindex{STAT_MACROS_BROKEN}
22873 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
22874 @end defmac
22876 @defmac AC_STDC_HEADERS
22877 @acindex{STDC_HEADERS}
22878 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
22879 @end defmac
22881 @defmac AC_STRCOLL
22882 @acindex{STRCOLL}
22883 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
22884 @end defmac
22886 @defmac AC_STRUCT_ST_BLKSIZE
22887 @acindex{STRUCT_ST_BLKSIZE}
22888 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
22889 @cvindex HAVE_ST_BLKSIZE
22890 If @code{struct stat} contains an @code{st_blksize} member, define
22891 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
22892 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
22893 the future.  This macro is obsoleted, and should be replaced by
22895 @example
22896 AC_CHECK_MEMBERS([struct stat.st_blksize])
22897 @end example
22898 @noindent
22899 @xref{AC_CHECK_MEMBERS}.
22900 @end defmac
22902 @defmac AC_STRUCT_ST_RDEV
22903 @acindex{STRUCT_ST_RDEV}
22904 @cvindex HAVE_ST_RDEV
22905 @cvindex HAVE_STRUCT_STAT_ST_RDEV
22906 If @code{struct stat} contains an @code{st_rdev} member, define
22907 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
22908 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
22909 in the future.  Actually, even the new macro is obsolete and should be
22910 replaced by:
22911 @example
22912 AC_CHECK_MEMBERS([struct stat.st_rdev])
22913 @end example
22914 @noindent
22915 @xref{AC_CHECK_MEMBERS}.
22916 @end defmac
22918 @defmac AC_ST_BLKSIZE
22919 @acindex{ST_BLKSIZE}
22920 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
22921 @end defmac
22923 @defmac AC_ST_BLOCKS
22924 @acindex{ST_BLOCKS}
22925 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
22926 @end defmac
22928 @defmac AC_ST_RDEV
22929 @acindex{ST_RDEV}
22930 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
22931 @end defmac
22933 @defmac AC_SYS_RESTARTABLE_SYSCALLS
22934 @acindex{SYS_RESTARTABLE_SYSCALLS}
22935 @cvindex HAVE_RESTARTABLE_SYSCALLS
22936 If the system automatically restarts a system call that is interrupted
22937 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
22938 not check whether system calls are restarted in general---it checks whether a
22939 signal handler installed with @code{signal} (but not @code{sigaction})
22940 causes system calls to be restarted.  It does not check whether system calls
22941 can be restarted when interrupted by signals that have no handler.
22943 These days portable programs should use @code{sigaction} with
22944 @code{SA_RESTART} if they want restartable system calls.  They should
22945 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
22946 system call is restartable is a dynamic issue, not a configuration-time
22947 issue.
22948 @end defmac
22950 @defmac AC_SYS_SIGLIST_DECLARED
22951 @acindex{SYS_SIGLIST_DECLARED}
22952 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
22953 name is obsolete, as the same functionality is now acheived via
22954 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
22955 @end defmac
22957 @defmac AC_TEST_CPP
22958 @acindex{TEST_CPP}
22959 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
22960 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
22961 @end defmac
22963 @defmac AC_TEST_PROGRAM
22964 @acindex{TEST_PROGRAM}
22965 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
22966 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
22967 @end defmac
22969 @defmac AC_TIMEZONE
22970 @acindex{TIMEZONE}
22971 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
22972 @end defmac
22974 @defmac AC_TIME_WITH_SYS_TIME
22975 @acindex{TIME_WITH_SYS_TIME}
22976 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
22977 @end defmac
22979 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
22980   @ovar{action-if-true}, @ovar{action-if-false})
22981 @acindex{TRY_COMPILE}
22982 Same as:
22984 @example
22985 AC_COMPILE_IFELSE(
22986   [AC_LANG_PROGRAM([[@var{includes}]],
22987      [[@var{function-body}]])],
22988   [@var{action-if-true}],
22989   [@var{action-if-false}])
22990 @end example
22992 @noindent
22993 @xref{Running the Compiler}.
22995 This macro double quotes both @var{includes} and @var{function-body}.
22997 For C and C++, @var{includes} is any @code{#include} statements needed
22998 by the code in @var{function-body} (@var{includes} is ignored if
22999 the currently selected language is Fortran or Fortran 77).  The compiler
23000 and compilation flags are determined by the current language
23001 (@pxref{Language Choice}).
23002 @end defmac
23004 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
23005 @acindex{TRY_CPP}
23006 Same as:
23008 @example
23009 AC_PREPROC_IFELSE(
23010   [AC_LANG_SOURCE([[@var{input}]])],
23011   [@var{action-if-true}],
23012   [@var{action-if-false}])
23013 @end example
23015 @noindent
23016 @xref{Running the Preprocessor}.
23018 This macro double quotes the @var{input}.
23019 @end defmac
23021 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
23022   @ovar{action-if-true}, @ovar{action-if-false})
23023 @acindex{TRY_LINK}
23024 Same as:
23026 @example
23027 AC_LINK_IFELSE(
23028   [AC_LANG_PROGRAM([[@var{includes}]],
23029      [[@var{function-body}]])],
23030   [@var{action-if-true}],
23031   [@var{action-if-false}])
23032 @end example
23034 @noindent
23035 @xref{Running the Compiler}.
23037 This macro double quotes both @var{includes} and @var{function-body}.
23039 Depending on the current language (@pxref{Language Choice}), create a
23040 test program to see whether a function whose body consists of
23041 @var{function-body} can be compiled and linked.  If the file compiles
23042 and links successfully, run shell commands @var{action-if-found},
23043 otherwise run @var{action-if-not-found}.
23045 This macro double quotes both @var{includes} and @var{function-body}.
23047 For C and C++, @var{includes} is any @code{#include} statements needed
23048 by the code in @var{function-body} (@var{includes} is ignored if
23049 the currently selected language is Fortran or Fortran 77).  The compiler
23050 and compilation flags are determined by the current language
23051 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
23052 @code{LIBS} are used for linking.
23053 @end defmac
23055 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
23056   @ovar{action-if-not-found})
23057 @acindex{TRY_LINK_FUNC}
23058 This macro is equivalent to
23059 @example
23060 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
23061   [@var{action-if-found}], [@var{action-if-not-found}])
23062 @end example
23063 @noindent
23064 @xref{AC_LINK_IFELSE}.
23065 @end defmac
23067 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
23068   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
23069 @acindex{TRY_RUN}
23070 Same as:
23072 @example
23073 AC_RUN_IFELSE(
23074   [AC_LANG_SOURCE([[@var{program}]])],
23075   [@var{action-if-true}],
23076   [@var{action-if-false}],
23077   [@var{action-if-cross-compiling}])
23078 @end example
23080 @noindent
23081 @xref{Runtime}.
23082 @end defmac
23084 @anchor{AC_TYPE_SIGNAL}
23085 @defmac AC_TYPE_SIGNAL
23086 @acindex{TYPE_SIGNAL}
23087 @cvindex RETSIGTYPE
23088 @hdrindex{signal.h}
23089 If @file{signal.h} declares @code{signal} as returning a pointer to a
23090 function returning @code{void}, define @code{RETSIGTYPE} to be
23091 @code{void}; otherwise, define it to be @code{int}.  These days, it is
23092 portable to assume C89, and that signal handlers return @code{void},
23093 without needing to use this macro or @code{RETSIGTYPE}.
23095 When targetting older K&R C, it is possible to define signal handlers as
23096 returning type @code{RETSIGTYPE}, and omit a return statement:
23098 @example
23099 @group
23100 RETSIGTYPE
23101 hup_handler ()
23103 @dots{}
23105 @end group
23106 @end example
23107 @end defmac
23109 @defmac AC_UID_T
23110 @acindex{UID_T}
23111 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
23112 @end defmac
23114 @defmac AC_UNISTD_H
23115 @acindex{UNISTD_H}
23116 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
23117 @end defmac
23119 @defmac AC_USG
23120 @acindex{USG}
23121 @cvindex USG
23122 Define @code{USG} if the BSD string functions are defined in
23123 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
23124 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
23125 @end defmac
23127 @defmac AC_UTIME_NULL
23128 @acindex{UTIME_NULL}
23129 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
23130 @end defmac
23132 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
23133 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
23134 If the cache file is inconsistent with the current host, target and
23135 build system types, it used to execute @var{cmd} or print a default
23136 error message.  This is now handled by default.
23137 @end defmac
23139 @defmac AC_VERBOSE (@var{result-description})
23140 @acindex{VERBOSE}
23141 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
23142 @end defmac
23144 @defmac AC_VFORK
23145 @acindex{VFORK}
23146 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
23147 @end defmac
23149 @defmac AC_VPRINTF
23150 @acindex{VPRINTF}
23151 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
23152 @end defmac
23154 @defmac AC_WAIT3
23155 @acindex{WAIT3}
23156 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
23157 portable programs should use @code{waitpid}, not @code{wait3}, as
23158 @code{wait3} has been removed from Posix.
23159 @end defmac
23161 @defmac AC_WARN
23162 @acindex{WARN}
23163 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
23164 @end defmac
23166 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
23167   @ovar{action-if-not-given})
23168 @acindex{WITH}
23169 This is an obsolete version of @code{AC_ARG_WITH} that does not
23170 support providing a help string (@pxref{AC_ARG_WITH}).
23171 @end defmac
23173 @defmac AC_WORDS_BIGENDIAN
23174 @acindex{WORDS_BIGENDIAN}
23175 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
23176 @end defmac
23178 @defmac AC_XENIX_DIR
23179 @acindex{XENIX_DIR}
23180 @ovindex LIBS
23181 This macro used to add @option{-lx} to output variable @code{LIBS} if on
23182 Xenix.  Also, if @file{dirent.h} is being checked for, added
23183 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
23184 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
23185 running XENIX on which you should not depend:
23187 @example
23188 AC_MSG_CHECKING([for Xenix])
23189 AC_EGREP_CPP([yes],
23190 [#if defined M_XENIX && !defined M_UNIX
23191   yes
23192 #endif],
23193              [AC_MSG_RESULT([yes]); XENIX=yes],
23194              [AC_MSG_RESULT([no]); XENIX=])
23195 @end example
23196 @noindent
23197 Don't use this macro, the dignified means to check the nature of the
23198 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23199 @end defmac
23201 @defmac AC_YYTEXT_POINTER
23202 @acindex{YYTEXT_POINTER}
23203 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
23204 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23205 @end defmac
23207 @node Autoconf 1
23208 @section Upgrading From Version 1
23209 @cindex Upgrading autoconf
23210 @cindex Autoconf upgrading
23212 Autoconf version 2 is mostly backward compatible with version 1.
23213 However, it introduces better ways to do some things, and doesn't
23214 support some of the ugly things in version 1.  So, depending on how
23215 sophisticated your @file{configure.ac} files are, you might have to do
23216 some manual work in order to upgrade to version 2.  This chapter points
23217 out some problems to watch for when upgrading.  Also, perhaps your
23218 @command{configure} scripts could benefit from some of the new features in
23219 version 2; the changes are summarized in the file @file{NEWS} in the
23220 Autoconf distribution.
23222 @menu
23223 * Changed File Names::          Files you might rename
23224 * Changed Makefiles::           New things to put in @file{Makefile.in}
23225 * Changed Macros::              Macro calls you might replace
23226 * Changed Results::             Changes in how to check test results
23227 * Changed Macro Writing::       Better ways to write your own macros
23228 @end menu
23230 @node Changed File Names
23231 @subsection Changed File Names
23233 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
23234 in a particular package's source directory), you must rename it to
23235 @file{acsite.m4}.  @xref{autoconf Invocation}.
23237 If you distribute @file{install.sh} with your package, rename it to
23238 @file{install-sh} so @command{make} builtin rules don't inadvertently
23239 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
23240 looks for the script under both names, but it is best to use the new name.
23242 If you were using @file{config.h.top}, @file{config.h.bot}, or
23243 @file{acconfig.h}, you still can, but you have less clutter if you
23244 use the @code{AH_} macros.  @xref{Autoheader Macros}.
23246 @node Changed Makefiles
23247 @subsection Changed Makefiles
23249 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
23250 your @file{Makefile.in} files, so they can take advantage of the values
23251 of those variables in the environment when @command{configure} is run.
23252 Doing this isn't necessary, but it's a convenience for users.
23254 Also add @samp{@@configure_input@@} in a comment to each input file for
23255 @code{AC_OUTPUT}, so that the output files contain a comment saying
23256 they were produced by @command{configure}.  Automatically selecting the
23257 right comment syntax for all the kinds of files that people call
23258 @code{AC_OUTPUT} on became too much work.
23260 Add @file{config.log} and @file{config.cache} to the list of files you
23261 remove in @code{distclean} targets.
23263 If you have the following in @file{Makefile.in}:
23265 @example
23266 prefix = /usr/local
23267 exec_prefix = $(prefix)
23268 @end example
23270 @noindent
23271 you must change it to:
23273 @example
23274 prefix = @@prefix@@
23275 exec_prefix = @@exec_prefix@@
23276 @end example
23278 @noindent
23279 The old behavior of replacing those variables without @samp{@@}
23280 characters around them has been removed.
23282 @node Changed Macros
23283 @subsection Changed Macros
23285 Many of the macros were renamed in Autoconf version 2.  You can still
23286 use the old names, but the new ones are clearer, and it's easier to find
23287 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
23288 new names for the old macros.  Use the @command{autoupdate} program to
23289 convert your @file{configure.ac} to using the new macro names.
23290 @xref{autoupdate Invocation}.
23292 Some macros have been superseded by similar ones that do the job better,
23293 but are not call-compatible.  If you get warnings about calling obsolete
23294 macros while running @command{autoconf}, you may safely ignore them, but
23295 your @command{configure} script generally works better if you follow
23296 the advice that is printed about what to replace the obsolete macros with.  In
23297 particular, the mechanism for reporting the results of tests has
23298 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
23299 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
23300 looks better if you switch to @code{AC_MSG_CHECKING} and
23301 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
23302 in conjunction with cache variables.  @xref{Caching Results}.
23306 @node Changed Results
23307 @subsection Changed Results
23309 If you were checking the results of previous tests by examining the
23310 shell variable @code{DEFS}, you need to switch to checking the values of
23311 the cache variables for those tests.  @code{DEFS} no longer exists while
23312 @command{configure} is running; it is only created when generating output
23313 files.  This difference from version 1 is because properly quoting the
23314 contents of that variable turned out to be too cumbersome and
23315 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
23316 Variable Names}.
23318 For example, here is a @file{configure.ac} fragment written for Autoconf
23319 version 1:
23321 @example
23322 AC_HAVE_FUNCS(syslog)
23323 case "$DEFS" in
23324 *-DHAVE_SYSLOG*) ;;
23325 *) # syslog is not in the default libraries.  See if it's in some other.
23326   saved_LIBS="$LIBS"
23327   for lib in bsd socket inet; do
23328     AC_CHECKING(for syslog in -l$lib)
23329     LIBS="-l$lib $saved_LIBS"
23330     AC_HAVE_FUNCS(syslog)
23331     case "$DEFS" in
23332     *-DHAVE_SYSLOG*) break ;;
23333     *) ;;
23334     esac
23335     LIBS="$saved_LIBS"
23336   done ;;
23337 esac
23338 @end example
23340 Here is a way to write it for version 2:
23342 @example
23343 AC_CHECK_FUNCS([syslog])
23344 if test "x$ac_cv_func_syslog" = xno; then
23345   # syslog is not in the default libraries.  See if it's in some other.
23346   for lib in bsd socket inet; do
23347     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
23348       LIBS="-l$lib $LIBS"; break])
23349   done
23351 @end example
23353 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
23354 backslashes before quotes, you need to remove them.  It now works
23355 predictably, and does not treat quotes (except back quotes) specially.
23356 @xref{Setting Output Variables}.
23358 All of the Boolean shell variables set by Autoconf macros now use
23359 @samp{yes} for the true value.  Most of them use @samp{no} for false,
23360 though for backward compatibility some use the empty string instead.  If
23361 you were relying on a shell variable being set to something like 1 or
23362 @samp{t} for true, you need to change your tests.
23364 @node Changed Macro Writing
23365 @subsection Changed Macro Writing
23367 When defining your own macros, you should now use @code{AC_DEFUN}
23368 instead of @code{define}.  @code{AC_DEFUN} automatically calls
23369 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
23370 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
23371 messages on the screen.  There's no actual harm in continuing to use the
23372 older way, but it's less convenient and attractive.  @xref{Macro
23373 Definitions}.
23375 You probably looked at the macros that came with Autoconf as a guide for
23376 how to do things.  It would be a good idea to take a look at the new
23377 versions of them, as the style is somewhat improved and they take
23378 advantage of some new features.
23380 If you were doing tricky things with undocumented Autoconf internals
23381 (macros, variables, diversions), check whether you need to change
23382 anything to account for changes that have been made.  Perhaps you can
23383 even use an officially supported technique in version 2 instead of
23384 kludging.  Or perhaps not.
23386 To speed up your locally written feature tests, add caching to them.
23387 See whether any of your tests are of general enough usefulness to
23388 encapsulate them into macros that you can share.
23391 @node Autoconf 2.13
23392 @section Upgrading From Version 2.13
23393 @cindex Upgrading autoconf
23394 @cindex Autoconf upgrading
23396 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
23397 suits this section@enddots{}
23399 @quotation
23400 Autoconf version 2.50 is mostly backward compatible with version 2.13.
23401 However, it introduces better ways to do some things, and doesn't
23402 support some of the ugly things in version 2.13.  So, depending on how
23403 sophisticated your @file{configure.ac} files are, you might have to do
23404 some manual work in order to upgrade to version 2.50.  This chapter
23405 points out some problems to watch for when upgrading.  Also, perhaps
23406 your @command{configure} scripts could benefit from some of the new
23407 features in version 2.50; the changes are summarized in the file
23408 @file{NEWS} in the Autoconf distribution.
23409 @end quotation
23411 @menu
23412 * Changed Quotation::           Broken code which used to work
23413 * New Macros::                  Interaction with foreign macros
23414 * Hosts and Cross-Compilation::  Bugward compatibility kludges
23415 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
23416 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
23417 @end menu
23419 @node Changed Quotation
23420 @subsection Changed Quotation
23422 The most important changes are invisible to you: the implementation of
23423 most macros have completely changed.  This allowed more factorization of
23424 the code, better error messages, a higher uniformity of the user's
23425 interface etc.  Unfortunately, as a side effect, some construct which
23426 used to (miraculously) work might break starting with Autoconf 2.50.
23427 The most common culprit is bad quotation.
23429 For instance, in the following example, the message is not properly
23430 quoted:
23432 @example
23433 AC_INIT
23434 AC_CHECK_HEADERS(foo.h, ,
23435   AC_MSG_ERROR(cannot find foo.h, bailing out))
23436 AC_OUTPUT
23437 @end example
23439 @noindent
23440 Autoconf 2.13 simply ignores it:
23442 @example
23443 $ @kbd{autoconf-2.13; ./configure --silent}
23444 creating cache ./config.cache
23445 configure: error: cannot find foo.h
23447 @end example
23449 @noindent
23450 while Autoconf 2.50 produces a broken @file{configure}:
23452 @example
23453 $ @kbd{autoconf-2.50; ./configure --silent}
23454 configure: error: cannot find foo.h
23455 ./configure: exit: bad non-numeric arg `bailing'
23456 ./configure: exit: bad non-numeric arg `bailing'
23458 @end example
23460 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
23461 too!
23463 @example
23464 AC_INIT([Example], [1.0], [bug-example@@example.org])
23465 AC_CHECK_HEADERS([foo.h], [],
23466   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
23467 AC_OUTPUT
23468 @end example
23470 Many many (and many more) Autoconf macros were lacking proper quotation,
23471 including no less than@dots{} @code{AC_DEFUN} itself!
23473 @example
23474 $ @kbd{cat configure.in}
23475 AC_DEFUN([AC_PROG_INSTALL],
23476 [# My own much better version
23478 AC_INIT
23479 AC_PROG_INSTALL
23480 AC_OUTPUT
23481 $ @kbd{autoconf-2.13}
23482 autoconf: Undefined macros:
23483 ***BUG in Autoconf--please report*** AC_FD_MSG
23484 ***BUG in Autoconf--please report*** AC_EPI
23485 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
23486 configure.in:5:AC_PROG_INSTALL
23487 $ @kbd{autoconf-2.50}
23489 @end example
23492 @node New Macros
23493 @subsection New Macros
23495 @cindex undefined macro
23496 @cindex @code{_m4_divert_diversion}
23498 While Autoconf was relatively dormant in the late 1990s, Automake
23499 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
23500 in 2001, Autoconf provided
23501 versions of these macros, integrated in the @code{AC_} namespace,
23502 instead of @code{AM_}.  But in order to ease the upgrading via
23503 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
23505 Unfortunately older versions of Automake (e.g., Automake 1.4)
23506 did not quote the names of these macros.
23507 Therefore, when @command{m4} finds something like
23508 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
23509 @code{AM_TYPE_PTRDIFF_T} is
23510 expanded, replaced with its Autoconf definition.
23512 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
23513 complains, in its own words:
23515 @example
23516 $ @kbd{cat configure.ac}
23517 AC_INIT([Example], [1.0], [bug-example@@example.org])
23518 AM_TYPE_PTRDIFF_T
23519 $ @kbd{aclocal-1.4}
23520 $ @kbd{autoconf}
23521 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
23522 aclocal.m4:17: the top level
23523 autom4te: m4 failed with exit status: 1
23525 @end example
23527 Modern versions of Automake no longer define most of these
23528 macros, and properly quote the names of the remaining macros.
23529 If you must use an old Automake, do not depend upon macros from Automake
23530 as it is simply not its job
23531 to provide macros (but the one it requires itself):
23533 @example
23534 $ @kbd{cat configure.ac}
23535 AC_INIT([Example], [1.0], [bug-example@@example.org])
23536 AM_TYPE_PTRDIFF_T
23537 $ @kbd{rm aclocal.m4}
23538 $ @kbd{autoupdate}
23539 autoupdate: `configure.ac' is updated
23540 $ @kbd{cat configure.ac}
23541 AC_INIT([Example], [1.0], [bug-example@@example.org])
23542 AC_CHECK_TYPES([ptrdiff_t])
23543 $ @kbd{aclocal-1.4}
23544 $ @kbd{autoconf}
23546 @end example
23549 @node Hosts and Cross-Compilation
23550 @subsection Hosts and Cross-Compilation
23551 @cindex Cross compilation
23553 Based on the experience of compiler writers, and after long public
23554 debates, many aspects of the cross-compilation chain have changed:
23556 @itemize @minus
23557 @item
23558 the relationship between the build, host, and target architecture types,
23560 @item
23561 the command line interface for specifying them to @command{configure},
23563 @item
23564 the variables defined in @command{configure},
23566 @item
23567 the enabling of cross-compilation mode.
23568 @end itemize
23570 @sp 1
23572 The relationship between build, host, and target have been cleaned up:
23573 the chain of default is now simply: target defaults to host, host to
23574 build, and build to the result of @command{config.guess}.  Nevertheless,
23575 in order to ease the transition from 2.13 to 2.50, the following
23576 transition scheme is implemented.  @emph{Do not rely on it}, as it will
23577 be completely disabled in a couple of releases (we cannot keep it, as it
23578 proves to cause more problems than it cures).
23580 They all default to the result of running @command{config.guess}, unless
23581 you specify either @option{--build} or @option{--host}.  In this case,
23582 the default becomes the system type you specified.  If you specify both,
23583 and they're different, @command{configure} enters cross compilation
23584 mode, so it doesn't run any tests that require execution.
23586 Hint: if you mean to override the result of @command{config.guess},
23587 prefer @option{--build} over @option{--host}.  In the future,
23588 @option{--host} will not override the name of the build system type.
23589 Whenever you specify @option{--host}, be sure to specify @option{--build}
23590 too.
23592 @sp 1
23594 For backward compatibility, @command{configure} accepts a system
23595 type as an option by itself.  Such an option overrides the
23596 defaults for build, host, and target system types.  The following
23597 configure statement configures a cross toolchain that runs on
23598 NetBSD/alpha but generates code for GNU Hurd/sparc,
23599 which is also the build platform.
23601 @example
23602 ./configure --host=alpha-netbsd sparc-gnu
23603 @end example
23605 @sp 1
23607 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
23608 and @code{target} had a different semantics before and after the
23609 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
23610 @option{--build} is strictly copied into @code{build_alias}, and is left
23611 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
23612 set to the canonicalized build type.  To ease the transition, before,
23613 its contents is the same as that of @code{build_alias}.  Do @emph{not}
23614 rely on this broken feature.
23616 For consistency with the backward compatibility scheme exposed above,
23617 when @option{--host} is specified but @option{--build} isn't, the build
23618 system is assumed to be the same as @option{--host}, and
23619 @samp{build_alias} is set to that value.  Eventually, this
23620 historically incorrect behavior will go away.
23622 @sp 1
23624 The former scheme to enable cross-compilation proved to cause more harm
23625 than good, in particular, it used to be triggered too easily, leaving
23626 regular end users puzzled in front of cryptic error messages.
23627 @command{configure} could even enter cross-compilation mode only
23628 because the compiler was not functional.  This is mainly because
23629 @command{configure} used to try to detect cross-compilation, instead of
23630 waiting for an explicit flag from the user.
23632 Now, @command{configure} enters cross-compilation mode if and only if
23633 @option{--host} is passed.
23635 That's the short documentation.  To ease the transition between 2.13 and
23636 its successors, a more complicated scheme is implemented.  @emph{Do not
23637 rely on the following}, as it will be removed in the near future.
23639 If you specify @option{--host}, but not @option{--build}, when
23640 @command{configure} performs the first compiler test it tries to run
23641 an executable produced by the compiler.  If the execution fails, it
23642 enters cross-compilation mode.  This is fragile.  Moreover, by the time
23643 the compiler test is performed, it may be too late to modify the
23644 build-system type: other tests may have already been performed.
23645 Therefore, whenever you specify @option{--host}, be sure to specify
23646 @option{--build} too.
23648 @example
23649 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
23650 @end example
23652 @noindent
23653 enters cross-compilation mode.  The former interface, which
23654 consisted in setting the compiler to a cross-compiler without informing
23655 @command{configure} is obsolete.  For instance, @command{configure}
23656 fails if it can't run the code generated by the specified compiler if you
23657 configure as follows:
23659 @example
23660 ./configure CC=m68k-coff-gcc
23661 @end example
23664 @node AC_LIBOBJ vs LIBOBJS
23665 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
23667 Up to Autoconf 2.13, the replacement of functions was triggered via the
23668 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
23669 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
23670 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
23672 This change is mandated by the unification of the GNU Build System
23673 components.  In particular, the various fragile techniques used to parse
23674 a @file{configure.ac} are all replaced with the use of traces.  As a
23675 consequence, any action must be traceable, which obsoletes critical
23676 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
23677 and it can even be handled gracefully (read, ``without your having to
23678 change something'').
23680 There were two typical uses of @code{LIBOBJS}: asking for a replacement
23681 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
23683 @sp 1
23685 As for function replacement, the fix is immediate: use
23686 @code{AC_LIBOBJ}.  For instance:
23688 @example
23689 LIBOBJS="$LIBOBJS fnmatch.o"
23690 LIBOBJS="$LIBOBJS malloc.$ac_objext"
23691 @end example
23693 @noindent
23694 should be replaced with:
23696 @example
23697 AC_LIBOBJ([fnmatch])
23698 AC_LIBOBJ([malloc])
23699 @end example
23701 @sp 1
23703 @ovindex LIBOBJDIR
23704 When used with Automake 1.10 or newer, a suitable value for
23705 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
23706 can be referenced from any @file{Makefile.am}.  Even without Automake,
23707 arranging for @code{LIBOBJDIR} to be set correctly enables
23708 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
23709 The @code{LIBOBJDIR} feature is experimental.
23712 @node AC_ACT_IFELSE vs AC_TRY_ACT
23713 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
23714 @c the anchor keeps the old node name, to try to avoid breaking links
23715 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
23717 @acindex{@var{ACT}_IFELSE}
23718 @acindex{TRY_@var{ACT}}
23719 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
23720 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
23721 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
23722 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
23723 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
23724 @code{AC_TRY_RUN}.  The motivations where:
23725 @itemize @minus
23726 @item
23727 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
23728 quoting their arguments;
23730 @item
23731 the combinatoric explosion is solved by decomposing on the one hand the
23732 generation of sources, and on the other hand executing the program;
23734 @item
23735 this scheme helps supporting more languages than plain C and C++.
23736 @end itemize
23738 In addition to the change of syntax, the philosophy has changed too:
23739 while emphasis was put on speed at the expense of accuracy, today's
23740 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
23741 expense of speed.
23744 As a perfect example of what is @emph{not} to be done, here is how to
23745 find out whether a header file contains a particular declaration, such
23746 as a typedef, a structure, a structure member, or a function.  Use
23747 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
23748 header file; on some systems the symbol might be defined in another
23749 header file that the file you are checking includes.
23751 As a (bad) example, here is how you should not check for C preprocessor
23752 symbols, either defined by header files or predefined by the C
23753 preprocessor: using @code{AC_EGREP_CPP}:
23755 @example
23756 @group
23757 AC_EGREP_CPP(yes,
23758 [#ifdef _AIX
23759   yes
23760 #endif
23761 ], is_aix=yes, is_aix=no)
23762 @end group
23763 @end example
23765 The above example, properly written would (i) use
23766 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
23768 @example
23769 @group
23770 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
23771 [[#ifndef _AIX
23772  error: This isn't AIX!
23773 #endif
23774 ]])],
23775                    [is_aix=yes],
23776                    [is_aix=no])
23777 @end group
23778 @end example
23781 @c ============================= Generating Test Suites with Autotest
23783 @node Using Autotest
23784 @chapter Generating Test Suites with Autotest
23786 @cindex Autotest
23788 @display
23789 @strong{N.B.: This section describes a feature which is still
23790 stabilizing.  Although we believe that Autotest is useful as-is, this
23791 documentation describes an interface which might change in the future:
23792 do not depend upon Autotest without subscribing to the Autoconf mailing
23793 lists.}
23794 @end display
23796 It is paradoxical that portable projects depend on nonportable tools
23797 to run their test suite.  Autoconf by itself is the paragon of this
23798 problem: although it aims at perfectly portability, up to 2.13 its
23799 test suite was using DejaGNU, a rich and complex testing
23800 framework, but which is far from being standard on Posix systems.
23801 Worse yet, it was likely to be missing on the most fragile platforms,
23802 the very platforms that are most likely to torture Autoconf and
23803 exhibit deficiencies.
23805 To circumvent this problem, many package maintainers have developed their
23806 own testing framework, based on simple shell scripts whose sole outputs
23807 are exit status values describing whether the test succeeded.  Most of
23808 these tests share common patterns, and this can result in lots of
23809 duplicated code and tedious maintenance.
23811 Following exactly the same reasoning that yielded to the inception of
23812 Autoconf, Autotest provides a test suite generation framework, based on
23813 M4 macros building a portable shell script.  The suite itself is
23814 equipped with automatic logging and tracing facilities which greatly
23815 diminish the interaction with bug reporters, and simple timing reports.
23817 Autoconf itself has been using Autotest for years, and we do attest that
23818 it has considerably improved the strength of the test suite and the
23819 quality of bug reports.  Other projects are known to use some generation
23820 of Autotest, such as Bison, Free Recode, Free Wdiff, GNU Tar, each of
23821 them with different needs, and this usage has validated Autotest as a general
23822 testing framework.
23824 Nonetheless, compared to DejaGNU, Autotest is inadequate for
23825 interactive tool testing, which is probably its main limitation.
23827 @menu
23828 * Using an Autotest Test Suite::  Autotest and the user
23829 * Writing Testsuites::          Autotest macros
23830 * testsuite Invocation::        Running @command{testsuite} scripts
23831 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
23832 @end menu
23834 @node Using an Autotest Test Suite
23835 @section Using an Autotest Test Suite
23837 @menu
23838 * testsuite Scripts::           The concepts of Autotest
23839 * Autotest Logs::               Their contents
23840 @end menu
23842 @node testsuite Scripts
23843 @subsection @command{testsuite} Scripts
23845 @cindex @command{testsuite}
23847 Generating testing or validation suites using Autotest is rather easy.
23848 The whole validation suite is held in a file to be processed through
23849 @command{autom4te}, itself using GNU M4 under the hood, to
23850 produce a stand-alone Bourne shell script which then gets distributed.
23851 Neither @command{autom4te} nor GNU M4 are needed at
23852 the installer's end.
23854 @cindex test group
23855 Each test of the validation suite should be part of some test group.  A
23856 @dfn{test group} is a sequence of interwoven tests that ought to be
23857 executed together, usually because one test in the group creates data
23858 files than a later test in the same group needs to read.  Complex test
23859 groups make later debugging more tedious.  It is much better to
23860 keep only a few tests per test group.  Ideally there is only one test
23861 per test group.
23863 For all but the simplest packages, some file such as @file{testsuite.at}
23864 does not fully hold all test sources, as these are often easier to
23865 maintain in separate files.  Each of these separate files holds a single
23866 test group, or a sequence of test groups all addressing some common
23867 functionality in the package.  In such cases, @file{testsuite.at}
23868 merely initializes the validation suite, and sometimes does elementary
23869 health checking, before listing include statements for all other test
23870 files.  The special file @file{package.m4}, containing the
23871 identification of the package, is automatically included if found.
23873 A convenient alternative consists in moving all the global issues
23874 (local Autotest macros, elementary health checking, and @code{AT_INIT}
23875 invocation) into the file @code{local.at}, and making
23876 @file{testsuite.at} be a simple list of @code{m4_include} of sub test
23877 suites.  In such case, generating the whole test suite or pieces of it
23878 is only a matter of choosing the @command{autom4te} command line
23879 arguments.
23881 The validation scripts that Autotest produces are by convention called
23882 @command{testsuite}.  When run, @command{testsuite} executes each test
23883 group in turn, producing only one summary line per test to say if that
23884 particular test succeeded or failed.  At end of all tests, summarizing
23885 counters get printed.  One debugging directory is left for each test
23886 group which failed, if any: such directories are named
23887 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
23888 the test group, and they include:
23890 @itemize @bullet
23891 @item a debugging script named @file{run} which reruns the test in
23892 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
23893 of debugging scripts has the purpose of easing the chase for bugs.
23895 @item all the files created with @code{AT_DATA}
23897 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
23899 @item a log of the run, named @file{testsuite.log}
23900 @end itemize
23902 In the ideal situation, none of the tests fail, and consequently no
23903 debugging directory is left behind for validation.
23905 It often happens in practice that individual tests in the validation
23906 suite need to get information coming out of the configuration process.
23907 Some of this information, common for all validation suites, is provided
23908 through the file @file{atconfig}, automatically created by
23909 @code{AC_CONFIG_TESTDIR}.  For configuration informations which your
23910 testing environment specifically needs, you might prepare an optional
23911 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
23912 The configuration process produces @file{atconfig} and @file{atlocal}
23913 out of these two input files, and these two produced files are
23914 automatically read by the @file{testsuite} script.
23916 Here is a diagram showing the relationship between files.
23918 @noindent
23919 Files used in preparing a software package for distribution:
23921 @example
23922                 [package.m4] -->.
23923                                  \
23924 subfile-1.at ->.  [local.at] ---->+
23925     ...         \                  \
23926 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
23927     ...         /
23928 subfile-n.at ->'
23929 @end example
23931 @noindent
23932 Files used in configuring a software package:
23934 @example
23935                                      .--> atconfig
23936                                     /
23937 [atlocal.in] -->  config.status* --<
23938                                     \
23939                                      `--> [atlocal]
23940 @end example
23942 @noindent
23943 Files created during test suite execution:
23945 @example
23946 atconfig -->.                    .--> testsuite.log
23947              \                  /
23948               >-- testsuite* --<
23949              /                  \
23950 [atlocal] ->'                    `--> [testsuite.dir]
23951 @end example
23954 @node Autotest Logs
23955 @subsection Autotest Logs
23957 When run, the test suite creates a log file named after itself, e.g., a
23958 test suite named @command{testsuite} creates @file{testsuite.log}.  It
23959 contains a lot of information, usually more than maintainers actually
23960 need, but therefore most of the time it contains all that is needed:
23962 @table @asis
23963 @item command line arguments
23964 A bad but unfortunately widespread habit consists of
23965 setting environment variables before the command, such as in
23966 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
23967 know this change, hence (i) it cannot report it to you, and (ii)
23968 it cannot preserve the value of @code{CC} for subsequent runs.
23969 Autoconf faced exactly the same problem, and solved it by asking
23970 users to pass the variable definitions as command line arguments.
23971 Autotest requires this rule, too, but has no means to enforce it; the log
23972 then contains a trace of the variables that were changed by the user.
23974 @item @file{ChangeLog} excerpts
23975 The topmost lines of all the @file{ChangeLog} files found in the source
23976 hierarchy.  This is especially useful when bugs are reported against
23977 development versions of the package, since the version string does not
23978 provide sufficient information to know the exact state of the sources
23979 the user compiled.  Of course, this relies on the use of a
23980 @file{ChangeLog}.
23982 @item build machine
23983 Running a test suite in a cross-compile environment is not an easy task,
23984 since it would mean having the test suite run on a machine @var{build},
23985 while running programs on a machine @var{host}.  It is much simpler to
23986 run both the test suite and the programs on @var{host}, but then, from
23987 the point of view of the test suite, there remains a single environment,
23988 @var{host} = @var{build}.  The log contains relevant information on the
23989 state of the @var{build} machine, including some important environment
23990 variables.
23991 @c FIXME: How about having an M4sh macro to say `hey, log the value
23992 @c of `@dots{}'?  This would help both Autoconf and Autotest.
23994 @item tested programs
23995 The absolute file name and answers to @option{--version} of the tested
23996 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
23998 @item configuration log
23999 The contents of @file{config.log}, as created by @command{configure},
24000 are appended.  It contains the configuration flags and a detailed report
24001 on the configuration itself.
24002 @end table
24005 @node Writing Testsuites
24006 @section Writing @file{testsuite.at}
24008 The @file{testsuite.at} is a Bourne shell script making use of special
24009 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
24010 its beginning followed by one call to @code{m4_include} per source file
24011 for tests.  Each such included file, or the remainder of
24012 @file{testsuite.at} if include files are not used, contain a sequence of
24013 test groups.  Each test group begins with a call to @code{AT_SETUP},
24014 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
24015 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
24016 groups can be categorized by a call to @code{AT_BANNER}.
24018 All of the public Autotest macros have all-uppercase names in the
24019 namespace @samp{^AT_} to prevent them from accidentally conflicting with
24020 other text; Autoconf also reserves the namespace @samp{^_AT_} for
24021 internal macros.  All shell variables used in the testsuite for internal
24022 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
24023 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
24024 makes use of the file system namespace @samp{^at-}.
24026 Since Autoconf is built on top of M4sugar (@pxref{Programming in
24027 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
24028 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
24029 @emph{should not use} the namespace of a package that does not own the
24030 macro or shell code you are writing.
24032 @defmac AT_INIT (@ovar{name})
24033 @atindex{INIT}
24034 @c FIXME: Not clear, plus duplication of the information.
24035 Initialize Autotest.  Giving a @var{name} to the test suite is
24036 encouraged if your package includes several test suites.  Before this
24037 macro is called, @code{AT_PACKAGE_STRING} and
24038 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
24039 information about the testsuite to the user.  Typically, these macros
24040 are provided by a file @file{package.m4} built by @command{make}
24041 (@pxref{Making testsuite Scripts}), in order to inherit the package
24042 name, version, and bug reporting address from @file{configure.ac}.
24043 @end defmac
24045 @defmac AT_COPYRIGHT (@var{copyright-notice})
24046 @atindex{COPYRIGHT}
24047 @cindex Copyright Notice
24048 State that, in addition to the Free Software Foundation's copyright on
24049 the Autotest macros, parts of your test suite are covered by
24050 @var{copyright-notice}.
24052 The @var{copyright-notice} shows up in both the head of
24053 @command{testsuite} and in @samp{testsuite --version}.
24054 @end defmac
24056 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
24057   @ovar{action-if-given}, @ovar{action-if-not-given})
24058 @atindex{ARG_OPTION}
24059 @vrindex at_arg_@var{option}
24060 Accept options from the space-separated list @var{options}, a list that
24061 has leading dashes removed from the options.  Long options will be
24062 prefixed with @samp{--}, single-character options with @samp{-}.  The
24063 first word in this list is the primary @var{option}, any others are
24064 assumed to be short-hand aliases.  The variable associated with it
24065 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
24066 with underscores.
24068 If the user passes @option{--@var{option}} to the @command{testsuite},
24069 the variable will be set to @samp{:}.  If the user does not pass the
24070 option, or passes @option{--no-@var{option}}, then the variable will be
24071 set to @samp{false}.
24073 @vrindex at_optarg
24074 @vrindex at_optarg_@var{option}
24075 @var{action-if-given} is run each time the option is encountered; here,
24076 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
24077 appropriate.  @code{at_optarg} is actually just a copy of
24078 @code{at_arg_@var{option}}.
24080 @var{action-if-not-given} will be run once after option parsing is
24081 complete and if no option from @var{options} was used.
24083 @var{help-text} is added to the end of the list of options shown in
24084 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
24086 It it recommended that you use a package-specific prefix to @var{options}
24087 names in order to avoid clashes with future Autotest built-in options.
24088 @end defmac
24090 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
24091   @ovar{action-if-given}, @ovar{action-if-not-given})
24092 @atindex{ARG_OPTION_ARG}
24093 @vrindex at_arg_@var{option}
24094 Accept options with arguments from the space-separated list
24095 @var{options}, a list that has leading dashes removed from the options.
24096 Long options will be prefixed with @samp{--}, single-character options
24097 with @samp{-}.  The first word in this list is the primary @var{option},
24098 any others are assumed to be short-hand aliases.  The variable associated
24099 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
24100 replaced with underscores.
24102 If the user passes @option{--@var{option}=@var{arg}} or
24103 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
24104 variable will be set to @samp{@var{arg}}.
24106 @vrindex at_optarg
24107 @var{action-if-given} is run each time the option is encountered; here,
24108 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
24109 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
24111 @var{action-if-not-given} will be run once after option parsing is
24112 complete and if no option from @var{options} was used.
24114 @var{help-text} is added to the end of the list of options shown in
24115 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
24117 It it recommended that you use a package-specific prefix to @var{options}
24118 names in order to avoid clashes with future Autotest built-in options.
24119 @end defmac
24121 @defmac AT_COLOR_TESTS
24122 @atindex{COLOR_TESTS}
24123 Enable colored test results by default when the output is connected to
24124 a terminal.
24125 @end defmac
24127 @defmac AT_TESTED (@var{executables})
24128 @atindex{TESTED}
24129 Log the file name and answer to @option{--version} of each program in
24130 space-separated list @var{executables}.  Several invocations register
24131 new executables, in other words, don't fear registering one program
24132 several times.
24134 Autotest test suites rely on @env{PATH} to find the tested program.
24135 This avoids the need to generate absolute names of the various tools, and
24136 makes it possible to test installed programs.  Therefore, knowing which
24137 programs are being exercised is crucial to understanding problems in
24138 the test suite itself, or its occasional misuses.  It is a good idea to
24139 also subscribe foreign programs you depend upon, to avoid incompatible
24140 diagnostics.
24141 @end defmac
24143 @sp 1
24145 @defmac AT_BANNER (@var{test-category-name})
24146 @atindex{BANNER}
24147 This macro identifies the start of a category of related test groups.
24148 When the resulting @file{testsuite} is invoked with more than one test
24149 group to run, its output will include a banner containing
24150 @var{test-category-name} prior to any tests run from that category.  The
24151 banner should be no more than about 40 or 50 characters.  A blank banner
24152 indicates uncategorized tests; an empty line will be inserted after
24153 tests from an earlier category, effectively ending that category.
24154 @end defmac
24156 @defmac AT_SETUP (@var{test-group-name})
24157 @atindex{SETUP}
24158 This macro starts a group of related tests, all to be executed in the
24159 same subshell.  It accepts a single argument, which holds a few words
24160 (no more than about 30 or 40 characters) quickly describing the purpose
24161 of the test group being started.  @var{test-group-name} must not expand
24162 to unbalanced quotes, although quadrigraphs can be used.
24163 @end defmac
24165 @defmac AT_KEYWORDS (@var{keywords})
24166 @atindex{KEYWORDS}
24167 Associate the space-separated list of @var{keywords} to the enclosing
24168 test group.  This makes it possible to run ``slices'' of the test suite.
24169 For instance, if some of your test groups exercise some @samp{foo}
24170 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
24171 @samp{./testsuite -k foo} to run exclusively these test groups.  The
24172 @var{test-group-name} of the test group is automatically recorded to
24173 @code{AT_KEYWORDS}.
24175 Several invocations within a test group accumulate new keywords.  In
24176 other words, don't fear registering the same keyword several times in a
24177 test group.
24178 @end defmac
24180 @defmac AT_CAPTURE_FILE (@var{file})
24181 @atindex{CAPTURE_FILE}
24182 If the current test group fails, log the contents of @var{file}.
24183 Several identical calls within one test group have no additional effect.
24184 @end defmac
24186 @defmac AT_FAIL_IF (@var{shell-condition})
24187 @atindex{FAIL_IF}
24188 Make the test group fail and skip the rest of its execution, if
24189 @var{shell-condition} is true.  @var{shell-condition} is a shell expression
24190 such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
24191 will be executed and may still cause the test group to be skipped.
24192 You can instantiate this macro many times from within the same test group.
24194 You should use this macro only for very simple failure conditions.  If the
24195 @var{shell-condition} could emit any kind of output you should instead
24196 use @command{AT_CHECK} like
24197 @example
24198 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
24199 @end example
24200 @noindent
24201 so that such output is properly recorded in the @file{testsuite.log}
24202 file.
24203 @end defmac
24205 @defmac AT_SKIP_IF (@var{shell-condition})
24206 @atindex{SKIP_IF}
24207 Determine whether the test should be skipped because it requires
24208 features that are unsupported on the machine under test.
24209 @var{shell-condition} is a shell expression such as a @code{test}
24210 command.  Tests before @command{AT_SKIP_IF} will be executed
24211 and may still cause the test group to fail.  You can instantiate this
24212 macro many times from within the same test group.
24214 You should use this macro only for very simple skip conditions.  If the
24215 @var{shell-condition} could emit any kind of output you should instead
24216 use @command{AT_CHECK} like
24217 @example
24218 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
24219 @end example
24220 @noindent
24221 so that such output is properly recorded in the @file{testsuite.log}
24222 file.
24223 @end defmac
24225 @defmac AT_XFAIL_IF (@var{shell-condition})
24226 @atindex{XFAIL_IF}
24227 Determine whether the test is expected to fail because it is a known
24228 bug (for unsupported features, you should skip the test).
24229 @var{shell-condition} is a shell expression such as a @code{test}
24230 command; you can instantiate this macro many times from within the
24231 same test group, and one of the conditions is enough to turn
24232 the test into an expected failure.
24233 @end defmac
24235 @defmac AT_CLEANUP
24236 @atindex{CLEANUP}
24237 End the current test group.
24238 @end defmac
24240 @sp 1
24242 @defmac AT_DATA (@var{file}, @var{contents})
24243 @atindex{DATA}
24244 Initialize an input data @var{file} with given @var{contents}.  Of
24245 course, the @var{contents} have to be properly quoted between square
24246 brackets to protect against included commas or spurious M4
24247 expansion.  @var{contents} must be empty or end with a newline.
24248 @var{file} must
24249 be a single shell word that expands into a single file name.
24250 @end defmac
24252 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
24253   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
24254 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
24255   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
24256 @atindex{CHECK}
24257 @atindex{CHECK_UNQUOTED}
24258 @vrindex at_status
24259 Execute a test by performing given shell @var{commands} in a subshell.
24260 @var{commands} is output as-is, so shell expansions are honored.  These
24261 commands should normally exit with @var{status}, while producing expected
24262 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
24263 unexpected status 77, then the rest of the test group is skipped.  If
24264 @var{commands} exit with unexpected status 99, then the test group is
24265 immediately failed.  Otherwise, if this test fails, run shell commands
24266 @var{run-if-fail} or, if this test passes, run shell commands
24267 @var{run-if-pass}, both inside the current shell execution environment.
24268 At the beginning of @var{run-if-fail} and @var{run-if-pass}, the status of
24269 @var{commands} is available in the @code{at_status} shell variable.
24271 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
24273 If @var{status} is the literal @samp{ignore}, then the corresponding
24274 exit status is not checked, except for the special cases of 77 (skip)
24275 and 99 (hard failure).  The existence of hard failures allows one to
24276 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
24277 feature has not yet been implemented, but to still distinguish between
24278 gracefully handling the missing feature and dumping core.  A hard
24279 failure also inhibits post-test actions in @var{run-if-fail}.
24281 If the value of the @var{stdout} or @var{stderr} parameter is one of the
24282 literals in the following table, then the test treats the output
24283 according to the rules of that literal.  Otherwise, the value of the
24284 parameter is treated as text that must exactly match the output given by
24285 @var{commands} on standard output and standard error (including an empty
24286 parameter for no output); any differences are captured in the testsuite
24287 log and the test is failed (unless an unexpected exit status of 77
24288 skipped the test instead).  The difference between @code{AT_CHECK} and
24289 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
24290 expansion (@samp{$}), command substitution (@samp{`}), and backslash
24291 escaping (@samp{\}) on comparison text given in the @var{stdout} and
24292 @var{stderr} arguments; if the text includes a trailing newline, this
24293 would be the same as if it were specified via an unquoted
24294 here-document.  (However, there is no difference in the interpretation
24295 of @var{commands}).
24297 @table @samp
24298 @item ignore
24299 The content of the output is ignored, but still captured in the test
24300 group log (if the testsuite is run with option @option{-v}, the test
24301 group log is displayed as the test is run; if the test group later
24302 fails, the test group log is also copied into the overall testsuite
24303 log).  This action is valid for both @var{stdout} and @var{stderr}.
24305 @item ignore-nolog
24306 The content of the output is ignored, and nothing is captured in the log
24307 files.  If @var{commands} are likely to produce binary output (including
24308 long lines) or large amounts of output, then logging the output can make
24309 it harder to locate details related to subsequent tests within the
24310 group, and could potentially corrupt terminal display of a user running
24311 @command{testsuite -v}.
24313 @item stdout
24314 For the @var{stdout} parameter, capture the content of standard output
24315 to both the file @file{stdout} and the test group log.  Subsequent
24316 commands in the test group can then post-process the file.  This action
24317 is often used when it is desired to use @command{grep} to look for a
24318 substring in the output, or when the output must be post-processed to
24319 normalize error messages into a common form.
24321 @item stderr
24322 Like @samp{stdout}, except that it only works for the @var{stderr}
24323 parameter, and the standard error capture file will be named
24324 @file{stderr}.
24326 @item stdout-nolog
24327 @itemx stderr-nolog
24328 Like @samp{stdout} or @samp{stderr}, except that the captured output is
24329 not duplicated into the test group log.  This action is particularly
24330 useful for an intermediate check that produces large amounts of data,
24331 which will be followed by another check that filters down to the
24332 relevant data, as it makes it easier to locate details in the log.
24334 @item expout
24335 For the @var{stdout} parameter, compare standard output contents with
24336 the previously created file @file{expout}, and list any differences in
24337 the testsuite log.
24339 @item experr
24340 Like @samp{expout}, except that it only works for the @var{stderr}
24341 parameter, and the standard error contents are compared with
24342 @file{experr}.
24343 @end table
24344 @end defmac
24346 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
24347   @ovar{run-if-fail}, @ovar{run-if-pass})
24348 @atindex{CHECK_EUNIT}
24349 Initialize and execute an Erlang module named @var{module} that performs
24350 tests following the @var{test-spec} EUnit test specification.
24351 @var{test-spec} must be a valid EUnit test specification, as defined in
24352 the @uref{http://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
24353 Reference Manual}.  @var{erlflags} are optional command-line options
24354 passed to the Erlang interpreter to execute the test Erlang module.
24355 Typically, @var{erlflags} defines at least the paths to directories
24356 containing the compiled Erlang modules under test, as @samp{-pa path1
24357 path2 ...}.
24359 For example, the unit tests associated with Erlang module @samp{testme},
24360 which compiled code is in subdirectory @file{src}, can be performed
24361 with:
24363 @example
24364 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
24365                [-pa "$@{abs_top_builddir@}/src"])
24366 @end example
24368 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
24370 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
24371 must be defined as the path of the Erlang interpreter, the path of the
24372 Erlang compiler, and the command-line flags to pass to the compiler,
24373 respectively.  Those variables should be configured in
24374 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
24375 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
24376 variables are automatically defined in the testsuite.  If @code{ERL} or
24377 @code{ERLC} is not defined, the test group is skipped.
24379 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
24380 be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
24381 an invalid EUnit test specification, the test group fails.  Otherwise,
24382 if the EUnit test passes, shell commands @var{run-if-pass} are executed
24383 or, if the EUnit test fails, shell commands @var{run-if-fail} are
24384 executed and the test group fails.
24386 Only the generated test Erlang module is automatically compiled and
24387 executed.  If @var{test-spec} involves testing other Erlang modules,
24388 e.g. module @samp{testme} in the example above, those modules must be
24389 already compiled.
24391 If the testsuite is run in verbose mode, with option @option{--verbose},
24392 EUnit is also run in verbose mode to output more details about
24393 individual unit tests.
24394 @end defmac
24397 @node testsuite Invocation
24398 @section Running @command{testsuite} Scripts
24399 @cindex @command{testsuite}
24401 Autotest test suites support the following options:
24403 @table @option
24404 @item --help
24405 @itemx -h
24406 Display the list of options and exit successfully.
24408 @item --version
24409 @itemx -V
24410 Display the version of the test suite and exit successfully.
24412 @item --directory=@var{dir}
24413 @itemx -C @var{dir}
24414 Change the current directory to @var{dir} before creating any files.
24415 Useful for running the testsuite in a subdirectory from a top-level
24416 Makefile.
24418 @item --jobs@r{[}=@var{n}@r{]}
24419 @itemx -j@ovar{n}
24420 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
24421 run all given tests in parallel.  Note that there should be no space
24422 before the argument to @option{-j}, as @option{-j @var{number}} denotes
24423 the separate arguments @option{-j} and @option{@var{number}}, see below.
24425 In parallel mode, the standard input device of the testsuite script is
24426 not available to commands inside a test group.  Furthermore, banner
24427 lines are not printed, and the summary line for each test group is
24428 output after the test group completes.  Summary lines may appear
24429 unordered.  If verbose and trace output are enabled (see below), they
24430 may appear intermixed from concurrently running tests.
24432 Parallel mode requires the @command{mkfifo} command to work, and will be
24433 silently disabled otherwise.
24435 @item --clean
24436 @itemx -c
24437 Remove all the files the test suite might have created and exit.  Meant
24438 for @code{clean} Make targets.
24440 @item --list
24441 @itemx -l
24442 List all the tests (or only the selection), including their possible
24443 keywords.
24444 @end table
24446 @sp 1
24448 By default all tests are performed (or described with @option{--list})
24449 silently in the default environment, but the environment, set of tests,
24450 and verbosity level can be tuned:
24452 @table @samp
24453 @item @var{variable}=@var{value}
24454 Set the environment @var{variable} to @var{value}.  Use this rather
24455 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
24456 different environment.
24458 @cindex @code{AUTOTEST_PATH}
24459 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
24460 to @env{PATH}.  Relative directory names (not starting with
24461 @samp{/}) are considered to be relative to the top level of the
24462 package being built.  All directories are made absolute, first
24463 starting from the top level @emph{build} tree, then from the
24464 @emph{source} tree.  For instance @samp{./testsuite
24465 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
24466 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
24467 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
24468 @env{PATH}.
24470 @item @var{number}
24471 @itemx @var{number}-@var{number}
24472 @itemx @var{number}-
24473 @itemx -@var{number}
24474 Add the corresponding test groups, with obvious semantics, to the
24475 selection.
24477 @item --keywords=@var{keywords}
24478 @itemx -k @var{keywords}
24479 Add to the selection the test groups with title or keywords (arguments
24480 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
24481 of the comma separated list @var{keywords}, case-insensitively.  Use
24482 @samp{!} immediately before the keyword to invert the selection for this
24483 keyword.  By default, the keywords match whole words; enclose them in
24484 @samp{.*} to also match parts of words.
24486 For example, running
24488 @example
24489 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
24490 @end example
24492 @noindent
24493 selects all tests tagged @samp{autoupdate} @emph{and} with tags
24494 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
24495 etc.), while
24497 @example
24498 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
24499 @end example
24501 @noindent
24502 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
24503 containing @samp{FUNC}.
24505 @item --errexit
24506 @itemx -e
24507 If any test fails, immediately abort testing.  This implies
24508 @option{--debug}: post test group clean up, and top-level logging
24509 are inhibited.  This option is meant for the full test
24510 suite, it is not really useful for generated debugging scripts.
24511 If the testsuite is run in parallel mode using @option{--jobs},
24512 then concurrently running tests will finish before exiting.
24514 @item --verbose
24515 @itemx -v
24516 Force more verbosity in the detailed output of what is being done.  This
24517 is the default for debugging scripts.
24519 @item --color
24520 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
24521 Enable colored test results.  Without an argument, or with @samp{always},
24522 test results will be colored.  With @samp{never}, color mode is turned
24523 off.  Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
24524 the testsuite author, or the argument @samp{auto} is given, then test
24525 results are colored if standard output is connected to a terminal.
24527 @item --debug
24528 @itemx -d
24529 Do not remove the files after a test group was performed---but they are
24530 still removed @emph{before}, therefore using this option is sane when
24531 running several test groups.  Create debugging scripts.  Do not
24532 overwrite the top-level
24533 log (in order to preserve a supposedly existing full log file).  This is
24534 the default for debugging scripts, but it can also be useful to debug
24535 the testsuite itself.
24537 @item --recheck
24538 Add to the selection all test groups that failed or passed unexpectedly
24539 during the last non-debugging test run.
24541 @item --trace
24542 @itemx -x
24543 Trigger shell tracing of the test groups.
24544 @end table
24546 Besides these options accepted by every Autotest testsuite, the
24547 testsuite author might have added package-specific options
24548 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
24549 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
24550 the package documentation for details.
24553 @node Making testsuite Scripts
24554 @section Making @command{testsuite} Scripts
24556 For putting Autotest into movement, you need some configuration and
24557 makefile machinery.  We recommend, at least if your package uses deep or
24558 shallow hierarchies, that you use @file{tests/} as the name of the
24559 directory holding all your tests and their makefile.  Here is a
24560 check list of things to do.
24562 @itemize @minus
24564 @item
24565 @cindex @file{package.m4}
24566 @atindex{PACKAGE_STRING}
24567 @atindex{PACKAGE_BUGREPORT}
24568 @atindex{PACKAGE_NAME}
24569 @atindex{PACKAGE_TARNAME}
24570 @atindex{PACKAGE_VERSION}
24571 @atindex{PACKAGE_URL}
24572 Make sure to create the file @file{package.m4}, which defines the
24573 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
24574 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
24575 address to which bug reports should be sent.  For sake of completeness,
24576 we suggest that you also define @code{AT_PACKAGE_NAME},
24577 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
24578 @code{AT_PACKAGE_URL}.
24579 @xref{Initializing configure}, for a description of these variables.
24580 Be sure to distribute @file{package.m4} and to put it into the source
24581 hierarchy: the test suite ought to be shipped!  See below for an example
24582 @file{Makefile} excerpt.
24584 @item
24585 Invoke @code{AC_CONFIG_TESTDIR}.
24587 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
24588 @acindex{CONFIG_TESTDIR}
24589 An Autotest test suite is to be configured in @var{directory}.  This
24590 macro causes @file{@var{directory}/atconfig} to be created by
24591 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
24592 @var{test-path} (@pxref{testsuite Invocation}).
24593 @end defmac
24595 @item
24596 Still within @file{configure.ac}, as appropriate, ensure that some
24597 @code{AC_CONFIG_FILES} command includes substitution for
24598 @file{tests/atlocal}.
24600 @item
24601 The appropriate @file{Makefile} should be modified so the validation in
24602 your package is triggered by @samp{make check}.  An example is provided
24603 below.
24604 @end itemize
24606 With Automake, here is a minimal example for inclusion in
24607 @file{tests/Makefile.am}, in order to link @samp{make check} with a
24608 validation suite.
24610 @example
24611 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
24612 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
24613         :;@{ \
24614           echo '# Signature of the current package.' && \
24615           echo 'm4_define([AT_PACKAGE_NAME],' && \
24616           echo '  [$(PACKAGE_NAME)])' && \
24617           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
24618           echo '  [$(PACKAGE_TARNAME)])' && \
24619           echo 'm4_define([AT_PACKAGE_VERSION],' && \
24620           echo '  [$(PACKAGE_VERSION)])' && \
24621           echo 'm4_define([AT_PACKAGE_STRING],' && \
24622           echo '  [$(PACKAGE_STRING)])' && \
24623           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
24624           echo '  [$(PACKAGE_BUGREPORT)])'; \
24625           echo 'm4_define([AT_PACKAGE_URL],' && \
24626           echo '  [$(PACKAGE_URL)])'; \
24627         @} >'$(srcdir)/package.m4'
24629 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
24630 TESTSUITE = $(srcdir)/testsuite
24632 check-local: atconfig atlocal $(TESTSUITE)
24633         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
24635 installcheck-local: atconfig atlocal $(TESTSUITE)
24636         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
24637           $(TESTSUITEFLAGS)
24639 clean-local:
24640         test ! -f '$(TESTSUITE)' || \
24641          $(SHELL) '$(TESTSUITE)' --clean
24643 AUTOM4TE = $(SHELL) $(srcdir)/build-aux/missing --run autom4te
24644 AUTOTEST = $(AUTOM4TE) --language=autotest
24645 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
24646         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
24647         mv $@@.tmp $@@
24648 @end example
24650 Note that the built testsuite is distributed; this is necessary because
24651 users might not have Autoconf installed, and thus would not be able to
24652 rebuild it.  Likewise, the use of @file{missing} provides the user with
24653 a nicer error message if they modify a source file to the testsuite, and
24654 accidentally trigger the rebuild rules.
24656 You might want to list explicitly the dependencies, i.e., the list of
24657 the files @file{testsuite.at} includes.
24659 If you don't use Automake, you should include the above example in
24660 @file{tests/@/Makefile.in}, along with additional lines inspired from
24661 the following:
24663 @example
24664 subdir = tests
24665 PACKAGE_NAME = @@PACKAGE_NAME@@
24666 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
24667 PACKAGE_VERSION = @@PACKAGE_VERSION@@
24668 PACKAGE_STRING = @@PACKAGE_STRING@@
24669 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
24670 PACKAGE_URL = @@PACKAGE_URL@@
24672 atconfig: $(top_builddir)/config.status
24673         cd $(top_builddir) && \
24674            $(SHELL) ./config.status $(subdir)/$@@
24676 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
24677         cd $(top_builddir) && \
24678            $(SHELL) ./config.status $(subdir)/$@@
24679 @end example
24681 @noindent
24682 and manage to have @code{$(EXTRA_DIST)} distributed.  You will also want
24683 to distribute the file @file{build-aux/@/missing} from the Automake
24684 project; a copy of this file resides in the Autoconf source tree.
24686 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
24687 within your makefile, you can fine-tune test suite execution with this
24688 variable, for example:
24690 @example
24691 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
24692 @end example
24696 @c =============================== Frequent Autoconf Questions, with answers
24698 @node FAQ
24699 @chapter Frequent Autoconf Questions, with answers
24701 Several questions about Autoconf come up occasionally.  Here some of them
24702 are addressed.
24704 @menu
24705 * Distributing::                Distributing @command{configure} scripts
24706 * Why GNU M4::                  Why not use the standard M4?
24707 * Bootstrapping::               Autoconf and GNU M4 require each other?
24708 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
24709 * Defining Directories::        Passing @code{datadir} to program
24710 * Autom4te Cache::              What is it?  Can I remove it?
24711 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
24712 * Expanded Before Required::    Expanded Before Required
24713 * Debugging::                   Debugging @command{configure} scripts
24714 @end menu
24716 @node Distributing
24717 @section Distributing @command{configure} Scripts
24718 @cindex License
24720 @display
24721 What are the restrictions on distributing @command{configure}
24722 scripts that Autoconf generates?  How does that affect my
24723 programs that use them?
24724 @end display
24726 There are no restrictions on how the configuration scripts that Autoconf
24727 produces may be distributed or used.  In Autoconf version 1, they were
24728 covered by the GNU General Public License.  We still encourage
24729 software authors to distribute their work under terms like those of the
24730 GPL, but doing so is not required to use Autoconf.
24732 Of the other files that might be used with @command{configure},
24733 @file{config.h.in} is under whatever copyright you use for your
24734 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
24735 exception to the GPL when they are used with an Autoconf-generated
24736 @command{configure} script, which permits you to distribute them under the
24737 same terms as the rest of your package.  @file{install-sh} is from the X
24738 Consortium and is not copyrighted.
24740 @node Why GNU M4
24741 @section Why Require GNU M4?
24743 @display
24744 Why does Autoconf require GNU M4?
24745 @end display
24747 Many M4 implementations have hard-coded limitations on the size and
24748 number of macros that Autoconf exceeds.  They also lack several
24749 builtin macros that it would be difficult to get along without in a
24750 sophisticated application like Autoconf, including:
24752 @example
24753 m4_builtin
24754 m4_indir
24755 m4_bpatsubst
24756 __file__
24757 __line__
24758 @end example
24760 Autoconf requires version 1.4.6 or later of GNU M4.
24762 Since only software maintainers need to use Autoconf, and since GNU
24763 M4 is simple to configure and install, it seems reasonable to require
24764 GNU M4 to be installed also.  Many maintainers of GNU and
24765 other free software already have most of the GNU utilities
24766 installed, since they prefer them.
24768 @node Bootstrapping
24769 @section How Can I Bootstrap?
24770 @cindex Bootstrap
24772 @display
24773 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
24774 @command{configure} script, how do I bootstrap?  It seems like a chicken
24775 and egg problem!
24776 @end display
24778 This is a misunderstanding.  Although GNU M4 does come with a
24779 @command{configure} script produced by Autoconf, Autoconf is not required
24780 in order to run the script and install GNU M4.  Autoconf is only
24781 required if you want to change the M4 @command{configure} script, which few
24782 people have to do (mainly its maintainer).
24784 @node Why Not Imake
24785 @section Why Not Imake?
24786 @cindex Imake
24788 @display
24789 Why not use Imake instead of @command{configure} scripts?
24790 @end display
24792 Several people have written addressing this question, so
24793 adaptations of their explanations are included here.
24795 The following answer is based on one written by Richard Pixley:
24797 @quotation
24798 Autoconf generated scripts frequently work on machines that it has
24799 never been set up to handle before.  That is, it does a good job of
24800 inferring a configuration for a new system.  Imake cannot do this.
24802 Imake uses a common database of host specific data.  For X11, this makes
24803 sense because the distribution is made as a collection of tools, by one
24804 central authority who has control over the database.
24806 GNU tools are not released this way.  Each GNU tool has a
24807 maintainer; these maintainers are scattered across the world.  Using a
24808 common database would be a maintenance nightmare.  Autoconf may appear
24809 to be this kind of database, but in fact it is not.  Instead of listing
24810 host dependencies, it lists program requirements.
24812 If you view the GNU suite as a collection of native tools, then the
24813 problems are similar.  But the GNU development tools can be
24814 configured as cross tools in almost any host+target permutation.  All of
24815 these configurations can be installed concurrently.  They can even be
24816 configured to share host independent files across hosts.  Imake doesn't
24817 address these issues.
24819 Imake templates are a form of standardization.  The GNU coding
24820 standards address the same issues without necessarily imposing the same
24821 restrictions.
24822 @end quotation
24825 Here is some further explanation, written by Per Bothner:
24827 @quotation
24828 One of the advantages of Imake is that it easy to generate large
24829 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
24830 However, @code{cpp} is not programmable: it has limited conditional
24831 facilities, and no looping.  And @code{cpp} cannot inspect its
24832 environment.
24834 All of these problems are solved by using @code{sh} instead of
24835 @code{cpp}.  The shell is fully programmable, has macro substitution,
24836 can execute (or source) other shell scripts, and can inspect its
24837 environment.
24838 @end quotation
24841 Paul Eggert elaborates more:
24843 @quotation
24844 With Autoconf, installers need not assume that Imake itself is already
24845 installed and working well.  This may not seem like much of an advantage
24846 to people who are accustomed to Imake.  But on many hosts Imake is not
24847 installed or the default installation is not working well, and requiring
24848 Imake to install a package hinders the acceptance of that package on
24849 those hosts.  For example, the Imake template and configuration files
24850 might not be installed properly on a host, or the Imake build procedure
24851 might wrongly assume that all source files are in one big directory
24852 tree, or the Imake configuration might assume one compiler whereas the
24853 package or the installer needs to use another, or there might be a
24854 version mismatch between the Imake expected by the package and the Imake
24855 supported by the host.  These problems are much rarer with Autoconf,
24856 where each package comes with its own independent configuration
24857 processor.
24859 Also, Imake often suffers from unexpected interactions between
24860 @command{make} and the installer's C preprocessor.  The fundamental problem
24861 here is that the C preprocessor was designed to preprocess C programs,
24862 not makefiles.  This is much less of a problem with Autoconf,
24863 which uses the general-purpose preprocessor M4, and where the
24864 package's author (rather than the installer) does the preprocessing in a
24865 standard way.
24866 @end quotation
24869 Finally, Mark Eichin notes:
24871 @quotation
24872 Imake isn't all that extensible, either.  In order to add new features to
24873 Imake, you need to provide your own project template, and duplicate most
24874 of the features of the existing one.  This means that for a sophisticated
24875 project, using the vendor-provided Imake templates fails to provide any
24876 leverage---since they don't cover anything that your own project needs
24877 (unless it is an X11 program).
24879 On the other side, though:
24881 The one advantage that Imake has over @command{configure}:
24882 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
24883 than @file{Makefile.in} files.  There is a fix to this, however---at least
24884 for the Kerberos V5 tree, we've modified things to call in common
24885 @file{post.in} and @file{pre.in} makefile fragments for the
24886 entire tree.  This means that a lot of common things don't have to be
24887 duplicated, even though they normally are in @command{configure} setups.
24888 @end quotation
24891 @node Defining Directories
24892 @section How Do I @code{#define} Installation Directories?
24894 @display
24895 My program needs library files, installed in @code{datadir} and
24896 similar.  If I use
24898 @example
24899 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
24900   [Define to the read-only architecture-independent
24901    data directory.])
24902 @end example
24904 @noindent
24905 I get
24907 @example
24908 #define DATADIR "$@{prefix@}/share"
24909 @end example
24910 @end display
24912 As already explained, this behavior is on purpose, mandated by the
24913 GNU Coding Standards, see @ref{Installation Directory
24914 Variables}.  There are several means to achieve a similar goal:
24916 @itemize @minus
24917 @item
24918 Do not use @code{AC_DEFINE} but use your makefile to pass the
24919 actual value of @code{datadir} via compilation flags.
24920 @xref{Installation Directory Variables}, for the details.
24922 @item
24923 This solution can be simplified when compiling a program: you may either
24924 extend the @code{CPPFLAGS}:
24926 @example
24927 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
24928 @end example
24930 @noindent
24931 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
24933 @example
24934 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
24935 @end example
24937 @noindent
24938 Alternatively, create a dedicated header file:
24940 @example
24941 DISTCLEANFILES = myprog-paths.h
24942 myprog-paths.h: Makefile
24943         echo '#define DATADIR "$(datadir)"' >$@@
24944 @end example
24946 @item
24947 Use @code{AC_DEFINE} but have @command{configure} compute the literal
24948 value of @code{datadir} and others.  Many people have wrapped macros to
24949 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
24950 the @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
24951 Archive}.
24953 This solution does not conform to the GNU Coding Standards.
24955 @item
24956 Note that all the previous solutions hard wire the absolute name of
24957 these directories in the executables, which is not a good property.  You
24958 may try to compute the names relative to @code{prefix}, and try to
24959 find @code{prefix} at runtime, this way your package is relocatable.
24960 @end itemize
24963 @node Autom4te Cache
24964 @section What is @file{autom4te.cache}?
24966 @display
24967 What is this directory @file{autom4te.cache}?  Can I safely remove it?
24968 @end display
24970 In the GNU Build System, @file{configure.ac} plays a central
24971 role and is read by many tools: @command{autoconf} to create
24972 @file{configure}, @command{autoheader} to create @file{config.h.in},
24973 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
24974 check the completeness of @file{configure.ac}, @command{autoreconf} to
24975 check the GNU Build System components that are used.  To
24976 ``read @file{configure.ac}'' actually means to compile it with M4,
24977 which can be a long process for complex @file{configure.ac}.
24979 This is why all these tools, instead of running directly M4, invoke
24980 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
24981 a specific demand, stores additional information in
24982 @file{autom4te.cache} for future runs.  For instance, if you run
24983 @command{autoconf}, behind the scenes, @command{autom4te} also
24984 stores information for the other tools, so that when you invoke
24985 @command{autoheader} or @command{automake} etc., reprocessing
24986 @file{configure.ac} is not needed.  The speed up is frequently 30%,
24987 and is increasing with the size of @file{configure.ac}.
24989 But it is and remains being simply a cache: you can safely remove it.
24991 @sp 1
24993 @display
24994 Can I permanently get rid of it?
24995 @end display
24997 The creation of this cache can be disabled from
24998 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
24999 details.  You should be aware that disabling the cache slows down the
25000 Autoconf test suite by 40%.  The more GNU Build System
25001 components are used, the more the cache is useful; for instance
25002 running @samp{autoreconf -f} on the Core Utilities is twice slower without
25003 the cache @emph{although @option{--force} implies that the cache is
25004 not fully exploited}, and eight times slower than without
25005 @option{--force}.
25008 @node Present But Cannot Be Compiled
25009 @section Header Present But Cannot Be Compiled
25011 The most important guideline to bear in mind when checking for
25012 features is to mimic as much as possible the intended use.
25013 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
25014 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
25015 the preprocessor, instead of the compiler, to check for headers.  As a
25016 result, incompatibilities between headers went unnoticed during
25017 configuration, and maintainers finally had to deal with this issue
25018 elsewhere.
25020 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
25021 checks are performed, and @command{configure} complains loudly if the
25022 compiler and the preprocessor do not agree.  However, only the compiler
25023 result is considered.
25025 Consider the following example:
25027 @smallexample
25028 $ @kbd{cat number.h}
25029 typedef int number;
25030 $ @kbd{cat pi.h}
25031 const number pi = 3;
25032 $ @kbd{cat configure.ac}
25033 AC_INIT([Example], [1.0], [bug-example@@example.org])
25034 AC_CHECK_HEADERS([pi.h])
25035 $ @kbd{autoconf -Wall}
25036 $ @kbd{./configure}
25037 checking for gcc... gcc
25038 checking for C compiler default output file name... a.out
25039 checking whether the C compiler works... yes
25040 checking whether we are cross compiling... no
25041 checking for suffix of executables...
25042 checking for suffix of object files... o
25043 checking whether we are using the GNU C compiler... yes
25044 checking whether gcc accepts -g... yes
25045 checking for gcc option to accept ISO C89... none needed
25046 checking how to run the C preprocessor... gcc -E
25047 checking for grep that handles long lines and -e... grep
25048 checking for egrep... grep -E
25049 checking for ANSI C header files... yes
25050 checking for sys/types.h... yes
25051 checking for sys/stat.h... yes
25052 checking for stdlib.h... yes
25053 checking for string.h... yes
25054 checking for memory.h... yes
25055 checking for strings.h... yes
25056 checking for inttypes.h... yes
25057 checking for stdint.h... yes
25058 checking for unistd.h... yes
25059 checking pi.h usability... no
25060 checking pi.h presence... yes
25061 configure: WARNING: pi.h: present but cannot be compiled
25062 configure: WARNING: pi.h:     check for missing prerequisite headers?
25063 configure: WARNING: pi.h: see the Autoconf documentation
25064 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
25065 configure: WARNING: pi.h: proceeding with the compiler's result
25066 configure: WARNING:     ## -------------------------------------- ##
25067 configure: WARNING:     ## Report this to bug-example@@example.org ##
25068 configure: WARNING:     ## -------------------------------------- ##
25069 checking for pi.h... yes
25070 @end smallexample
25072 @noindent
25073 The proper way the handle this case is using the fourth argument
25074 (@pxref{Generic Headers}):
25076 @example
25077 $ @kbd{cat configure.ac}
25078 AC_INIT([Example], [1.0], [bug-example@@example.org])
25079 AC_CHECK_HEADERS([number.h pi.h], [], [],
25080 [[#ifdef HAVE_NUMBER_H
25081 # include <number.h>
25082 #endif
25084 $ @kbd{autoconf -Wall}
25085 $ @kbd{./configure}
25086 checking for gcc... gcc
25087 checking for C compiler default output... a.out
25088 checking whether the C compiler works... yes
25089 checking whether we are cross compiling... no
25090 checking for suffix of executables...
25091 checking for suffix of object files... o
25092 checking whether we are using the GNU C compiler... yes
25093 checking whether gcc accepts -g... yes
25094 checking for gcc option to accept ANSI C... none needed
25095 checking for number.h... yes
25096 checking for pi.h... yes
25097 @end example
25099 See @ref{Particular Headers}, for a list of headers with their
25100 prerequisites.
25102 @node Expanded Before Required
25103 @section Expanded Before Required
25105 @cindex expanded before required
25106 Older versions of Autoconf silently built files with incorrect ordering
25107 between dependent macros if an outer macro first expanded, then later
25108 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
25109 situation no longer generates out-of-order code, but results in
25110 duplicate output and a syntax warning:
25112 @example
25113 $ @kbd{cat configure.ac}
25114 @result{}AC_DEFUN([TESTA], [[echo in A
25115 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
25116 @result{}SEEN_A=:]])
25117 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
25118 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
25119 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
25120 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
25121 @result{}TESTA
25122 @result{}TESTC])
25123 @result{}AC_INIT
25124 @result{}OUTER
25125 @result{}AC_OUTPUT
25126 $ @kbd{autoconf}
25127 @result{}configure.ac:11: warning: AC_REQUIRE:
25128 @result{} `TESTA' was expanded before it was required
25129 @result{}configure.ac:4: TESTB is expanded from...
25130 @result{}configure.ac:6: TESTC is expanded from...
25131 @result{}configure.ac:7: OUTER is expanded from...
25132 @result{}configure.ac:11: the top level
25133 @end example
25135 @noindent
25136 To avoid this warning, decide what purpose the macro in question serves.
25137 If it only needs to be expanded once (for example, if it provides
25138 initialization text used by later macros), then the simplest fix is to
25139 change the macro to be declared with @code{AC_DEFUN_ONCE}
25140 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
25141 newer.  A more portable fix is to change all
25142 instances of direct calls to instead go through @code{AC_REQUIRE}
25143 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
25144 by arguments or by the current definition of other macros in the m4
25145 environment, then the macro should always be directly expanded instead
25146 of required.
25148 For another case study, consider this example trimmed down from an
25149 actual package.  Originally, the package contained shell code and
25150 multiple macro invocations at the top level of @file{configure.ac}:
25152 @example
25153 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25154 foobar=
25155 AC_PROG_CC
25157 @end example
25159 @noindent
25160 but that was getting complex, so the author wanted to offload some of
25161 the text into a new macro in another file included via
25162 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
25163 macro:
25165 @example
25166 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25167 AC_DEFUN([BAR], [
25168 foobar=
25169 AC_PROG_CC
25173 @end example
25175 @noindent
25176 With older versions of Autoconf, the setting of @samp{foobar=} occurs
25177 before the single compiler check, as the author intended.  But with
25178 Autoconf 2.64, this issues the ``expanded before it was required''
25179 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
25180 check, one before @samp{foobar=}, and one after.  To understand why this
25181 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
25182 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
25183 the documented semantics of @code{AC_REQUIRE}, this means that
25184 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
25185 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceeding the
25186 use of @samp{foobar=}.  The older versions of Autoconf were broken with
25187 regards to the rules of @code{AC_REQUIRE}, which explains why the code
25188 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
25189 autoconf.  In other words, the author was unknowingly relying on a bug
25190 exploit to get the desired results, and that exploit broke once the bug
25191 was fixed.
25193 So, what recourse does the author have, to restore their intended
25194 semantics of setting @samp{foobar=} prior to a single compiler check,
25195 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
25196 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
25197 there is always the possibility of using the lower-level
25198 @code{m4_define}:
25200 @example
25201 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25202 m4_define([BAR], [
25203 foobar=
25204 AC_PROG_CC
25208 @end example
25210 @noindent
25211 This works great if everything is in the same file.  However, it does
25212 not help in the case where the author wants to have @command{aclocal}
25213 find the definition of @code{BAR} from its own file, since
25214 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
25215 better fix is to recognize that if @code{BAR} also uses
25216 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
25217 to a subsequent require.  Then, by creating yet another helper macro,
25218 the author can once again guarantee a single invocation of
25219 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
25220 author can also use @code{AC_BEFORE} to make sure no other macro
25221 appearing before @code{BAR} has triggered an unwanted expansion of
25222 @code{AC_PROG_CC}.
25224 @example
25225 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25226 AC_DEFUN([BEFORE_CC], [
25227 foobar=
25229 AC_DEFUN([BAR], [
25230 AC_BEFORE([$0], [AC_PROG_CC])dnl
25231 AC_REQUIRE([BEFORE_CC])dnl
25232 AC_REQUIRE([AC_PROG_CC])dnl
25236 @end example
25239 @node Debugging
25240 @section Debugging @command{configure} scripts
25242 While in general, @command{configure} scripts generated by Autoconf
25243 strive to be fairly portable to various systems, compilers, shells, and
25244 other tools, it may still be necessary to debug a failing test, broken
25245 script or makefile, or fix or override an incomplete, faulty, or erroneous
25246 test, especially during macro development.  Failures can occur at all levels,
25247 in M4 syntax or semantics, shell script issues, or due to bugs in the
25248 test or the tools invoked by @command{configure}.  Together with the
25249 rather arcane error message that @command{m4} and @command{make} may
25250 produce when their input contains syntax errors, this can make debugging
25251 rather painful.
25253 Nevertheless, here is a list of hints and strategies that may help:
25255 @itemize
25256 @item
25257 When @command{autoconf} fails, common causes for error include:
25259 @itemize
25260 @item
25261 mismatched or unbalanced parentheses or braces (@pxref{Balancing
25262 Parentheses}),
25264 @item under- or overquoted macro arguments (@pxref{Autoconf
25265 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
25266 Macros}),
25268 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
25269 Language}).
25270 @end itemize
25272 Typically, it helps to go back to the last working version of the input
25273 and compare the differences for each of these errors.  Another
25274 possibility is to sprinkle pairs of @code{m4_traceon} and
25275 @code{m4_traceoff} judiciously in the code, either without a parameter
25276 or listing some macro names and watch @command{m4} expand its input
25277 verbosely (@pxref{Debugging via autom4te}).
25279 @item
25280 Sometimes @command{autoconf} succeeds but the generated
25281 @command{configure} script has invalid shell syntax.  You can detect this
25282 case by running @samp{bash -n configure} or @samp{sh -n configure}.
25283 If this command fails, the same tips apply, as if @command{autoconf} had
25284 failed.
25286 @item
25287 Debugging @command{configure} script execution may be done by sprinkling
25288 pairs of @code{set -x} and @code{set +x} into the shell script before
25289 and after the region that contains a bug.  Running the whole script with
25290 @samp{@var{shell} ./configure -vx 2>&1 | tee @var{log-file}} with a decent
25291 @var{shell} may work, but produces lots of output.  Here, it can help to
25292 search for markers like @samp{checking for} a particular test in the
25293 @var{log-file}.
25295 @item
25296 Alternatively, you might use a shell with debugging capabilities like
25297 @uref{http://bashdb.sourceforge.net/, bashdb}.
25299 @item
25300 When @command{configure} tests produce invalid results for your system,
25301 it may be necessary to override them:
25303 @itemize
25304 @item
25305 For programs, tools or libraries variables, preprocessor, compiler, or
25306 linker flags, it is often sufficient to override them at @command{make}
25307 run time with some care (@pxref{Macros and Submakes}).  Since this
25308 normally won't cause @command{configure} to be run again with these
25309 changed settings, it may fail if the changed variable would have caused
25310 different test results from @command{configure}, so this may work only
25311 for simple differences.
25313 @item
25314 Most tests which produce their result in a substituted variable allow to
25315 override the test by setting the variable on the @command{configure}
25316 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
25317 @pxref{Particular Systems}).
25319 @item
25320 Many tests store their result in a cache variable (@pxref{Caching
25321 Results}).  This lets you override them either on the
25322 @command{configure} command line as above, or through a primed cache or
25323 site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
25324 cache variable is documented with a test macro or may be inferred from
25325 @ref{Cache Variable Names}; the precise semantics of undocumented
25326 variables are often internal details, subject to change.
25327 @end itemize
25329 @item
25330 Alternatively, @command{configure} may produce invalid results because
25331 of uncaught programming errors, in your package or in an upstream
25332 library package.  For example, when @code{AC_CHECK_LIB} fails to find a
25333 library with a specified function, always check @file{config.log}.  This
25334 will reveal the exact error that produced the failing result: the
25335 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
25336 @end itemize
25338 Conversely, as macro author, you can make it easier for users of your
25339 macro:
25341 @itemize
25342 @item
25343 by minimizing dependencies between tests and between test results as far
25344 as possible,
25346 @item
25347 by using @command{make} variables to factorize and allow
25348 override of settings at @command{make} run time,
25350 @item
25351 by honoring the GNU Coding Standards and not overriding flags
25352 reserved for the user except temporarily during @command{configure}
25353 tests,
25355 @item
25356 by not requiring users of your macro to use the cache variables.
25357 Instead, expose the result of the test via @var{run-if-true} and
25358 @var{run-if-false} parameters.  If the result is not a boolean,
25359 then provide it through documented shell variables.
25360 @end itemize
25363 @c ===================================================== History of Autoconf.
25365 @node History
25366 @chapter History of Autoconf
25367 @cindex History of autoconf
25369 @emph{This chapter was written by the original author, David MacKenzie.}
25371 You may be wondering, Why was Autoconf originally written?  How did it
25372 get into its present form?  (Why does it look like gorilla spit?)  If
25373 you're not wondering, then this chapter contains no information useful
25374 to you, and you might as well skip it.  If you @emph{are} wondering,
25375 then let there be light@enddots{}
25377 @menu
25378 * Genesis::                     Prehistory and naming of @command{configure}
25379 * Exodus::                      The plagues of M4 and Perl
25380 * Leviticus::                   The priestly code of portability arrives
25381 * Numbers::                     Growth and contributors
25382 * Deuteronomy::                 Approaching the promises of easy configuration
25383 @end menu
25385 @node Genesis
25386 @section Genesis
25388 In June 1991 I was maintaining many of the GNU utilities for the
25389 Free Software Foundation.  As they were ported to more platforms and
25390 more programs were added, the number of @option{-D} options that users
25391 had to select in the makefile (around 20) became burdensome.
25392 Especially for me---I had to test each new release on a bunch of
25393 different systems.  So I wrote a little shell script to guess some of
25394 the correct settings for the fileutils package, and released it as part
25395 of fileutils 2.0.  That @command{configure} script worked well enough that
25396 the next month I adapted it (by hand) to create similar @command{configure}
25397 scripts for several other GNU utilities packages.  Brian Berliner
25398 also adapted one of my scripts for his CVS revision control system.
25400 Later that summer, I learned that Richard Stallman and Richard Pixley
25401 were developing similar scripts to use in the GNU compiler tools;
25402 so I adapted my @command{configure} scripts to support their evolving
25403 interface: using the file name @file{Makefile.in} as the templates;
25404 adding @samp{+srcdir}, the first option (of many); and creating
25405 @file{config.status} files.
25407 @node Exodus
25408 @section Exodus
25410 As I got feedback from users, I incorporated many improvements, using
25411 Emacs to search and replace, cut and paste, similar changes in each of
25412 the scripts.  As I adapted more GNU utilities packages to use
25413 @command{configure} scripts, updating them all by hand became impractical.
25414 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
25415 mail saying that the @command{configure} scripts were great, and asking if
25416 I had a tool for generating them that I could send him.  No, I thought,
25417 but I should!  So I started to work out how to generate them.  And the
25418 journey from the slavery of hand-written @command{configure} scripts to the
25419 abundance and ease of Autoconf began.
25421 Cygnus @command{configure}, which was being developed at around that time,
25422 is table driven; it is meant to deal mainly with a discrete number of
25423 system types with a small number of mainly unguessable features (such as
25424 details of the object file format).  The automatic configuration system
25425 that Brian Fox had developed for Bash takes a similar approach.  For
25426 general use, it seems to me a hopeless cause to try to maintain an
25427 up-to-date database of which features each variant of each operating
25428 system has.  It's easier and more reliable to check for most features on
25429 the fly---especially on hybrid systems that people have hacked on
25430 locally or that have patches from vendors installed.
25432 I considered using an architecture similar to that of Cygnus
25433 @command{configure}, where there is a single @command{configure} script that
25434 reads pieces of @file{configure.in} when run.  But I didn't want to have
25435 to distribute all of the feature tests with every package, so I settled
25436 on having a different @command{configure} made from each
25437 @file{configure.in} by a preprocessor.  That approach also offered more
25438 control and flexibility.
25440 I looked briefly into using the Metaconfig package, by Larry Wall,
25441 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
25442 reasons.  The @command{Configure} scripts it produces are interactive,
25443 which I find quite inconvenient; I didn't like the ways it checked for
25444 some features (such as library functions); I didn't know that it was
25445 still being maintained, and the @command{Configure} scripts I had
25446 seen didn't work on many modern systems (such as System V R4 and NeXT);
25447 it wasn't flexible in what it could do in response to a feature's
25448 presence or absence; I found it confusing to learn; and it was too big
25449 and complex for my needs (I didn't realize then how much Autoconf would
25450 eventually have to grow).
25452 I considered using Perl to generate my style of @command{configure}
25453 scripts, but decided that M4 was better suited to the job of simple
25454 textual substitutions: it gets in the way less, because output is
25455 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
25456 the GNU extensions to M4.)  Also, some of my friends at the
25457 University of Maryland had recently been putting M4 front ends on
25458 several programs, including @code{tvtwm}, and I was interested in trying
25459 out a new language.
25461 @node Leviticus
25462 @section Leviticus
25464 Since my @command{configure} scripts determine the system's capabilities
25465 automatically, with no interactive user intervention, I decided to call
25466 the program that generates them Autoconfig.  But with a version number
25467 tacked on, that name would be too long for old Unix file systems,
25468 so I shortened it to Autoconf.
25470 In the fall of 1991 I called together a group of fellow questers after
25471 the Holy Grail of portability (er, that is, alpha testers) to give me
25472 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
25473 and continued to add features and improve the techniques used in the
25474 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
25475 with the idea of making an Autoconf shell script to run M4
25476 and check for unresolved macro calls; Richard Pixley, who suggested
25477 running the compiler instead of searching the file system to find
25478 include files and symbols, for more accurate results; Karl Berry, who
25479 got Autoconf to configure @TeX{} and added the macro index to the
25480 documentation; and Ian Lance Taylor, who added support for creating a C
25481 header file as an alternative to putting @option{-D} options in a
25482 makefile, so he could use Autoconf for his UUCP package.
25483 The alpha testers cheerfully adjusted their files again and again as the
25484 names and calling conventions of the Autoconf macros changed from
25485 release to release.  They all contributed many specific checks, great
25486 ideas, and bug fixes.
25488 @node Numbers
25489 @section Numbers
25491 In July 1992, after months of alpha testing, I released Autoconf 1.0,
25492 and converted many GNU packages to use it.  I was surprised by how
25493 positive the reaction to it was.  More people started using it than I
25494 could keep track of, including people working on software that wasn't
25495 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
25496 Autoconf continued to improve rapidly, as many people using the
25497 @command{configure} scripts reported problems they encountered.
25499 Autoconf turned out to be a good torture test for M4 implementations.
25500 Unix M4 started to dump core because of the length of the
25501 macros that Autoconf defined, and several bugs showed up in GNU
25502 M4 as well.  Eventually, we realized that we needed to use some
25503 features that only GNU M4 has.  4.3BSD M4, in
25504 particular, has an impoverished set of builtin macros; the System V
25505 version is better, but still doesn't provide everything we need.
25507 More development occurred as people put Autoconf under more stresses
25508 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
25509 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
25510 invalid arguments.  Jim Blandy bravely coerced it into configuring
25511 GNU Emacs, laying the groundwork for several later improvements.
25512 Roland McGrath got it to configure the GNU C Library, wrote the
25513 @command{autoheader} script to automate the creation of C header file
25514 templates, and added a @option{--verbose} option to @command{configure}.
25515 Noah Friedman added the @option{--autoconf-dir} option and
25516 @code{AC_MACRODIR} environment variable.  (He also coined the term
25517 @dfn{autoconfiscate} to mean ``adapt a software package to use
25518 Autoconf''.)  Roland and Noah improved the quoting protection in
25519 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
25520 dealing with portability problems from February through June, 1993.
25522 @node Deuteronomy
25523 @section Deuteronomy
25525 A long wish list for major features had accumulated, and the effect of
25526 several years of patching by various people had left some residual
25527 cruft.  In April 1994, while working for Cygnus Support, I began a major
25528 revision of Autoconf.  I added most of the features of the Cygnus
25529 @command{configure} that Autoconf had lacked, largely by adapting the
25530 relevant parts of Cygnus @command{configure} with the help of david zuhn
25531 and Ken Raeburn.  These features include support for using
25532 @file{config.sub}, @file{config.guess}, @option{--host}, and
25533 @option{--target}; making links to files; and running @command{configure}
25534 scripts in subdirectories.  Adding these features enabled Ken to convert
25535 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
25536 Autoconf.
25538 I added more features in response to other peoples' requests.  Many
25539 people had asked for @command{configure} scripts to share the results of
25540 the checks between runs, because (particularly when configuring a large
25541 source tree, like Cygnus does) they were frustratingly slow.  Mike
25542 Haertel suggested adding site-specific initialization scripts.  People
25543 distributing software that had to unpack on MS-DOS asked for a way to
25544 override the @file{.in} extension on the file names, which produced file
25545 names like @file{config.h.in} containing two dots.  Jim Avera did an
25546 extensive examination of the problems with quoting in @code{AC_DEFINE}
25547 and @code{AC_SUBST}; his insights led to significant improvements.
25548 Richard Stallman asked that compiler output be sent to @file{config.log}
25549 instead of @file{/dev/null}, to help people debug the Emacs
25550 @command{configure} script.
25552 I made some other changes because of my dissatisfaction with the quality
25553 of the program.  I made the messages showing results of the checks less
25554 ambiguous, always printing a result.  I regularized the names of the
25555 macros and cleaned up coding style inconsistencies.  I added some
25556 auxiliary utilities that I had developed to help convert source code
25557 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
25558 the macros not interrupt each others' messages.  (That feature revealed
25559 some performance bottlenecks in GNU M4, which he hastily
25560 corrected!)  I reorganized the documentation around problems people want
25561 to solve.  And I began a test suite, because experience had shown that
25562 Autoconf has a pronounced tendency to regress when we change it.
25564 Again, several alpha testers gave invaluable feedback, especially
25565 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
25566 and Mark Eichin.
25568 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
25569 have free time again.  I think.  Yeah, right.)
25572 @c ========================================================== Appendices
25575 @node GNU Free Documentation License
25576 @appendix GNU Free Documentation License
25578 @include fdl.texi
25580 @node Indices
25581 @appendix Indices
25583 @menu
25584 * Environment Variable Index::  Index of environment variables used
25585 * Output Variable Index::       Index of variables set in output files
25586 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
25587 * Cache Variable Index::        Index of documented cache variables
25588 * Autoconf Macro Index::        Index of Autoconf macros
25589 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
25590 * Autotest Macro Index::        Index of Autotest macros
25591 * Program & Function Index::    Index of those with portability problems
25592 * Concept Index::               General index
25593 @end menu
25595 @node Environment Variable Index
25596 @appendixsec Environment Variable Index
25598 This is an alphabetical list of the environment variables that might
25599 influence Autoconf checks.
25601 @printindex ev
25603 @node Output Variable Index
25604 @appendixsec Output Variable Index
25606 This is an alphabetical list of the variables that Autoconf can
25607 substitute into files that it creates, typically one or more
25608 makefiles.  @xref{Setting Output Variables}, for more information
25609 on how this is done.
25611 @printindex ov
25613 @node Preprocessor Symbol Index
25614 @appendixsec Preprocessor Symbol Index
25616 This is an alphabetical list of the C preprocessor symbols that the
25617 Autoconf macros define.  To work with Autoconf, C source code needs to
25618 use these names in @code{#if} or @code{#ifdef} directives.
25620 @printindex cv
25622 @node Cache Variable Index
25623 @appendixsec Cache Variable Index
25625 This is an alphabetical list of documented cache variables used
25626 by macros defined in Autoconf.  Autoconf macros may use additional cache
25627 variables internally.
25628 @ifset shortindexflag
25629 To make the list easier to use, the variables are listed without their
25630 preceding @samp{ac_cv_}.
25631 @end ifset
25633 @printindex CA
25635 @node Autoconf Macro Index
25636 @appendixsec Autoconf Macro Index
25638 This is an alphabetical list of the Autoconf macros.
25639 @ifset shortindexflag
25640 To make the list easier to use, the macros are listed without their
25641 preceding @samp{AC_}.
25642 @end ifset
25644 @printindex AC
25646 @node M4 Macro Index
25647 @appendixsec M4 Macro Index
25649 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
25650 @ifset shortindexflag
25651 To make the list easier to use, the macros are listed without their
25652 preceding @samp{m4_} or @samp{AS_}.  The prefix is @samp{m4_} for
25653 all-lowercase macro names and @samp{AS_} for all-uppercase macro
25654 names.
25655 @end ifset
25657 @printindex MS
25659 @node Autotest Macro Index
25660 @appendixsec Autotest Macro Index
25662 This is an alphabetical list of the Autotest macros.
25663 @ifset shortindexflag
25664 To make the list easier to use, the macros are listed without their
25665 preceding @samp{AT_}.
25666 @end ifset
25668 @printindex AT
25670 @node Program & Function Index
25671 @appendixsec Program and Function Index
25673 This is an alphabetical list of the programs and functions whose
25674 portability is discussed in this document.
25676 @printindex pr
25678 @node Concept Index
25679 @appendixsec Concept Index
25681 This is an alphabetical list of the files, tools, and concepts
25682 introduced in this document.
25684 @printindex cp
25686 @bye
25688 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
25689 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
25690 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
25691 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
25692 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
25693 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
25694 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
25695 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
25696 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
25697 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
25698 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
25699 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
25700 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
25701 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
25702 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
25703 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
25704 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
25705 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
25706 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
25707 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
25708 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
25709 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
25710 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
25711 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
25712 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
25713 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
25714 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
25715 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
25716 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
25717 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
25718 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
25719 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
25720 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
25721 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
25722 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
25723 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
25724 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
25725 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
25726 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
25727 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
25728 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
25729 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
25730 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
25731 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
25732 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
25733 @c  LocalWords:  STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
25734 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
25735 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
25736 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
25737 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
25738 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
25739 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
25740 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
25741 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
25742 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
25743 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
25744 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
25745 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
25746 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
25747 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
25748 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
25749 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
25750 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
25751 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
25752 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
25753 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
25754 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
25755 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
25756 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
25757 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
25758 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
25759 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
25760 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
25761 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
25762 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
25763 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
25764 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
25765 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
25766 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
25767 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
25768 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
25769 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
25770 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
25771 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
25772 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
25773 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
25774 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
25775 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
25776 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
25777 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
25778 @c  LocalWords:  Dynix descrips basename aname cname macroexpands xno xcheck
25779 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
25781 @c Local Variables:
25782 @c fill-column: 72
25783 @c ispell-local-dictionary: "american"
25784 @c indent-tabs-mode: nil
25785 @c whitespace-check-buffer-indent: nil
25786 @c End: